From 9cfe1371257e80a9f8a47326239add58813a6811 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 09:33:36 -0500 Subject: [PATCH 01/21] docs(id): start phase 4, groups, encryption, and history [phase 4 start] --- ...-12T14-33-36Z_phase_4_groups_encryption.md | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md diff --git a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md new file mode 100644 index 0000000000..37996833de --- /dev/null +++ b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md @@ -0,0 +1,43 @@ +# Phase 4: groups, encryption, and history + +- Plan: [phased plan](../../2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md), section 9. +- Start commit: `c12448c9` (origin/main after Phase 3). +- Base branch `phase-4`. Tracks: `p4-adapter` (P4.1, P4.2, P4.3; first, it unblocks the rest), then `p4-scheme` (P4.4), `p4-history` (P4.5, P4.6, P4.12), `p4-heads` (P4.7), `p4-warn` (P4.8 to P4.11). +- Decisions in force: full history by default; recent:N per world (32, 128 presets); scheme v1 (serde_bytes) as the first released scheme; from_join fork kept in the fork; no periodic rotation; PCS recovery by remove and re-add; warnings at 96, 128, 1000; BeeKEM not adopted. + +## Steps + +| Step | Track | Status | Commits | Tests | Notes | +| ------------------------------------- | ------- | ------ | ------- | ----- | --------------- | +| P4.1 DataScheme adapter | adapter | todo | | | blocks the rest | +| P4.2 Our DGM and the from_join fork | adapter | todo | | | | +| P4.3 from_join withholding rule | adapter | todo | | | | +| P4.4 Scheme v1 | scheme | todo | | | | +| P4.5 recent:N and full | history | todo | | | | +| P4.6 Lazy full history | history | todo | | | | +| P4.7 Heads rule | heads | todo | | | | +| P4.8 Rotation policy and PCS recovery | warn | todo | | | | +| P4.9 Warnings | warn | todo | | | | +| P4.10 scheme none notice | warn | todo | | | | +| P4.11 DataScheme cost measurement | warn | todo | | | | +| P4.12 Welcome chunking | history | todo | | | | + +## Decisions + +- See the decisions above and the index. + +## Open questions + +- None yet. + +## Changes to the plan + +- None yet. + +## Review notes and regression tests + +- To be filled. + +## End + +- Pending. From a630a440173c05c7481de016ba0dae6911153194 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 09:47:36 -0500 Subject: [PATCH 02/21] feat(rust): DataScheme adapter over the group model [P4.1] Adds src/encryption/: a Session per device and group over p2panda-encryption (git rev 3e84cac, data_scheme on, test_utils and message_scheme off). Create, add, remove, update, send and process. Membership is the member set the group model holds after the event; after each membership change the crate's roster is checked against it. Adds call Dcgka::add with the full bundle and run the local steps themselves. Application messages whose group secret the device does not hold are withheld before the crate sees them. The orderer and the roster are our own, since the crate's MessageOrderer and TestDgm are test-only. --- pkgs/id/Cargo.lock | 349 ++++++++++++++++++++++++++++- pkgs/id/Cargo.toml | 3 + pkgs/id/src/encryption/mod.rs | 23 ++ pkgs/id/src/encryption/ordering.rs | 258 +++++++++++++++++++++ pkgs/id/src/encryption/roster.rs | 78 +++++++ pkgs/id/src/encryption/scheme.rs | 309 +++++++++++++++++++++++++ pkgs/id/src/encryption/tests.rs | 345 ++++++++++++++++++++++++++++ pkgs/id/src/lib.rs | 1 + 8 files changed, 1362 insertions(+), 4 deletions(-) create mode 100644 pkgs/id/src/encryption/mod.rs create mode 100644 pkgs/id/src/encryption/ordering.rs create mode 100644 pkgs/id/src/encryption/roster.rs create mode 100644 pkgs/id/src/encryption/scheme.rs create mode 100644 pkgs/id/src/encryption/tests.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index bf9a3193c7..de86cab5a5 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -527,6 +527,26 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "597bb81c80a54b6a4381b23faba8d7774b144c94cbd1d6fe3f1329bd776554ab" +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.11.1" @@ -714,7 +734,7 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", ] [[package]] @@ -723,6 +743,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -809,6 +838,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "clap" version = "4.6.7" @@ -994,6 +1034,17 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core-models" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee3344d349528f449816cfa85e558c439bdca5a6d8a738cfb21e69f0b2b1952f" +dependencies = [ + "hax-lib", + "pastey", + "rand 0.10.3", +] + [[package]] name = "core_detect" version = "1.0.0" @@ -1024,6 +1075,17 @@ dependencies = [ "libc", ] +[[package]] +name = "crabgrind" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7459e07732f6de74001fcf73a3fdfbb0f368e4fd8e2392f4a2206a065e6e95" +dependencies = [ + "bindgen", + "cc", + "pkg-config", +] + [[package]] name = "cranelift-assembler-x64" version = "0.130.2" @@ -2253,6 +2315,12 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "gloo-timers" version = "0.3.0" @@ -2361,6 +2429,43 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hax-lib" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a33cb227f97ee5c419064c31d7c55a7d895f28d8019ccdadc311cc036500c4" +dependencies = [ + "hax-lib-macros", + "num-bigint 0.4.8", + "num-traits", +] + +[[package]] +name = "hax-lib-macros" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28da835a5f153e9f3d0cc1f42ee605a1cfa9093c93348193793d60a1b0908b51" +dependencies = [ + "hax-lib-macros-types", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "hax-lib-macros-types" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed327e9a28d6ee018a4a9ba842d4ee27e378c8a591d2beb6f42f32b24a02fcb" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "uuid", +] + [[package]] name = "heapless" version = "0.7.17" @@ -2480,6 +2585,51 @@ dependencies = [ "zeroize", ] +[[package]] +name = "hpke-rs" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812de62ab573b876c6c40d7553bae9402ae3bad95b64af06f964388eecb9b7b1" +dependencies = [ + "hpke-rs-crypto", + "libcrux-sha3", + "log", + "subtle", + "zeroize", +] + +[[package]] +name = "hpke-rs-crypto" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c461da2e0c9c93d875b597f0c78214fb0d2d5c57834b2ef2a2fa057fa20e24" +dependencies = [ + "rand 0.10.3", + "zeroize", +] + +[[package]] +name = "hpke-rs-rust-crypto" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a606ac19851da841862ef5f39d26d6227bfcfb4047417801a66c1f6e6652d71" +dependencies = [ + "aes-gcm 0.10.3", + "chacha20poly1305", + "hkdf 0.13.0", + "hpke-rs-crypto", + "k256", + "p256 0.13.2", + "p384 0.13.1", + "rand 0.10.3", + "rand_chacha 0.10.0", + "rand_core 0.10.1", + "sha2 0.11.0", + "subtle", + "x25519-dalek", + "zeroize", +] + [[package]] name = "http" version = "1.5.0" @@ -2740,6 +2890,7 @@ dependencies = [ "mime_guess", "p2panda-auth", "p2panda-core", + "p2panda-encryption", "p2panda-store", "p2panda-sync", "postcard", @@ -3272,6 +3423,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.14.0" @@ -3382,6 +3542,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "k256" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "elliptic-curve 0.13.8", +] + [[package]] name = "keccak" version = "0.2.2" @@ -3420,6 +3590,67 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "libcrux-intrinsics" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98a0c574d4eb81d0814bc2b91e4a433d7e0b35851b1d62eb5dd95c064f1f76d0" +dependencies = [ + "core-models", + "hax-lib", +] + +[[package]] +name = "libcrux-platform" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9e21d7ed31a92ac539bd69a8c970b183ee883872d2d19ce27036e24cb8ecc4" +dependencies = [ + "libc", +] + +[[package]] +name = "libcrux-secrets" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79054fc9037cb70d6a546cf094cea7d7df06af5e49d230ba24103d27ccc886f1" +dependencies = [ + "crabgrind", + "hax-lib", +] + +[[package]] +name = "libcrux-sha3" +version = "0.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c09f5c39afae0528e1f70a3c1e3c6ee649ec1f19dda26fc9b6ea91108fb879ef" +dependencies = [ + "hax-lib", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-traits", +] + +[[package]] +name = "libcrux-traits" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fa7a21e8c2e8baa8b40f0b176740f2ca4baadd79d1b00e48d6b1e363c42085a" +dependencies = [ + "libcrux-secrets", + "rand 0.10.3", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + [[package]] name = "libm" version = "0.2.16" @@ -4293,6 +4524,29 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "p2panda-encryption" +version = "0.7.1" +source = "git+https://github.com/p2panda/p2panda?rev=3e84cac48bba05c6857cce2ec433862b97f8d53c#3e84cac48bba05c6857cce2ec433862b97f8d53c" +dependencies = [ + "chacha20poly1305", + "curve25519-dalek 4.1.3", + "hex", + "hkdf 0.12.4", + "hpke-rs", + "hpke-rs-crypto", + "hpke-rs-rust-crypto", + "p2panda-core", + "rand_chacha 0.9.0", + "serde", + "serde_bytes", + "sha2 0.10.9", + "subtle", + "thiserror 2.0.21", + "x25519-dalek", + "zeroize", +] + [[package]] name = "p2panda-store" version = "0.7.1" @@ -4319,6 +4573,16 @@ dependencies = [ "tracing", ] +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "elliptic-curve 0.13.8", + "primeorder 0.13.6", +] + [[package]] name = "p384" version = "0.14.0" @@ -4421,6 +4685,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pbkdf2" version = "0.13.0" @@ -4775,6 +5045,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + [[package]] name = "primefield" version = "0.14.0" @@ -4846,6 +5126,28 @@ dependencies = [ "version_check", ] +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "proc-macro-hack" version = "0.5.20+deprecated" @@ -5008,6 +5310,16 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_chacha" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb" +dependencies = [ + "ppv-lite86", + "rand_core 0.10.1", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -5150,6 +5462,18 @@ dependencies = [ "smallvec", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + [[package]] name = "regex-automata" version = "0.4.18" @@ -5335,7 +5659,7 @@ dependencies = [ "module-lattice", "num-bigint 0.5.1", "p256 0.14.0", - "p384", + "p384 0.14.0", "p521", "pageant", "pbkdf2", @@ -5936,6 +6260,12 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -6143,7 +6473,7 @@ dependencies = [ "hex", "hmac 0.13.0", "p256 0.14.0", - "p384", + "p384 0.14.0", "p521", "rand_core 0.10.1", "rsa", @@ -6885,6 +7215,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -7173,7 +7514,7 @@ dependencies = [ "cranelift-frontend", "cranelift-native", "gimli", - "itertools", + "itertools 0.14.0", "log", "object", "pulley-interpreter", diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index f2d647978e..79ec7e1587 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -61,6 +61,9 @@ p2panda-sync = { path = "vendor/p2panda-sync" } # which the event store keeps with each group operation. `test_utils` is not enabled: it turns on # test-only behaviour in p2panda-core, so the test types come from our own tests. p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", 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 = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", default-features = false, features = ["data_scheme"] } postcard = { version = "1", features = ["alloc"] } rand = "0.10" redb = "=4.3.0" diff --git a/pkgs/id/src/encryption/mod.rs b/pkgs/id/src/encryption/mod.rs new file mode 100644 index 0000000000..e3a31231c7 --- /dev/null +++ b/pkgs/id/src/encryption/mod.rs @@ -0,0 +1,23 @@ +//! Group encryption on the `DataScheme` of `p2panda-encryption` (Phase 4, P4.1 to P4.3). +//! +//! - [`scheme`]: the adapter. One [`Session`] per device and group, with create, add, remove, +//! update, send and process. Membership comes from the group model: the caller passes the member +//! set the model holds after the event. +//! - [`roster`]: the membership the crate keeps. The adapter checks it against the model after each +//! local membership change. +//! - [`ordering`]: causal delivery, and the [`Envelope`] messages travel in. +//! +//! A group member is the key the group model holds (`crate::groups::Key`). The crate's identity is +//! the matching `p2panda_core::VerifyingKey`. + +pub mod ordering; +pub mod roster; +pub mod scheme; + +pub use ordering::{Envelope, Orderer, OrdererError}; +pub use roster::Roster; +pub use scheme::{Received, SchemeError, Session, key_bundle, key_of, new_keys, registry}; + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests; diff --git a/pkgs/id/src/encryption/ordering.rs b/pkgs/id/src/encryption/ordering.rs new file mode 100644 index 0000000000..313f94db89 --- /dev/null +++ b/pkgs/id/src/encryption/ordering.rs @@ -0,0 +1,258 @@ +//! The `DataScheme` orderer and the envelope it delivers. +//! +//! The crate's orderer (`MessageOrderer`) is test-only, so the adapter brings its own with the same +//! rules. A message names the last control message the sender had delivered from each author, and +//! it is delivered once every message it names is delivered. Nothing is delivered before the device +//! is welcomed: a create or a welcome opens delivery, and earlier messages wait in the queue. +//! +//! Application messages are never named by other messages, so the adapter may leave one out +//! without stalling anything. [`super::scheme`] does that for messages whose group secret the +//! device does not hold. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; + +use p2panda_core::cbor::encode_cbor; +use p2panda_core::{Hash, VerifyingKey}; +use p2panda_encryption::crypto::xchacha20::XAeadNonce; +use p2panda_encryption::data_scheme::group_secret::GroupSecretId; +use p2panda_encryption::data_scheme::{ControlMessage, DirectMessage}; +use p2panda_encryption::traits::{GroupMessage, GroupMessageContent, Ordering}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use super::roster::Roster; + +/// One published group message: a control message with its direct messages, or an application +/// message. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Envelope { + /// Hash of the sequence number, the sender, the names and the content. + id: Hash, + sender: VerifyingKey, + /// The last control message seen from each author when this was published. + previous: Vec, + content: Content, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +enum Content { + Control { + control: ControlMessage, + direct: Vec>, + }, + Application { + group_secret_id: GroupSecretId, + nonce: XAeadNonce, + ciphertext: Vec, + }, +} + +impl Envelope { + fn new( + seq: u64, + sender: VerifyingKey, + previous: Vec, + content: Content, + ) -> Result { + let bytes = encode_cbor(&(seq, sender, &previous, &content)) + .map_err(|err| OrdererError::Encode(err.to_string()))?; + Ok(Self { + id: Hash::digest(&bytes), + sender, + previous, + content, + }) + } +} + +impl GroupMessage for Envelope { + fn id(&self) -> Hash { + self.id + } + + fn sender(&self) -> VerifyingKey { + self.sender + } + + fn content(&self) -> GroupMessageContent { + match &self.content { + Content::Control { control, .. } => GroupMessageContent::Control(control.clone()), + Content::Application { + group_secret_id, + nonce, + ciphertext, + } => GroupMessageContent::Application { + group_secret_id: *group_secret_id, + nonce: *nonce, + ciphertext: ciphertext.clone(), + }, + } + } + + fn direct_messages(&self) -> Vec> { + match &self.content { + Content::Control { direct, .. } => direct.clone(), + Content::Application { .. } => Vec::new(), + } + } +} + +/// An error from the orderer. +#[derive(Debug, Error)] +pub enum OrdererError { + /// The message could not be encoded to compute its hash. + #[error("cannot encode the message: {0}")] + Encode(String), +} + +/// The orderer. Its state is [`OrdererState`]. +#[derive(Clone, Copy, Debug)] +pub struct Orderer; + +impl Orderer { + /// The state before a create or a welcome. + pub const fn init(my_id: VerifyingKey) -> OrdererState { + OrdererState { + my_id, + next_seq: 0, + previous: BTreeMap::new(), + messages: BTreeMap::new(), + ready: BTreeSet::new(), + waiting: BTreeMap::new(), + deliverable: VecDeque::new(), + welcomed: false, + } + } +} + +/// The orderer's state: our sequence, the last control message from each author, and the messages +/// that are not delivered yet. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct OrdererState { + my_id: VerifyingKey, + next_seq: u64, + /// The last control message delivered from each author, including our own. + previous: BTreeMap, + /// Every message received, by ID. + messages: BTreeMap, + /// Messages that are ready: every message they name is ready. Our own published messages are + /// ready, since we processed them locally. + ready: BTreeSet, + /// Received messages that still lack a named message, with the names they lack. + waiting: BTreeMap>, + /// Ready messages the group has not taken yet, oldest first. + deliverable: VecDeque, + /// Set by a create or a welcome. Nothing is delivered before it. + welcomed: bool, +} + +impl OrdererState { + /// Publishes our own message. It names the control messages we have seen, and it is ready. + fn publish(&mut self, content: Content) -> Result { + let seq = self.next_seq; + self.next_seq += 1; + let previous = self.previous.values().copied().collect(); + let envelope = Envelope::new(seq, self.my_id, previous, content)?; + self.ready.insert(envelope.id); + Ok(envelope) + } + + /// Marks `id` ready, then every waiting message that it completes. + fn make_ready(&mut self, id: Hash) { + self.ready.insert(id); + self.deliverable.push_back(id); + while let Some(next) = self + .waiting + .iter() + .find(|(_, missing)| missing.iter().all(|named| self.ready.contains(named))) + .map(|(id, _)| *id) + { + self.waiting.remove(&next); + self.ready.insert(next); + self.deliverable.push_back(next); + } + } +} + +impl Ordering for Orderer { + type State = OrdererState; + + type Error = OrdererError; + + type Message = Envelope; + + fn next_control_message( + mut y: Self::State, + control_message: &ControlMessage, + direct_messages: &[DirectMessage], + ) -> Result<(Self::State, Self::Message), Self::Error> { + let content = Content::Control { + control: control_message.clone(), + direct: direct_messages.to_vec(), + }; + let envelope = y.publish(content)?; + y.previous.insert(y.my_id, envelope.id); + Ok((y, envelope)) + } + + fn next_application_message( + mut y: Self::State, + group_secret_id: GroupSecretId, + nonce: XAeadNonce, + ciphertext: Vec, + ) -> Result<(Self::State, Self::Message), Self::Error> { + let content = Content::Application { + group_secret_id, + nonce, + ciphertext, + }; + let envelope = y.publish(content)?; + Ok((y, envelope)) + } + + fn queue(mut y: Self::State, message: &Self::Message) -> Result { + if y.ready.contains(&message.id) || y.messages.contains_key(&message.id) { + return Ok(y); + } + y.messages.insert(message.id, message.clone()); + + let missing: Vec = message + .previous + .iter() + .filter(|named| !y.ready.contains(named)) + .copied() + .collect(); + if missing.is_empty() { + y.make_ready(message.id); + } else { + y.waiting.insert(message.id, missing); + } + Ok(y) + } + + fn set_welcome( + mut y: Self::State, + _message: &Self::Message, + ) -> Result { + y.welcomed = true; + Ok(y) + } + + fn next_ready_message( + mut y: Self::State, + ) -> Result<(Self::State, Option), Self::Error> { + if !y.welcomed { + return Ok((y, None)); + } + let Some(id) = y.deliverable.pop_front() else { + return Ok((y, None)); + }; + let Some(envelope) = y.messages.get(&id).cloned() else { + return Ok((y, None)); + }; + if let Content::Control { .. } = envelope.content { + y.previous.insert(envelope.sender, id); + } + Ok((y, Some(envelope))) + } +} diff --git a/pkgs/id/src/encryption/roster.rs b/pkgs/id/src/encryption/roster.rs new file mode 100644 index 0000000000..8d3a551c2e --- /dev/null +++ b/pkgs/id/src/encryption/roster.rs @@ -0,0 +1,78 @@ +//! The `DataScheme` membership: the roster the adapter keeps for the crate. +//! +//! The crate's test membership (`TestDgm`) is not used. The roster follows the control messages the +//! crate processes: `add` and `remove` change it, and `from_welcome` takes the adder's roster from a +//! welcome. The adapter checks it against the group model after each local membership change (see +//! [`super::scheme`]). + +use std::collections::{BTreeSet, HashSet}; +use std::convert::Infallible; + +use p2panda_core::{Hash, VerifyingKey}; +use p2panda_encryption::traits::GroupMembership; +use serde::{Deserialize, Serialize}; + +/// The `DataScheme` membership. A member is its verifying key, and an operation is its envelope hash. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Roster; + +/// The members one device believes are in the group. Kept sorted, so every device serializes the +/// same members to the same bytes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RosterState { + members: BTreeSet, +} + +impl Roster { + /// An empty roster, before a create or a welcome. + pub const fn initial_state() -> RosterState { + RosterState { + members: BTreeSet::new(), + } + } +} + +impl GroupMembership for Roster { + type State = RosterState; + + type Error = Infallible; + + fn create( + _my_id: VerifyingKey, + initial_members: &[VerifyingKey], + ) -> Result { + Ok(RosterState { + members: initial_members.iter().copied().collect(), + }) + } + + /// The welcome carries the adder's roster from before the add, so it lacks the joiner. The + /// joiner is put back by the crate's `process_welcome`, in the vendored fork (P4.2). + fn from_welcome(_my_id: VerifyingKey, y: Self::State) -> Result { + Ok(y) + } + + fn add( + mut y: Self::State, + _adder: VerifyingKey, + added: VerifyingKey, + _operation_id: Hash, + ) -> Result { + y.members.insert(added); + Ok(y) + } + + fn remove( + mut y: Self::State, + _remover: VerifyingKey, + removed: &VerifyingKey, + _operation_id: Hash, + ) -> Result { + y.members.remove(removed); + Ok(y) + } + + fn members(y: &Self::State) -> Result, Self::Error> { + Ok(y.members.iter().copied().collect()) + } +} diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs new file mode 100644 index 0000000000..92c3f8f73e --- /dev/null +++ b/pkgs/id/src/encryption/scheme.rs @@ -0,0 +1,309 @@ +//! The `DataScheme` adapter: one device's encryption state for one group, over `p2panda-encryption`. +//! +//! Membership comes from the group model. The caller passes the member set the model holds after +//! the event (the `members` of [`crate::groups::GroupView`], from [`crate::groups::fold`]). After +//! each local membership change the adapter checks the crate's roster against that set, so the two +//! cannot drift apart without an error. +//! +//! An add calls `Dcgka::add` with the full secret bundle, then runs the local steps that +//! `EncryptionGroup::add` runs. The crate keeps those steps private, and the lower-level call is +//! what a smaller bundle (`recent:N`) needs. +//! +//! The crate moves the group state into each call and does not return it on error. After a failed +//! call the session reports [`SchemeError::Poisoned`]. Preconditions are checked before the call, +//! so a rejected request does not poison the session. + +// The crate's `GroupError` is large, and every crate call returns it. Boxing it would hide the crate's +// error from callers, so the lint is allowed for this module. +#![allow(clippy::result_large_err)] + +use std::collections::BTreeSet; + +use p2panda_core::{Hash, VerifyingKey}; +use p2panda_encryption::crypto::Rng; +use p2panda_encryption::crypto::x25519::SecretKey; +use p2panda_encryption::data_scheme::dcgka::{Dcgka, OperationOutput, ProcessInput}; +use p2panda_encryption::data_scheme::group::{ + EncryptionGroup, GroupError, GroupOutput, GroupResult, GroupState, +}; +use p2panda_encryption::data_scheme::group_secret::{GroupSecret, GroupSecretId}; +use p2panda_encryption::key_bundle::{Lifetime, LongTermKeyBundle}; +use p2panda_encryption::key_manager::{KeyManager, KeyManagerState}; +use p2panda_encryption::key_registry::{KeyRegistry, KeyRegistryState}; +use p2panda_encryption::traits::{GroupMessage, GroupMessageContent, Ordering as _, PreKeyManager}; +use thiserror::Error; + +use super::ordering::{Envelope, Orderer}; +use super::roster::Roster; +use crate::groups::Key; + +type Pki = KeyRegistry; + +type Group = GroupState; + +type Step = GroupResult; + +/// What a device reads from one message it is given. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Received { + /// The plaintext of an application message. + Plaintext(Vec), + /// A removal that took this device out of the group. + Removed, + /// An application message whose group secret this device does not hold. It was not given to the + /// crate, so it can be offered again later, once a welcome or an update brings the secret. + Withheld(Hash), +} + +/// What the adapter can fail with. +#[derive(Debug, Error)] +pub enum SchemeError { + /// A failed crate call consumed the session's state. + #[error("the session is poisoned: a failed crate call consumed its state")] + Poisoned, + /// The device has neither created nor joined the group. + #[error("the group has not been created or joined on this device")] + NotWelcomed, + /// An error from `p2panda-encryption`. + #[error("data scheme: {0}")] + Crate(String), + /// A group-model key is not a valid verifying key. + #[error("invalid identity key: {0}")] + InvalidKey(String), + /// The key is not a member in the group model, so it cannot be added. + #[error("{0} is not in the group model, so it cannot be added")] + NotInModel(String), + /// The key is still a member in the group model, so it cannot be removed. + #[error("{0} is still in the group model, so it cannot be removed")] + StillInModel(String), + /// The crate's roster and the group model hold different members. + #[error("the encryption roster disagrees with the group model: {0}")] + RosterMismatch(String), +} + +/// One device's encryption state for one group. +#[derive(Debug)] +pub struct Session { + me: VerifyingKey, + state: Option, +} + +impl Session { + /// A device's state before it creates or joins the group. `registry` must hold the long-term + /// bundles of every member who may take part. + pub fn init( + me: VerifyingKey, + keys: KeyManagerState, + registry: KeyRegistryState, + ) -> Self { + let state: Group = EncryptionGroup::init( + me, + keys, + registry, + Roster::initial_state(), + Orderer::init(me), + ); + Self { + me, + state: Some(state), + } + } + + /// Whether this device has created or joined the group. + pub fn is_welcomed(&self) -> bool { + self.state.as_ref().is_some_and(|y| y.is_welcomed) + } + + /// The current epoch: the ID of the newest group secret this device holds. + pub fn epoch(&self) -> Option { + self.state.as_ref()?.secrets.latest().map(GroupSecret::id) + } + + /// The members the crate's roster holds, as group-model keys. + pub fn members(&self) -> Result, SchemeError> { + let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; + let members = EncryptionGroup::members(y).map_err(crate_error)?; + Ok(members.into_iter().map(key_of).collect()) + } + + /// Creates the group with `model` as its members. This device must be one of them. + pub fn create(&mut self, model: &BTreeSet, rng: &Rng) -> Result { + if !model.contains(&key_of(self.me)) { + return Err(SchemeError::NotInModel(short(key_of(self.me)))); + } + let initial: Vec = members_of(model)?; + let message = self.step(|y| EncryptionGroup::create(y, initial, rng))?; + self.check_roster(model)?; + Ok(message) + } + + /// Adds `added`, which `model` must already list, with a welcome that carries the full bundle. + pub fn add( + &mut self, + model: &BTreeSet, + added: Key, + rng: &Rng, + ) -> Result { + self.ensure_welcomed()?; + if !model.contains(&added) { + return Err(SchemeError::NotInModel(short(added))); + } + let added_key = member_of(added)?; + let message = self.step(|mut y| { + let (dcgka, output) = Dcgka::add(y.dcgka, added_key, &y.secrets, rng)?; + y.dcgka = dcgka; + publish(y, output) + })?; + self.check_roster(model)?; + Ok(message) + } + + /// Removes `removed`, which `model` must no longer list. The removal rotates the epoch. + pub fn remove( + &mut self, + model: &BTreeSet, + removed: Key, + rng: &Rng, + ) -> Result { + self.ensure_welcomed()?; + if model.contains(&removed) { + return Err(SchemeError::StillInModel(short(removed))); + } + let removed_key = member_of(removed)?; + let message = self.step(|y| EncryptionGroup::remove(y, removed_key, rng))?; + self.check_roster(model)?; + Ok(message) + } + + /// Rotates the epoch by giving every current member a new secret. + pub fn update(&mut self, rng: &Rng) -> Result { + self.ensure_welcomed()?; + self.step(|y| EncryptionGroup::update(y, rng)) + } + + /// Encrypts `plaintext` under the current epoch. + pub fn send(&mut self, plaintext: &[u8], rng: &Rng) -> Result { + self.ensure_welcomed()?; + self.step(|y| EncryptionGroup::send(y, plaintext, rng)) + } + + /// Handles a message from the group. An application message whose secret this device does not + /// hold is withheld and not given to the crate (P4.3). + pub fn process(&mut self, message: &Envelope) -> Result, SchemeError> { + if let GroupMessageContent::Application { + group_secret_id, .. + } = message.content() + { + // The crate fails the whole call, and loses the state, on a secret it does not hold. + let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; + if !y.secrets.contains(&group_secret_id) { + return Ok(vec![Received::Withheld(message.id())]); + } + } + let outputs = self.step(|y| EncryptionGroup::receive(y, message))?; + Ok(outputs + .into_iter() + .filter_map(|output| match output { + GroupOutput::Application { plaintext } => Some(Received::Plaintext(plaintext)), + GroupOutput::Removed => Some(Received::Removed), + GroupOutput::Control(_) => None, + }) + .collect()) + } + + const fn ensure_welcomed(&self) -> Result<(), SchemeError> { + match &self.state { + None => Err(SchemeError::Poisoned), + Some(y) if !y.is_welcomed => Err(SchemeError::NotWelcomed), + Some(_) => Ok(()), + } + } + + /// Runs one crate call. On error the state is gone, so the session is poisoned. + fn step(&mut self, op: impl FnOnce(Group) -> Step) -> Result { + let y = self.state.take().ok_or(SchemeError::Poisoned)?; + let (y, value) = op(y).map_err(crate_error)?; + self.state = Some(y); + Ok(value) + } + + fn check_roster(&self, model: &BTreeSet) -> Result<(), SchemeError> { + let roster = self.members()?; + if roster == *model { + return Ok(()); + } + Err(SchemeError::RosterMismatch(format!( + "the roster has {} members, the model {}", + roster.len(), + model.len() + ))) + } +} + +/// The local steps `EncryptionGroup` runs after a control operation: publish the control message, +/// then process it as its sender. +fn publish(mut y: Group, output: OperationOutput) -> Step { + let (orderer, message) = + Orderer::next_control_message(y.orderer, &output.control_message, &output.direct_messages) + .map_err(GroupError::Orderer)?; + y.orderer = orderer; + + let (dcgka, _) = Dcgka::process( + y.dcgka, + ProcessInput { + seq: message.id(), + sender: message.sender(), + control_message: output.control_message, + direct_message: None, + }, + )?; + y.dcgka = dcgka; + Ok((y, message)) +} + +/// A device's long-term keys: its identity and one pre-key. +pub fn new_keys( + identity: &SecretKey, + lifetime: Lifetime, + rng: &Rng, +) -> Result { + let keys = KeyManager::init(identity).map_err(crate_error)?; + KeyManager::rotate_prekey(keys, lifetime, rng).map_err(crate_error) +} + +/// The bundle other members need to reach this device. +pub fn key_bundle(keys: &KeyManagerState) -> Result { + KeyManager::prekey_bundle(keys).map_err(crate_error) +} + +/// A registry that holds each member's bundle. +pub fn registry( + bundles: &[(VerifyingKey, LongTermKeyBundle)], +) -> Result, SchemeError> { + bundles + .iter() + .try_fold(KeyRegistry::init(), |registry, (member, bundle)| { + KeyRegistry::add_longterm_bundle(registry, *member, bundle.clone()).map_err(crate_error) + }) +} + +/// The group-model key of a device. +pub fn key_of(member: VerifyingKey) -> Key { + *member.as_bytes() +} + +fn member_of(key: Key) -> Result { + VerifyingKey::from_bytes(&key).map_err(|err| SchemeError::InvalidKey(err.to_string())) +} + +fn members_of(model: &BTreeSet) -> Result, SchemeError> { + model.iter().map(|key| member_of(*key)).collect() +} + +fn crate_error(err: impl std::fmt::Display) -> SchemeError { + SchemeError::Crate(err.to_string()) +} + +fn short(key: Key) -> String { + format!("{:02x}{:02x}{:02x}{:02x}", key[0], key[1], key[2], key[3]) +} diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs new file mode 100644 index 0000000000..2fe0f2bbe4 --- /dev/null +++ b/pkgs/id/src/encryption/tests.rs @@ -0,0 +1,345 @@ +//! Tests for the `DataScheme` adapter: unit tests per operation, and a three-member integration. +//! +//! Everyone in a cast gets keys and a session up front. Control messages go to every member of the +//! cast, since a joiner needs the control history to take the welcome. Application messages go only +//! to the members who may read them. + +use std::collections::{BTreeMap, BTreeSet}; + +use p2panda_core::{SigningKey, VerifyingKey}; +use p2panda_encryption::crypto::Rng; +use p2panda_encryption::crypto::x25519::SecretKey as IdentitySecret; +use p2panda_encryption::data_scheme::group_secret::GroupSecretId; +use p2panda_encryption::key_bundle::Lifetime; +use p2panda_encryption::key_manager::KeyManagerState; +use p2panda_encryption::traits::GroupMessage; + +use super::*; +use crate::groups::Key; + +fn person(seed: u8) -> (Key, VerifyingKey) { + let verifying = SigningKey::from_bytes(&[seed; 32]).verifying_key(); + (key_of(verifying), verifying) +} + +fn id(seed: u8) -> Key { + person(seed).0 +} + +fn text(message: &str) -> Received { + Received::Plaintext(message.as_bytes().to_vec()) +} + +/// Every person's keys and one session per person, all sharing one registry of bundles. +struct Cast { + rng: Rng, + sessions: BTreeMap, + /// The member set the group model holds after the last operation. + model: BTreeSet, +} + +impl Cast { + fn new(seeds: &[u8]) -> Self { + let rng = Rng::default(); + let mut bundles = Vec::new(); + let mut keys: BTreeMap = BTreeMap::new(); + for seed in seeds { + let (key, verifying) = person(*seed); + let identity = IdentitySecret::from_rng(&rng).expect("identity"); + let state = new_keys(&identity, Lifetime::default(), &rng).expect("keys"); + bundles.push((verifying, key_bundle(&state).expect("bundle"))); + keys.insert(key, (verifying, state)); + } + let registry = registry(&bundles).expect("registry"); + let sessions = keys + .into_iter() + .map(|(key, (verifying, state))| { + let session = Session::init(verifying, state, registry.clone()); + (key, session) + }) + .collect(); + Self { + rng, + sessions, + model: BTreeSet::new(), + } + } + + fn session(&self, who: u8) -> &Session { + self.sessions.get(&id(who)).expect("session") + } + + fn create(&mut self, by: u8, members: &[u8]) -> Envelope { + self.model = members.iter().map(|seed| id(*seed)).collect(); + let model = self.model.clone(); + self.sessions + .get_mut(&id(by)) + .expect("session") + .create(&model, &self.rng) + .expect("create") + } + + fn add(&mut self, by: u8, who: u8) -> Envelope { + self.model.insert(id(who)); + let model = self.model.clone(); + self.sessions + .get_mut(&id(by)) + .expect("session") + .add(&model, id(who), &self.rng) + .expect("add") + } + + fn remove(&mut self, by: u8, who: u8) -> Envelope { + self.model.remove(&id(who)); + let model = self.model.clone(); + self.sessions + .get_mut(&id(by)) + .expect("session") + .remove(&model, id(who), &self.rng) + .expect("remove") + } + + fn update(&mut self, by: u8) -> Envelope { + self.sessions + .get_mut(&id(by)) + .expect("session") + .update(&self.rng) + .expect("update") + } + + fn send(&mut self, by: u8, message: &str) -> Envelope { + self.sessions + .get_mut(&id(by)) + .expect("session") + .send(message.as_bytes(), &self.rng) + .expect("send") + } + + /// Hands `message` to each of `to`, in order, and returns what each one read. + fn deliver(&mut self, message: &Envelope, to: &[u8]) -> Vec> { + to.iter() + .map(|seed| { + self.sessions + .get_mut(&id(*seed)) + .expect("session") + .process(message) + .expect("process") + }) + .collect() + } + + fn members_of(&self, who: u8) -> BTreeSet { + self.session(who).members().expect("members") + } + + fn epoch(&self, who: u8) -> Option { + self.session(who).epoch() + } +} + +// --- create --------------------------------------------------------------------------------------- + +#[test] +fn test_create_gives_every_member_the_model_roster() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + for who in [1, 2, 3] { + assert!(cast.session(who).is_welcomed(), "member {who} is welcomed"); + assert_eq!(cast.members_of(who), cast.model, "member {who} roster"); + } + assert_eq!(cast.epoch(1), cast.epoch(2)); + assert_eq!(cast.epoch(2), cast.epoch(3)); +} + +#[test] +fn test_create_rejects_a_device_outside_the_model() { + let mut cast = Cast::new(&[1, 2]); + let model: BTreeSet = std::iter::once(id(2)).collect(); + let rng = Rng::default(); + let result = cast + .sessions + .get_mut(&id(1)) + .expect("session") + .create(&model, &rng); + assert!(matches!(result, Err(SchemeError::NotInModel(_)))); + assert!( + !cast.session(1).is_welcomed(), + "a rejected create leaves the session usable" + ); +} + +#[test] +fn test_operations_before_create_are_rejected_without_poisoning() { + let mut cast = Cast::new(&[1, 2]); + let rng = Rng::default(); + let session = cast.sessions.get_mut(&id(1)).expect("session"); + assert!(matches!( + session.send(b"early", &rng), + Err(SchemeError::NotWelcomed) + )); + assert!(matches!( + session.update(&rng), + Err(SchemeError::NotWelcomed) + )); + let create_model: BTreeSet = [id(1), id(2)].into_iter().collect(); + assert!( + session.create(&create_model, &rng).is_ok(), + "the session still creates" + ); +} + +// --- add ------------------------------------------------------------------------------------------ + +#[test] +fn test_add_is_applied_by_the_adder_and_the_existing_members() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + let add = cast.add(1, 4); + cast.deliver(&add, &[2, 3]); + + for who in [1, 2, 3] { + assert_eq!( + cast.members_of(who), + cast.model, + "member {who} roster after add" + ); + } +} + +#[test] +fn test_add_rejects_a_key_the_model_does_not_list() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2]); + cast.deliver(&create, &[2]); + + let model = cast.model.clone(); + let rng = Rng::default(); + let result = cast + .sessions + .get_mut(&id(1)) + .expect("session") + .add(&model, id(3), &rng); + assert!(matches!(result, Err(SchemeError::NotInModel(_)))); + assert_eq!(cast.members_of(1), cast.model, "the roster is untouched"); +} + +// --- update --------------------------------------------------------------------------------------- + +#[test] +fn test_update_rotates_the_epoch_for_every_member() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + let before = cast.epoch(1); + + let update = cast.update(2); + cast.deliver(&update, &[1, 3]); + assert_ne!(cast.epoch(1), before, "the update rotates the epoch"); + assert_eq!(cast.epoch(1), cast.epoch(2)); + assert_eq!(cast.epoch(2), cast.epoch(3)); + + let message = cast.send(1, "after the update"); + let read = cast.deliver(&message, &[2, 3]); + assert_eq!( + read, + vec![ + vec![text("after the update")], + vec![text("after the update")] + ] + ); +} + +// --- remove --------------------------------------------------------------------------------------- + +#[test] +fn test_remove_takes_the_member_out_and_it_cannot_read_later_messages() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + let remove = cast.remove(1, 3); + let read = cast.deliver(&remove, &[2, 3]); + assert_eq!( + read[1], + vec![Received::Removed], + "the removed member learns it was removed" + ); + assert_eq!( + cast.members_of(1), + cast.model, + "the remover's roster drops the member" + ); + + let message = cast.send(1, "after the removal"); + assert_eq!( + cast.deliver(&message, &[2]), + vec![vec![text("after the removal")]] + ); + let to_removed = cast.deliver(&message, &[3]); + assert_eq!( + to_removed, + vec![vec![Received::Withheld(message.id())]], + "the removed member cannot read a message sent under the new epoch" + ); +} + +#[test] +fn test_remove_rejects_a_member_the_model_still_lists() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + let model = cast.model.clone(); + let rng = Rng::default(); + let result = cast + .sessions + .get_mut(&id(1)) + .expect("session") + .remove(&model, id(3), &rng); + assert!(matches!(result, Err(SchemeError::StillInModel(_)))); +} + +// --- integration: three members ------------------------------------------------------------------- + +#[test] +fn test_three_members_create_send_update_and_remove_in_step() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + let first = cast.send(2, "first"); + assert_eq!( + cast.deliver(&first, &[1, 3]), + vec![vec![text("first")], vec![text("first")]] + ); + + let update = cast.update(3); + cast.deliver(&update, &[1, 2]); + let second = cast.send(1, "second"); + assert_eq!( + cast.deliver(&second, &[2, 3]), + vec![vec![text("second")], vec![text("second")]] + ); + + let remove = cast.remove(1, 2); + let read = cast.deliver(&remove, &[2, 3]); + assert_eq!(read[0], vec![Received::Removed]); + assert_eq!(cast.members_of(1), cast.model); + assert_eq!( + cast.members_of(3), + cast.model, + "the remaining member agrees" + ); + assert_eq!( + cast.epoch(1), + cast.epoch(3), + "the remaining members share an epoch" + ); + + let third = cast.send(3, "third"); + assert_eq!(cast.deliver(&third, &[1]), vec![vec![text("third")]]); +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 5d00a99d66..15f187e2e8 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -172,6 +172,7 @@ pub mod directory_mail; pub mod directory_view; pub mod discovery; #[cfg(feature = "world")] +pub mod encryption; pub mod envelope_net; #[cfg(feature = "world")] pub mod envelope_outbox; From e57c12235afebfadf5f73d7b94ab5393ad150c93 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 09:50:21 -0500 Subject: [PATCH 03/21] feat(rust): vendored p2panda-encryption with the from_join membership fix [P4.2] Vendors p2panda-encryption at rev 3e84cac under pkgs/id/vendor, as the p2panda-sync copy was in P3.2. The copy carries the S3 patch: the joiner applies its own add in process_welcome, so a welcome's roster that predates the add no longer leaves the joiner out, and EncryptionGroup::add_from_join. The fix is ours, not upstream (owner decision). Each change is recorded in vendor/README.md. The fork's own test fails on the stock crate (the joiner's roster is [0, 1, 2]) and passes with the patch. The adapter's joiner tests failed the same way before the switch to the fork. --- pkgs/id/Cargo.lock | 1 - pkgs/id/Cargo.toml | 2 +- pkgs/id/src/encryption/tests.rs | 74 + pkgs/id/vendor/README.md | 29 + pkgs/id/vendor/p2panda-encryption/Cargo.toml | 46 + .../LICENSES/Apache-2.0.txt | 201 +++ .../p2panda-encryption/LICENSES/MIT.txt | 21 + pkgs/id/vendor/p2panda-encryption/README.md | 215 +++ .../p2panda-encryption/src/crypto/aead.rs | 110 ++ .../p2panda-encryption/src/crypto/hkdf.rs | 48 + .../p2panda-encryption/src/crypto/hpke.rs | 157 ++ .../p2panda-encryption/src/crypto/mod.rs | 28 + .../p2panda-encryption/src/crypto/rng.rs | 85 + .../p2panda-encryption/src/crypto/secret.rs | 47 + .../p2panda-encryption/src/crypto/sha2.rs | 28 + .../p2panda-encryption/src/crypto/x25519.rs | 122 ++ .../src/crypto/xchacha20.rs | 111 ++ .../p2panda-encryption/src/crypto/xeddsa.rs | 234 +++ .../src/data_scheme/data.rs | 43 + .../src/data_scheme/dcgka.rs | 666 +++++++ .../src/data_scheme/group.rs | 634 +++++++ .../src/data_scheme/group_secret.rs | 444 +++++ .../p2panda-encryption/src/data_scheme/mod.rs | 93 + .../src/data_scheme/test_utils/dcgka.rs | 71 + .../src/data_scheme/test_utils/dgm.rs | 87 + .../src/data_scheme/test_utils/mod.rs | 6 + .../src/data_scheme/test_utils/network.rs | 171 ++ .../src/data_scheme/test_utils/ordering.rs | 268 +++ .../src/data_scheme/tests.rs | 689 ++++++++ .../src/key_bundle/key_bundle.rs | 285 +++ .../src/key_bundle/lifetime.rs | 182 ++ .../p2panda-encryption/src/key_bundle/mod.rs | 57 + .../src/key_bundle/prekey.rs | 154 ++ .../p2panda-encryption/src/key_manager.rs | 470 +++++ .../p2panda-encryption/src/key_registry.rs | 386 ++++ pkgs/id/vendor/p2panda-encryption/src/lib.rs | 51 + .../src/message_scheme/dcgka.rs | 1569 +++++++++++++++++ .../src/message_scheme/group.rs | 725 ++++++++ .../src/message_scheme/message.rs | 62 + .../src/message_scheme/mod.rs | 74 + .../src/message_scheme/ratchet.rs | 356 ++++ .../src/message_scheme/test_utils/dcgka.rs | 978 ++++++++++ .../src/message_scheme/test_utils/dgm.rs | 1137 ++++++++++++ .../src/message_scheme/test_utils/mod.rs | 6 + .../src/message_scheme/test_utils/network.rs | 172 ++ .../src/message_scheme/test_utils/ordering.rs | 300 ++++ .../src/message_scheme/tests/concurrency.rs | 615 +++++++ .../message_scheme/tests/group_operations.rs | 738 ++++++++ .../src/message_scheme/tests/mod.rs | 4 + .../vendor/p2panda-encryption/src/ordering.rs | 143 ++ .../p2panda-encryption/src/test_utils.rs | 58 + .../p2panda-encryption/src/traits/dgm.rs | 101 ++ .../src/traits/key_bundle.rs | 19 + .../src/traits/key_manager.rs | 45 + .../src/traits/key_registry.rs | 24 + .../p2panda-encryption/src/traits/message.rs | 127 ++ .../p2panda-encryption/src/traits/mod.rs | 58 + .../p2panda-encryption/src/traits/ordering.rs | 205 +++ .../p2panda-encryption/src/two_party/mod.rs | 31 + .../src/two_party/two_party.rs | 767 ++++++++ .../p2panda-encryption/src/two_party/x3dh.rs | 288 +++ 61 files changed, 14916 insertions(+), 2 deletions(-) create mode 100644 pkgs/id/vendor/p2panda-encryption/Cargo.toml create mode 100644 pkgs/id/vendor/p2panda-encryption/LICENSES/Apache-2.0.txt create mode 100644 pkgs/id/vendor/p2panda-encryption/LICENSES/MIT.txt create mode 100644 pkgs/id/vendor/p2panda-encryption/README.md create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/aead.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/hkdf.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/hpke.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/rng.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/secret.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/sha2.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/x25519.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/xchacha20.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/crypto/xeddsa.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/data.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/dcgka.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/group.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/group_secret.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/dcgka.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/dgm.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/network.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/ordering.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/data_scheme/tests.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/key_bundle/key_bundle.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/key_bundle/lifetime.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/key_bundle/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/key_bundle/prekey.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/key_manager.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/key_registry.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/lib.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/dcgka.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/group.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/message.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/ratchet.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/dcgka.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/dgm.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/network.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/ordering.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/concurrency.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/group_operations.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/ordering.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/test_utils.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/traits/dgm.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/traits/key_bundle.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/traits/key_manager.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/traits/key_registry.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/traits/message.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/traits/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/traits/ordering.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/two_party/mod.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/two_party/two_party.rs create mode 100644 pkgs/id/vendor/p2panda-encryption/src/two_party/x3dh.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index de86cab5a5..5afc80bfe4 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -4527,7 +4527,6 @@ dependencies = [ [[package]] name = "p2panda-encryption" version = "0.7.1" -source = "git+https://github.com/p2panda/p2panda?rev=3e84cac48bba05c6857cce2ec433862b97f8d53c#3e84cac48bba05c6857cce2ec433862b97f8d53c" dependencies = [ "chacha20poly1305", "curve25519-dalek 4.1.3", diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 79ec7e1587..70e3b64d2a 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -63,7 +63,7 @@ p2panda-sync = { path = "vendor/p2panda-sync" } p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", 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 = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", default-features = false, features = ["data_scheme"] } +p2panda-encryption = { path = "vendor/p2panda-encryption", default-features = false, features = ["data_scheme"] } postcard = { version = "1", features = ["alloc"] } rand = "0.10" redb = "=4.3.0" diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index 2fe0f2bbe4..e85ee9ae8a 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -343,3 +343,77 @@ fn test_three_members_create_send_update_and_remove_in_step() { let third = cast.send(3, "third"); assert_eq!(cast.deliver(&third, &[1]), vec![vec![text("third")]]); } + +// --- a joiner (P4.2) ------------------------------------------------------------------------------ + +#[test] +fn test_joiner_reads_messages_sent_after_the_add() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + + let add = cast.add(1, 4); + cast.deliver(&add, &[2, 3, 4]); + assert!(cast.session(4).is_welcomed(), "the add welcomes the joiner"); + assert_eq!( + cast.members_of(4), + cast.model, + "the joiner's roster matches the model" + ); + + let message = cast.send(2, "after the join"); + assert_eq!( + cast.deliver(&message, &[1, 3, 4]), + vec![ + vec![text("after the join")], + vec![text("after the join")], + vec![text("after the join")] + ] + ); +} + +#[test] +fn test_five_members_converge_through_add_update_and_remove() { + let mut cast = Cast::new(&[1, 2, 3, 4, 5]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4, 5]); + + let add_four = cast.add(1, 4); + cast.deliver(&add_four, &[2, 3, 4, 5]); + let add_five = cast.add(2, 5); + cast.deliver(&add_five, &[1, 3, 4, 5]); + + let update = cast.update(5); + cast.deliver(&update, &[1, 2, 3, 4]); + for who in [1, 2, 3, 4, 5] { + assert_eq!( + cast.members_of(who), + cast.model, + "member {who} roster after joins" + ); + assert_eq!(cast.epoch(who), cast.epoch(1), "member {who} epoch"); + } + + let before = cast.send(4, "before the removal"); + cast.deliver(&before, &[1, 2, 3, 5]); + + let remove = cast.remove(1, 2); + let read = cast.deliver(&remove, &[2, 3, 4, 5]); + assert_eq!(read[0], vec![Received::Removed]); + + let after = cast.send(5, "after the removal"); + assert_eq!( + cast.deliver(&after, &[1, 3, 4]), + vec![ + vec![text("after the removal")], + vec![text("after the removal")], + vec![text("after the removal")] + ] + ); + assert_eq!( + cast.epoch(3), + cast.epoch(5), + "the remaining members share an epoch" + ); + assert_eq!(cast.members_of(5), cast.model); +} diff --git a/pkgs/id/vendor/README.md b/pkgs/id/vendor/README.md index 8d24e9a739..8f737762aa 100644 --- a/pkgs/id/vendor/README.md +++ b/pkgs/id/vendor/README.md @@ -33,3 +33,32 @@ git -C "$SRC/.." rev-parse HEAD # 3e84cac48bba05c6857cce2ec433862 `sqlx` is absent from the build. `cargo tree -i sqlx` reports no match, and `store_traits`'s `test_the_lock_has_no_sqlite_with_logsync_wired` fails if `Cargo.lock` names `sqlx`, `sqlite`, `rusqlite` or `libsqlite3-sys`, or if the `p2panda-store` line above loses `default-features = false`. **To update.** Change the rev in the three places it appears (this file, the two git lines in `vendor/p2panda-sync/Cargo.toml`, and the git lines in `pkgs/id/Cargo.toml`). Then copy the crate again and reapply the changes above. + +## p2panda-encryption 0.7.1 (DataScheme fork) + +**Origin.** `https://github.com/p2panda/p2panda`, rev `3e84cac48bba05c6857cce2ec433862b97f8d53c`, crate `p2panda-encryption/`. The same rev as the other p2panda crates in `pkgs/id/Cargo.toml`. License `MIT OR Apache-2.0` (`p2panda-encryption/LICENSES/`). + +**Why.** The crate's `process_welcome` overwrites the joiner's membership with the welcome's copy, and that copy lacks the joiner, so the joiner is never welcomed and reads nothing. The fix, and `add_from_join` (the welcome carries no earlier secret, so the group needs an immediate update after each join), are in our fork and not upstream. Decision (owner): keep the fix in this repo. Source: the spike `doc/2026-10-11T03-44-33Z_design_groups_events_delegation/spikes/shared/s3-history/` (`logs/patch.diff`, `RESULTS.md`). + +**The changes** (the S3 patch, applied by hand): + +- `src/data_scheme/dcgka.rs`: `process_add` skips `DGM::add` for the joiner. `process_welcome` takes the add's `seq`, calls `DGM::from_welcome`, then `DGM::add` for the joiner itself. Both are needed; the test is `joiner_is_welcomed_and_reads_messages_after_the_add` in `src/data_scheme/tests.rs`. +- `src/data_scheme/group.rs`: new public `EncryptionGroup::add_from_join` (25 lines). It calls `Dcgka::add` with an empty bundle and runs the same local steps as `add`. No existing item changes visibility. +- `src/data_scheme/tests.rs`: the regression test above, which fails on the stock crate (the joiner's roster is `[0, 1, 2]`). +- `Cargo.toml`: every `workspace = true` is replaced by the root's value, since this copy is outside the p2panda workspace. `[lints] workspace = true` is removed. `p2panda-core` is the same git source and rev, with `default-features = false`, as upstream's workspace declares it. `[dev-dependencies]` is unchanged (none). +- `LICENSES/` is added. + +**Size.** `src/` differs from upstream by 63 lines added and 2 removed (3 files); `Cargo.toml` by 13 changed lines. + +**Features.** `data_scheme` on, `test_utils` and `message_scheme` off. The `test_utils` tests in the fork use the crate's own `Network` and `TestDgm`, which the test cfg enables. + +**Verify.** + +```sh +C=$(ls -d ~/.cargo/git/checkouts/p2panda-*/3e84cac) +diff -rq "$C/p2panda-encryption" pkgs/id/vendor/p2panda-encryption # the files above differ, nothing else +git -C "$C/.." rev-parse HEAD # 3e84cac48bba05c6857cce2ec433862b97f8d53c +cd pkgs/id/vendor/p2panda-encryption && cargo test --lib data_scheme # run standalone; delete the Cargo.lock it writes +``` + +**To update.** Change the rev in the three places it appears (this section, the `p2panda-encryption/Cargo.toml` git lines, and `pkgs/id/Cargo.toml`). Copy the crate again, then reapply the changes above and run the fork's test. diff --git a/pkgs/id/vendor/p2panda-encryption/Cargo.toml b/pkgs/id/vendor/p2panda-encryption/Cargo.toml new file mode 100644 index 0000000000..e485e94759 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "p2panda-encryption" +version = "0.7.1" +edition = "2024" +authors = [ + "adz ", + "sandreae ", + "glyph ", +] +description = "Decentralised data- and message encryption for groups with post-compromise security and optional forward secrecy" +repository = "https://github.com/p2panda/p2panda" +license = "MIT OR Apache-2.0" +readme = "README.md" +keywords = ["p2p", "encryption", "groups", "double-ratchet"] +rust-version = "1.96" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] + +[features] +default = ["data_scheme"] +data_scheme = [] +message_scheme = [] +test_utils = [ + "data_scheme", + "message_scheme", +] + +[dependencies] +chacha20poly1305 = { version = "0.10.1", features = ["alloc"], default-features = false } +curve25519-dalek = "4.1.3" +hex = "0.4.3" +hkdf = "0.12.4" +hpke-rs = "0.7.0" +hpke-rs-crypto = "0.7.0" +hpke-rs-rust-crypto = "0.7.0" +p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", default-features = false } +rand_chacha = { version = "0.9.0", features = ["os_rng"] } +serde = { version = "1.0.228", features = ["derive"] } +serde_bytes = "0.11.19" +sha2 = "0.10.8" +subtle = "2.6.1" +thiserror = "2.0.18" +x25519-dalek = { version = "2.0.1", features = ["static_secrets"] } +zeroize = { version = "1.8.1", features = ["derive"] } diff --git a/pkgs/id/vendor/p2panda-encryption/LICENSES/Apache-2.0.txt b/pkgs/id/vendor/p2panda-encryption/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000000..2fed0ca7f4 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/LICENSES/Apache-2.0.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright (c) 2024 p2panda contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/pkgs/id/vendor/p2panda-encryption/LICENSES/MIT.txt b/pkgs/id/vendor/p2panda-encryption/LICENSES/MIT.txt new file mode 100644 index 0000000000..e72233d5ea --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/LICENSES/MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 p2panda contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/pkgs/id/vendor/p2panda-encryption/README.md b/pkgs/id/vendor/p2panda-encryption/README.md new file mode 100644 index 0000000000..489600fc1a --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/README.md @@ -0,0 +1,215 @@ +

p2panda-encryption

+ +
+ + Decentralised data- and message encryption for groups + +
+ + + +`p2panda-encryption` provides decentralised, secure data- and message encryption for groups with +post-compromise security and optional forward secrecy. + +The crate implements two different group key-agreement and encryption schemes for a whole range of +use cases for applications which can't rely on a stable network connection or centralised +coordination. + +More detail about the particular implementation and design choices of `p2panda-encryption` can be +found in our [in-depth blog post](https://p2panda.org/2025/02/24/group-encryption.html). + +> 🚧 This library is under active development and the APIs are not yet considered stable for +> production use. Core data types and user-facing APIs may still undergo breaking changes. Stability +> guarantees will improve with the release of v1.0.0. + +## Features + +### Strong Security Guarantees + +Key agreement in `p2panda-encryption` provides strong forward secrecy, while the security of the +data itself depends on the encryption scheme used. The crate offers two different encryption +schemes: + +**Data Encryption** re-uses the same symmetric key known to the peer until a new key is introduced +to the group, for example on member removal. Keys will stay in the network to allow decrypting older +data, unless they are manually removed by the application for optional forward secrecy. + +For **Message Encryption** peers agree on a secret to establish a [message +ratchet](https://en.wikipedia.org/wiki/Double_Ratchet_Algorithm) per member, deriving a new key for +each message sent. After decrypting the ciphertext of the message the key gets dropped for forward +secrecy. + +### Framework-Independent + +This implementation is compatible with any data type, encoding format or transport, made for p2p +applications which do not rely on constant internet connectivity. + +Similar to our other p2panda crates, we aim to make our implementation "framework independent" while +providing optional "glue code" to integrate it in into the larger [p2panda +ecosystem](https://p2panda.org). + +We're currently working on a high-level, easy-to-use integration layer which combines `p2panda-auth` +and `p2panda-encryption` into a feature-complete and tested solution with authenticated roles and +group management, nested groups, multi-device support, atomic transactions, message ordering and +validation. + +### Robustness in Decentralised Systems + +`p2panda-encryption` has been specifically designed to be robust when used in decentralised systems. +It accounts for use in scenarios without guaranteed connectivity between members of the group and +corner cases where group changes (adding, removing members etc.) take place concurrently. No +centralised server is required for coordination of the group. + +The code in this crate is expressed as [pure functions](https://en.wikipedia.org/wiki/Pure_function) +where state is passed around until it is finally "committed" into a persistence layer inside an +atomic transaction. This allows fault-resilient writes to any database and makes applications robust +against corruption of their state when crashes occur. + +## Design + +### Encryption Schemes + +The first scheme we simply call **"Data Encryption"**, allowing peers to encrypt any data with a +secret, symmetric key for a group. This will be useful for building applications where users who +enter a group late will still have access to previously-created content, for example knowledge +databases, wiki applications or a booking tool for rehearsal rooms. + +A member will not learn about any newly-created data once they are removed from the group since the +key gets rotated on member removal. This should accommodate for many use-cases in p2p applications +which rely on basic group encryption with post-compromise security (PCS) and forward secrecy (FS) +during key agreement. Applications can optionally choose to remove encryption keys for forward +secrecy if they so desire. + +The second scheme is **"Message Encryption"**, offering a forward secure (FS) messaging ratchet, +similar to Signal's [Double Ratchet +algorithm](https://en.wikipedia.org/wiki/Double_Ratchet_Algorithm). Since secret keys are always +generated for each message, a user can not easily learn about previously-created messages when +getting hold of such key. We believe that the latter scheme will be used in more specialised +applications, for example p2p group chats, as strong forward secrecy comes with it's own UX +requirements, but we are excited to offer a solution for both worlds, depending on the application's +needs. + +### Key Bundles and Pre-Keys + +Key bundles are published into the network by peers. These bundles include identity- and pre-keys +which can be used by other peers to invite them into an encrypted group. + +Pre-keys are used during the initial [X3DG](https://signal.org/docs/specifications/x3dh/) key +agreement between two peers and can be limited to a single use or for a specified lifetime for +forward secrecy. + +### Secure Key-Agreement + +To encrypt any data towards a group we need to first securely and efficiently make all members of +the group aware of the secret key which will be used to encrypt the message. This takes place inside +a key agreement protocol. + +Both encryption schemes use the Two-Party Secure Messaging (2SM) Key Agreement Protocol as specified +in the paper ["Key Agreement for Decentralized Secure Group Messaging with Strong Security +Guarantees"](https://eprint.iacr.org/2020/1281.pdf>) (2020). + +During the initial 2SM "round" (via X3DH) the forward secrecy is defined by the lifetime of the used +pre-keys. For strong security guarantees it is recommended to use one-time pre-keys. If this +requirement can be relaxed it is possible to use long-term pre-keys, with a lifetime defined by the +application. + +Each subsequent 2SM round (via HPKE) uses exactly one secret key, which is then dropped and replaced +by a newly-generated key-pair. This gives the key-agreement protocol strong forward secrecy +guarantees for each round, independent of the initially used pre-keys. + +2SM is optimised to allow a group to learn about a new group secret (for example, after a member +removal or group compromise) in `O(n)` steps where `n` is the number of members. + +## Usage & Integration + +There are various ways to use `p2panda-encryption`. We're currently working on a p2panda crate which +gives a tested end-to-end solution for building secure, decentralised applications with p2panda data +types. If you're interested in group encryption, roles and members management for your application +but not building the "p2p backend", this is for you. + +The second option comes with more flexibility if you're interested in integrating group encryption +into your custom p2p data-types and algorithms but also requires more care around message ordering, +group management, validation and authentication. We've tried to reduce the API surface for +integrations into custom applications as much as possible. If you still struggle, please [reach +out](https://p2panda.org/#contact) to us. + +## Security + +End-to-end encryption (E2EE) solutions like `p2panda-encryption` prevent third parties from reading +your application data but they can never guarantee full security, especially in decentralised, +experimental networks. + +We currently _cannot_ recommend using this technology for high-risk use-cases when you cannot fully +guarantee control over all devices and transport channels. + +### Audit + +This crate has not yet received a security audit. + +### Meta-Data + +In the current implementation all group control messages are _unencrypted_. While application data +is fully protected, an adversary who gains access to the network will be able to observe control +messages and reason about which members are inside the group. The cryptographic identities in the +group are not necessarily connected to any concrete persons but can potentially reveal enough +meta-data to prove harmful. + +We're working on an integration of `p2panda-encryption` where even control messages are encrypted. +Sender and recipient info can also be protected, but this unfortunately comes with worse performance +and special UX requirements but we still believe there is a use-case for smaller groups. + +### Post-Quantum + +While a future of post-quantum computers may seem far away, `p2panda-encryption` is not secure +against so called harvest-now-decrypt-later (HNDL) quantum adversaries as we're not using any +post-quantum-ready cryptography. + +## Credits + +We have been particularly inspired by the ["Key Agreement for Decentralized Secure Group Messaging +with Strong Security Guarantees"](https://eprint.iacr.org/2020/1281.pdf) (DCGKA) paper by Matthew +Weidner, Martin Kleppmann, Daniel Hugenroth and Alastair R. Beresford (published in 2020) which is +the first paper we are aware of which introduces a PCS and FS encryption scheme with a local-first +mindset. On top there's already an almost-complete [Java +implementation](https://github.com/trvedata/key-agreement) of the paper, which helped with realising +our Rust version. + +The paper formed the initial starting point of our work. In particular, we followed the +Double-Ratchet "Message Encryption" scheme with some improvements around managing group membership. +We also carried over some of the ideas in the paper to accommodate for the simpler "Data Encryption" +approach. + +Our implementation uses Signal's [X3DH](https://signal.org/docs/specifications/x3dh) key-agreement +for initial rounds. This includes Signal's work around the +[XEdDSA](https://signal.org/docs/specifications/xeddsa) signature schemes. + +## License + +Licensed under either of [Apache License, Version 2.0] or [MIT license] at your option. + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in +p2panda by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. + +[Apache License, Version 2.0]: https://github.com/p2panda/p2panda/blob/main/LICENSES/Apache-2.0.txt +[MIT license]: https://github.com/p2panda/p2panda/blob/main/LICENSES/MIT.txt + +--- + +_This project has received funding from the European Union’s Horizon 2020 research and innovation +programme within the framework of the NGI-POINTER Project funded under grant agreement No 871528, +NGI-ASSURE No 957073, NGI0-ENTRUST No 101069594 and NGI0-COMMONS No 101135429._ diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/aead.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/aead.rs new file mode 100644 index 0000000000..3a44948290 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/aead.rs @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! ChaCha20Poly1305 authenticated encryption with additional data (AEAD). +//! +//! +use chacha20poly1305::{AeadInPlace, ChaCha20Poly1305, Key, KeyInit, Nonce}; +use thiserror::Error; + +/// 96-bit nonce. +pub type AeadNonce = [u8; 12]; + +/// 256-bit secret key. +pub type AeadKey = [u8; 32]; + +/// ChaCha20Poly1305 AEAD encryption function. +#[allow(deprecated, reason = "generic_array < v1.0 is deprecated")] +pub fn aead_encrypt( + key: &AeadKey, + plaintext: &[u8], + nonce: AeadNonce, + aad: Option<&[u8]>, +) -> Result, AeadError> { + // Implementation attaches authenticated tag (16 bytes) automatically to the end of ciphertext. + let key = Key::from_slice(key); + let nonce = Nonce::from_slice(&nonce); + let mut ciphertext_with_tag: Vec = Vec::from(plaintext); + let cipher = ChaCha20Poly1305::new(key); + cipher + .encrypt_in_place(nonce, aad.unwrap_or_default(), &mut ciphertext_with_tag) + .map_err(AeadError::Encrypt)?; + Ok(ciphertext_with_tag) +} + +/// ChaCha20Poly1305 AEAD decryption function. +#[allow(deprecated, reason = "generic_array < v1.0 is deprecated")] +pub fn aead_decrypt( + key: &AeadKey, + ciphertext_with_tag: &[u8], + nonce: AeadNonce, + aad: Option<&[u8]>, +) -> Result, AeadError> { + let key = Key::from_slice(key); + let nonce = Nonce::from_slice(&nonce); + let mut plaintext: Vec = Vec::from(ciphertext_with_tag); + let cipher = ChaCha20Poly1305::new(key); + cipher + .decrypt_in_place(nonce, aad.unwrap_or_default(), &mut plaintext) + .map_err(AeadError::Decrypt)?; + Ok(plaintext) +} + +#[derive(Debug, Error)] +pub enum AeadError { + #[error("plaintext could not be encrypted with aead: {0}")] + Encrypt(chacha20poly1305::Error), + + #[error("ciphertext could not be decrypted with aead: {0}")] + Decrypt(chacha20poly1305::Error), +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + + use super::{AeadError, AeadKey, AeadNonce, aead_decrypt, aead_encrypt}; + + #[test] + fn encrypt_decrypt() { + let rng = Rng::from_seed([1; 32]); + + let key: AeadKey = rng.random_array().unwrap(); + let nonce: AeadNonce = rng.random_array().unwrap(); + + let ciphertext = aead_encrypt(&key, b"Hello, Panda!", nonce, None).unwrap(); + let plaintext = aead_decrypt(&key, &ciphertext, nonce, None).unwrap(); + + assert_eq!(plaintext, b"Hello, Panda!"); + } + + #[test] + fn decryption_failed() { + let rng = Rng::from_seed([1; 32]); + + let key: AeadKey = rng.random_array().unwrap(); + let nonce: AeadNonce = rng.random_array().unwrap(); + + let ciphertext = aead_encrypt(&key, b"Hello, Panda!", nonce, None).unwrap(); + + let invalid_key: AeadKey = rng.random_array().unwrap(); + let invalid_nonce: AeadNonce = rng.random_array().unwrap(); + + // Invalid key. + std::assert_matches!( + aead_decrypt(&invalid_key, &ciphertext, nonce, None), + Err(AeadError::Decrypt(chacha20poly1305::Error)) + ); + + // Invalid nonce. + std::assert_matches!( + aead_decrypt(&key, &ciphertext, invalid_nonce, None), + Err(AeadError::Decrypt(chacha20poly1305::Error)) + ); + + // Invalid additional data. + std::assert_matches!( + aead_decrypt(&key, &ciphertext, nonce, Some(b"invalid aad")), + Err(AeadError::Decrypt(chacha20poly1305::Error)) + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/hkdf.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/hkdf.rs new file mode 100644 index 0000000000..a678e8286c --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/hkdf.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Hashed Message Authentication Code (HMAC)-based key derivation function (HKDF) using +//! "hash-mode" with SHA256. +//! +//! +use hkdf::Hkdf; +use sha2::Sha256; +use thiserror::Error; + +pub fn hkdf( + salt: &[u8], + ikm: &[u8], + info: Option<&[u8]>, +) -> Result<[u8; N], HkdfError> { + let salt = if salt.is_empty() { None } else { Some(salt) }; + let hk = Hkdf::::new(salt, ikm); + let mut okm = [0u8; N]; + hk.expand(info.unwrap_or_default(), &mut okm) + .map_err(|_| HkdfError::InvalidArguments)?; + Ok(okm) +} + +#[derive(Debug, Error)] +pub enum HkdfError { + #[error("arguments too large for hkdf")] + InvalidArguments, +} + +#[cfg(test)] +mod tests { + use super::hkdf; + + #[test] + fn key_material_len() { + let result_1: [u8; 18] = hkdf(b"salt", b"ikm", None).unwrap(); + assert_eq!(result_1.len(), 18); + } + + #[test] + fn info_needs_to_match() { + let result_1: [u8; 18] = hkdf(b"salt", b"ikm", Some(b"info")).unwrap(); + let result_2: [u8; 18] = hkdf(b"salt", b"ikm", Some(b"info")).unwrap(); + let result_3: [u8; 18] = hkdf(b"salt", b"ikm", Some(b"different info")).unwrap(); + assert_eq!(result_1, result_2); + assert_ne!(result_2, result_3); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/hpke.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/hpke.rs new file mode 100644 index 0000000000..b17759235b --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/hpke.rs @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Hybrid Public Key Encryption (HPKE) with DHKEM-X25519, HKDF SHA256 and ChaCha20Poly1305 AEAD +//! parameters. +//! +//! +use hpke_rs::{Hpke, HpkePrivateKey, HpkePublicKey, Mode}; +use hpke_rs_crypto::types::{AeadAlgorithm, KdfAlgorithm, KemAlgorithm}; +use hpke_rs_rust_crypto::HpkeRustCrypto; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::x25519::{PublicKey, SecretKey}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HpkeCiphertext { + /// Encrypted, shared secret generated for this transaction. + #[serde(with = "serde_bytes")] + pub kem_output: Vec, + + /// Encrypted payload. + #[serde(with = "serde_bytes")] + pub ciphertext: Vec, +} + +/// Encrypt a secret payload to a public key using HPKE. +/// +/// The sender in HPKE uses a KEM to generate the shared secret as well as the encapsulation. The +/// shared secret is then used in an AEAD (after running it through a key schedule) in order to +/// encrypt a payload. +/// +/// In order to encrypt a payload to a public key the sender needs to provide the receiver’s public +/// key, some information `info` and additional data `aad` to bind the encryption to a certain +/// context, as well as the payload `plaintext`. +pub fn hpke_seal( + verifying_key: &PublicKey, + info: Option<&[u8]>, + aad: Option<&[u8]>, + plaintext: &[u8], +) -> Result { + // Unfortunately `hpke-rs` doesn't allow us to pass in our own rng without writing a lot of + // boilerplate, so we hope to replace it with a different API or solution sometime. + let mut hpke = Hpke::::new( + Mode::Base, + KemAlgorithm::DhKem25519, + KdfAlgorithm::HkdfSha256, + AeadAlgorithm::ChaCha20Poly1305, + ); + let pk_r = HpkePublicKey::new(verifying_key.as_bytes().to_vec()); + let (kem_output, ciphertext) = hpke + .seal( + &pk_r, + info.unwrap_or_default(), + aad.unwrap_or_default(), + plaintext, + None, + None, + None, + ) + .map_err(HpkeError::Encryption)?; + Ok(HpkeCiphertext { + kem_output, + ciphertext, + }) +} + +/// Decrypt a secret payload for a receiver holding the secret key using HPKE. +/// +/// When decrypting the receiver uses the secret key to retrieve the shared secret and decrypt the +/// ciphertext. The `info` and `aad` (additional data) are the same as entered on the sender’s +/// side. +pub fn hpke_open( + input: &HpkeCiphertext, + secret_key: &SecretKey, + info: Option<&[u8]>, + aad: Option<&[u8]>, +) -> Result, HpkeError> { + let hpke = Hpke::::new( + Mode::Base, + KemAlgorithm::DhKem25519, + KdfAlgorithm::HkdfSha256, + AeadAlgorithm::ChaCha20Poly1305, + ); + let sk_r = HpkePrivateKey::new(secret_key.as_bytes().to_vec()); + let plaintext = hpke + .open( + &input.kem_output, + &sk_r, + info.unwrap_or_default(), + aad.unwrap_or_default(), + &input.ciphertext, + None, + None, + None, + ) + .map_err(HpkeError::Decryption)?; + Ok(plaintext) +} + +#[derive(Debug, Error)] +pub enum HpkeError { + #[error("could not encrypt with hpke: {0:?}")] + Encryption(hpke_rs::HpkeError), + + #[error("could not decrypt with hpke: {0:?}")] + Decryption(hpke_rs::HpkeError), +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + use crate::crypto::x25519::SecretKey; + + use super::{HpkeError, hpke_open, hpke_seal}; + + #[test] + fn seal_and_open() { + let rng = Rng::from_seed([1; 32]); + + let secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let verifying_key = secret_key.verifying_key().unwrap(); + + let info = b"some info"; + let aad = b"some aad"; + let ciphertext = + hpke_seal(&verifying_key, Some(info), Some(aad), b"Hello, Panda!").unwrap(); + let plaintext = hpke_open(&ciphertext, &secret_key, Some(info), Some(aad)).unwrap(); + + assert_eq!(plaintext, b"Hello, Panda!"); + } + + #[test] + fn decryption_failed() { + let rng = Rng::from_seed([1; 32]); + + let valid_secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let verifying_key = valid_secret_key.verifying_key().unwrap(); + + let info = b"some info"; + let aad = b"some aad"; + let ciphertext = + hpke_seal(&verifying_key, Some(info), Some(aad), b"Hello, Panda!").unwrap(); + + // Invalid secret key. + let invalid_secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let result = hpke_open(&ciphertext, &invalid_secret_key, Some(info), Some(aad)); + std::assert_matches!(result, Err(HpkeError::Decryption(_))); + + // Invalid info tag. + let result = hpke_open(&ciphertext, &valid_secret_key, None, Some(aad)); + std::assert_matches!(result, Err(HpkeError::Decryption(_))); + + // Invalid aad. + let result = hpke_open(&ciphertext, &valid_secret_key, Some(info), None); + std::assert_matches!(result, Err(HpkeError::Decryption(_))); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/mod.rs new file mode 100644 index 0000000000..7527e6f5f0 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/mod.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Core cryptographic algorithms and random number generator. +//! +//! "Basic" Algorithms: +//! - DHKEM-X25519 HPKE +//! - SHA256 HKDF +//! - ChaCha20Poly1305 AEAD +//! - Ed25519 (SHA512) DSA +//! +//! "Extended" Algorithms: +//! - XEdDSA (DSA with X25519) +//! - XChaCha20Poly1305 (large IVs) +//! +//! Random Number Generator: +//! - ChaCha20 stream cipher, seeded via `getrandom` +pub mod aead; +pub mod hkdf; +pub mod hpke; +mod rng; +mod secret; +pub mod sha2; +pub mod x25519; +pub mod xchacha20; +pub mod xeddsa; + +pub use rng::{Rng, RngError}; +pub use secret::Secret; diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/rng.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/rng.rs new file mode 100644 index 0000000000..47711fceea --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/rng.rs @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::sync::Mutex; + +use rand_chacha::rand_core::{SeedableRng, TryRngCore}; +use thiserror::Error; + +/// Cryptographically-secure random number generator that uses the ChaCha algorithm. +#[derive(Debug)] +pub struct Rng { + rng: Mutex, +} + +impl Default for Rng { + fn default() -> Self { + Self { + rng: Mutex::new(rand_chacha::ChaCha20Rng::from_os_rng()), + } + } +} + +impl Rng { + pub fn from_rng(rng: &Rng) -> Result { + Ok(Self::from_seed(rng.random_array()?)) + } + + pub fn random_array(&self) -> Result<[u8; N], RngError> { + let mut rng = self.rng.lock().map_err(|_| RngError::LockPoisoned)?; + let mut out = [0u8; N]; + rng.try_fill_bytes(&mut out) + .map_err(|_| RngError::NotEnoughRandomness)?; + Ok(out) + } + + pub fn random_vec(&self, len: usize) -> Result, RngError> { + let mut rng = self.rng.lock().map_err(|_| RngError::LockPoisoned)?; + let mut out = vec![0u8; len]; + rng.try_fill_bytes(&mut out) + .map_err(|_| RngError::NotEnoughRandomness)?; + Ok(out) + } + + #[cfg(any(test, feature = "test_utils"))] + pub fn from_seed(seed: [u8; 32]) -> Self { + Self { + rng: Mutex::new(rand_chacha::ChaCha20Rng::from_seed(seed)), + } + } + + #[cfg(not(any(test, feature = "test_utils")))] + fn from_seed(seed: [u8; 32]) -> Self { + Self { + rng: Mutex::new(rand_chacha::ChaCha20Rng::from_seed(seed)), + } + } +} + +#[derive(Debug, Error)] +pub enum RngError { + #[error("rng lock is poisoned")] + LockPoisoned, + + #[error("unable to collect enough randomness")] + NotEnoughRandomness, +} + +#[cfg(test)] +mod tests { + use super::Rng; + + #[test] + fn deterministic_randomness() { + let sample_1 = { + let rng = Rng::from_seed([1; 32]); + rng.random_vec(128).unwrap() + }; + + let sample_2 = { + let rng = Rng::from_seed([1; 32]); + rng.random_vec(128).unwrap() + }; + + assert_eq!(sample_1, sample_2); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/secret.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/secret.rs new file mode 100644 index 0000000000..2d6b33b6ac --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/secret.rs @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +#[cfg(not(test))] +use std::fmt; + +use serde::{Deserialize, Serialize}; +use subtle::ConstantTimeEq; +use zeroize::ZeroizeOnDrop; + +/// Generic container for sensitive bytes with best-effort security measures. +/// +/// In particular this implementation provides: +/// 1. Zeroise memory on drop. +/// 2. Private API methods to retrieve bytes, preventing misuse. +/// 3. Hide bytes value when printing debug info. +/// 4. Constant-time comparison implementation to prevent timing attacks. +/// +/// This represents a "best-effort" attempt, since side-channels are ultimately a property of a +/// deployed cryptographic system including the hardware it runs on, not just of software. +#[derive(Clone, Eq, Serialize, Deserialize, ZeroizeOnDrop)] +#[cfg_attr(test, derive(Debug))] +pub struct Secret(#[serde(with = "serde_bytes")] [u8; N]); + +impl Secret { + pub(crate) fn from_bytes(bytes: [u8; N]) -> Self { + Self(bytes) + } + + pub(crate) fn as_bytes(&self) -> &[u8; N] { + &self.0 + } +} + +impl PartialEq for Secret { + fn eq(&self, other: &Self) -> bool { + // Constant-time comparison. + bool::from(self.0.ct_eq(&other.0)) + } +} + +#[cfg(not(test))] +impl fmt::Debug for Secret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Do not reveal secret values when printing debug info. + f.debug_struct("Secret").field("value", &"***").finish() + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/sha2.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/sha2.rs new file mode 100644 index 0000000000..9b3b65b25e --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/sha2.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! SHA2 hashing functions. +use sha2::{Digest, Sha256, Sha512}; + +pub const SHA512_DIGEST_SIZE: usize = 64; + +pub const SHA256_DIGEST_SIZE: usize = 32; + +/// SHA2-512 hashing function. +pub fn sha2_512(messages: &[&[u8]]) -> [u8; SHA512_DIGEST_SIZE] { + let mut hasher = Sha512::new(); + for message in messages { + hasher.update(message); + } + let result = hasher.finalize(); + result[..].try_into().expect("sha512 digest size") +} + +/// SHA2-256 hashing function. +pub fn sha2_256(messages: &[&[u8]]) -> [u8; SHA256_DIGEST_SIZE] { + let mut hasher = Sha256::new(); + for message in messages { + hasher.update(message); + } + let result = hasher.finalize(); + result[..].try_into().expect("sha256 digest size") +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/x25519.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/x25519.rs new file mode 100644 index 0000000000..676cb06819 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/x25519.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Elliptic-curve Diffie–Hellman (ECDH) key agreement scheme (X25519). +use std::fmt; +use std::hash::Hash as StdHash; + +use curve25519_dalek::scalar::clamp_integer; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::Secret; +use crate::{Rng, RngError}; + +/// 256-bit secret key size. +pub const SECRET_KEY_SIZE: usize = 32; + +/// 256-bit public key size. +pub const PUBLIC_KEY_SIZE: usize = 32; + +/// 256-bit shared secret size. +pub const SHARED_SECRET_SIZE: usize = 32; + +/// Secret Curve25519 key used for ECDH key agreement. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SecretKey(Secret); + +impl SecretKey { + #[cfg(not(feature = "test_utils"))] + pub(crate) fn from_bytes(bytes: [u8; SECRET_KEY_SIZE]) -> Self { + SecretKey(Secret::from_bytes(clamp_integer(bytes))) + } + + #[cfg(feature = "test_utils")] + pub fn from_bytes(bytes: [u8; SECRET_KEY_SIZE]) -> Self { + SecretKey(Secret::from_bytes(clamp_integer(bytes))) + } + + pub fn from_rng(rng: &Rng) -> Result { + Ok(Self::from_bytes(rng.random_array()?)) + } + + pub(crate) fn as_bytes(&self) -> &[u8; SECRET_KEY_SIZE] { + self.0.as_bytes() + } + + pub fn verifying_key(&self) -> Result { + let static_secret = x25519_dalek::StaticSecret::from(*self.0.as_bytes()); + let verifying_key = x25519_dalek::PublicKey::from(&static_secret); + Ok(PublicKey(verifying_key.to_bytes())) + } + + pub fn calculate_agreement( + &self, + their_public: &PublicKey, + ) -> Result<[u8; SHARED_SECRET_SIZE], X25519Error> { + let static_secret = x25519_dalek::StaticSecret::from(*self.0.as_bytes()); + let shared_secret = + static_secret.diffie_hellman(&x25519_dalek::PublicKey::from(their_public.to_bytes())); + Ok(shared_secret.to_bytes()) + } +} + +/// Public Curve25519 key used for ECDH key agreement. +#[derive(Copy, Clone, Debug, PartialEq, Eq, StdHash, Serialize, Deserialize)] +pub struct PublicKey(#[serde(with = "serde_bytes")] [u8; PUBLIC_KEY_SIZE]); + +impl PublicKey { + pub fn from_bytes(verifying_key: [u8; PUBLIC_KEY_SIZE]) -> Self { + Self(verifying_key) + } + + pub fn as_bytes(&self) -> &[u8; PUBLIC_KEY_SIZE] { + &self.0 + } + + pub fn to_bytes(self) -> [u8; PUBLIC_KEY_SIZE] { + self.0 + } + + pub fn to_hex(self) -> String { + hex::encode(self.as_bytes()) + } +} + +impl fmt::Display for PublicKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.to_hex()) + } +} + +#[derive(Debug, Error)] +pub enum X25519Error { + #[error("invalid curve point or scalar")] + InvalidCurve, +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + + use super::SecretKey; + + #[test] + fn diffie_hellmann() { + let rng = Rng::from_seed([1; 32]); + + let alice_secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let alice_verifying_key = alice_secret_key.verifying_key().unwrap(); + + let bob_secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let bob_verifying_key = bob_secret_key.verifying_key().unwrap(); + + let alice_shared_secret = alice_secret_key + .calculate_agreement(&bob_verifying_key) + .unwrap(); + let bob_shared_secret = bob_secret_key + .calculate_agreement(&alice_verifying_key) + .unwrap(); + + assert_eq!(alice_shared_secret, bob_shared_secret); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/xchacha20.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/xchacha20.rs new file mode 100644 index 0000000000..9a8050fd23 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/xchacha20.rs @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! XChaCha20Poly1305 is a ChaCha20 AEAD variant with an extended 192-bit (24-byte) nonce. +use chacha20poly1305::{AeadInPlace, Key, KeyInit, XChaCha20Poly1305, XNonce}; +use thiserror::Error; + +/// "Extended" 192-bit nonce. +pub type XAeadNonce = [u8; 24]; + +/// 256-bit key. +pub type XAeadKey = [u8; 32]; + +/// XChaCha20-Poly1305 AEAD encryption function. +#[allow(deprecated, reason = "generic_array < v1.0 is deprecated")] +pub fn x_aead_encrypt( + key: &XAeadKey, + plaintext: &[u8], + nonce: XAeadNonce, + aad: Option<&[u8]>, +) -> Result, XAeadError> { + let key = Key::from_slice(key); + let nonce = XNonce::from_slice(&nonce); + let mut ciphertext: Vec = Vec::from(plaintext); + + let cipher = XChaCha20Poly1305::new(key); + cipher + .encrypt_in_place(nonce, aad.unwrap_or_default(), &mut ciphertext) + .map_err(XAeadError::Encrypt)?; + + Ok(ciphertext) +} + +/// XChaCha20-Poly1305 AEAD decryption function. +#[allow(deprecated, reason = "generic_array < v1.0 is deprecated")] +pub fn x_aead_decrypt( + key: &XAeadKey, + ciphertext_with_tag: &[u8], + nonce: XAeadNonce, + aad: Option<&[u8]>, +) -> Result, XAeadError> { + let key = Key::from_slice(key); + let nonce = XNonce::from_slice(&nonce); + let mut plaintext: Vec = Vec::from(ciphertext_with_tag); + + let cipher = XChaCha20Poly1305::new(key); + cipher + .decrypt_in_place(nonce, aad.unwrap_or_default(), &mut plaintext) + .map_err(XAeadError::Decrypt)?; + + Ok(plaintext) +} + +#[derive(Debug, Error)] +pub enum XAeadError { + #[error("plaintext could not be encrypted with xchacha20 aead: {0}")] + Encrypt(chacha20poly1305::Error), + + #[error("ciphertext could not be decrypted with xchacha20 aead: {0}")] + Decrypt(chacha20poly1305::Error), +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + + use super::{XAeadError, XAeadKey, XAeadNonce, x_aead_decrypt, x_aead_encrypt}; + + #[test] + fn encrypt_decrypt() { + let rng = Rng::from_seed([1; 32]); + + let key: XAeadKey = rng.random_array().unwrap(); + let nonce: XAeadNonce = rng.random_array().unwrap(); + + let ciphertext = x_aead_encrypt(&key, b"Hello, Panda!", nonce, None).unwrap(); + let plaintext = x_aead_decrypt(&key, &ciphertext, nonce, None).unwrap(); + + assert_eq!(plaintext, b"Hello, Panda!"); + } + + #[test] + fn decryption_failed() { + let rng = Rng::from_seed([1; 32]); + + let key: XAeadKey = rng.random_array().unwrap(); + let nonce: XAeadNonce = rng.random_array().unwrap(); + + let ciphertext = x_aead_encrypt(&key, b"Hello, Panda!", nonce, None).unwrap(); + + let invalid_key: XAeadKey = rng.random_array().unwrap(); + let invalid_nonce: XAeadNonce = rng.random_array().unwrap(); + + // Invalid key. + std::assert_matches!( + x_aead_decrypt(&invalid_key, &ciphertext, nonce, None), + Err(XAeadError::Decrypt(chacha20poly1305::Error)) + ); + + // Invalid nonce. + std::assert_matches!( + x_aead_decrypt(&key, &ciphertext, invalid_nonce, None), + Err(XAeadError::Decrypt(chacha20poly1305::Error)) + ); + + // Invalid additional data. + std::assert_matches!( + x_aead_decrypt(&key, &ciphertext, nonce, Some(b"invalid aad")), + Err(XAeadError::Decrypt(chacha20poly1305::Error)) + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/crypto/xeddsa.rs b/pkgs/id/vendor/p2panda-encryption/src/crypto/xeddsa.rs new file mode 100644 index 0000000000..613da1755f --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/crypto/xeddsa.rs @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! XEdDSA enables use of a single key pair format for both x25519 elliptic curve Diffie-Hellman +//! and Ed25199 signatures. +//! +//! +use std::fmt; + +use curve25519_dalek::constants::ED25519_BASEPOINT_TABLE; +use curve25519_dalek::{EdwardsPoint, MontgomeryPoint, Scalar}; +use serde::{Deserialize, Serialize}; +use subtle::ConstantTimeEq; +use thiserror::Error; + +use crate::crypto::sha2::sha2_512; +use crate::crypto::x25519::{PublicKey, SecretKey}; +use crate::crypto::{Rng, RngError}; + +/// 512-bit signature. +pub const SIGNATURE_SIZE: usize = 64; + +/// Hash1 changes the first byte to 0xFE. +const HASH_1_PREFIX: [u8; 32] = [ + 0xFEu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, + 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, + 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8, +]; + +/// XEdDSA signature. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct XSignature(#[serde(with = "serde_bytes")] [u8; SIGNATURE_SIZE]); + +impl XSignature { + pub fn from_bytes(bytes: [u8; SIGNATURE_SIZE]) -> Self { + Self(bytes) + } + + pub fn as_bytes(&self) -> &[u8; SIGNATURE_SIZE] { + &self.0 + } + + pub fn to_bytes(self) -> [u8; SIGNATURE_SIZE] { + self.0 + } + + pub fn to_hex(self) -> String { + hex::encode(self.as_bytes()) + } +} + +impl fmt::Display for XSignature { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.to_hex()) + } +} + +/// Calculates an XEdDSA signature using the X25519 secret key directly. +pub fn xeddsa_sign( + bytes: &[u8], + secret_key: &SecretKey, + rng: &Rng, +) -> Result { + // M = Message to sign (byte sequence) + let cap_m = bytes; + + // Z = 64 bytes secure random data (byte sequence) + let cap_z: [u8; SIGNATURE_SIZE] = rng.random_array()?; + + // A, a = calculate_key_pair(k) + let (cap_a, a) = { + // k = Montgomery private key (integer mod q) + let k_bytes = secret_key.as_bytes(); + let k = Scalar::from_bytes_mod_order(*k_bytes); + + // calculate_key_pair(k) + let cap_e = &k * ED25519_BASEPOINT_TABLE; // E = kB + let mut cap_a = cap_e.compress(); // A.y = E.y + let sign_bit = cap_a.0[31] >> 7; // sign_bit = E.s + cap_a.0[31] &= 0b0111_1111_u8; // A.s = 0 + + // if E.s == 1: + // a = -k (mod q) + // else: + // a = k (mod q) + let a = if sign_bit == 1 { -k } else { k }; + + (cap_a, a) + }; + + // r = hash1(a || M || Z) (mod q) + let r = Scalar::from_bytes_mod_order_wide(&{ + sha2_512(&[&HASH_1_PREFIX, a.as_bytes(), cap_m, &cap_z]) + }); + + // R = rB + let cap_r = (&r * ED25519_BASEPOINT_TABLE).compress(); + + // h = hash(R || A || M) (mod q) + let h = Scalar::from_bytes_mod_order_wide(&{ + sha2_512(&[cap_r.as_bytes(), cap_a.as_bytes(), cap_m]) + }); + + // s = r + ha (mod q) + let s = r + (h * a); + + // return R || s + let mut result = [0u8; SIGNATURE_SIZE]; + result[..32].copy_from_slice(cap_r.as_bytes()); + result[32..].copy_from_slice(s.as_bytes()); + Ok(XSignature::from_bytes(result)) +} + +/// Verifies a XEdDSA signature on provided data using the X25519 public counter-part. +pub fn xeddsa_verify( + bytes: &[u8], + their_verifying_key: &PublicKey, + signature: &XSignature, +) -> Result<(), XEdDSAError> { + // M = Message to sign (byte sequence) + let cap_m = bytes; + + // u = Montgomery public key (byte sequence of b bits). + let u = their_verifying_key; + + // R || s = Signature to verify (byte sequence of 2b bits) + let mut cap_r = [0u8; 32]; + cap_r.copy_from_slice(&signature.as_bytes()[..32]); + let mut s = [0u8; 32]; + s.copy_from_slice(&signature.as_bytes()[32..]); + s[31] &= 0b0111_1111_u8; + + // Reject s if it has excess bits. + if (s[31] & 0b1110_0000_u8) != 0 { + return Err(XEdDSAError::InvalidArgument); + } + + // convert_mont(u): + // umasked = u (mod 2|p|) + // P.y = u_to_y(umasked) + // P.s = 0 + // return P + let a = { + let mont_point = MontgomeryPoint(u.to_bytes()); + match mont_point.to_edwards(0) { + Some(x) => x, + // if not on_curve(A): + // return false + None => return Err(XEdDSAError::InvalidArgument), + } + }; + let cap_a = a.compress(); + + // h = hash(R || A || M) (mod q) + let h = Scalar::from_bytes_mod_order_wide(&{ sha2_512(&[&cap_r, cap_a.as_bytes(), cap_m]) }); + + // Rcheck = sB - hA + let cap_r_check = { + let minus_cap_a = -a; + let cap_r_check_point = EdwardsPoint::vartime_double_scalar_mul_basepoint( + &h, + &minus_cap_a, + &Scalar::from_bytes_mod_order(s), + ); + cap_r_check_point.compress() + }; + + // if bytes_equal(R, Rcheck): + // return true + if bool::from(cap_r_check.as_bytes().ct_eq(&cap_r)) { + Ok(()) + } else { + Err(XEdDSAError::VerificationFailed) + } +} + +#[derive(Debug, Error)] +pub enum XEdDSAError { + #[error(transparent)] + Rng(#[from] RngError), + + #[error("invalid xeddsa public key or signature")] + InvalidArgument, + + #[error("signature does not match public key and bytes")] + VerificationFailed, +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + use crate::crypto::x25519::SecretKey; + + use super::{XEdDSAError, xeddsa_sign, xeddsa_verify}; + + #[test] + fn xeddsa_signatures() { + let rng = Rng::from_seed([1; 32]); + + let secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let verifying_key = secret_key.verifying_key().unwrap(); + + let signature = xeddsa_sign(b"Hello, Panda!", &secret_key, &rng).unwrap(); + assert!(xeddsa_verify(b"Hello, Panda!", &verifying_key, &signature).is_ok()); + } + + #[test] + fn failed_verify() { + let rng = Rng::from_seed([1; 32]); + + let secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let verifying_key = secret_key.verifying_key().unwrap(); + let signature = xeddsa_sign(b"Hello, Panda!", &secret_key, &rng).unwrap(); + + let invalid_secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let invalid_verifying_key = invalid_secret_key.verifying_key().unwrap(); + let invalid_signature = xeddsa_sign(b"Hello, Panda!", &invalid_secret_key, &rng).unwrap(); + + assert_ne!(verifying_key, invalid_verifying_key); + assert_ne!(signature, invalid_signature); + + std::assert_matches!( + xeddsa_verify(b"Invalid Data", &verifying_key, &signature), + Err(XEdDSAError::VerificationFailed) + ); + std::assert_matches!( + xeddsa_verify(b"Hello, Panda!", &invalid_verifying_key, &signature), + Err(XEdDSAError::VerificationFailed) + ); + std::assert_matches!( + xeddsa_verify(b"Hello, Panda!", &verifying_key, &invalid_signature), + Err(XEdDSAError::VerificationFailed) + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/data.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/data.rs new file mode 100644 index 0000000000..47c5a2a925 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/data.rs @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::crypto::xchacha20::{XAeadError, XAeadNonce, x_aead_decrypt, x_aead_encrypt}; +use crate::data_scheme::group_secret::GroupSecret; + +pub fn encrypt_data( + plaintext: &[u8], + group_secret: &GroupSecret, + nonce: XAeadNonce, +) -> Result, XAeadError> { + let ciphertext = x_aead_encrypt(group_secret.as_bytes(), plaintext, nonce, None)?; + Ok(ciphertext) +} + +pub fn decrypt_data( + ciphertext: &[u8], + group_secret: &GroupSecret, + nonce: XAeadNonce, +) -> Result, XAeadError> { + let plaintext = x_aead_decrypt(group_secret.as_bytes(), ciphertext, nonce, None)?; + Ok(plaintext) +} + +#[cfg(test)] +mod tests { + use crate::Rng; + use crate::crypto::xchacha20::XAeadNonce; + use crate::data_scheme::GroupSecret; + + use super::{decrypt_data, encrypt_data}; + + #[test] + fn encrypt_decrypt() { + let rng = Rng::from_seed([1; 32]); + + let group_secret = GroupSecret::from_rng(&rng).unwrap(); + let nonce: XAeadNonce = rng.random_array().unwrap(); + + let message = encrypt_data(b"Service! Service!", &group_secret, nonce).unwrap(); + let receive = decrypt_data(&message, &group_secret, nonce).unwrap(); + assert_eq!(receive, b"Service! Service!"); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/dcgka.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/dcgka.rs new file mode 100644 index 0000000000..3132f96ba5 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/dcgka.rs @@ -0,0 +1,666 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! A decentralized continuous group key agreement protocol (DCGKA) for p2panda's "data encryption" +//! scheme with forward secrecy and post-compromise security. +//! +//! This uses the 2SM (Two-Party Secure Messaging) key agreement scheme internally with strong +//! forward secrecy guarantees. +use std::collections::{HashMap, HashSet}; +use std::fmt::{Debug, Display}; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::Rng; +use crate::data_scheme::{GroupSecret, GroupSecretError, SecretBundle, SecretBundleState}; +use crate::key_bundle::LongTermKeyBundle; +use crate::traits::{ + GroupMembership, IdentityHandle, IdentityManager, IdentityRegistry, OperationId, PreKeyManager, + PreKeyRegistry, +}; +use crate::two_party::{TwoParty, TwoPartyError, TwoPartyMessage, TwoPartyState}; + +/// A decentralized continuous group key agreement protocol (DCGKA) for p2panda's "data encryption" +/// scheme with forward secrecy and post-compromise security. +pub struct Dcgka { + _marker: PhantomData<(ID, OP, PKI, DGM, KMG)>, +} + +/// Serializable state of "data encryption" DCGKA (for persistence). +#[derive(Debug, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct DcgkaState +where + ID: IdentityHandle, + OP: OperationId, + PKI: IdentityRegistry + PreKeyRegistry, + DGM: GroupMembership, + KMG: IdentityManager + PreKeyManager, +{ + /// Public Key Infrastructure (PKI). From here we retrieve the identity keys and long-term + /// pre-key bundles for each member to do 2SM. + pub pki: PKI::State, + + /// Our own key manager state holding the secret parts for our own identity keys and published + /// long-term pre-key bundles so we can do 2SM. + pub my_keys: KMG::State, + + /// Our id which is used as a unique handle inside this group. + pub my_id: ID, + + /// Handlers for each member to manage the "Two-Party Secure Messaging" (2SM) key-agreement + /// protocol as specified in the paper. + pub two_party: HashMap>, + + /// Decentralised group membership (DGM) state. + pub dgm: DGM::State, +} + +impl Dcgka +where + ID: IdentityHandle, + OP: OperationId, + PKI: IdentityRegistry + PreKeyRegistry, + DGM: GroupMembership, + KMG: IdentityManager + PreKeyManager, +{ + /// Returns new DCGKA state with our own identity and key managers. + /// + /// Use this when creating a new group or before accepting an invitation to an existing one. + pub fn init( + my_id: ID, + my_keys: KMG::State, + pki: PKI::State, + dgm: DGM::State, + ) -> DcgkaState { + DcgkaState { + pki, + my_id, + my_keys, + two_party: HashMap::new(), + dgm, + } + } + + /// Handler for when a "remote" control message is received from the network or when we need to + /// process our "local" operation after calling "create", "update", "add" or "remove". + /// + /// It takes the user ID of the message sender, a control message, and a direct message (or + /// none if there is no associated direct message). + /// + /// Control messages are expected to be authenticated and causally ordered. + pub fn process( + y: DcgkaState, + input: ProcessInput, + ) -> DcgkaProcessResult { + let ProcessInput { + sender, + control_message, + direct_message, + seq, + } = input; + let (y_i, output) = match control_message { + ControlMessage::Create { initial_members } => { + Self::process_create(y, &sender, initial_members, direct_message)? + } + ControlMessage::Update => Self::process_update(y, &sender, direct_message)?, + ControlMessage::Remove { removed } => { + Self::process_remove(y, sender, seq, &removed, direct_message)? + } + ControlMessage::Add { added } => { + Self::process_add(y, sender, seq, added, direct_message)? + } + }; + Ok((y_i, output)) + } + + /// Takes a set of users IDs (including us), an initial group secret and creates a new group with those members who will learn about this secret. + /// + /// Note that every member ID needs to be unique for this group. + pub fn create( + y: DcgkaState, + initial_members: Vec, + group_secret: &GroupSecret, + rng: &Rng, + ) -> DcgkaOperationResult { + // De-duplicate members. + let mut initial_members: Vec = + initial_members.into_iter().fold(Vec::new(), |mut acc, id| { + if !acc.contains(&id) { + acc.push(id); + } + acc + }); + + // Add ourselves if the user hasn't done it yet. + if !initial_members.contains(&y.my_id) { + initial_members.push(y.my_id); + } + + // The "create" function constructs the "create" control message. + let control_message = ControlMessage::Create { + initial_members: initial_members.clone(), + }; + + // Generate the set of direct messages to send. + let (y_ii, direct_messages) = + Self::send_group_secret(y, &initial_members, group_secret, rng)?; + + Ok(( + y_ii, + OperationOutput { + control_message, + direct_messages, + }, + )) + } + + /// Called by group members when they receive the "create" message. + fn process_create( + mut y: DcgkaState, + sender: &ID, + initial_members: Vec, + direct_message: Option>, + ) -> DcgkaProcessResult { + y.dgm = + DGM::create(y.my_id, &initial_members).map_err(|err| DcgkaError::DgmOperation(err))?; + Self::process_secret(y, sender, direct_message) + } + + /// Establishes a new secret for the group. + pub fn update( + y: DcgkaState, + group_secret: &GroupSecret, + rng: &Rng, + ) -> DcgkaOperationResult { + let control_message = ControlMessage::Update; + + let recipient_ids: Vec = Self::members(&y)? + .into_iter() + .filter(|member| member != &y.my_id) + .collect(); + + let (y_i, direct_messages) = Self::send_group_secret(y, &recipient_ids, group_secret, rng)?; + + Ok(( + y_i, + OperationOutput { + control_message, + direct_messages, + }, + )) + } + + /// Called by group members when they receive the "update" control message. + fn process_update( + y: DcgkaState, + sender: &ID, + direct_message: Option>, + ) -> DcgkaProcessResult { + Self::process_secret(y, sender, direct_message) + } + + /// Remove a member from the group. + /// + /// This takes a new secret as an argument for the remaining members for post-compromise security (PCS). + pub fn remove( + y: DcgkaState, + removed: ID, + group_secret: &GroupSecret, + rng: &Rng, + ) -> DcgkaOperationResult { + let control_message = ControlMessage::Remove { removed }; + + let recipient_ids: Vec = Self::members(&y)? + .into_iter() + .filter(|member| member != &y.my_id && member != &removed) + .collect(); + + let (y_i, direct_messages) = Self::send_group_secret(y, &recipient_ids, group_secret, rng)?; + + Ok(( + y_i, + OperationOutput { + control_message, + direct_messages, + }, + )) + } + + /// Called by group members when they receive the "remove" control message. + fn process_remove( + mut y: DcgkaState, + sender: ID, + seq: OP, + removed: &ID, + direct_message: Option>, + ) -> DcgkaProcessResult { + y.dgm = DGM::remove(y.dgm, sender, removed, seq) + .map_err(|err| DcgkaError::DgmOperation(err))?; + Self::process_secret(y, &sender, direct_message) + } + + /// Adds a new group member. + /// + /// The added group member will receive a direct "welcome" message containing all previously + /// used secrets of the group in form of a [`SecretBundle`]. Every member will process + /// an "add" control message. + pub fn add( + y: DcgkaState, + added: ID, + bundle: &SecretBundleState, + rng: &Rng, + ) -> DcgkaOperationResult { + // Construct a control message of type "add" to broadcast to the group. + let control_message = ControlMessage::Add { added }; + + // Construct a welcome message that is sent to the new member as a direct message. + let (y_i, ciphertext) = { + let bundle_bytes = bundle.to_bytes()?; + Self::encrypt_to(y, &added, &bundle_bytes, rng)? + }; + let direct_message = DirectMessage { + recipient: added, + content: DirectMessageContent::Welcome { + ciphertext, + history: y_i.dgm.clone(), + }, + }; + + Ok(( + y_i, + OperationOutput { + control_message, + direct_messages: vec![direct_message], + }, + )) + } + + /// Called by both the sender and each recipient of an "add" control message, including the new + /// group member. + fn process_add( + mut y: DcgkaState, + sender: ID, + seq: OP, + added: ID, + direct_message: Option>, + ) -> DcgkaProcessResult { + // The joiner applies its own add in `process_welcome`, after the welcome's history. + if added != y.my_id { + y.dgm = + DGM::add(y.dgm, sender, added, seq).map_err(|err| DcgkaError::DgmOperation(err))?; + } + + if added == y.my_id { + let Some(DirectMessage { + recipient, + content: + DirectMessageContent::Welcome { + ciphertext, + history, + }, + .. + }) = direct_message + else { + return match direct_message { + Some(direct_message) => Err(DcgkaError::UnexpectedDirectMessageType( + DirectMessageType::Welcome, + direct_message.message_type(), + )), + None => Err(DcgkaError::MissingDirectMessage(DirectMessageType::Welcome)), + }; + }; + + if recipient != y.my_id { + return Err(DcgkaError::NotOurDirectMessage(y.my_id, recipient)); + } + + return Self::process_welcome(y, sender, seq, ciphertext, history); + } + + Ok((y, GroupSecretOutput::None)) + } + + /// Second function called by a newly added group member (the first is the call to init that + /// sets up their state). + fn process_welcome( + mut y: DcgkaState, + sender: ID, + seq: OP, + ciphertext: TwoPartyMessage, + history: DGM::State, + ) -> DcgkaProcessResult { + y.dgm = DGM::from_welcome(y.my_id, history).map_err(|err| DcgkaError::DgmOperation(err))?; + // The welcome's history predates this add, so the joiner applies the add itself. + y.dgm = + DGM::add(y.dgm, sender, y.my_id, seq).map_err(|err| DcgkaError::DgmOperation(err))?; + + let (y_i, bundle) = { + let (y_i, plaintext) = Self::decrypt_from(y, &sender, ciphertext)?; + let bundle = SecretBundle::try_from_bytes(&plaintext)?; + (y_i, bundle) + }; + + Ok((y_i, GroupSecretOutput::Bundle(bundle))) + } + + /// Takes a group secret, then calls `encrypt_to` to + /// encrypt it for each other group member using the 2SM protocol. It returns the updated + /// protocol state and the set of direct messages to send. + fn send_group_secret( + y: DcgkaState, + recipients: &[ID], + group_secret: &GroupSecret, + rng: &Rng, + ) -> SendSecretResult { + let mut direct_messages: Vec> = + Vec::with_capacity(recipients.len()); + + let y_i = { + let mut y_loop = y; + for recipient in recipients { + // Skip ourselves. + if recipient == &y_loop.my_id { + continue; + } + + // Encrypt to every recipient. + let (y_next, ciphertext) = + Self::encrypt_to(y_loop, recipient, &group_secret.to_bytes()?, rng)?; + y_loop = y_next; + + direct_messages.push(DirectMessage { + recipient: *recipient, + content: DirectMessageContent::TwoParty { ciphertext }, + }); + } + y_loop + }; + + Ok((y_i, direct_messages)) + } + + /// Handles a new secret for the group, received as an + /// encrypted, direct message from another member. + fn process_secret( + y: DcgkaState, + sender: &ID, + direct_message: Option>, + ) -> DcgkaProcessResult { + let Some(direct_message) = direct_message else { + return Ok((y, GroupSecretOutput::None)); + }; + + let DirectMessage { + recipient, + content: DirectMessageContent::TwoParty { ciphertext }, + .. + } = direct_message + else { + return Err(DcgkaError::UnexpectedDirectMessageType( + DirectMessageType::TwoParty, + direct_message.message_type(), + )); + }; + + if recipient != y.my_id { + return Err(DcgkaError::NotOurDirectMessage(y.my_id, recipient)); + } + + let (y_i, plaintext) = Self::decrypt_from(y, sender, ciphertext)?; + let group_secret = GroupSecret::try_from_bytes(&plaintext)?; + + Ok((y_i, GroupSecretOutput::Secret(group_secret))) + } + + /// Uses 2SM to encrypt a direct message for another group member. The first time a message is + /// encrypted to a particular recipient ID, the 2SM protocol state is initialised and stored in + /// γ.2sm[ID]. We then use 2SM-Send to encrypt the message, and store the updated protocol + /// state in γ. + fn encrypt_to( + mut y: DcgkaState, + recipient: &ID, + plaintext: &[u8], + rng: &Rng, + ) -> DcgkaResult { + let y_2sm = match y.two_party.remove(recipient) { + Some(y_2sm) => y_2sm, + None => { + let (pki_i, prekey_bundle) = PKI::key_bundle(y.pki, recipient) + .map_err(|err| DcgkaError::PreKeyRegistry(err))?; + y.pki = pki_i; + let prekey_bundle = prekey_bundle.ok_or(DcgkaError::MissingPreKeys(*recipient))?; + TwoParty::::init_to_send(prekey_bundle) + } + }; + let (y_2sm_i, ciphertext) = + TwoParty::::send(y_2sm, &y.my_keys, plaintext, rng)?; + y.two_party.insert(*recipient, y_2sm_i); + Ok((y, ciphertext)) + } + + /// Is the reverse of encrypt_to. It similarly initialises the protocol state on first use, and + /// then uses 2SM-Receive to decrypt the ciphertext, with the protocol state stored in + /// γ.2sm[ID]. + fn decrypt_from( + mut y: DcgkaState, + sender: &ID, + ciphertext: TwoPartyMessage, + ) -> DcgkaResult> { + let y_2sm = match y.two_party.remove(sender) { + Some(y_2sm) => y_2sm, + None => TwoParty::::init_to_receive(), + }; + let (y_2sm_i, y_my_keys_i, plaintext) = + TwoParty::::receive(y_2sm, y.my_keys, ciphertext)?; + y.my_keys = y_my_keys_i; + y.two_party.insert(*sender, y_2sm_i); + Ok((y, plaintext)) + } + + /// Returns the set of group members at the current time. + pub fn members( + y: &DcgkaState, + ) -> Result, DcgkaError> { + let members = DGM::members(&y.dgm).map_err(|err| DcgkaError::GroupMembership(err))?; + Ok(members) + } +} + +pub type SendSecretResult = Result< + ( + DcgkaState, + Vec>, + ), + DcgkaError, +>; + +pub type DcgkaResult = + Result<(DcgkaState, T), DcgkaError>; + +pub type DcgkaProcessResult = + DcgkaResult; + +pub type DcgkaOperationResult = + DcgkaResult>; + +/// Message that should be broadcast to the group. +/// +/// The control message must be distributed to the other group members through Authenticated Causal +/// Broadcast, calling the process function on the recipient when they are delivered. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ControlMessage { + Create { initial_members: Vec }, + Update, + Remove { removed: ID }, + Add { added: ID }, +} + +impl Display for ControlMessage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + ControlMessage::Create { .. } => "create", + ControlMessage::Update => "update", + ControlMessage::Remove { .. } => "remove", + ControlMessage::Add { .. } => "add", + } + ) + } +} + +/// Arguments required to process a group operation received from another member. +#[derive(Clone, Debug)] +pub struct ProcessInput +where + DGM: GroupMembership, +{ + /// Sequence number, which consecutively numbers successive control messages from the same + /// sender. + pub seq: OP, + + /// Author of this message. + pub sender: ID, + + /// Message received from this author. + pub control_message: ControlMessage, + + /// Optional direct message for us. + /// + /// Applications need to filter the direct message for the correct recipient before passing it + /// as an input. There can always only be max. 1 direct message per recipient. + pub direct_message: Option>, +} + +/// Secret encryption keys we've learned about after processing a member's control message. +#[derive(Debug, PartialEq, Eq)] +pub enum GroupSecretOutput { + None, + Secret(GroupSecret), + Bundle(SecretBundleState), +} + +/// Calling "create", "add", "remove" and "update" returns a control message that should be +/// broadcast to the group and a set of direct messages that should be sent to the regarding +/// members. +#[derive(Debug)] +pub struct OperationOutput +where + DGM: GroupMembership, +{ + /// Control message that should be broadcast to the group. + pub control_message: ControlMessage, + + /// Set of messages directly to be sent to specific users. + pub direct_messages: Vec>, +} + +/// Direct message that should be sent to a single member. +/// +/// The direct message must be distributed to the other group members through Authenticated Causal +/// Broadcast, calling the process function on the recipient when they are delivered. +/// +/// If direct messages are sent along with a control message, we assume that the direct message for +/// the appropriate recipient is delivered in the same call to process. Our algorithm never sends a +/// direct message without an associated broadcast control message. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(bound(serialize = "DGM::State: Serialize, ID: Serialize"))] +#[serde(bound(deserialize = "DGM::State: Deserialize<'de>, ID: Deserialize<'de>"))] +pub struct DirectMessage +where + DGM: GroupMembership, +{ + pub recipient: ID, + pub content: DirectMessageContent, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum DirectMessageType { + Welcome, + TwoParty, +} + +impl Display for DirectMessageType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + DirectMessageType::Welcome => "welcome", + DirectMessageType::TwoParty => "2sm", + } + ) + } +} + +impl DirectMessage +where + DGM: GroupMembership, +{ + pub fn message_type(&self) -> DirectMessageType { + match self.content { + DirectMessageContent::Welcome { .. } => DirectMessageType::Welcome, + DirectMessageContent::TwoParty { .. } => DirectMessageType::TwoParty, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(bound(serialize = "DGM::State: Serialize"))] +#[serde(bound(deserialize = "DGM::State: Deserialize<'de>"))] +pub enum DirectMessageContent +where + DGM: GroupMembership, +{ + Welcome { + ciphertext: TwoPartyMessage, + history: DGM::State, + }, + TwoParty { + ciphertext: TwoPartyMessage, + }, +} + +#[derive(Debug, Error)] +pub enum DcgkaError +where + PKI: IdentityRegistry + PreKeyRegistry, + DGM: GroupMembership, + KMG: PreKeyManager, +{ + #[error("expected direct message of type \"{0}\" but got nothing instead")] + MissingDirectMessage(DirectMessageType), + + #[error("expected direct message of type \"{0}\" but got message of type \"{1}\" instead")] + UnexpectedDirectMessageType(DirectMessageType, DirectMessageType), + + #[error("direct message recipient mismatch, expected recipient: {1}, actual recipient: {0}")] + NotOurDirectMessage(ID, ID), + + #[error("computing members view from dgm failed: {0}")] + GroupMembership(DGM::Error), + + #[error("dgm operation failed: {0}")] + DgmOperation(DGM::Error), + + #[error("failed retrieving bundle from pre key registry: {0}")] + PreKeyRegistry(>::Error), + + #[error("failed retrieving identity from registry: {0}")] + IdentityRegistry(>::Error), + + #[error("missing key bundle for member {0}")] + MissingPreKeys(ID), + + #[error(transparent)] + GroupSecret(#[from] GroupSecretError), + + #[error(transparent)] + KeyManager(KMG::Error), + + #[error(transparent)] + TwoParty(#[from] TwoPartyError), +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group.rs new file mode 100644 index 0000000000..2b59a4eb53 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group.rs @@ -0,0 +1,634 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! API to manage groups using the "Data Encryption" scheme and process remote control- and +//! application messages. +#![allow(clippy::type_complexity)] +use std::collections::{HashSet, VecDeque}; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::xchacha20::{XAeadError, XAeadNonce}; +use crate::crypto::{Rng, RngError}; +use crate::data_scheme::data::{decrypt_data, encrypt_data}; +use crate::data_scheme::dcgka::{ + ControlMessage, Dcgka, DcgkaError, DcgkaState, DirectMessage, GroupSecretOutput, + OperationOutput, ProcessInput, +}; +use crate::data_scheme::group_secret::{ + GroupSecret, GroupSecretError, GroupSecretId, SecretBundle, SecretBundleState, +}; +use crate::key_bundle::LongTermKeyBundle; +use crate::traits::{ + GroupMembership, GroupMessage, GroupMessageContent, IdentityHandle, IdentityManager, + IdentityRegistry, OperationId, Ordering, PreKeyManager, PreKeyRegistry, +}; + +/// API to manage groups using the "Data Encryption" scheme and process remote control messages. +pub struct EncryptionGroup { + _marker: PhantomData<(ID, OP, PKI, DGM, KMG, ORD)>, +} + +/// Group state for "data encryption" scheme. Serializable for persistence. +#[derive(Debug, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct GroupState +where + ID: IdentityHandle, + OP: OperationId, + PKI: IdentityRegistry + PreKeyRegistry, + PKI::State: Clone, + DGM: GroupMembership, + KMG: IdentityManager + PreKeyManager, + KMG::State: Clone, + ORD: Ordering, +{ + pub my_id: ID, + pub dcgka: DcgkaState, + pub orderer: ORD::State, + pub secrets: SecretBundleState, + pub is_welcomed: bool, +} + +impl EncryptionGroup +where + ID: IdentityHandle, + OP: OperationId, + PKI: IdentityRegistry + PreKeyRegistry, + PKI::State: Clone, + DGM: GroupMembership, + KMG: IdentityManager + PreKeyManager, + KMG::State: Clone, + ORD: Ordering, +{ + /// Returns initial state for group. + /// + /// This needs to be called before creating or being added to a group. + #[allow(unused)] + pub fn init( + my_id: ID, + my_keys: KMG::State, + pki: PKI::State, + dgm: DGM::State, + orderer: ORD::State, + ) -> GroupState { + GroupState { + my_id, + dcgka: Dcgka::init(my_id, my_keys, pki, dgm), + orderer, + secrets: SecretBundle::init(), + is_welcomed: false, + } + } + + /// Creates new group with initial set of members. + pub fn create( + mut y: GroupState, + initial_members: Vec, + rng: &Rng, + ) -> GroupResult { + if y.is_welcomed { + return Err(GroupError::GroupAlreadyEstablished); + } + + // Generate new group secret. + let group_secret = SecretBundle::generate(&y.secrets, rng)?; + + // Create new group with initial members. + let (y_dcgka_i, pre) = Dcgka::create(y.dcgka, initial_members, &group_secret, rng)?; + y.dcgka = y_dcgka_i; + + let (mut y_i, message) = Self::process_local(y, pre, Some(group_secret))?; + + // Set our own "create" as the "welcome" message. + let y_orderer_i = ORD::set_welcome(y_i.orderer, &message).map_err(GroupError::Orderer)?; + y_i.orderer = y_orderer_i; + y_i.is_welcomed = true; + + Ok((y_i, message)) + } + + /// Adds new member to group. + pub fn add( + mut y: GroupState, + added: ID, + rng: &Rng, + ) -> GroupResult { + if !y.is_welcomed { + return Err(GroupError::GroupNotYetEstablished); + } + + if y.my_id == added { + return Err(GroupError::NotAddOurselves); + } + + // Add a new member to the group. + let (y_dcgka_i, pre) = Dcgka::add(y.dcgka, added, &y.secrets, rng)?; + y.dcgka = y_dcgka_i; + + Self::process_local(y, pre, None) + } + + /// Adds new member to group, welcoming them with no earlier secrets. + /// + /// `add` mints no secret, and its welcome carries the adder's whole bundle. This welcome + /// carries an empty bundle, so the joiner learns no secret the group had before the add. The + /// caller must follow with `update` to rotate to a secret the joiner does learn. + pub fn add_from_join( + mut y: GroupState, + added: ID, + rng: &Rng, + ) -> GroupResult { + if !y.is_welcomed { + return Err(GroupError::GroupNotYetEstablished); + } + + if y.my_id == added { + return Err(GroupError::NotAddOurselves); + } + + // Pass an empty bundle, so the welcome carries no earlier secret. + let (y_dcgka_i, pre) = Dcgka::add(y.dcgka, added, &SecretBundle::init(), rng)?; + y.dcgka = y_dcgka_i; + + Self::process_local(y, pre, None) + } + + /// Removes member from group. It is possible to remove ourselves. + pub fn remove( + mut y: GroupState, + removed: ID, + rng: &Rng, + ) -> GroupResult { + if !y.is_welcomed { + return Err(GroupError::GroupNotYetEstablished); + } + + // Generate new group secret. + let group_secret = SecretBundle::generate(&y.secrets, rng)?; + + // Remove a member from the group. + let (y_dcgka_i, pre) = Dcgka::remove(y.dcgka, removed, &group_secret, rng)?; + y.dcgka = y_dcgka_i; + + Self::process_local(y, pre, Some(group_secret)) + } + + /// Updates group by providing all current members with new group secret. + pub fn update( + mut y: GroupState, + rng: &Rng, + ) -> GroupResult { + if !y.is_welcomed { + return Err(GroupError::GroupNotYetEstablished); + } + + // Generate new group secret. + let group_secret = SecretBundle::generate(&y.secrets, rng)?; + + // Update the group by generating a new seed. + let (y_dcgka_i, pre) = Dcgka::update(y.dcgka, &group_secret, rng)?; + y.dcgka = y_dcgka_i; + + Self::process_local(y, pre, Some(group_secret)) + } + + /// Handler for incoming, remote messages. + /// + /// This yields a list of "outputs" which can be either control messages which need to be + /// broadcast to all members in the group or decrypted application payloads. + /// + /// If we got removed after processing a control message we will receive an "removed" output + /// signal. + pub fn receive( + mut y: GroupState, + message: &ORD::Message, + ) -> GroupResult>, ID, OP, PKI, DGM, KMG, ORD> { + let message_content = message.content(); + let mut is_create_or_welcome = false; + + // Accept "create" control messages if we haven't established our state yet and if we are + // part of the initial members set. + if let GroupMessageContent::Control(ControlMessage::Create { + ref initial_members, + }) = message_content + { + if y.is_welcomed { + return Err(GroupError::GroupAlreadyEstablished); + } + + if initial_members.contains(&y.my_id) { + is_create_or_welcome = true; + } + } + + // Accept "add" control messages if we are being added by it. + if let GroupMessageContent::Control(ControlMessage::Add { added }) = message_content + && !y.is_welcomed + && added == y.my_id + { + is_create_or_welcome = true; + } + + let y_orderer_i = ORD::queue(y.orderer, message).map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + + if !y.is_welcomed && !is_create_or_welcome { + // We're receiving control- and application messages for this group but we haven't + // joined yet. We keep these messages for later. We don't know yet when we will join + // the group and which of these messages we can process afterwards. + return Ok((y, vec![])); + } + + if !y.is_welcomed && is_create_or_welcome { + // We've received a "create" or "add" (welcome) message for us and can join the group + // now. + let y_orderer_i = ORD::set_welcome(y.orderer, message).map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + } + + let mut results = Vec::new(); + let mut y_loop = y; + + let mut control_messages = VecDeque::new(); + let mut application_messages = VecDeque::new(); + + // Check if there's any correctly ordered messages ready to-be processed. + loop { + let (y_orderer_next, result) = + ORD::next_ready_message(y_loop.orderer).map_err(GroupError::Orderer)?; + y_loop.orderer = y_orderer_next; + + let Some(message) = result else { + break; + }; + + match message.content() { + GroupMessageContent::Control(_) => { + control_messages.push_back(message); + } + GroupMessageContent::Application { .. } => { + application_messages.push_back(message); + } + } + } + + // Process all control messages first. + while let Some(message) = control_messages.pop_front() { + let (y_next, result) = Self::process_ready(y_loop, &message)?; + y_loop = y_next; + if let Some(message) = result { + results.push(message); + } + } + + // .. then process all application messages. + while let Some(message) = application_messages.pop_front() { + let (y_next, result) = Self::process_ready(y_loop, &message)?; + y_loop = y_next; + if let Some(message) = result { + results.push(message); + } + } + + Ok((y_loop, results)) + } + + /// Encrypts application payload towards the current group. + /// + /// The returned message can then be broadcast to all members in the group. The underlying + /// protocol makes sure that all members will be able to decrypt this message. + pub fn send( + mut y: GroupState, + plaintext: &[u8], + rng: &Rng, + ) -> GroupResult { + if !y.is_welcomed { + return Err(GroupError::GroupNotYetEstablished); + } + + let Some(group_secret) = y.secrets.latest() else { + return Err(GroupError::NoGroupSecretAvailable); + }; + + // Encrypt application data. + let secret_id = group_secret.id(); + let (nonce, ciphertext) = Self::encrypt(group_secret, plaintext, rng)?; + + // Determine parameters for to-be-published application message. + let (y_orderer_i, message) = + ORD::next_application_message(y.orderer, secret_id, nonce, ciphertext) + .map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + + Ok((y, message)) + } + + /// Returns a list of all current members in this group from our perspective. + pub fn members( + y: &GroupState, + ) -> Result, GroupError> { + let members = Dcgka::members(&y.dcgka)?; + Ok(members) + } + + /// Applications can remove group secrets for forward secrecy based on their own logic. + /// + /// Make sure that the ordering implementation and higher-level application logic accounts for + /// error cases where past secrets might not exist anymore. + #[allow(unused)] + pub fn update_secrets( + mut y: GroupState, + update_fn: F, + ) -> GroupState + where + F: FnOnce(SecretBundleState) -> SecretBundleState, + { + y.secrets = update_fn(y.secrets); + y + } + + /// Processes our own locally created control messages. + fn process_local( + mut y: GroupState, + output: OperationOutput, + group_secret: Option, + ) -> GroupResult { + // Determine parameters for to-be-published control message. + let (y_orderer_i, message) = + ORD::next_control_message(y.orderer, &output.control_message, &output.direct_messages) + .map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + + // Process control message locally to update our state. + let (y_dcgka_i, _) = Dcgka::process( + y.dcgka, + ProcessInput { + seq: message.id(), + sender: message.sender(), + control_message: output.control_message, + direct_message: None, + }, + )?; + y.dcgka = y_dcgka_i; + + // Add new generated secret to bundle when given. + if let Some(group_secret) = group_secret { + y.secrets = SecretBundle::insert(y.secrets, group_secret); + } + + Ok((y, message)) + } + + /// Processes remote messages which have been marked as "ready" by the orderer. + fn process_ready( + y: GroupState, + message: &ORD::Message, + ) -> GroupResult>, ID, OP, PKI, DGM, KMG, ORD> { + match message.content() { + GroupMessageContent::Control(control_message) => { + let direct_message = message + .direct_messages() + .into_iter() + .find(|dm| dm.recipient == y.my_id); + + let (mut y_i, output) = Self::process_remote( + y, + message.id(), + message.sender(), + control_message, + direct_message, + )?; + + // Check if processing this message added us to the group. + let we_are_members = Self::members(&y_i)?.contains(&y_i.my_id); + if !y_i.is_welcomed && we_are_members { + y_i.is_welcomed = true; + } + + // Check if processing this message removed us from the group. + let is_removed = y_i.is_welcomed && !we_are_members; + if is_removed { + Ok((y_i, Some(GroupOutput::Removed))) + } else { + Ok((y_i, output.map(|msg| GroupOutput::Control(msg)))) + } + } + GroupMessageContent::Application { + group_secret_id, + ciphertext, + nonce, + } => { + let (y_i, plaintext) = Self::decrypt(y, nonce, group_secret_id, ciphertext)?; + Ok((y_i, Some(GroupOutput::Application { plaintext }))) + } + } + } + + /// Internal method to process remote control message. + fn process_remote( + mut y: GroupState, + seq: OP, + sender: ID, + control_message: ControlMessage, + direct_message: Option>, + ) -> GroupResult, ID, OP, PKI, DGM, KMG, ORD> { + let (y_dcgka_i, output) = Dcgka::process( + y.dcgka, + ProcessInput { + seq, + sender, + control_message, + direct_message, + }, + )?; + y.dcgka = y_dcgka_i; + + // Add newly learned group secrets to our bundle. + y.secrets = match output { + GroupSecretOutput::Secret(group_secret) => { + SecretBundle::insert(y.secrets, group_secret) + } + GroupSecretOutput::Bundle(secret_bundle_state) => { + SecretBundle::extend(y.secrets, secret_bundle_state) + } + GroupSecretOutput::None => y.secrets, + }; + + // Processing remote control messages never results in new messages. + Ok((y, None)) + } + + /// Encrypt message by using the latest known group secret and a random nonce. + fn encrypt( + group_secret: &GroupSecret, + plaintext: &[u8], + rng: &Rng, + ) -> Result<(XAeadNonce, Vec), GroupError> { + let nonce: XAeadNonce = rng.random_array()?; + let ciphertext = encrypt_data(plaintext, group_secret, nonce)?; + Ok((nonce, ciphertext)) + } + + /// Decrypt message by using a group secret. + fn decrypt( + y: GroupState, + nonce: XAeadNonce, + group_secret_id: GroupSecretId, + ciphertext: Vec, + ) -> GroupResult, ID, OP, PKI, DGM, KMG, ORD> { + let Some(group_secret) = y.secrets.get(&group_secret_id) else { + return Err(GroupError::UnknownGroupSecret(hex::encode(group_secret_id))); + }; + let plaintext = decrypt_data(&ciphertext, group_secret, nonce)?; + Ok((y, plaintext)) + } +} + +pub type GroupResult = + Result<(GroupState, T), GroupError>; + +/// Result from processing a remote message or calling a local group operation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GroupOutput +where + DGM: GroupMembership, + ORD: Ordering, +{ + /// Control message for group encryption which should be broadcast to all members of the group. + Control(ORD::Message), + + /// Decrypted payload of message. + Application { plaintext: Vec }, + + /// Signal that we've been removed from the group. + Removed, +} + +#[derive(Debug, Error)] +pub enum GroupError +where + PKI: IdentityRegistry + PreKeyRegistry, + DGM: GroupMembership, + KMG: PreKeyManager, + ORD: Ordering, +{ + #[error(transparent)] + Rng(#[from] RngError), + + #[error(transparent)] + Dcgka(#[from] DcgkaError), + + #[error(transparent)] + Orderer(ORD::Error), + + #[error(transparent)] + XAead(#[from] XAeadError), + + #[error(transparent)] + GroupSecret(#[from] GroupSecretError), + + #[error("creating or joining a group is not possible, state is already established")] + GroupAlreadyEstablished, + + #[error("state is not ready yet, group needs to be created or joined first")] + GroupNotYetEstablished, + + #[error("can not add ourselves to the group")] + NotAddOurselves, + + #[error("we do not have created or learned about any group secrets yet")] + NoGroupSecretAvailable, + + #[error("tried to decrypt message with an unknown group secret: {0}")] + UnknownGroupSecret(String), +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + use crate::data_scheme::group::GroupOutput; + use crate::data_scheme::test_utils::network::init_group_state; + use crate::traits::{GroupMembership, Ordering}; + + use super::{EncryptionGroup, GroupError}; + + pub fn assert_payload( + messages: &[GroupOutput], + expected_payload: &[u8], + ) where + DGM: GroupMembership, + ORD: Ordering, + { + let message = messages.first().expect("expected at least one message"); + if let GroupOutput::Application { plaintext } = message { + assert_eq!( + plaintext, expected_payload, + "expected payload does not match" + ); + } else { + panic!("expected application message"); + } + } + + #[test] + fn post_compromise_security() { + let rng = Rng::from_seed([1; 32]); + + let alice = 0; + let bob = 1; + let charlie = 2; + + let [y_alice, y_bob, y_charlie] = init_group_state([alice, bob, charlie], &rng); + + // Alice creates a group with Bob and Charlie. + let (y_alice, alice_message_0) = + EncryptionGroup::create(y_alice, vec![alice, bob, charlie], &rng).unwrap(); + let (y_bob, _) = EncryptionGroup::receive(y_bob, &alice_message_0).unwrap(); + let (y_charlie, _) = EncryptionGroup::receive(y_charlie, &alice_message_0).unwrap(); + + // Alice encrypts data for Bob and Charlie. + let (y_alice, alice_message_1) = EncryptionGroup::send(y_alice, b"Da Da Da", &rng).unwrap(); + + // Both Bob and Charlie can decrypt the payload. + let (y_bob, bob_output) = EncryptionGroup::receive(y_bob, &alice_message_1).unwrap(); + assert_payload(&bob_output, b"Da Da Da"); + let (y_charlie, charlie_output) = + EncryptionGroup::receive(y_charlie, &alice_message_1).unwrap(); + assert_payload(&charlie_output, b"Da Da Da"); + + // Bob removes Charlie. + let (y_bob, bob_message_0) = EncryptionGroup::remove(y_bob, charlie, &rng).unwrap(); + let (y_alice, alice_output) = EncryptionGroup::receive(y_alice, &bob_message_0).unwrap(); + assert!(alice_output.is_empty()); + + // Alice and Bob should have both the same "latest" secret. + assert_eq!( + y_alice.secrets.latest().unwrap().id(), + y_bob.secrets.latest().unwrap().id() + ); + + // Charlie receives the signal that they got removed by this message. + let (y_charlie, charlie_output) = + EncryptionGroup::receive(y_charlie, &bob_message_0).unwrap(); + let GroupOutput::Removed = charlie_output.first().unwrap() else { + panic!("expected removed output"); + }; + + // Alice encrypts data for Bob. + let (_y_alice, alice_message_2) = + EncryptionGroup::send(y_alice, b"Ich lieb dich nicht / Du liebst mich nicht", &rng) + .unwrap(); + + // Bob can still decrypt this message from Alice. + let (_y_bob, bob_output) = EncryptionGroup::receive(y_bob, &alice_message_2).unwrap(); + assert_payload(&bob_output, b"Ich lieb dich nicht / Du liebst mich nicht"); + + // Charlie can not decrypt the latest message anymore. + std::assert_matches!( + EncryptionGroup::receive(y_charlie, &alice_message_2), + Err(GroupError::UnknownGroupSecret(_)) + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group_secret.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group_secret.rs new file mode 100644 index 0000000000..9e8e4f2b64 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group_secret.rs @@ -0,0 +1,444 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Methods to create and maintain multiple secrets known by a group which are used to encrypt and decrypt data. +use std::collections::HashMap; +use std::collections::hash_map::{IntoIter, Iter, Keys, Values}; +use std::fmt; +use std::hash::Hash as StdHash; +use std::time::{SystemTime, SystemTimeError, UNIX_EPOCH}; + +use p2panda_core::cbor::{DecodeError, EncodeError, decode_cbor, encode_cbor}; +use serde::de::{SeqAccess, Visitor}; +use serde::ser::SerializeSeq; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::sha2::{SHA256_DIGEST_SIZE, sha2_256}; +use crate::crypto::{Rng, RngError, Secret}; + +/// 256-bit secret group key. +pub const GROUP_SECRET_SIZE: usize = 32; + +/// Public identifier for each secret. This is the SHA256 digest of the secret key itself. +/// +/// Can be used to help the receiver of a ciphertext to understand which key they can use to +/// decrypt the message. +pub type GroupSecretId = [u8; SHA256_DIGEST_SIZE]; + +/// UNIX timestamp indicating when the key was generated. +/// +/// This helps peers to pick the "latest" key or remove keys based on their age (for forward secrecy) +/// depending on the application. If other ordering strategies are applied by the application they +/// can also be used instead to reason about the "latest" group secret. +pub type Timestamp = u64; + +/// Secret known by a group which is used to encrypt and decrypt data. +/// +/// Group secrets can be used multiple times and are dropped never or manually by the application, +/// thus providing a weaker forward secrecy than p2panda's "message encryption" scheme. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GroupSecret(Secret, Timestamp); + +impl GroupSecret { + #[cfg(any(test, feature = "test_utils"))] + pub fn new(bytes: [u8; GROUP_SECRET_SIZE], timestamp: Timestamp) -> Self { + Self(Secret::from_bytes(bytes), timestamp) + } + + /// Create a new group secret with current timestamp from random-number generator. + pub(crate) fn from_rng(rng: &Rng) -> Result { + let bytes: [u8; GROUP_SECRET_SIZE] = rng.random_array()?; + Self::from_bytes(bytes) + } + + /// Create a new group secret with current timestamp from random byte string. + pub(crate) fn from_bytes(bytes: [u8; GROUP_SECRET_SIZE]) -> Result { + let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(); + Ok(Self(Secret::from_bytes(bytes), now)) + } + + /// Deserialize group secret from CBOR representation. + pub(crate) fn try_from_bytes(bytes: &[u8]) -> Result { + Ok(decode_cbor(bytes)?) + } + + /// Returns identifier (SHA256 hash) for this secret. + pub fn id(&self) -> GroupSecretId { + sha2_256(&[self.0.as_bytes()]) + } + + /// Return creation date (UNIX timestamp in seconds) of this secret. + pub fn timestamp(&self) -> Timestamp { + self.1 + } + + /// Adjust the timestamp. + pub(crate) fn set_timestamp(&mut self, timestamp: Timestamp) { + self.1 = timestamp; + } + + /// Returns secret key as bytes. + pub(crate) fn as_bytes(&self) -> &[u8; GROUP_SECRET_SIZE] { + self.0.as_bytes() + } + + /// Serialize group secret into CBOR representation. + pub(crate) fn to_bytes(&self) -> Result, GroupSecretError> { + Ok(encode_cbor(self)?) + } +} + +impl StdHash for GroupSecret { + fn hash(&self, state: &mut H) { + self.id().hash(state); + } +} + +/// Bundle of all secrets used by a group to encrypt and decrypt it's data. +/// +/// Peers manage all secrets they generated or learned about in this bundle. New secrets are added +/// to the bundle when a group got updated, a member was added or removed. +/// +/// Secrets inside the bundle can be removed if the application considers them due, otherwise +/// a bundle will grow in size and no forward secrecy is given. +#[derive(Debug)] +pub struct SecretBundle; + +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct SecretBundleState { + secrets: HashMap, + latest: Option, +} + +impl SecretBundleState { + /// Returns the latest known secret which should preferably used for encrypting new data. + pub fn latest(&self) -> Option<&GroupSecret> { + self.latest.as_ref().and_then(|id| self.secrets.get(id)) + } + + /// Returns a secret based on the id. + /// + /// This can be used to retrieve a secret to decrypt data where we know which secret id has been + /// used. + pub fn get(&self, id: &GroupSecretId) -> Option<&GroupSecret> { + self.secrets.get(id) + } + + /// Returns true when the bundle contains a secret with the given id. + pub fn contains(&self, id: &GroupSecretId) -> bool { + self.secrets.contains_key(id) + } + + /// Returns number of all secrets in this bundle. + pub fn len(&self) -> usize { + self.secrets.len() + } + + /// Returns true if there's no secrets in this bundle. + pub fn is_empty(&self) -> bool { + self.secrets.is_empty() + } + + /// Iterator over secrets (values) and their ids (keys). + pub fn iter(&self) -> Iter<'_, GroupSecretId, GroupSecret> { + self.secrets.iter() + } + + /// Iterator over all ids. + pub fn ids(&self) -> Keys<'_, GroupSecretId, GroupSecret> { + self.secrets.keys() + } + + /// Iterator over all secrets. + pub fn secrets(&self) -> Values<'_, GroupSecretId, GroupSecret> { + self.secrets.values() + } + + /// Encodes bundle in CBOR format. + pub(crate) fn to_bytes(&self) -> Result, GroupSecretError> { + Ok(encode_cbor(self)?) + } +} + +impl std::iter::IntoIterator for SecretBundleState { + type Item = (GroupSecretId, GroupSecret); + + type IntoIter = IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.secrets.into_iter() + } +} + +impl Serialize for SecretBundleState { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let mut s = serializer.serialize_seq(Some(self.secrets.len()))?; + for secret in self.secrets.values() { + s.serialize_element(secret)?; + } + s.end() + } +} + +impl<'de> Deserialize<'de> for SecretBundleState { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + struct SecretListVisitor; + + impl<'de> Visitor<'de> for SecretListVisitor { + type Value = Vec; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("list of group secrets") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let mut result = Vec::new(); + while let Some(secret) = seq.next_element()? { + result.push(secret); + } + Ok(result) + } + } + + let secrets = deserializer.deserialize_seq(SecretListVisitor)?; + + Ok(SecretBundle::from_secrets(secrets)) + } +} + +impl SecretBundle { + /// Initialises empty secret bundle state. + pub fn init() -> SecretBundleState { + SecretBundleState { + secrets: HashMap::new(), + latest: None, + } + } + + /// Initialises secret bundle state from a list of group secrets. + pub fn from_secrets(secrets: Vec) -> SecretBundleState { + let secrets = HashMap::from_iter(secrets.into_iter().map(|secret| (secret.id(), secret))); + SecretBundleState { + latest: find_latest(&secrets), + secrets, + } + } + + /// Initialises secret bundle state from an encoded CBOR representation. + pub(crate) fn try_from_bytes(bytes: &[u8]) -> Result { + Ok(decode_cbor(bytes)?) + } + + /// Generates and returns a new secret. + /// + /// To prevent issues with invalid timestamps (too far in the future) of previous secrets, we + /// force our newly generated secret to be the "latest" when needed. + /// + /// The secret is not yet inserted into the bundle, this needs to be done manually. + pub fn generate(y: &SecretBundleState, rng: &Rng) -> Result { + let mut secret = GroupSecret::from_rng(rng)?; + + let latest_timestamp = y.latest().map(|latest| latest.timestamp()).unwrap_or(0); + if secret.timestamp() <= latest_timestamp { + secret.set_timestamp(latest_timestamp + 1); + } + + Ok(secret) + } + + /// Inserts secret into bundle, ignoring duplicates. + pub fn insert(mut y: SecretBundleState, secret: GroupSecret) -> SecretBundleState { + y.secrets.insert(secret.id(), secret); + y.latest = find_latest(&y.secrets); + y + } + + /// Removes secret from bundle. + pub fn remove( + mut y: SecretBundleState, + id: &GroupSecretId, + ) -> (SecretBundleState, Option) { + let result = y.secrets.remove(id); + y.latest = find_latest(&y.secrets); + (y, result) + } + + /// Merges one bundle with another, ignoring duplicates. + pub fn extend(mut y: SecretBundleState, other: SecretBundleState) -> SecretBundleState { + y.secrets.extend(other.secrets); + y.latest = find_latest(&y.secrets); + y + } +} + +/// Finds the "latest" secret to use from a list by comparing timestamps. If the timestamps of two +/// distinct secrets match the id is used as a tie-breaker. +fn find_latest(secrets: &HashMap) -> Option { + let mut latest_timestamp: Timestamp = 0; + let mut latest_secret_id: Option = None; + for (id, secret) in secrets { + let timestamp = secret.timestamp(); + if latest_timestamp < timestamp + || (latest_timestamp == timestamp + && *id > latest_secret_id.unwrap_or([0; SHA256_DIGEST_SIZE])) + { + latest_timestamp = timestamp; + latest_secret_id = Some(id.to_owned()); + } + } + latest_secret_id +} + +#[derive(Debug, Error)] +pub enum GroupSecretError { + #[error("the given key does not match the required 32 byte length")] + InvalidKeySize, + + #[error(transparent)] + Rng(#[from] RngError), + + #[error(transparent)] + Encode(#[from] EncodeError), + + #[error(transparent)] + Decode(#[from] DecodeError), + + #[error(transparent)] + SystemTime(#[from] SystemTimeError), +} + +#[cfg(test)] +mod tests { + use crate::Rng; + + use super::{GroupSecret, SecretBundle}; + + #[test] + fn group_secret_bundle() { + let rng = Rng::from_seed([1; 32]); + + let secret = GroupSecret::from_rng(&rng).unwrap(); + + let bundle_1 = SecretBundle::from_secrets(vec![secret.clone()]); + let bundle_2 = SecretBundle::from_secrets(vec![secret.clone()]); + assert_eq!(bundle_1.len(), 1); + assert_eq!(bundle_2.len(), 1); + + assert_eq!(bundle_1.get(&secret.id()), bundle_2.get(&secret.id())); + assert!(bundle_1.get(&secret.id()).is_some()); + assert!(bundle_1.contains(&secret.id())); + + let unknown_secret = GroupSecret::from_rng(&rng).unwrap(); + assert!(bundle_1.get(&unknown_secret.id()).is_none()); + assert!(!bundle_1.contains(&unknown_secret.id())); + + let secret_2 = GroupSecret::from_rng(&rng).unwrap(); + let bundle_2 = SecretBundle::insert(bundle_2, secret_2.clone()); + assert_eq!(bundle_2.len(), 2); + + let bundle_1 = SecretBundle::extend(bundle_1, bundle_2); + assert_eq!(bundle_1.len(), 2); + + let (bundle_1, result) = SecretBundle::remove(bundle_1, &secret_2.id()); + assert_eq!(result, Some(secret_2)); + assert_eq!(bundle_1.len(), 1); + } + + #[test] + fn latest_secret() { + let bundle = SecretBundle::init(); + assert!(bundle.latest().is_none()); + + let secret_1 = GroupSecret::new([1; 32], 234); + assert_eq!(secret_1.timestamp(), 234); + let secret_2 = GroupSecret::new([2; 32], 234); // same timestamp + assert_eq!(secret_2.timestamp(), 234); + let secret_3 = GroupSecret::new([3; 32], 345); + assert_eq!(secret_3.timestamp(), 345); + let secret_4 = GroupSecret::new([4; 32], 123); + assert_eq!(secret_4.timestamp(), 123); + + // Inserted secret 1 is the latest. + let bundle = SecretBundle::insert(bundle, secret_1.clone()); + assert_eq!(bundle.len(), 1); + assert_eq!(bundle.latest(), Some(&secret_1)); + + // Inserted secret 2 is the "latest" as the higher hash wins when both timestamps are the + // same. + let bundle = SecretBundle::insert(bundle, secret_2.clone()); + assert_eq!(bundle.len(), 2); + assert_eq!(bundle.latest(), Some(&secret_2)); + + // Use a separate group to confirm that the order of insertion does not matter here. + { + let bundle_2 = SecretBundle::init(); + let bundle_2 = SecretBundle::insert(bundle_2, secret_2.clone()); + let bundle_2 = SecretBundle::insert(bundle_2, secret_1.clone()); + assert_eq!(bundle_2.latest(), Some(&secret_2)); + } + + // Inserted 3 is the latest. + let bundle = SecretBundle::insert(bundle, secret_3.clone()); + assert_eq!(bundle.len(), 3); + assert_eq!(bundle.latest(), Some(&secret_3)); + + // Inserted 3 is still the latest. + let bundle = SecretBundle::insert(bundle, secret_4.clone()); + assert_eq!(bundle.len(), 4); + assert_eq!(bundle.latest(), Some(&secret_3)); + } + + #[test] + fn serde() { + let rng = Rng::from_seed([1; 32]); + + // Serialize & deserialize bundle. + let bundle = SecretBundle::from_secrets(vec![ + GroupSecret::from_rng(&rng).unwrap(), + GroupSecret::from_rng(&rng).unwrap(), + GroupSecret::from_rng(&rng).unwrap(), + GroupSecret::from_rng(&rng).unwrap(), + ]); + + let bytes = bundle.to_bytes().unwrap(); + assert_eq!(bundle, SecretBundle::try_from_bytes(&bytes).unwrap()); + + // Serialize & deserialize single secret. + let secret = GroupSecret::from_rng(&rng).unwrap(); + let timestamp = secret.timestamp(); + + let bytes = secret.to_bytes().unwrap(); + let secret_again = GroupSecret::try_from_bytes(&bytes).unwrap(); + assert_eq!(secret, secret_again); + assert_eq!(timestamp, secret_again.timestamp()); + } + + #[test] + fn generated_always_latest() { + let rng = Rng::from_seed([1; 32]); + + let bundle = SecretBundle::init(); + + let secret_0 = SecretBundle::generate(&bundle, &rng).unwrap(); + let bundle = SecretBundle::insert(bundle, secret_0.clone()); + assert_eq!(bundle.latest(), Some(&secret_0)); + + let secret_1 = SecretBundle::generate(&bundle, &rng).unwrap(); + let bundle = SecretBundle::insert(bundle, secret_1.clone()); + assert_eq!(bundle.latest(), Some(&secret_1)); + + let secret_2 = SecretBundle::generate(&bundle, &rng).unwrap(); + let bundle = SecretBundle::insert(bundle, secret_2.clone()); + assert_eq!(bundle.latest(), Some(&secret_2)); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/mod.rs new file mode 100644 index 0000000000..afaf82ac41 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/mod.rs @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Data encryption for groups with post-compromise security and optional forward secrecy. +//! +//! This "Data Encryption" scheme allows peers to encrypt any data with a secret, symmetric key for +//! a group. This will be useful for building applications where users who enter a group late will +//! still have access to previously-created content, for example private knowledge or wiki +//! applications or a booking tool for rehearsal rooms. +//! +//! A member will not learn about any newly-created data after they are removed from the group, +//! since the key gets rotated on member removal or manual key update. This should accommodate for +//! many use-cases in p2p applications which rely on basic group encryption with post-compromise +//! security (PCS) and forward secrecy (FS) during key agreement. +//! +//! ## Messages +//! +//! Every group operation ([create](EncryptionGroup::create) or [update](EncryptionGroup::update) +//! group, [add](EncryptionGroup::add) or [remove](EncryptionGroup::remove) member) results in a +//! [`ControlMessage`] which is broadcast to the network for each group member, along with a set of direct messages. +//! +//! A [`DirectMessage`] is sent to a specific group member and contains the group secrets encrypted +//! towards them for key agreement. +//! +//! Application messages contain the ciphertexts and parameters required to decrypt it. +//! +//! ## Key agreement and encryption +//! +//! The "Data Encryption" group API is mostly a wrapper around the [2SM (Two-Party Secure +//! Messaging) key agreement protocol](crate::two_party). On creating or updating a group and +//! removing a member, a new, random [`GroupSecret`] is [generated](SecretBundle::generate). Every +//! secret is identified with a unique [`GroupSecretId`] and has a UNIX timestamp indicating when +//! it was created. +//! +//! Peers maintain a [`SecretBundle`] with all group secrets inside. Secrets are added to the +//! bundle when local group operations took place or when learning about a new secret from another +//! member after receiving a control message. +//! +//! When sending new data into the group we [look up the latest secret](SecretBundleState::latest) +//! in the bundle (via comparing timestamps) and use XChaCha20Poly1305 as an AEAD to [encrypt the +//! payload](encrypt_data) with a random nonce. Next to each ciphertext the used nonce and group +//! secret id is mentioned so other members of the group can [decrypt the data](decrypt_data). +//! +//! Members who have been added to the group will learn about the whole secret bundle included in a +//! direct "welcome" message encrypted towards them using the 2SM protocol. Through this the added +//! member will be able to decrypt all previously-created content as they will learn about all +//! used secrets. +//! +//! ## Optional forward secrecy +//! +//! Applications can remove group secrets for forward secrecy based on their own logic. For +//! removing group secrets implementers can use the [`EncryptionGroup::update_secrets`] method. +//! +//! For stronger forward secrecy guarantees have a look at the ["Message +//! Encryption"](crate::message_scheme) scheme. +//! +//! ## Key bundles +//! +//! For initial key agreement (X3DH) peers need to publish key bundles into the network to allow +//! others to invite them into groups. For the "Data Encryption" scheme we're using long-term +//! pre-keys with lifetimes specified by the application. +//! +//! More on key bundles can be read [here](crate::key_bundle). +//! +//! ## Usage +//! +//! Check out the [`EncryptionGroup`] API for establishing and maintaining groups using the "Data +//! Encryption" scheme. +//! +//! [`GroupSecret`] and [`SecretBundle`] are always explicitly passed into every group operation +//! ("add member", "remove member", etc.) to allow full control over the managed keys for +//! applications. +//! +//! Developers need to bring their own data types with [group message +//! interfaces](crate::traits::GroupMessage), [decentralised group +//! membership](crate::traits::GroupMembership) (DGM) and [ordering](crate::traits::Ordering) +//! implementations when using this crate directly. For easier use without this overhead it's +//! recommended to look into higher-level integrations using the p2panda stack. +mod data; +pub mod dcgka; +pub mod group; +pub mod group_secret; +#[cfg(any(test, feature = "test_utils"))] +pub mod test_utils; +#[cfg(test)] +mod tests; + +pub use data::{decrypt_data, encrypt_data}; +pub use dcgka::{ControlMessage, DirectMessage, DirectMessageContent, DirectMessageType}; +pub use group::{EncryptionGroup, GroupError, GroupOutput, GroupResult, GroupState}; +pub use group_secret::{ + GROUP_SECRET_SIZE, GroupSecret, GroupSecretError, GroupSecretId, SecretBundle, + SecretBundleState, +}; diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/dcgka.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/dcgka.rs new file mode 100644 index 0000000000..9757188833 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/dcgka.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::collections::HashMap; + +use crate::Rng; +use crate::crypto::x25519::SecretKey; +use crate::data_scheme::dcgka::{Dcgka, DcgkaState}; +use crate::data_scheme::test_utils::dgm::TestDgm; +use crate::key_bundle::Lifetime; +use crate::key_manager::KeyManager; +use crate::key_registry::KeyRegistry; +use crate::test_utils::{MemberId, MessageId}; +use crate::traits::PreKeyManager; + +pub type TestDcgkaState = DcgkaState< + MemberId, + MessageId, + KeyRegistry, + TestDgm, + KeyManager, +>; + +/// Helper method returning initialised DCGKA state for each member of a test group using the "data +/// encryption" scheme. +/// +/// The method will automatically generate all required long-term pre-key bundles from each member +/// and register them for each other. +pub fn init_dcgka_state( + member_ids: [MemberId; N], + rng: &Rng, +) -> [TestDcgkaState; N] { + let mut key_bundles = HashMap::new(); + let mut key_managers = HashMap::new(); + + // Generate a pre-key bundle for each other member of the group. + for id in member_ids { + let identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let manager = + KeyManager::init_and_generate_prekey(&identity_secret, Lifetime::default(), rng) + .unwrap(); + + let mut bundle_list = Vec::with_capacity(member_ids.len()); + for _ in member_ids { + let key_bundle = KeyManager::prekey_bundle(&manager).unwrap(); + bundle_list.push(key_bundle); + } + + key_bundles.insert(id, bundle_list); + key_managers.insert(id, manager); + } + + // Register each other's pre-key bundles and initialise DCGKA state. + let mut result = Vec::with_capacity(member_ids.len()); + for id in member_ids { + let dgm = TestDgm::init(id); + let registry = { + let mut state = KeyRegistry::init(); + for bundle_id in member_ids { + let bundle = key_bundles.get_mut(&bundle_id).unwrap().pop().unwrap(); + let state_i = KeyRegistry::add_longterm_bundle(state, bundle_id, bundle).unwrap(); + state = state_i; + } + state + }; + let manager = key_managers.remove(&id).unwrap(); + let dcgka: TestDcgkaState = Dcgka::init(id, manager, registry, dgm); + result.push(dcgka); + } + + result.try_into().unwrap() +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/dgm.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/dgm.rs new file mode 100644 index 0000000000..aca682e240 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/dgm.rs @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::collections::HashSet; +use std::convert::Infallible; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; + +use crate::traits::{GroupMembership, IdentityHandle, OperationId}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestDgm { + _marker: PhantomData<(ID, OP)>, +} + +impl TestDgm +where + ID: IdentityHandle + Serialize + for<'a> Deserialize<'a>, +{ + pub fn init(my_id: ID) -> TestDgmState { + TestDgmState { + my_id, + members: HashSet::new(), + _marker: PhantomData, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestDgmState +where + ID: IdentityHandle, +{ + my_id: ID, + members: HashSet, + _marker: PhantomData, +} + +impl GroupMembership for TestDgm +where + ID: IdentityHandle + Serialize + for<'a> Deserialize<'a>, + OP: OperationId + Serialize + for<'a> Deserialize<'a>, +{ + type State = TestDgmState; + + type Error = Infallible; + + fn create(my_id: ID, initial_members: &[ID]) -> Result { + Ok(TestDgmState { + my_id, + members: HashSet::from_iter(initial_members.iter().cloned()), + _marker: PhantomData, + }) + } + + fn from_welcome(my_id: ID, y: Self::State) -> Result { + Ok(TestDgmState { + my_id, + members: y.members, + _marker: PhantomData, + }) + } + + fn add( + mut y: Self::State, + _adder: ID, + added: ID, + _operation_id: OP, + ) -> Result { + y.members.insert(added); + Ok(y) + } + + fn remove( + mut y: Self::State, + _remover: ID, + removed: &ID, + _operation_id: OP, + ) -> Result { + y.members.remove(removed); + Ok(y) + } + + fn members(y: &Self::State) -> Result, Self::Error> { + Ok(y.members.clone()) + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/mod.rs new file mode 100644 index 0000000000..d4f3896ea2 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/mod.rs @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +pub mod dcgka; +pub mod dgm; +pub mod network; +pub mod ordering; diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/network.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/network.rs new file mode 100644 index 0000000000..cd51dd87f2 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/network.rs @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::collections::{HashMap, HashSet, VecDeque}; + +use crate::crypto::Rng; +use crate::data_scheme::ControlMessage; +use crate::data_scheme::group::{EncryptionGroup, GroupOutput, GroupState}; +use crate::data_scheme::group_secret::SecretBundle; +use crate::data_scheme::test_utils::dcgka::init_dcgka_state; +use crate::data_scheme::test_utils::dgm::TestDgm; +use crate::data_scheme::test_utils::ordering::{MessageOrderer, TestMessage}; +use crate::key_manager::KeyManager; +use crate::key_registry::KeyRegistry; +use crate::test_utils::{MemberId, MessageId}; +use crate::traits::{GroupMessage, GroupMessageContent}; + +pub type TestGroupState = GroupState< + MemberId, + MessageId, + KeyRegistry, + TestDgm, + KeyManager, + MessageOrderer>, +>; + +pub fn init_group_state( + member_ids: [MemberId; N], + rng: &Rng, +) -> [TestGroupState; N] { + init_dcgka_state(member_ids, rng) + .into_iter() + .map(|dcgka| { + let orderer = MessageOrderer::>::init(dcgka.my_id); + TestGroupState { + my_id: dcgka.my_id, + dcgka, + orderer, + secrets: SecretBundle::init(), + is_welcomed: false, + } + }) + .collect::>() + .try_into() + .unwrap() +} + +pub struct Network { + rng: Rng, + pub members: HashMap, + pub removed_members: HashSet, + pub queue: VecDeque>>, +} + +impl Network { + pub fn new(members: [MemberId; N], rng: Rng) -> Self { + let members = init_group_state(members, &rng); + Self { + rng, + members: HashMap::from_iter(members.into_iter().map(|state| (state.my_id, state))), + removed_members: HashSet::new(), + queue: VecDeque::new(), + } + } + + pub fn create(&mut self, creator: MemberId, initial_members: Vec) { + let y = self.get_y(&creator); + let (y_i, message) = EncryptionGroup::create(y, initial_members, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + } + + pub fn add(&mut self, adder: MemberId, added: MemberId) { + let y = self.get_y(&adder); + let (y_i, message) = EncryptionGroup::add(y, added, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + } + + pub fn remove(&mut self, remover: MemberId, removed: MemberId) { + let y = self.get_y(&remover); + let (y_i, message) = EncryptionGroup::remove(y, removed, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + self.removed_members.insert(removed); + } + + pub fn update(&mut self, updater: MemberId) { + let y = self.get_y(&updater); + let (y_i, message) = EncryptionGroup::update(y, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + } + + pub fn send(&mut self, sender: MemberId, plaintext: &[u8]) { + let y = self.get_y(&sender); + let (y_i, message) = EncryptionGroup::send(y, plaintext, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + } + + pub fn process(&mut self) -> Vec<(MemberId, MemberId, Vec)> { + if self.queue.is_empty() { + return Vec::new(); + } + + let mut decrypted_messages = Vec::new(); + let member_ids: Vec = self + .members + .keys() + .cloned() + .filter(|id| !self.removed_members.contains(id)) + .collect(); + + while let Some(message) = self.queue.pop_front() { + for id in &member_ids { + // Do not process our own messages. + if &message.sender() == id { + continue; + } + + // Member processes each message broadcast to the group. + let y = self.get_y(id); + let (y_i, result) = EncryptionGroup::receive(y, &message).unwrap(); + self.set_y(y_i); + + for output in result { + match output { + GroupOutput::Control(control_message) => { + // Processing messages might yield new ones, process these as well. + self.queue.push_back(control_message); + } + GroupOutput::Application { plaintext } => decrypted_messages.push(( + message.sender(), // Sender + *id, // Receiver + plaintext, // Decrypted content + )), + GroupOutput::Removed => (), + } + } + + // Update set of removed members if any. + if let GroupMessageContent::Control(ControlMessage::Remove { removed }) = + message.content() + { + self.removed_members.insert(removed); + } + } + } + + decrypted_messages.sort(); + decrypted_messages + } + + pub fn members(&self, member: &MemberId) -> Vec { + let y = self.members.get(member).expect("member exists"); + let mut members = Vec::from_iter(EncryptionGroup::members(y).unwrap()); + members.sort(); + members + } + + fn get_y(&mut self, member: &MemberId) -> TestGroupState { + self.members.remove(member).expect("member exists") + } + + fn set_y(&mut self, y: TestGroupState) { + assert!( + self.members.insert(y.my_id, y).is_none(), + "state was removed before insertion" + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/ordering.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/ordering.rs new file mode 100644 index 0000000000..59010cc5b5 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/test_utils/ordering.rs @@ -0,0 +1,268 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::collections::HashMap; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::xchacha20::XAeadNonce; +use crate::data_scheme::{ControlMessage, DirectMessage, GroupSecretId}; +use crate::ordering::{Orderer, OrdererError, OrdererState}; +use crate::test_utils::{MemberId, MessageId}; +use crate::traits::{GroupMembership, GroupMessage, GroupMessageContent, Ordering}; + +/// Orderer for testing the "data encryption" group APIs. +/// +/// This is sufficient for the current testing setup but for anything "production ready" a more +/// sophisticated solution will be required as all messages are kept in memory. +#[derive(Clone, Debug)] +pub struct MessageOrderer { + _marker: PhantomData, +} + +impl MessageOrderer +where + DGM: Clone + GroupMembership, +{ + pub fn init(my_id: MemberId) -> MessageOrdererState { + MessageOrdererState { + next_message_seq: 0, + previous: HashMap::new(), + orderer: Orderer::init(), + my_id, + messages: HashMap::new(), + welcome_message: None, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct MessageOrdererState +where + DGM: Clone + GroupMembership, +{ + /// Sequence number of the next, message to-be published. + next_message_seq: usize, + + /// Our own member id. + my_id: MemberId, + + /// Internal helper to order messages based on their "previous" dependencies. + orderer: OrdererState, + + /// Latest known message id's from each group member. This is the "head" of the DAG. + previous: HashMap, + + /// In-memory store of all messages. + messages: HashMap>, + + /// "Create" or "Add" message which got us into the group. + welcome_message: Option>, +} + +impl Ordering for MessageOrderer +where + DGM: std::fmt::Debug + + Clone + + GroupMembership + + Serialize + + for<'a> Deserialize<'a>, +{ + type State = MessageOrdererState; + + type Error = MessageOrdererError; + + type Message = TestMessage; + + fn next_control_message( + mut y: Self::State, + control_message: &ControlMessage, + direct_messages: &[DirectMessage], + ) -> Result<(Self::State, Self::Message), Self::Error> { + let seq = y.next_message_seq; + let sender = y.my_id; + let previous = y.previous.values().cloned().collect(); + + let message = TestMessage { + seq, + sender, + previous, + content: TestMessageContent::System { + control_message: control_message.to_owned(), + direct_messages: direct_messages.to_owned(), + }, + }; + + y.next_message_seq += 1; + y.previous.insert(y.my_id, message.id()); + + Ok((y, message)) + } + + fn next_application_message( + mut y: Self::State, + group_secret_id: GroupSecretId, + nonce: XAeadNonce, + ciphertext: Vec, + ) -> Result<(Self::State, Self::Message), Self::Error> { + let seq = y.next_message_seq; + let sender = y.my_id; + let previous = y.previous.values().cloned().collect(); + + let message = TestMessage { + seq, + sender, + previous, + content: TestMessageContent::Application { + ciphertext, + group_secret_id, + nonce, + }, + }; + + y.next_message_seq += 1; + + Ok((y, message)) + } + + fn queue(mut y: Self::State, message: &Self::Message) -> Result { + let id = message.id(); + + // TODO: We keep all messages in memory currently which is bad. This needs a persistence + // layer as soon as we've looked into how it all plays together with our access control and + // stream APIs. + y.messages.insert(id, message.clone()); + + let previous: Vec = message + .previous + .iter() + .filter(|id| id.sender != y.my_id) + .cloned() + .collect(); + + if !Orderer::ready(&y.orderer, &previous)? { + let (y_orderer_i, _) = Orderer::mark_pending(y.orderer, id, previous)?; + y.orderer = y_orderer_i; + return Ok(y); + } + + let (y_orderer_i, _) = Orderer::mark_ready(y.orderer, id)?; + let y_orderer_ii = Orderer::process_pending(y_orderer_i, id)?; + y.orderer = y_orderer_ii; + + Ok(y) + } + + fn set_welcome( + mut y: Self::State, + message: &Self::Message, + ) -> Result { + y.welcome_message = Some(message.clone()); + Ok(y) + } + + fn next_ready_message( + mut y: Self::State, + ) -> Result<(Self::State, Option), Self::Error> { + // We have not joined the group yet, don't process any messages yet. + if y.welcome_message.is_none() { + return Ok((y, None)); + }; + + let (y_orderer_i, next_ready) = Orderer::take_next_ready(y.orderer)?; + y.orderer = y_orderer_i; + + let message = next_ready.map(|id| { + y.messages + .get(&id) + .expect("ids map consistently to messages") + .to_owned() + }); + + if let Some(ref message) = message + && let GroupMessageContent::Control(_) = message.content() + { + // Mark messages as "last seen" so we can mention the "previous" ones as soon + // as we publish a message ourselves. + y.previous.insert(message.sender(), message.id()); + } + + Ok((y, message)) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TestMessage +where + DGM: Clone + GroupMembership, +{ + seq: usize, + sender: usize, + previous: Vec, + content: TestMessageContent, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum TestMessageContent +where + DGM: Clone + GroupMembership, +{ + Application { + ciphertext: Vec, + group_secret_id: GroupSecretId, + nonce: XAeadNonce, + }, + System { + control_message: ControlMessage, + direct_messages: Vec>, + }, +} + +impl GroupMessage for TestMessage +where + DGM: Clone + GroupMembership, +{ + fn id(&self) -> MessageId { + MessageId { + sender: self.sender, + seq: self.seq, + } + } + + fn sender(&self) -> MemberId { + self.sender + } + + fn content(&self) -> GroupMessageContent { + match &self.content { + TestMessageContent::Application { + ciphertext, + group_secret_id, + nonce, + } => GroupMessageContent::Application { + group_secret_id: *group_secret_id, + nonce: *nonce, + ciphertext: ciphertext.to_vec(), + }, + TestMessageContent::System { + control_message, .. + } => GroupMessageContent::Control(control_message.clone()), + } + } + + fn direct_messages(&self) -> Vec> { + match &self.content { + TestMessageContent::Application { .. } => Vec::new(), + TestMessageContent::System { + direct_messages, .. + } => direct_messages.clone(), + } + } +} + +#[derive(Debug, Error)] +pub enum MessageOrdererError { + #[error(transparent)] + Orderer(#[from] OrdererError), +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/tests.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/tests.rs new file mode 100644 index 0000000000..54da9b376a --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/tests.rs @@ -0,0 +1,689 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::crypto::Rng; +use crate::crypto::x25519::SecretKey; +use crate::data_scheme::dcgka::{Dcgka, DcgkaError, DcgkaState, GroupSecretOutput, ProcessInput}; +use crate::data_scheme::group_secret::SecretBundle; +use crate::data_scheme::test_utils::dgm::TestDgm; +use crate::key_bundle::Lifetime; +use crate::key_manager::KeyManager; +use crate::key_registry::KeyRegistry; +use crate::test_utils::{MemberId, MessageId}; +use crate::traits::PreKeyManager; + +type TestDcgkaState = DcgkaState< + MemberId, + MessageId, + KeyRegistry, + TestDgm, + KeyManager, +>; + +#[test] +fn group_operations() { + let rng = Rng::from_seed([1; 32]); + + let alice = 0; + let bob = 1; + let charlie = 2; + + // Alice initialises their key material. + + let alice_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let alice_dgm = TestDgm::init(alice); + let alice_pki = KeyRegistry::init(); + let alice_keys = + KeyManager::init_and_generate_prekey(&alice_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let alice_prekeys = KeyManager::prekey_bundle(&alice_keys).unwrap(); + + // Bob initialises their key material. + + let bob_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let bob_dgm = TestDgm::init(bob); + let bob_pki = KeyRegistry::init(); + let bob_keys = + KeyManager::init_and_generate_prekey(&bob_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let bob_prekeys = KeyManager::prekey_bundle(&bob_keys).unwrap(); + + // Charlie initialises their key material. + + let charlie_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let charlie_dgm = TestDgm::init(charlie); + let charlie_pki = KeyRegistry::init(); + let charlie_keys = + KeyManager::init_and_generate_prekey(&charlie_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let charlie_prekeys = KeyManager::prekey_bundle(&charlie_keys).unwrap(); + + // Register key bundles. + + let alice_pki = + KeyRegistry::add_longterm_bundle(alice_pki, alice, alice_prekeys.clone()).unwrap(); + let alice_pki = KeyRegistry::add_longterm_bundle(alice_pki, bob, bob_prekeys.clone()).unwrap(); + let alice_pki = + KeyRegistry::add_longterm_bundle(alice_pki, charlie, charlie_prekeys.clone()).unwrap(); + + let bob_pki = KeyRegistry::add_longterm_bundle(bob_pki, alice, alice_prekeys.clone()).unwrap(); + let bob_pki = KeyRegistry::add_longterm_bundle(bob_pki, bob, bob_prekeys.clone()).unwrap(); + let bob_pki = + KeyRegistry::add_longterm_bundle(bob_pki, charlie, charlie_prekeys.clone()).unwrap(); + + let charlie_pki = + KeyRegistry::add_longterm_bundle(charlie_pki, alice, alice_prekeys.clone()).unwrap(); + let charlie_pki = + KeyRegistry::add_longterm_bundle(charlie_pki, bob, bob_prekeys.clone()).unwrap(); + let charlie_pki = + KeyRegistry::add_longterm_bundle(charlie_pki, charlie, charlie_prekeys.clone()).unwrap(); + + // Initialise DCGKA states. + + let alice_bundle = SecretBundle::init(); + let alice_dcgka: TestDcgkaState = Dcgka::init(alice, alice_keys, alice_pki, alice_dgm); + + let bob_bundle = SecretBundle::init(); + let bob_dcgka: TestDcgkaState = Dcgka::init(bob, bob_keys, bob_pki, bob_dgm); + + let charlie_bundle = SecretBundle::init(); + let charlie_dcgka: TestDcgkaState = + Dcgka::init(charlie, charlie_keys, charlie_pki, charlie_dgm); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Alice creates a group with Bob + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + let alice_group_secret_0 = SecretBundle::generate(&alice_bundle, &rng).unwrap(); + let (alice_dcgka, output) = + Dcgka::create(alice_dcgka, vec![alice, bob], &alice_group_secret_0, &rng).unwrap(); + let (alice_dcgka, _) = Dcgka::process( + alice_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + control_message: output.control_message.clone(), + direct_message: None, + }, + ) + .unwrap(); + let alice_bundle = SecretBundle::insert(alice_bundle, alice_group_secret_0.clone()); + assert_eq!(alice_bundle.len(), 1); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Bob processes Alice's "create" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + assert_eq!(output.control_message.to_string(), "create"); + + let direct_message = output + .direct_messages + .into_iter() + .find(|dm| dm.recipient == bob) + .expect("direct message for bob"); + + let (bob_dcgka, output) = Dcgka::process( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + control_message: output.control_message.clone(), + direct_message: Some(direct_message), + }, + ) + .unwrap(); + + let GroupSecretOutput::Secret(bob_group_secret_0) = output else { + panic!("expected group secret"); + }; + let bob_bundle = SecretBundle::insert(bob_bundle, bob_group_secret_0.clone()); + assert_eq!(bob_bundle.len(), 1); + + // Alice and bob share the same group secret. + assert_eq!(alice_group_secret_0, bob_group_secret_0); + assert_eq!(alice_bundle, bob_bundle); + + // ~~~~~~~~~~~~~~~~ + // Bob adds Charlie + // ~~~~~~~~~~~~~~~~ + + let (bob_dcgka, add_output) = Dcgka::add(bob_dcgka, charlie, &bob_bundle, &rng).unwrap(); + let (bob_dcgka, _) = Dcgka::process( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: bob, + seq: 0, + }, + sender: bob, + control_message: add_output.control_message.clone(), + direct_message: None, + }, + ) + .unwrap(); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Charlie processes Bob's "add" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + assert_eq!(add_output.control_message.to_string(), "add"); + + let direct_message = add_output + .direct_messages + .into_iter() + .find(|dm| dm.recipient == charlie) + .expect("direct message for charlie"); + + let (charlie_dcgka, output) = Dcgka::process( + charlie_dcgka, + ProcessInput { + seq: MessageId { + sender: bob, + seq: 0, + }, + sender: bob, + control_message: add_output.control_message.clone(), + direct_message: Some(direct_message), + }, + ) + .unwrap(); + + let GroupSecretOutput::Bundle(charlie_secret_bundle_0) = output else { + panic!("expected group secret bundle"); + }; + let charlie_bundle = SecretBundle::extend(charlie_bundle, charlie_secret_bundle_0.clone()); + assert_eq!(charlie_bundle.len(), 1); + + // Alice, Bob and Charlie share the same secrets. + assert_eq!(alice_bundle, bob_bundle); + assert_eq!(alice_bundle, charlie_bundle); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Alice processes Bob's "add" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + let (alice_dcgka, output) = Dcgka::process( + alice_dcgka, + ProcessInput { + seq: MessageId { + sender: bob, + seq: 0, + }, + sender: bob, + control_message: add_output.control_message, + direct_message: None, + }, + ) + .unwrap(); + assert_eq!(output, GroupSecretOutput::None); + + // ~~~~~~~~~~~~~~~~~~~~~~~ + // Alice updates the group + // ~~~~~~~~~~~~~~~~~~~~~~~ + + let alice_group_secret_1 = SecretBundle::generate(&alice_bundle, &rng).unwrap(); + let (alice_dcgka, update_output) = + Dcgka::update(alice_dcgka, &alice_group_secret_1, &rng).unwrap(); + let (alice_dcgka, _) = Dcgka::process( + alice_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + control_message: update_output.control_message.clone(), + direct_message: None, + }, + ) + .unwrap(); + assert_eq!(update_output.direct_messages.len(), 2); // dm's for Bob and Charlie + + let alice_bundle = SecretBundle::insert(alice_bundle, alice_group_secret_1.clone()); + assert_eq!(alice_bundle.len(), 2); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Bob processes Alice's "update" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + assert_eq!(update_output.control_message.to_string(), "update"); + + let direct_message = update_output + .direct_messages + .iter() + .find(|dm| dm.recipient == bob) + .expect("direct message for bob"); + + let (bob_dcgka, output) = Dcgka::process( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + control_message: update_output.control_message.clone(), + direct_message: Some(direct_message.clone()), + }, + ) + .unwrap(); + + let GroupSecretOutput::Secret(bob_group_secret_1) = output else { + panic!("expected group secret"); + }; + let bob_bundle = SecretBundle::insert(bob_bundle, bob_group_secret_1.clone()); + assert_eq!(bob_bundle.len(), 2); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Charlie processes Alice's "update" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + let direct_message = update_output + .direct_messages + .into_iter() + .find(|dm| dm.recipient == charlie) + .expect("direct message for charlie"); + + let (charlie_dcgka, output) = Dcgka::process( + charlie_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + control_message: update_output.control_message.clone(), + direct_message: Some(direct_message.clone()), + }, + ) + .unwrap(); + + let GroupSecretOutput::Secret(charlie_group_secret_1) = output else { + panic!("expected group secret"); + }; + let charlie_bundle = SecretBundle::insert(charlie_bundle, charlie_group_secret_1.clone()); + assert_eq!(charlie_bundle.len(), 2); + + // Alice, Bob and Charlie share the same secrets. + assert_eq!(alice_bundle, bob_bundle); + assert_eq!(alice_bundle, charlie_bundle); + assert_eq!(alice_bundle.latest(), bob_bundle.latest()); + assert_eq!(charlie_bundle.latest(), bob_bundle.latest()); + + // ~~~~~~~~~~~~~~~~~~~~~ + // Charlie removes Alice + // ~~~~~~~~~~~~~~~~~~~~~ + + let charlie_group_secret_2 = SecretBundle::generate(&charlie_bundle, &rng).unwrap(); + let (charlie_dcgka, remove_output) = + Dcgka::remove(charlie_dcgka, alice, &charlie_group_secret_2, &rng).unwrap(); + let (_charlie_dcgka, _) = Dcgka::process( + charlie_dcgka, + ProcessInput { + seq: MessageId { + sender: charlie, + seq: 0, + }, + sender: charlie, + control_message: remove_output.control_message.clone(), + direct_message: None, + }, + ) + .unwrap(); + + assert_eq!(remove_output.direct_messages.len(), 1); + + let charlie_bundle = SecretBundle::insert(charlie_bundle, charlie_group_secret_2.clone()); + assert_eq!(charlie_bundle.len(), 3); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Bob processes Charlie's "remove" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + assert_eq!(remove_output.control_message.to_string(), "remove"); + + let direct_message = remove_output + .direct_messages + .into_iter() + .find(|dm| dm.recipient == bob) + .expect("direct message for bob"); + + let (_bob_dcgka, output) = Dcgka::process( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: charlie, + seq: 0, + }, + sender: charlie, + control_message: remove_output.control_message.clone(), + direct_message: Some(direct_message.clone()), + }, + ) + .unwrap(); + + let GroupSecretOutput::Secret(bob_group_secret_2) = output else { + panic!("expected group secret"); + }; + let bob_bundle = SecretBundle::insert(bob_bundle, bob_group_secret_2.clone()); + assert_eq!(bob_bundle.len(), 3); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Alice tries to process Charlie's "remove" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + std::assert_matches!( + Dcgka::process( + alice_dcgka, + ProcessInput { + seq: MessageId { + sender: charlie, + seq: 0, + }, + sender: charlie, + control_message: remove_output.control_message, + direct_message: Some(direct_message), + }, + ), + Err(DcgkaError::NotOurDirectMessage(_, _)) + ); + + // Bob and Charlie share the same secrets. + assert_eq!(charlie_bundle, bob_bundle); + assert_eq!(charlie_bundle.latest(), bob_bundle.latest()); + + // Alice does not share the latest secrets with Bob and Charlie. + assert_ne!(alice_bundle.latest(), bob_bundle.latest()); + assert_ne!(alice_bundle.latest(), charlie_bundle.latest()); +} + +#[test] +fn not_required_key_bundle_on_process_create() { + let rng = Rng::from_seed([1; 32]); + + let alice = 0; + let bob = 1; + + // Alice initialises their key material. + + let alice_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let alice_dgm = TestDgm::init(alice); + let alice_pki = KeyRegistry::init(); + let alice_keys = + KeyManager::init_and_generate_prekey(&alice_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let alice_prekeys = KeyManager::prekey_bundle(&alice_keys).unwrap(); + + // Bob initialises their key material. + + let bob_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let bob_dgm = TestDgm::init(bob); + let bob_pki = KeyRegistry::init(); + let bob_keys = + KeyManager::init_and_generate_prekey(&bob_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let bob_prekeys = KeyManager::prekey_bundle(&bob_keys).unwrap(); + + // Register key bundles. + + // Alice registers their own and Bob's pre-key bundles. + let alice_pki = KeyRegistry::add_longterm_bundle(alice_pki, alice, alice_prekeys).unwrap(); + let alice_pki = KeyRegistry::add_longterm_bundle(alice_pki, bob, bob_prekeys.clone()).unwrap(); + + // Bob registers their own, but not Alice's pre-key bundle. + let bob_pki = KeyRegistry::add_longterm_bundle(bob_pki, bob, bob_prekeys).unwrap(); + + // Initialise DCGKA states. + + let alice_bundle = SecretBundle::init(); + let alice_dcgka: TestDcgkaState = Dcgka::init(alice, alice_keys, alice_pki, alice_dgm); + + let bob_bundle = SecretBundle::init(); + let bob_dcgka: TestDcgkaState = Dcgka::init(bob, bob_keys, bob_pki, bob_dgm); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Alice creates a group with Bob + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + let alice_group_secret_0 = SecretBundle::generate(&alice_bundle, &rng).unwrap(); + let (alice_dcgka, output) = + Dcgka::create(alice_dcgka, vec![alice, bob], &alice_group_secret_0, &rng).unwrap(); + let (_alice_dcgka, _) = Dcgka::process( + alice_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + control_message: output.control_message.clone(), + direct_message: None, + }, + ) + .unwrap(); + let alice_bundle = SecretBundle::insert(alice_bundle, alice_group_secret_0.clone()); + assert_eq!(alice_bundle.len(), 1); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Bob processes Alice's "create" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + assert_eq!(output.control_message.to_string(), "create"); + + let direct_message = output + .direct_messages + .into_iter() + .find(|dm| dm.recipient == bob) + .expect("direct message for bob"); + + let (_bob_dcgka, output) = Dcgka::process( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + control_message: output.control_message.clone(), + direct_message: Some(direct_message), + }, + ) + .unwrap(); + + let GroupSecretOutput::Secret(bob_group_secret_0) = output else { + panic!("expected group secret"); + }; + let bob_bundle = SecretBundle::insert(bob_bundle, bob_group_secret_0.clone()); + assert_eq!(bob_bundle.len(), 1); + + // Alice and bob share the same group secret. + assert_eq!(alice_group_secret_0, bob_group_secret_0); + assert_eq!(alice_bundle, bob_bundle); +} + +#[test] +fn not_required_key_bundle_on_process_add() { + let rng = Rng::from_seed([1; 32]); + + let alice = 0; + let bob = 1; + + // Alice initialises their key material. + + let alice_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let alice_dgm = TestDgm::init(alice); + let alice_pki = KeyRegistry::init(); + let alice_keys = + KeyManager::init_and_generate_prekey(&alice_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let alice_prekeys = KeyManager::prekey_bundle(&alice_keys).unwrap(); + + // Bob initialises their key material. + + let bob_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let bob_dgm = TestDgm::init(bob); + let bob_pki = KeyRegistry::init(); + let bob_keys = + KeyManager::init_and_generate_prekey(&bob_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let bob_prekeys = KeyManager::prekey_bundle(&bob_keys).unwrap(); + + // Register key bundles. + + // Alice registers their own and Bob's pre-key bundles. + let alice_pki = KeyRegistry::add_longterm_bundle(alice_pki, alice, alice_prekeys).unwrap(); + let alice_pki = KeyRegistry::add_longterm_bundle(alice_pki, bob, bob_prekeys.clone()).unwrap(); + + // Bob registers their own, but not Alice's pre-key bundle. + let bob_pki = KeyRegistry::add_longterm_bundle(bob_pki, bob, bob_prekeys).unwrap(); + + // Initialise DCGKA states. + + let alice_bundle = SecretBundle::init(); + let alice_dcgka: TestDcgkaState = Dcgka::init(alice, alice_keys, alice_pki, alice_dgm); + + let bob_bundle = SecretBundle::init(); + let bob_dcgka: TestDcgkaState = Dcgka::init(bob, bob_keys, bob_pki, bob_dgm); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Alice creates a group + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + let alice_group_secret_0 = SecretBundle::generate(&alice_bundle, &rng).unwrap(); + let (alice_dcgka, output) = + Dcgka::create(alice_dcgka, vec![alice], &alice_group_secret_0, &rng).unwrap(); + let (alice_dcgka, _) = Dcgka::process( + alice_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + control_message: output.control_message.clone(), + direct_message: None, + }, + ) + .unwrap(); + let alice_bundle = SecretBundle::insert(alice_bundle, alice_group_secret_0.clone()); + assert_eq!(alice_bundle.len(), 1); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Bob processes Alice's "create" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + assert_eq!(output.control_message.to_string(), "create"); + + let (bob_dcgka, _output) = Dcgka::process( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + control_message: output.control_message.clone(), + direct_message: None, + }, + ) + .unwrap(); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Alice adds Bob to the group + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + let _ = SecretBundle::generate(&alice_bundle, &rng).unwrap(); + let (alice_dcgka, output) = Dcgka::add(alice_dcgka, bob, &alice_bundle, &rng).unwrap(); + let (_alice_dcgka, _) = Dcgka::process( + alice_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + control_message: output.control_message.clone(), + direct_message: None, + }, + ) + .unwrap(); + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Bob processes Alice's "add" message + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + assert_eq!(output.control_message.to_string(), "add"); + + let direct_message = output + .direct_messages + .into_iter() + .find(|dm| dm.recipient == bob) + .expect("direct message for bob"); + + let (_bob_dcgka, output) = Dcgka::process( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + control_message: output.control_message.clone(), + direct_message: Some(direct_message), + }, + ) + .unwrap(); + + let GroupSecretOutput::Bundle(bob_secret_bundle_0) = output else { + panic!("expected group secret bundle"); + }; + let bob_bundle = SecretBundle::extend(bob_bundle, bob_secret_bundle_0.clone()); + assert_eq!(bob_bundle.len(), 1); +} + +/// The joiner applies its own add after the welcome, so the welcome's roster, which predates the +/// add, does not leave it out. Without that the joiner is never welcomed and reads nothing (the +/// membership fix, P4.2). Uses the stock `TestDgm`. +#[test] +fn joiner_is_welcomed_and_reads_messages_after_the_add() { + let mut network = crate::data_scheme::test_utils::network::Network::new( + [0, 1, 2, 3], + Rng::from_seed([4; 32]), + ); + network.create(0, vec![0, 1, 2]); + network.process(); + + network.add(0, 3); + network.process(); + assert_eq!( + network.members(&3), + vec![0, 1, 2, 3], + "the joiner's roster lists the joiner" + ); + + network.send(1, b"after the join"); + let decrypted = network.process(); + assert!( + decrypted.contains(&(1, 3, b"after the join".to_vec())), + "the joiner reads a message sent after its add: {decrypted:?}" + ); +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/key_bundle/key_bundle.rs b/pkgs/id/vendor/p2panda-encryption/src/key_bundle/key_bundle.rs new file mode 100644 index 0000000000..30854403d2 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/key_bundle/key_bundle.rs @@ -0,0 +1,285 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::x25519::PublicKey; +use crate::crypto::xeddsa::{XEdDSAError, XSignature, xeddsa_verify}; +use crate::key_bundle::{Lifetime, LifetimeError, OneTimePreKey, OneTimePreKeyId, PreKey}; +use crate::traits::KeyBundle; + +/// Key-bundle with public keys to be used exactly _once_. +/// +/// Note that while pre-keys are signed for X3DH, bundles should be part of an authenticated +/// messaging format where the whole payload (and thus it's lifetime and one-time pre-key) is +/// signed by the same identity to prevent replay and impersonation attacks. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OneTimeKeyBundle { + identity_key: PublicKey, + signed_prekey: PreKey, + prekey_signature: XSignature, + onetime_prekey: Option, +} + +impl OneTimeKeyBundle { + pub fn new( + identity_key: PublicKey, + signed_prekey: PreKey, + prekey_signature: XSignature, + onetime_prekey: Option, + ) -> Self { + Self { + identity_key, + signed_prekey, + prekey_signature, + onetime_prekey, + } + } +} + +impl KeyBundle for OneTimeKeyBundle { + fn identity_key(&self) -> &PublicKey { + &self.identity_key + } + + fn signed_prekey(&self) -> &PublicKey { + self.signed_prekey.key() + } + + fn onetime_prekey(&self) -> Option<&PublicKey> { + self.onetime_prekey.as_ref().map(|key| key.key()) + } + + fn onetime_prekey_id(&self) -> Option { + self.onetime_prekey.as_ref().map(|key| key.id()) + } + + fn lifetime(&self) -> &Lifetime { + self.signed_prekey.lifetime() + } + + fn verify(&self) -> Result<(), KeyBundleError> { + // Check lifetime. + self.signed_prekey.verify_lifetime()?; + + // Check signature. + xeddsa_verify( + self.signed_prekey.as_bytes(), + &self.identity_key, + &self.prekey_signature, + )?; + + Ok(()) + } +} + +/// Key-bundle with public keys to be used until the pre-key expired. +/// +/// Note that while pre-keys are signed for X3DH, bundles should be part of an authenticated +/// messaging format where the whole payload (and thus it's lifetime) is signed by the same +/// identity to prevent replay and impersonation attacks. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LongTermKeyBundle { + identity_key: PublicKey, + signed_prekey: PreKey, + prekey_signature: XSignature, +} + +impl LongTermKeyBundle { + pub fn new( + identity_key: PublicKey, + signed_prekey: PreKey, + prekey_signature: XSignature, + ) -> Self { + Self { + identity_key, + signed_prekey, + prekey_signature, + } + } +} + +impl KeyBundle for LongTermKeyBundle { + fn identity_key(&self) -> &PublicKey { + &self.identity_key + } + + fn signed_prekey(&self) -> &PublicKey { + self.signed_prekey.key() + } + + fn onetime_prekey(&self) -> Option<&PublicKey> { + // No one-time pre-key in long-term key bundle. + None + } + + fn onetime_prekey_id(&self) -> Option { + // No one-time pre-key in long-term key bundle. + None + } + + fn lifetime(&self) -> &Lifetime { + self.signed_prekey.lifetime() + } + + fn verify(&self) -> Result<(), KeyBundleError> { + // Check lifetime. + self.signed_prekey.verify_lifetime()?; + + // Check signature. + xeddsa_verify( + self.signed_prekey.as_bytes(), + &self.identity_key, + &self.prekey_signature, + )?; + + Ok(()) + } +} + +/// Helper method to identify the "latest" (valid and with furthest expiry date) key bundle from a +/// set. Returns `None` if no valid bundle was given. +pub fn latest_key_bundle<'a, KB>(bundles: &'a [KB]) -> Option<&'a KB> +where + KB: KeyBundle, +{ + let mut latest: Option<&'a KB> = None; + + for bundle in bundles { + // Remove all prekeys which are _too early_ or _too late_ (expired). + // + // Now + // too late --> [---] | + // | [----] <-- too early + // [-----|----] <-- valid + // | + // + // t --> + // + if bundle.lifetime().verify().is_err() { + continue; + } + + // Of all other, valid ones, find the one which has the "furthest" expiry date and is + // therefore the "latest" key bundle. + // + // Now + // | + // [-|---------] + // [-----|------------] <-- "latest" + // [---------|-----] + // | + // + // t --> + // + match latest { + Some(current_bundle) => { + if bundle.lifetime() > current_bundle.lifetime() { + latest = Some(bundle); + } + } + None => { + latest = Some(bundle); + } + } + } + + latest +} + +#[derive(Debug, Error)] +pub enum KeyBundleError { + #[error(transparent)] + XEdDSA(#[from] XEdDSAError), + + #[error(transparent)] + Lifetime(#[from] LifetimeError), + + #[error("no key bundles found")] + KeyBundlesNotFound, +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + use crate::crypto::x25519::SecretKey; + use crate::crypto::xeddsa::xeddsa_sign; + use crate::key_bundle::{Lifetime, LongTermKeyBundle, OneTimePreKey, PreKey}; + use crate::traits::KeyBundle; + + use super::OneTimeKeyBundle; + + #[test] + fn verify() { + let rng = Rng::from_seed([1; 32]); + + let secret_key = SecretKey::from_bytes(rng.random_array().unwrap()); + let identity_key = secret_key.verifying_key().unwrap(); + + let signed_prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let signed_prekey = PreKey::new( + signed_prekey_secret.verifying_key().unwrap(), + Lifetime::default(), + ); + let prekey_signature = xeddsa_sign(signed_prekey.as_bytes(), &secret_key, &rng).unwrap(); + + let onetime_prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let onetime_prekey = OneTimePreKey::new(onetime_prekey_secret.verifying_key().unwrap(), 1); + + // Valid key-bundles. + assert!( + OneTimeKeyBundle::new( + identity_key, + signed_prekey, + prekey_signature, + Some(onetime_prekey.clone()), + ) + .verify() + .is_ok() + ); + assert!( + LongTermKeyBundle::new(identity_key, signed_prekey, prekey_signature) + .verify() + .is_ok() + ); + + // Invalid lifetime of pre-key. + let signed_prekey = PreKey::new( + signed_prekey_secret.verifying_key().unwrap(), + Lifetime::from_range(0, 0), + ); + assert!( + OneTimeKeyBundle::new( + identity_key, + signed_prekey, + prekey_signature, + Some(onetime_prekey.clone()), + ) + .verify() + .is_err() + ); + assert!( + LongTermKeyBundle::new(identity_key, signed_prekey, prekey_signature) + .verify() + .is_err() + ); + + // Invalid signature of pre-key. + let prekey_signature = xeddsa_sign(b"wrong payload", &secret_key, &rng).unwrap(); + assert!( + OneTimeKeyBundle::new( + identity_key, + signed_prekey, + prekey_signature, + Some(onetime_prekey.clone()), + ) + .verify() + .is_err() + ); + assert!( + LongTermKeyBundle::new(identity_key, signed_prekey, prekey_signature) + .verify() + .is_err() + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/key_bundle/lifetime.rs b/pkgs/id/vendor/p2panda-encryption/src/key_bundle/lifetime.rs new file mode 100644 index 0000000000..4945ef8e71 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/key_bundle/lifetime.rs @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +/// Default lifetime which amounts to 3 * 28 Days, i.e. about 3 months. +const DEFAULT_LIFETIME: u64 = 60 * 60 * 24 * 28 * 3; + +/// The lifetime is extended into the past to allow for skewed clocks. The value is in seconds and +/// amounts to 1h. +const DEFAULT_LIFETIME_MARGIN: u64 = 60 * 60; + +/// Determines the lifetime of a pre-key by defining a time range. +/// +/// Implementations should reject received messages with expired pre-keys and disallow use. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Lifetime { + not_before: u64, + not_after: u64, +} + +impl Lifetime { + /// Create a new lifetime in seconds from now on. + /// + /// Note that the lifetime is extended 1h into the past to adapt to skewed clocks, i.e. + /// `not_before` is set to `now - 1h`. + pub fn new(t: u64) -> Self { + let lifetime_margin: u64 = DEFAULT_LIFETIME_MARGIN; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + let not_before = now - lifetime_margin; + let not_after = now + t; + Self { + not_before, + not_after, + } + } + + /// Returns true if this lifetime is valid. + pub fn verify(&self) -> Result<(), LifetimeError> { + let is_valid = match SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_secs()) + { + Ok(elapsed) => self.not_before < elapsed && elapsed < self.not_after, + Err(err) => return Err(LifetimeError::SystemTime(err)), + }; + + if is_valid { + Ok(()) + } else { + Err(LifetimeError::InvalidLifetime) + } + } + + /// Returns true if this lifetime with an additional window is valid. + /// + /// This method can be used to calculate if a lifetime _is about_ to expire, given a defined + /// time "window". + /// + /// ```plain + /// [-------] + /// | | + /// Lifetime: [---|----] | + /// | | + /// now + window + /// + /// -- t --> + /// ``` + pub fn verify_with_window(&self, window: Duration) -> Result<(), LifetimeError> { + let is_valid = match SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_secs()) + { + Ok(elapsed) => { + let elapsed = elapsed + window.as_secs(); + self.not_before < elapsed && elapsed < self.not_after + } + Err(err) => return Err(LifetimeError::SystemTime(err)), + }; + + if is_valid { + Ok(()) + } else { + Err(LifetimeError::InvalidLifetime) + } + } +} + +impl Default for Lifetime { + fn default() -> Self { + Lifetime::new(DEFAULT_LIFETIME) + } +} + +impl Ord for Lifetime { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.not_after.cmp(&other.not_after) + } +} + +impl PartialOrd for Lifetime { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +#[cfg(any(test, feature = "test_utils"))] +impl Lifetime { + pub fn from_range(not_before: u64, not_after: u64) -> Self { + Self { + not_before, + not_after, + } + } +} + +#[derive(Debug, Error)] +pub enum LifetimeError { + #[error("lifetime of pre-key is not valid")] + InvalidLifetime, + + #[error(transparent)] + SystemTime(std::time::SystemTimeError), +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + use super::Lifetime; + + #[test] + fn order() { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + + let lifetime_1 = Lifetime::from_range(now - 60, now + 30); + let lifetime_2 = Lifetime::from_range(now - 30, now + 60); + + assert!(lifetime_1 < lifetime_2); + assert!(lifetime_1 != lifetime_2); + } + + #[test] + fn verify() { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + + // Default lifetimes are correct. + let lifetime = Lifetime::default(); + assert!(lifetime.verify().is_ok()); + + // Lifetimes of a minute are correct. + let lifetime = Lifetime::new(60); + assert!(lifetime.verify().is_ok()); + assert!( + lifetime + .verify_with_window(Duration::from_secs(120)) + .is_err() + ); + + // Test interface for lifetime is correct. + let lifetime = Lifetime::from_range(now - 60, now + 60); + assert!(lifetime.verify().is_ok()); + + // Invalid lifetimes throw an error. + let lifetime = Lifetime::from_range(now + 60, now + 60); // too early + assert!(lifetime.verify().is_err()); + + let lifetime = Lifetime::from_range(now - 120, now - 60); // too late + assert!(lifetime.verify().is_err()); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/key_bundle/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/key_bundle/mod.rs new file mode 100644 index 0000000000..240f26f369 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/key_bundle/mod.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Key bundles to asynchronously receive encrypted data from others. +//! +//! This is for asynchronous settings where one user ("Bob") is offline but has published a key +//! bundle (containing their identity key, pre-keys, etc.) beforehands. Another user ("Alice") +//! wants to use that information to send encrypted data to Bob. +//! +//! Depending on the security of the chat group this key bundle should be _used only once_ with +//! [`OneTimeKeyBundle`] or only within a given "lifetime" (one day, two weeks, etc.) with +//! [`LongTermKeyBundle`]. Members need to make sure that there are always fresh key bundles from +//! them available in the network for others. +//! +//! ## Forward secrecy +//! +//! Some applications might have very strong forward secrecy requirements and only allow "one-time" +//! pre-keys per group. This means that we can only establish a Forward Secure (FS) communication +//! channel with a peer if we reliably made sure to only use the pre-key exactly once. This is hard +//! to guarantee in a decentralised setting. If we don’t care about very strong FS we can ease up +//! on that requirement a little bit and tolerate re-use with longer-living pre-keys which get +//! rotated frequently (every week for example). +//! +//! ## Public-key infrastructure (PKI) +//! +//! We assume that encrypted groups with strong FS guarantees using one-time key bundles only get +//! established when peers have explicitly exchanged their one-time pre-keys with each other, for +//! example in form of scanning QR codes. +//! +//! Another solution for very strong forward secrecy, where we can make sure the pre-key is only +//! used once, is a "bilateral session state establishment" process where peers can only establish +//! a group chat with each other after both parties have been online. They don't need to be online +//! at the same time, just to be online at least once and receive the messages of the other party. +//! This puts a slight restriction on the "offline-first" nature for peer-to-peer applications. +//! +//! Another solution is to rely on always-online and trusted key servers which maintain the +//! pre-keys for the network, but this puts an unnecessary centralisation point into the system and +//! seems even worse. +//! +//! For longer-living ("long-term") pre-key bundles we can lift the strict "use once" requirement +//! and peers can regularly publish fresh key bundles on the network, other peers need to make +//! sure they keep collecting the latest bundles regularly. +//! +//! ## Authenticated Messaging +//! +//! Note that while pre-keys are signed, bundles should be part of an authenticated messaging +//! scheme where the whole payload (and thus it's lifetime and maybe one-time pre-key) is signed by +//! the same identity to prevent replay- and impersonation attacks. +//! +//! Otherwise attackers might be able to re-play the same pre-key with different lifetimes. +#[allow(clippy::module_inception)] +mod key_bundle; +mod lifetime; +mod prekey; + +pub use key_bundle::{KeyBundleError, LongTermKeyBundle, OneTimeKeyBundle, latest_key_bundle}; +pub use lifetime::{Lifetime, LifetimeError}; +pub use prekey::{OneTimePreKey, OneTimePreKeyId, PreKey, PreKeyId, latest_prekey}; diff --git a/pkgs/id/vendor/p2panda-encryption/src/key_bundle/prekey.rs b/pkgs/id/vendor/p2panda-encryption/src/key_bundle/prekey.rs new file mode 100644 index 0000000000..a98058b6ca --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/key_bundle/prekey.rs @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use serde::{Deserialize, Serialize}; + +use crate::crypto::Rng; +use crate::crypto::x25519::{PUBLIC_KEY_SIZE, PublicKey, SecretKey}; +use crate::crypto::xeddsa::{XEdDSAError, XSignature, xeddsa_sign}; +use crate::key_bundle::{Lifetime, LifetimeError}; + +/// Pre-key with key material for X3DH key agreement to be used until it's lifetime has expired. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PreKey(PublicKey, Lifetime); + +/// Unique identifier of a member's pre-key which can be used to address long-term key bundles. +pub type PreKeyId = PublicKey; + +impl PreKey { + pub fn new(prekey: PublicKey, lifetime: Lifetime) -> Self { + Self(prekey, lifetime) + } + + pub fn key(&self) -> &PublicKey { + &self.0 + } + + pub fn as_bytes(&self) -> &[u8; PUBLIC_KEY_SIZE] { + self.0.as_bytes() + } + + pub fn to_bytes(self) -> [u8; PUBLIC_KEY_SIZE] { + self.0.to_bytes() + } + + pub fn sign(&self, secret_key: &SecretKey, rng: &Rng) -> Result { + xeddsa_sign(self.0.as_bytes(), secret_key, rng) + } + + pub fn lifetime(&self) -> &Lifetime { + &self.1 + } + + pub fn verify_lifetime(&self) -> Result<(), LifetimeError> { + self.1.verify() + } +} + +/// Unique identifier of a member's one-time pre-key. +pub type OneTimePreKeyId = u64; + +/// Pre-key with key material for X3DH key agreement to be used exactly _once_. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OneTimePreKey(PublicKey, OneTimePreKeyId); + +impl OneTimePreKey { + pub fn new(onetime_prekey: PublicKey, id: OneTimePreKeyId) -> Self { + Self(onetime_prekey, id) + } + + pub fn key(&self) -> &PublicKey { + &self.0 + } + + pub fn id(&self) -> OneTimePreKeyId { + self.1 + } + + pub fn as_bytes(&self) -> &[u8; PUBLIC_KEY_SIZE] { + self.0.as_bytes() + } + + pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_SIZE] { + self.0.to_bytes() + } +} + +/// Helper method to identify the "latest" (valid and with furthest expiry date) pre-key from a +/// set. Returns `None` if no valid key was given. +pub fn latest_prekey<'a>(prekeys: Vec<&'a PreKey>) -> Option<&'a PreKey> { + let mut latest: Option<&'a PreKey> = None; + + for prekey in prekeys { + // Remove all prekeys which are _too early_ or _too late_ (expired). + // + // Now + // too late --> [---] | + // | [----] <-- too early + // [-----|----] <-- valid + // | + // + // t --> + // + if prekey.lifetime().verify().is_err() { + continue; + } + + // Of all other, valid ones, find the one which has the "furthest" expiry date and is + // therefore the "latest" key bundle. + // + // Now + // | + // [-|---------] + // [-----|------------] <-- "latest" + // [---------|-----] + // | + // + // t --> + // + match latest { + Some(current_prekey) => { + if prekey.lifetime() > current_prekey.lifetime() { + latest = Some(prekey); + } + } + None => { + latest = Some(prekey); + } + } + } + + latest +} + +#[cfg(test)] +mod tests { + use std::time::{SystemTime, UNIX_EPOCH}; + + use crate::Rng; + use crate::crypto::x25519::SecretKey; + use crate::key_bundle::Lifetime; + + use super::PreKey; + + #[test] + fn latest_prekey() { + let rng = Rng::from_seed([1; 32]); + let public_key = SecretKey::from_rng(&rng).unwrap().verifying_key().unwrap(); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + + // NOW + // ===|=== (1) + // =|====== (2) <-- "latest" + // | === (3) + let prekey_1 = PreKey::new(public_key, Lifetime::from_range(now - 30, now + 30)); + let prekey_2 = PreKey::new(public_key, Lifetime::from_range(now - 10, now + 60)); + let prekey_3 = PreKey::new(public_key, Lifetime::from_range(now + 60, now + 90)); + + let result = super::latest_prekey(vec![&prekey_1, &prekey_2, &prekey_3]); + assert_eq!(result, Some(&prekey_2)); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/key_manager.rs b/pkgs/id/vendor/p2panda-encryption/src/key_manager.rs new file mode 100644 index 0000000000..5d97748ab2 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/key_manager.rs @@ -0,0 +1,470 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Manager for our own secret key material. +//! +//! Peers should automatically rotate their key bundles if the lifetime is close to expiring. It is +//! recommended to do this in good time before the actual expiration date to allow others to +//! receive it even when the network is unstable or peers are longer offline. +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::x25519::{PublicKey, SecretKey, X25519Error}; +use crate::crypto::xeddsa::{XEdDSAError, XSignature}; +use crate::crypto::{Rng, RngError}; +use crate::key_bundle::{ + Lifetime, LongTermKeyBundle, OneTimeKeyBundle, OneTimePreKey, OneTimePreKeyId, PreKey, + PreKeyId, latest_prekey, +}; +use crate::traits::{IdentityManager, PreKeyManager}; + +/// Key manager to maintain secret key material (like our identity key) and to generate signed +/// public pre-key bundles. +#[derive(Clone, Debug)] +pub struct KeyManager; + +/// Serializable state of key manager. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct KeyManagerState { + identity_secret: SecretKey, + identity_key: PublicKey, + prekeys: PreKeyBundlesState, + // @TODO(adz): Could make sense to factor out one-time secrets into a similar structure like + // pre-keys as well, so they can be independently handled in a storage layer. + onetime_secrets: HashMap, + onetime_next_id: OneTimePreKeyId, +} + +impl KeyManagerState { + pub fn prekey_bundles(&self) -> &PreKeyBundlesState { + &self.prekeys + } +} + +/// Collection of all known, publishable pre-keys with their regarding secrets and signatures in +/// this key manager. Offers a form of "garbage collection" to automatically remove expired +/// pre-keys. +/// +/// This can be serialized and independently stored from the identity secrets. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PreKeyBundlesState(HashMap); + +impl PreKeyBundlesState { + /// Initializes and returns new instance of pre-key bundles state. + fn new() -> Self { + Self::default() + } + + /// Returns latest pre-key if valid and available and `None` otherwise. + fn latest(&self) -> Option { + let prekeys = self.0.values().map(|state| &state.prekey).collect(); + let latest = latest_prekey(prekeys); + latest.map(|prekey| { + self.0 + .get(prekey.key()) + .expect("we know the item exists in the set") + .clone() + }) + } + + fn contains(&self, id: &PreKeyId) -> bool { + self.0.contains_key(id) + } + + #[allow(unused)] + fn len(&self) -> usize { + self.0.len() + } + + fn get(&self, id: &PreKeyId) -> Option<&PreKeyBundle> { + self.0.get(id) + } + + /// Insert pre-key bundle into set. + fn insert(mut self, bundle: PreKeyBundle) -> Self { + self.0.insert(bundle.id(), bundle); + self + } + + /// Remove all expired key bundles from manager. + #[allow(clippy::manual_retain)] + fn remove_expired(self) -> Self { + Self( + self.0 + .into_iter() + .filter(|(_, prekey)| prekey.prekey.verify_lifetime().is_ok()) + .collect(), + ) + } +} + +/// Extended pre-key struct holding the public and secret parts and signature, authenticating the +/// pre-key with an identity. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PreKeyBundle { + prekey: PreKey, + signature: XSignature, + secret: SecretKey, +} + +impl PreKeyBundle { + /// Generates, signs new pre-key and returns struct holding signature and pre-key secret + /// next to the public part. + pub fn new( + identity_secret: &SecretKey, + lifetime: Lifetime, + rng: &Rng, + ) -> Result { + let secret = SecretKey::from_bytes(rng.random_array()?); + let prekey = PreKey::new(secret.verifying_key()?, lifetime); + let signature = prekey.sign(identity_secret, rng)?; + + Ok(Self { + prekey, + signature, + secret, + }) + } + + pub fn id(&self) -> PreKeyId { + *self.prekey.key() + } + + pub fn lifetime(&self) -> &Lifetime { + self.prekey.lifetime() + } +} + +impl KeyManager { + /// Returns newly initialised key-manager state, holding our identity secret. + pub fn init(identity_secret: &SecretKey) -> Result { + Ok(KeyManagerState { + identity_key: identity_secret.verifying_key()?, + identity_secret: identity_secret.clone(), + prekeys: PreKeyBundlesState::new(), + onetime_secrets: HashMap::new(), + onetime_next_id: 0, + }) + } + + /// Returns newly initialised key-manager state, holding our identity secret with existing + /// pre-key bundles. + pub fn init_from_prekey_bundles( + identity_secret: &SecretKey, + prekeys: PreKeyBundlesState, + ) -> Result { + Ok(KeyManagerState { + identity_key: identity_secret.verifying_key()?, + identity_secret: identity_secret.clone(), + prekeys, + onetime_secrets: HashMap::new(), + onetime_next_id: 0, + }) + } + + /// Returns newly initialised key-manager state, holding our identity secret and an + /// automatically generated, first pre-key secret which can be used to generate key-bundles. + #[cfg(any(test, feature = "test_utils"))] + pub fn init_and_generate_prekey( + identity_secret: &SecretKey, + lifetime: Lifetime, + rng: &Rng, + ) -> Result { + let bundle = PreKeyBundle::new(identity_secret, lifetime, rng)?; + let prekeys = PreKeyBundlesState::new().insert(bundle); + + Ok(KeyManagerState { + identity_key: identity_secret.verifying_key()?, + identity_secret: identity_secret.clone(), + prekeys, + onetime_secrets: HashMap::new(), + onetime_next_id: 0, + }) + } + + /// Remove all expired pre-key bundles from manager. + #[allow(clippy::manual_retain)] + pub fn remove_expired(mut y: KeyManagerState) -> KeyManagerState { + // Remove all expired pre keys. + y.prekeys = y.prekeys.remove_expired(); + + // Remove one-time bundles which do not have a valid pre-key anymore. + y.onetime_secrets = y + .onetime_secrets + .into_iter() + .filter(|(_, (prekey_id, _))| y.prekeys.contains(prekey_id)) + .collect(); + + y + } +} + +impl IdentityManager for KeyManager { + /// Returns identity key secret. + fn identity_secret(y: &KeyManagerState) -> &SecretKey { + &y.identity_secret + } +} + +impl PreKeyManager for KeyManager { + type State = KeyManagerState; + + type Error = KeyManagerError; + + /// Returns long-term pre-key secret by id. + /// + /// Throws an error if pre-key was not found (for example because it expired and was removed). + fn prekey_secret<'a>( + y: &'a Self::State, + id: &'a PreKeyId, + ) -> Result<&'a SecretKey, Self::Error> { + match y.prekeys.get(id) { + Some(prekey) => Ok(&prekey.secret), + None => Err(KeyManagerError::UnknownPreKeySecret(*id)), + } + } + + /// Generates a new long-term pre-key secret with the given lifetime. + fn rotate_prekey( + mut y: Self::State, + lifetime: Lifetime, + rng: &Rng, + ) -> Result { + let prekey = PreKeyBundle::new(&y.identity_secret, lifetime, rng)?; + y.prekeys = y.prekeys.insert(prekey); + Ok(y) + } + + /// Returns latest, public long-term key-bundle which can be published on the network. + /// + /// Note that key bundles can be expired and thus invalid, this method will return an error in + /// this case and applications need to generate new ones when necessary. + fn prekey_bundle(y: &Self::State) -> Result { + y.prekeys + .latest() + .map(|latest| LongTermKeyBundle::new(y.identity_key, latest.prekey, latest.signature)) + .ok_or(KeyManagerError::NoPreKeysAvailable) + } + + /// Creates a new public one-time key-bundle. + fn generate_onetime_bundle( + mut y: Self::State, + rng: &Rng, + ) -> Result<(Self::State, OneTimeKeyBundle), Self::Error> { + let latest = y + .prekeys + .latest() + .ok_or(KeyManagerError::NoPreKeysAvailable)?; + + let onetime_secret = SecretKey::from_bytes(rng.random_array()?); + let onetime_key = OneTimePreKey::new(onetime_secret.verifying_key()?, y.onetime_next_id); + + { + let existing_key = y + .onetime_secrets + .insert(onetime_key.id(), (latest.id(), onetime_secret)); + // Sanity check. + assert!( + existing_key.is_none(), + "should never insert same id more than once" + ); + }; + + let bundle = OneTimeKeyBundle::new( + y.identity_key, + latest.prekey, + latest.signature, + Some(onetime_key), + ); + + y.onetime_next_id += 1; + + Ok((y, bundle)) + } + + /// Returns one-time pre-key secret used by a sender during X3DH. + /// + /// Throws an error when requested pre-key secret is unknown (and thus probably was already + /// used once). + /// + /// Returns none when this key-manager doesn't have any one-time pre-keys. New ones can be + /// created by calling `generate_onetime_bundle`. + fn use_onetime_secret( + mut y: Self::State, + id: OneTimePreKeyId, + ) -> Result<(Self::State, Option), Self::Error> { + match y.onetime_secrets.remove(&id) { + Some(secret) => Ok((y, Some(secret.1))), + None => Err(KeyManagerError::UnknownOneTimeSecret(id)), + } + } +} + +#[derive(Debug, Error)] +pub enum KeyManagerError { + #[error(transparent)] + Rng(#[from] RngError), + + #[error(transparent)] + XEdDSA(#[from] XEdDSAError), + + #[error(transparent)] + X25519(#[from] X25519Error), + + #[error("could not find one-time pre-key secret with id {0}")] + UnknownOneTimeSecret(OneTimePreKeyId), + + #[error("could not find pre-key secret with id {0}")] + UnknownPreKeySecret(PreKeyId), + + #[error("no valid pre-keys available, they are either expired or too early")] + NoPreKeysAvailable, +} + +#[cfg(test)] +mod tests { + use std::time::{SystemTime, UNIX_EPOCH}; + + use crate::crypto::Rng; + use crate::crypto::x25519::SecretKey; + use crate::key_bundle::Lifetime; + use crate::key_manager::KeyManagerError; + use crate::traits::KeyBundle; + + use super::{KeyManager, PreKeyManager}; + + #[test] + fn generate_onetime_keys() { + let rng = Rng::from_seed([1; 32]); + + let identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let state = + KeyManager::init_and_generate_prekey(&identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let (state, bundle_1) = KeyManager::generate_onetime_bundle(state, &rng).unwrap(); + let (state, bundle_2) = KeyManager::generate_onetime_bundle(state, &rng).unwrap(); + + // Prekey stays the same between each bundle and match the secret key. + assert_eq!( + bundle_1.signed_prekey(), + &KeyManager::prekey_secret(&state, bundle_1.signed_prekey()) + .expect("non-expired prekey exists") + .verifying_key() + .unwrap() + ); + assert_eq!(bundle_1.signed_prekey(), bundle_2.signed_prekey()); + + // Identity key matches the identity secret. + assert_eq!( + bundle_1.identity_key(), + &identity_secret.verifying_key().unwrap() + ); + assert_eq!( + bundle_2.identity_key(), + &identity_secret.verifying_key().unwrap() + ); + + // Signature is correct. + assert!(bundle_1.verify().is_ok()); + assert!(bundle_2.verify().is_ok()); + + let (state, onetime_secret_1) = + KeyManager::use_onetime_secret(state, bundle_1.onetime_prekey_id().unwrap()).unwrap(); + let (state, onetime_secret_2) = + KeyManager::use_onetime_secret(state, bundle_2.onetime_prekey_id().unwrap()).unwrap(); + + // Secrets got removed from state. + assert_eq!(state.onetime_secrets.len(), 0); + + // Retrieving unknown one-time prekeys throws an error. + assert!(KeyManager::use_onetime_secret(state.clone(), 42).is_err()); + + // Re-retrieving known one-time prekeys throws an error. + assert!( + KeyManager::use_onetime_secret(state.clone(), bundle_1.onetime_prekey_id().unwrap()) + .is_err() + ); + assert!( + KeyManager::use_onetime_secret(state.clone(), bundle_2.onetime_prekey_id().unwrap()) + .is_err() + ); + + // One-time prekeys match the secret. + assert_eq!( + bundle_1.onetime_prekey().unwrap(), + &onetime_secret_1.unwrap().verifying_key().unwrap() + ); + assert_eq!( + bundle_2.onetime_prekey().unwrap(), + &onetime_secret_2.unwrap().verifying_key().unwrap() + ); + + // One-time prekeys are unique. + assert_ne!(bundle_1.onetime_prekey(), bundle_2.onetime_prekey()); + assert_ne!(bundle_1.onetime_prekey_id(), bundle_2.onetime_prekey_id()); + } + + #[test] + fn expired_prekey_bundles() { + let rng = Rng::from_seed([1; 32]); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + + let identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let y = KeyManager::init_and_generate_prekey( + &identity_secret, + Lifetime::from_range(now - 120, now - 60), // expired lifetime + &rng, + ) + .unwrap(); + + // Current pre-key bundle is invalid. + std::assert_matches!( + KeyManager::prekey_bundle(&y), + Err(KeyManagerError::NoPreKeysAvailable) + ); + + // Can't generate one-time key bundle with expired pre keys. + std::assert_matches!( + KeyManager::generate_onetime_bundle(y.clone(), &rng), + Err(KeyManagerError::NoPreKeysAvailable) + ); + + // Generate a new one. + let y_i = KeyManager::rotate_prekey(y, Lifetime::default(), &rng).unwrap(); + assert!(KeyManager::prekey_bundle(&y_i).is_ok()); + } + + #[test] + fn garbage_collection() { + let rng = Rng::from_seed([1; 32]); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + + let identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + // Initialise key manager with one invalid key bundle. + let y = KeyManager::init_and_generate_prekey( + &identity_secret, + Lifetime::from_range(now - 120, now - 60), // expired lifetime + &rng, + ) + .unwrap(); + assert_eq!(y.prekeys.len(), 1); + + // Add second _valid_ key bundle. + let y = KeyManager::rotate_prekey(y, Lifetime::default(), &rng).unwrap(); + assert_eq!(y.prekeys.len(), 2); + + // Remove all expired bundles. + let y = KeyManager::remove_expired(y); + assert_eq!(y.prekeys.len(), 1); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/key_registry.rs b/pkgs/id/vendor/p2panda-encryption/src/key_registry.rs new file mode 100644 index 0000000000..a50b073574 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/key_registry.rs @@ -0,0 +1,386 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Manager for public key material of other members. +//! +//! Peers should actively look for fresh key bundles in the network, check for invalid or expired +//! ones and automatically choose the latest for groups. +use std::collections::HashMap; +use std::convert::Infallible; +use std::fmt::Debug; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::x25519::PublicKey; +use crate::key_bundle::{KeyBundleError, LongTermKeyBundle, OneTimeKeyBundle, latest_key_bundle}; +use crate::traits::{IdentityHandle, IdentityRegistry, KeyBundle, PreKeyRegistry}; + +/// Key registry to maintain public key material of other members we've collected. +#[derive(Clone, Debug)] +pub struct KeyRegistry { + _marker: PhantomData, +} + +/// Serializable state of key registry (for persistence). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct KeyRegistryState +where + ID: IdentityHandle, +{ + identities: HashMap, + onetime_bundles: HashMap>, + longterm_bundles: HashMap>, +} + +impl KeyRegistry +where + ID: IdentityHandle + Serialize + for<'a> Deserialize<'a>, +{ + /// Returns newly initialised key-registry state. + pub fn init() -> KeyRegistryState { + KeyRegistryState { + identities: HashMap::new(), + onetime_bundles: HashMap::new(), + longterm_bundles: HashMap::new(), + } + } + + /// Remove all expired key bundles from registry. + pub fn remove_expired(mut y: KeyRegistryState) -> KeyRegistryState { + y.longterm_bundles = + y.longterm_bundles + .into_iter() + .fold(HashMap::new(), |mut acc, (id, bundles)| { + let bundles = bundles + .into_iter() + .filter(|bundle| bundle.verify().is_ok()) + .collect::>(); + acc.insert(id, bundles); + acc + }); + + y.onetime_bundles = + y.onetime_bundles + .into_iter() + .fold(HashMap::new(), |mut acc, (id, bundles)| { + let bundles = bundles + .into_iter() + .filter(|bundle| bundle.verify().is_ok()) + .collect::>(); + acc.insert(id, bundles); + acc + }); + y + } + + /// Adds long-term pre-key bundle to the registry. + /// + /// This throws an error if an expired or invalid bundle was added. + pub fn add_longterm_bundle( + mut y: KeyRegistryState, + id: ID, + key_bundle: LongTermKeyBundle, + ) -> Result, KeyRegistryError> { + key_bundle.verify()?; + let existing = y.identities.insert(id, *key_bundle.identity_key()); + if let Some(existing) = existing { + // Sanity check. + assert_eq!(&existing, key_bundle.identity_key()); + } + y.longterm_bundles + .entry(id) + .and_modify(|bundles| bundles.push(key_bundle.clone())) + .or_insert(vec![key_bundle]); + Ok(y) + } + + #[cfg(test)] + #[allow(non_snake_case)] + fn add_longterm_bundle_UNVERIFIED( + mut y: KeyRegistryState, + id: ID, + key_bundle: LongTermKeyBundle, + ) -> KeyRegistryState { + y.longterm_bundles + .entry(id) + .and_modify(|bundles| bundles.push(key_bundle.clone())) + .or_insert(vec![key_bundle]); + y + } + + /// Adds one-time pre-key bundle to the registry. + /// + /// This throws an error if an expired or invalid bundle was added. + pub fn add_onetime_bundle( + mut y: KeyRegistryState, + id: ID, + key_bundle: OneTimeKeyBundle, + ) -> Result, KeyRegistryError> { + key_bundle.verify()?; + let existing = y.identities.insert(id, *key_bundle.identity_key()); + if let Some(existing) = existing { + // Sanity check. + assert_eq!(&existing, key_bundle.identity_key()); + } + y.onetime_bundles + .entry(id) + .and_modify(|bundles| bundles.push(key_bundle.clone())) + .or_insert(vec![key_bundle]); + Ok(y) + } +} + +impl PreKeyRegistry for KeyRegistry +where + ID: IdentityHandle + Serialize + for<'a> Deserialize<'a>, +{ + type State = KeyRegistryState; + + type Error = Infallible; + + fn key_bundle( + mut y: Self::State, + id: &ID, + ) -> Result<(Self::State, Option), Self::Error> { + let bundle = y + .onetime_bundles + .get_mut(id) + .and_then(|bundles| bundles.pop()); + Ok((y, bundle)) + } +} + +impl PreKeyRegistry for KeyRegistry +where + ID: IdentityHandle + Serialize + for<'a> Deserialize<'a>, +{ + type State = KeyRegistryState; + + type Error = KeyRegistryError; + + fn key_bundle( + y: Self::State, + id: &ID, + ) -> Result<(Self::State, Option), Self::Error> { + let Some(bundles) = y.longterm_bundles.get(id) else { + return Ok((y, None)); + }; + + let valid_bundle = latest_key_bundle(bundles).cloned(); + + // Even though key bundles are available we couldn't find any non-expired ones. + if !bundles.is_empty() && valid_bundle.is_none() { + return Err(KeyRegistryError::KeyBundlesExpired); + } + + Ok((y, valid_bundle)) + } +} + +impl IdentityRegistry> for KeyRegistry +where + ID: IdentityHandle + Serialize + for<'a> Deserialize<'a>, +{ + type Error = Infallible; + + fn identity_key(y: &KeyRegistryState, id: &ID) -> Result, Self::Error> { + let key = y.identities.get(id).cloned(); + Ok(key) + } +} + +#[derive(Debug, Error)] +pub enum KeyRegistryError { + #[error(transparent)] + KeyBundle(#[from] KeyBundleError), + + #[error("no key bundles found")] + KeyBundlesNotFound, + + #[error("all available key bundles of this member expired")] + KeyBundlesExpired, +} + +#[cfg(test)] +mod tests { + use std::time::{SystemTime, UNIX_EPOCH}; + + use crate::Rng; + use crate::crypto::x25519::SecretKey; + use crate::key_bundle::{Lifetime, LongTermKeyBundle, PreKey}; + use crate::traits::PreKeyRegistry; + + use super::KeyRegistry; + + #[test] + fn latest_key_bundle() { + let rng = Rng::from_seed([1; 32]); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + + let member_id = 0; + let identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + // Generate first bundle. + let bundle_1 = { + let prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let prekey = PreKey::new( + prekey_secret.verifying_key().unwrap(), + Lifetime::from_range(now - 60, now + 60), + ); + let prekey_signature = prekey.sign(&identity_secret, &rng).unwrap(); + + LongTermKeyBundle::new( + identity_secret.verifying_key().unwrap(), + prekey, + prekey_signature, + ) + }; + + // Generate second bundle (which expires earlier). + let bundle_2 = { + let prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let prekey = PreKey::new( + prekey_secret.verifying_key().unwrap(), + Lifetime::from_range(now - 60, now + 30), + ); + let prekey_signature = prekey.sign(&identity_secret, &rng).unwrap(); + + LongTermKeyBundle::new( + identity_secret.verifying_key().unwrap(), + prekey, + prekey_signature, + ) + }; + + // Initialize key registry and register both bundles there. + let pki = { + let y = KeyRegistry::init(); + let y = KeyRegistry::add_longterm_bundle(y, member_id, bundle_1.clone()).unwrap(); + let y = KeyRegistry::add_longterm_bundle(y, member_id, bundle_2).unwrap(); + y + }; + + // Registry returns bundle which has the "furthest" expiry date. + assert_eq!( + KeyRegistry::key_bundle(pki, &member_id).unwrap().1, + Some(bundle_1) + ); + } + + #[test] + fn invalid_bundles() { + let rng = Rng::from_seed([1; 32]); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + + let member_id = 0; + let identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let invalid_bundle = { + let prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let prekey = PreKey::new( + prekey_secret.verifying_key().unwrap(), + Lifetime::from_range(now - 60, now - 30), + ); + let prekey_signature = prekey.sign(&identity_secret, &rng).unwrap(); + + LongTermKeyBundle::new( + identity_secret.verifying_key().unwrap(), + prekey, + prekey_signature, + ) + }; + + let pki = KeyRegistry::init(); + + // Registry should throw an error when trying to add an expired bundle. + assert!( + KeyRegistry::add_longterm_bundle(pki.clone(), member_id, invalid_bundle.clone()) + .is_err() + ); + + let pki = + KeyRegistry::add_longterm_bundle_UNVERIFIED(pki, member_id, invalid_bundle.clone()); + + // Registry should throw an error when we only have expired bundles of that member. + assert_eq!(pki.longterm_bundles.get(&member_id).unwrap().len(), 1); + assert!( + as PreKeyRegistry>::key_bundle( + pki.clone(), + &member_id + ) + .is_err() + ); + } + + #[test] + fn garbage_collection() { + let rng = Rng::from_seed([1; 32]); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime before UNIX EPOCH!") + .as_secs(); + + let member_id = 0; + let identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let invalid_bundle = { + let prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let prekey = PreKey::new( + prekey_secret.verifying_key().unwrap(), + Lifetime::from_range(now - 60, now - 30), + ); + let prekey_signature = prekey.sign(&identity_secret, &rng).unwrap(); + + LongTermKeyBundle::new( + identity_secret.verifying_key().unwrap(), + prekey, + prekey_signature, + ) + }; + + let valid_bundle = { + let prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let prekey = PreKey::new( + prekey_secret.verifying_key().unwrap(), + Lifetime::from_range(now - 60, now + 60), + ); + let prekey_signature = prekey.sign(&identity_secret, &rng).unwrap(); + + LongTermKeyBundle::new( + identity_secret.verifying_key().unwrap(), + prekey, + prekey_signature, + ) + }; + + let pki = { + let y = KeyRegistry::init(); + let y = + KeyRegistry::add_longterm_bundle_UNVERIFIED(y, member_id, invalid_bundle.clone()); + let y = KeyRegistry::add_longterm_bundle_UNVERIFIED(y, member_id, valid_bundle.clone()); + y + }; + + assert_eq!(pki.longterm_bundles.get(&member_id).unwrap().len(), 2); + + // Remove invalid bundles. + let pki = KeyRegistry::remove_expired(pki); + assert_eq!(pki.longterm_bundles.get(&member_id).unwrap().len(), 1); + + // Registry returns correct and valid bundle. + assert_eq!( + KeyRegistry::key_bundle(pki, &member_id).unwrap().1, + Some(valid_bundle) + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/lib.rs b/pkgs/id/vendor/p2panda-encryption/src/lib.rs new file mode 100644 index 0000000000..0c3e63ae11 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/lib.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +#![cfg_attr(docsrs, feature(doc_cfg))] + +//! `p2panda-encryption` provides decentralized, secure data- and message encryption for groups +//! with post-compromise security and optional forward secrecy. +//! +//! The crate implements two different group key-agreement and encryption schemes for a whole range +//! of use cases for applications which can't rely on a stable network connection or centralised +//! coordination. +//! +//! The first scheme we simply call [**"Data Encryption"**](data_scheme), allowing peers to encrypt any data with +//! a secret, symmetric key for a group (using XChaCha20-Poly1305). This will be useful for building +//! applications where users who enter a group late will still have access to previously-created +//! content, for example knowledge databases, wiki applications or a booking tool for rehearsal +//! rooms. +//! +//! A member will not learn about any newly-created data after they are removed from the group, +//! since the key gets rotated on member removal. This should accommodate for many use-cases in p2p +//! applications which rely on basic group encryption with post-compromise security (PCS) and +//! forward secrecy (FS) during key agreement. Applications can optionally choose to remove +//! encryption keys for forward secrecy if they so desire. +//! +//! The second scheme is [**"Message Encryption"**](message_scheme), offering a forward secure (FS) +//! messaging ratchet, similar to Signal's [Double Ratchet +//! algorithm](https://en.wikipedia.org/wiki/Double_Ratchet_Algorithm). Since secret keys are +//! always generated for each message, a user can not easily learn about previously-created +//! messages when getting hold of such a key. We believe that the latter scheme will be used in +//! more specialised applications, for example p2p group chats, as strong forward secrecy comes +//! with it's own UX requirements. We are nonetheless excited to offer a solution for both worlds, +//! depending on the application's needs. +//! +//! More detail about the particular implementation and design choices of `p2panda-encryption` can +//! be found in our [in-depth blog post](https://p2panda.org/2025/02/24/group-encryption.html) and +//! [README](https://github.com/p2panda/p2panda/blob/main/p2panda-encryption/README.md). +pub mod crypto; +#[cfg(any(test, feature = "data_scheme"))] +pub mod data_scheme; +pub mod key_bundle; +pub mod key_manager; +pub mod key_registry; +#[cfg(any(test, feature = "message_scheme"))] +pub mod message_scheme; +#[cfg(any(test, feature = "test_utils"))] +mod ordering; +#[cfg(any(test, feature = "test_utils"))] +pub mod test_utils; +pub mod traits; +pub mod two_party; + +pub use crypto::{Rng, RngError}; diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/dcgka.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/dcgka.rs new file mode 100644 index 0000000000..bad81cd378 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/dcgka.rs @@ -0,0 +1,1569 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! A decentralized continuous group key agreement protocol (DCGKA) for p2panda's "message +//! encryption" scheme with strong forward secrecy and post-compromise security. +//! +//! ## Protocol +//! +//! DCGKA generates a sequence of update secrets for each group member, which are used as input to +//! a ratchet to encrypt/decrypt application messages sent by that member. Only group members learn +//! these update secrets, and fresh secrets are generated every time a user is added or removed, or +//! a PCS update is requested. The DCGKA protocol ensures that all users observe the same sequence +//! of update secrets for each group member, regardless of the order in which concurrent messages +//! are received. +//! +//! ```text +//! ┌────────────────────────────────────────────────┐ +//! │ "Outer" Ratchet │ +//! Alice ├────────────────────────────────────────────────┤ +//! │ │ │ +//! │ │ Previous Chain Secret │ +//! │ │ for Bob │ +//! Delivered │ │ +//! via 2SM │ │ │ +//! │ │ │ │ +//! │ │ │ │ ┌─────┐ +//! ▼ │ │ ◄───────────┼───│"Ack"│ +//! ┌────┐ │ │ │ └─────┘ +//! │Seed├───────│──► HKDF │ │ +//! └────┘ │ │ Bob │ │ +//! │ │ ┌─────────────┐ │ │ +//! │ ├───► │Member Secret├───────┼─► HKDF ─────┼──► Update Secret +//! │ │ └─────────────┘ │ │ │ +//! │ │ ▼ │ │ +//! │ │ Charlie HKDF │ │ +//! │ │ ┌─────────────┐ │ │ │ +//! │ ├───► │Member Secret├─... │ │ ▼ +//! │ │ └─────────────┘ │ │ ┌───────────────┐ +//! │ │ │ │ │Message Ratchet│ +//! │ │ ... │ │ └───────────────┘ +//! │ │ ┌─────────────┐ │ │ +//! │ └───► │Member Secret├─... │ │ +//! │ └─────────────┘ │ │ +//! │ │ │ +//! │ ▼ │ +//! │ New Chain Secret │ +//! │ │ │ +//! │ │ │ +//! │ ▼ ... │ +//! │ │ +//! └────────────────────────────────────────────────┘ +//! ``` +//! +//! To initiate a PCS update, a user generates a fresh random value called a seed secret, and sends +//! it to each other group member via a two-party secure channel, like in Sender Keys. On receiving +//! a seed secret, a group member deterministically derives from it an update secret for the +//! sender's ratchet, and also an update secret for its own ratchet. Moreover, the recipient +//! broadcasts an unencrypted acknowledgment to the group indicating that it has applied the +//! update. Every recipient of the acknowledgment then updates not only the ratchet for the sender +//! of the original update, but also the ratchet for the sender of the acknowledgment. Thus, after +//! one seed secret has been disseminated via n - 1 two-party messages, and confirmed via n - 1 +//! broadcast acknowledgments, each group member has derived an update secret from it and updated +//! their ratchet. +//! +//! ## Credits +//! +//! The implementation follows the DCGKA protocol specified in the paper: "Key Agreement for +//! Decentralized Secure Group Messaging with Strong Security Guarantees" by Matthew Weidner, +//! Martin Kleppmann, Daniel Hugenroth, Alastair R. Beresford (2020). +//! +//! +//! +//! Some adjustments have been made to the version in the paper: +//! +//! * Renamed `process` to `process_remote`. +//! * Added `rng` as an argument to most methods. +//! * `seq` is taken care of _outside_ of this implementation. Methods return control messages +//! which need to be manually assigned a "seq", that is a vector clock, hash, seq_num or similar. +//! * After calling a group operation "create", "add", "remove" or "update" the user needs to process +//! the output themselves by calling `process_local`. This allows a user of the API to correctly +//! craft a `seq` for their control messages (see point above). +//! * Instead of sending the history of control messages in "welcome" messages we send the +//! "processed" and potentially garbage-collected CRDT state of DGM. This also allows +//! implementations where control messages are encrypted as well. +//! * We're not recording the "add" control message to the history before sending a "welcome" +//! message after adding a member, the receiver of the "welcome" message needs to add themselves. +use std::collections::{HashMap, HashSet}; +use std::fmt::Display; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::hkdf::{HkdfError, hkdf}; +use crate::crypto::{Rng, RngError, Secret}; +use crate::key_bundle::OneTimeKeyBundle; +use crate::traits::{ + AckedGroupMembership, IdentityHandle, IdentityManager, IdentityRegistry, OperationId, + PreKeyManager, PreKeyRegistry, +}; +use crate::two_party::{TwoParty, TwoPartyError, TwoPartyMessage, TwoPartyState}; + +/// 256-bit secret "outer" chain- and update key. +const RATCHET_KEY_SIZE: usize = 32; + +/// A decentralized continuous group key agreement protocol (DCGKA) for p2panda's "message +/// encryption" scheme with strong forward secrecy and post-compromise security. +pub struct Dcgka { + _marker: PhantomData<(ID, OP, PKI, DGM, KMG)>, +} + +/// Serializable state of DCGKA (for persistence). +#[derive(Debug, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct DcgkaState +where + ID: IdentityHandle, + OP: OperationId, + PKI: IdentityRegistry + PreKeyRegistry, + DGM: AckedGroupMembership, + KMG: IdentityManager + PreKeyManager, +{ + /// Public Key Infrastructure (PKI). From here we retrieve the identity keys and one-time + /// prekey bundles for each member to do 2SM. + pub(crate) pki: PKI::State, + + /// Our own key manager state holding the secret parts for our own identity keys and published + /// one-time prekey bundles so we can do 2SM. + pub(crate) my_keys: KMG::State, + + /// Our id which is used as a unique handle inside this group. + pub(crate) my_id: ID, + + /// Randomly generated seed we keep temporarily around when creating or updating a group or + /// removing a member. + pub(crate) next_seed: Option, + + /// Handlers for each member to manage the "Two-Party Secure Messaging" (2SM) key-agreement + /// protocol as specified in the paper. + pub(crate) two_party: HashMap>, // "2sm" in paper + + /// Member secrets are "temporary" secrets we derive after receiving a new seed or adding + /// someone. We keep them around until we've received an acknowledgment of that member. + /// + /// We only store the member secrets, and not the seed secret, so that if the user's private + /// state is compromised, the adversary obtains only those member secrets that have not yet + /// been used. + /// + /// The first parameter in the key tuple is the "sender" or "original creator" of the update + /// secret. They generated the secret during the given "sequence" (second parameter) for a + /// "member" (third parameter). + pub(crate) member_secrets: HashMap<(ID, OP, ID), ChainSecret>, // key: "(sender, seq, ID)" in paper + + /// Chain secrets for the "outer" key-agreement ratchet. + /// + /// Secrets for the "inner" message ratchet are returned to the user as part of the + /// "sender_update_secret" and "me_update_secret" fields when invoking a group membership + /// operation or processing a control message. + pub(crate) ratchet: HashMap, + + /// Decentralised group membership (DGM) state. + pub(crate) dgm: DGM::State, +} + +impl Dcgka +where + ID: IdentityHandle, + OP: OperationId, + PKI: IdentityRegistry + PreKeyRegistry, + DGM: AckedGroupMembership, + KMG: IdentityManager + PreKeyManager, +{ + /// Returns new DCGKA state with our own identity and key managers. + /// + /// Use this when creating a new group or before accepting an invitation to an existing one. + pub fn init( + my_id: ID, + my_keys: KMG::State, + pki: PKI::State, + dgm: DGM::State, + ) -> DcgkaState { + DcgkaState { + pki, + my_id, + my_keys, + next_seed: None, + two_party: HashMap::new(), + member_secrets: HashMap::new(), + ratchet: HashMap::new(), + dgm, + } + } + + /// Handler for when a "remote" control message is received from the network. + /// + /// It takes the user ID of the message sender, a control message, and a direct message (or + /// none if there is no associated direct message). + /// + /// Control messages are expected to be authenticated and causally ordered. + pub fn process_remote( + y: DcgkaState, + input: ProcessInput, + rng: &Rng, + ) -> DcgkaProcessResult { + let ProcessInput { + sender, + seq, + direct_message, + control_message, + } = input; + assert_ne!(sender, y.my_id, "do not process own control messages"); + let (y_i, output) = match control_message { + ControlMessage::Create { initial_members } => { + Self::process_create(y, sender, seq, initial_members, direct_message, rng)? + } + ControlMessage::Ack { + ack_sender, + ack_seq, + } => Self::process_ack(y, sender, (&ack_sender, ack_seq), direct_message)?, + ControlMessage::Update => Self::process_update(y, sender, seq, direct_message, rng)?, + ControlMessage::Remove { removed } => { + Self::process_remove(y, sender, seq, &removed, direct_message, rng)? + } + ControlMessage::Add { added } => { + Self::process_add(y, sender, seq, added, direct_message, rng)? + } + ControlMessage::AddAck { + ack_sender, + ack_seq, + } => Self::process_add_ack(y, sender, (&ack_sender, ack_seq), direct_message)?, + }; + Ok((y_i, output)) + } + + /// Handler which is _always_ called _after_ every local group membership operation + /// ("create", "update", "remove" or "add") which was applied by us. + /// + /// Invoking a membership operation always returns a "control message" which needs to be + /// processed by the application _before_ we can process it locally (and thus finally updating + /// our local state). This is because some applications have more complex requirements around + /// wrapping the control message around their own message type which will be published on the + /// network (for example an append-only log entry with signature, vector clocks, etc.) and we + /// can't "guess" the resulting operation id. + /// + /// Calling this method will _never_ yield another control- or direct message. + pub fn process_local( + y: DcgkaState, + seq: OP, + input: OperationOutput, + rng: &Rng, + ) -> DcgkaOperationResult { + let my_id = y.my_id; + let (y_i, output) = match input.control_message { + ControlMessage::Create { + ref initial_members, + } => Self::process_create(y, my_id, seq, initial_members.clone(), None, rng)?, + ControlMessage::Update => Self::process_update(y, my_id, seq, None, rng)?, + ControlMessage::Remove { removed } => { + Self::process_remove(y, my_id, seq, &removed, None, rng)? + } + ControlMessage::Add { added } => Self::process_add(y, my_id, seq, added, None, rng)?, + _ => panic!( + "only call process_local after local create, update, remove or add operations" + ), + }; + + // Processing our local group operations should never yield control or direct messages. + assert!(output.control_message.is_none()); + assert!(output.direct_messages.is_empty()); + + Ok(( + y_i, + OperationOutput { + control_message: input.control_message, + direct_messages: input.direct_messages, + me_update_secret: Some(output.sender_update_secret.unwrap()), + }, + )) + } + + /// Takes a set of users IDs (including us) and creates a new group with those members. + /// + /// Note that every member ID needs to be unique for this group. + /// + /// A group is created in three steps: 1. one user calls "create" and broadcasts a control + /// message of type "create" (plus direct messages) to the initial members; 2. each member + /// processes that message and broadcasts an "ack" control message; 3. each member processes + /// the ack from each other member. + pub fn create( + y: DcgkaState, + initial_members: Vec, + rng: &Rng, + ) -> DcgkaOperationResult { + // De-duplicate members. + let mut initial_members: Vec = + initial_members.into_iter().fold(Vec::new(), |mut acc, id| { + if !acc.contains(&id) { + acc.push(id); + } + acc + }); + + // Add ourselves if the user hasn't done it yet. + if !initial_members.contains(&y.my_id) { + initial_members.push(y.my_id); + } + + // The "create" function constructs the "create" control message. + let control_message = ControlMessage::Create { + initial_members: initial_members.clone(), + }; + + // Generate the set of direct messages to send. + let (y_ii, direct_messages) = Self::generate_seed(y, &initial_members, rng)?; + + // It then calls process_create to process the control message for this user (as if it had + // received the message) before returning. + // + // process_create returns a tuple after updating the state including an update secret I; we + // use these and ignore the rest. + Ok(( + y_ii, + OperationOutput { + control_message, + direct_messages, + me_update_secret: None, + }, + )) + } + + /// Called by group members when they receive the "create" message. + fn process_create( + mut y: DcgkaState, + sender: ID, + seq: OP, + initial_members: Vec, + direct_message: Option>, + rng: &Rng, + ) -> DcgkaProcessResult { + y.dgm = + DGM::create(y.my_id, &initial_members).map_err(|err| DcgkaError::DgmOperation(err))?; + Self::process_seed(y, &sender, seq, direct_message, rng) + } + + /// Called by group members when they receive the "ack" message. + /// + /// In this function, `ackID` and `ackOP` are the user id and id of the acknowledged message. + fn process_ack( + mut y: DcgkaState, + sender: ID, + ack: (&ID, OP), + direct_message: Option>, + ) -> DcgkaProcessResult { + // If the acknowledged message was a group membership operation, we record the + // acknowledgment. We do this because the member_view function needs to know which + // operations have been acknowledged by which user. + // + // Acking the message will fail if it's an ack of the user's own removal. Thus we will + // refuse to process messages from a user that depend on their own removal. + if DGM::is_add(&y.dgm, ack.1) && DGM::is_remove(&y.dgm, ack.1) && sender != y.my_id { + // This condition will fail for acks of the creation and of updates. + y.dgm = DGM::ack(y.dgm, sender, ack.1).map_err(|err| DcgkaError::DgmOperation(err))?; + } + + // Read from γ.memberSecret the appropriate member secret that was previously derived from + // the seed secret in the message being acknowledged. The member secret is then deleted for + // forward secrecy. + let member_secret = y.member_secrets.remove(&(*ack.0, ack.1, sender)); // FS + + let (y_i, sender_member_secret) = match (member_secret, direct_message) { + (None, None) => return Ok((y, ProcessOutput::default())), + (Some(member_secret), _) => (y, member_secret), + ( + None, + Some(DirectMessage { + recipient, + content: DirectMessageContent::Forward { ciphertext }, + .. + }), + ) => { + if recipient != y.my_id { + // Direct message was not meant for us. + return Ok((y, ProcessOutput::default())); + } + + // The recipient of such a message handles concurrent adds here, where the + // forwarded member secret is decrypted and then used to update the ratchet for the + // "ack" sender. Note that this forwarding behavior does not violate forward + // secrecy: an application message can still only be decrypted by those users who + // were group members at the time of sending. + let (y_i, plaintext) = Self::decrypt_from(y, &sender, ciphertext)?; + (y_i, ChainSecret::try_from_bytes(&plaintext)?) + } + (None, Some(direct_message)) => { + return Err(DcgkaError::UnexpectedDirectMessageType( + DirectMessageType::Forward, + direct_message.message_type(), + )); + } + }; + + // We update the ratchet for the sender of the "ack" and return the resulting update + // secret. + let (y_ii, sender_update_secret) = + Self::update_ratchet(y_i, &sender, sender_member_secret)?; + + Ok(( + y_ii, + ProcessOutput { + control_message: None, + direct_messages: Vec::new(), + sender_update_secret: Some(sender_update_secret), + me_update_secret: None, + }, + )) + } + + /// Generate a new seed for the group. This "refreshes" the group's entropy and should be + /// called frequently if no other group operations took place for a while. + pub fn update( + y: DcgkaState, + rng: &Rng, + ) -> DcgkaOperationResult { + let control_message = ControlMessage::Update; + + let recipient_ids: Vec = Self::member_view(&y, &y.my_id)? + .into_iter() + .filter(|member| member != &y.my_id) + .collect(); + + let (y_i, direct_messages) = Self::generate_seed(y, &recipient_ids, rng)?; + + Ok(( + y_i, + OperationOutput { + control_message, + direct_messages, + me_update_secret: None, + }, + )) + } + + /// Called by group members when they receive the "update" control message. + fn process_update( + y: DcgkaState, + sender: ID, + seq: OP, + direct_message: Option>, + rng: &Rng, + ) -> DcgkaProcessResult { + Self::process_seed(y, &sender, seq, direct_message, rng) + } + + /// Remove a member from the group. + /// + /// This generates a new seed for the remaining members for post-compromise security (PCS). + pub fn remove( + y: DcgkaState, + removed: ID, + rng: &Rng, + ) -> DcgkaOperationResult { + let control_message = ControlMessage::Remove { removed }; + + let recipient_ids: Vec = Self::member_view(&y, &y.my_id)? + .into_iter() + .filter(|member| member != &y.my_id && member != &removed) + .collect(); + + let (y_i, direct_messages) = Self::generate_seed(y, &recipient_ids, rng)?; + + Ok(( + y_i, + OperationOutput { + control_message, + direct_messages, + me_update_secret: None, + }, + )) + } + + /// Called by group members when they receive the "remove" control message. + fn process_remove( + mut y: DcgkaState, + sender: ID, + seq: OP, + removed: &ID, + direct_message: Option>, + rng: &Rng, + ) -> DcgkaProcessResult { + y.dgm = DGM::remove(y.dgm, sender, removed, seq) + .map_err(|err| DcgkaError::DgmOperation(err))?; + Self::process_seed(y, &sender, seq, direct_message, rng) + } + + /// Adds a new group member. + /// + /// The added group member will receive a direct "welcome" message, every member will process + /// an "add" control message. + pub fn add( + y: DcgkaState, + added: ID, + rng: &Rng, + ) -> DcgkaOperationResult { + // Construct a control message of type "add" to broadcast to the group + let control_message = ControlMessage::Add { added }; + + // Construct a welcome message that is sent to the new member as a direct message. + // + // The welcome message contains the current KDF ratchet state of the sender, encrypted + // using 2SM, and the history of group membership operations to date (necessary so that the + // new member can evaluate the DGM function). + let (y_i, ciphertext) = { + let chain_secret_bytes = y + .ratchet + .get(&y.my_id) + .ok_or(DcgkaError::MissingRatchetSecret)? + .as_bytes() + .to_vec(); + Self::encrypt_to(y, &added, &chain_secret_bytes, rng)? + }; + let direct_message = DirectMessage { + recipient: added, + content: DirectMessageContent::Welcome { + ciphertext, + history: { + // Send current DGM state to added user. The benefit of doing it like that is + // that we can encrypt group operations as well, otherwise we would need to ask + // the added user to process all previous (unencrypted) group operations + // before. + y_i.dgm.clone() + }, + }, + }; + + Ok(( + y_i, + OperationOutput { + control_message, + direct_messages: vec![direct_message], + me_update_secret: None, + }, + )) + } + + /// Called by both the sender and each recipient of an "add" control message, including the new + /// group member. + /// + /// ## Concurrency + /// + /// Another scenario that needs to be handled is when two users are concurrently added to the + /// group. For example, in a group consisting initially of {A, B}, say A adds C to the group, + /// while concurrently B adds D. User C first processes its own addition and welcome message, + /// and then processes B's addition of D. However, since C was not a group member at the time B + /// sent its "add" message, C does not yet have B's ratchet state, so C cannot derive an update + /// secret for B's "add" message. + /// + /// When B finds out about the fact that A has added C, B sends C its ratchet state as usual, + /// so C can initialize its copy of B's ratchet as before. Similarly, when D finds out about + /// the fact that A has added C, D sends its ratchet state to C along with the "add-ack" + /// message. The existing logic therefore handles the concurrent additions: after all acks have + /// been delivered, C and D have both initialized their copies of all four ratchets, and so + /// they are able to decrypt application messages that any group member sent after processing + /// their addition. + fn process_add( + mut y: DcgkaState, + sender: ID, + seq: OP, + added: ID, + direct_message: Option>, + rng: &Rng, + ) -> DcgkaProcessResult { + // Local user is the new group member being added. Call "process_welcome" instead and + // return early. + if added == y.my_id { + let Some(DirectMessage { + recipient, + content: + DirectMessageContent::Welcome { + ciphertext, + history, + }, + .. + }) = direct_message + else { + return match direct_message { + Some(direct_message) => Err(DcgkaError::UnexpectedDirectMessageType( + DirectMessageType::Welcome, + direct_message.message_type(), + )), + None => Err(DcgkaError::MissingDirectMessage(DirectMessageType::Welcome)), + }; + }; + + if recipient != y.my_id { + return Err(DcgkaError::NotOurDirectMessage(y.my_id, recipient)); + } + + return Self::process_welcome(y, sender, seq, history, ciphertext); + } + + // Otherwise extend γ.history with the add operation. + y.dgm = DGM::add(y.dgm, sender, added, seq).map_err(|err| DcgkaError::DgmOperation(err))?; + + // Determine whether the local user was already a group member at the time the "add" + // message was sent. This is true in the common case, but may be false if multiple users + // were added concurrently. + let is_concurrent = !Self::member_view(&y, &sender)? + .iter() + .any(|member| member == &y.my_id); + + let (y_ii, sender_update_secret) = if is_concurrent { + (y, None) + } else { + // We twice update the ratchet for the sender of the "add" message. In both calls to + // update_ratchet, rather than using a random seed secret, the ratchet input is a + // constant string ("welcome" and "add" respectively). It is sufficient to use + // constants here because all existing group members are allowed to know the next + // update secrets following the add operation. + + // 1. The value returned by the first ratchet update is stored in γ.memberSecret as the + // added user's first member secret; + let (mut y_i, sender_member_secret) = + Self::update_ratchet(y, &sender, ChainSecret::from_welcome())?; + y_i.member_secrets.insert( + (sender, seq, added), + ChainSecret::from(sender_member_secret), + ); + // 2. The result of the second ratchet update becomes Isender, the update secret for + // the sender of the "add". + let (y_ii, sender_update_secret) = + Self::update_ratchet(y_i, &sender, ChainSecret::from_add())?; + (y_ii, Some(sender_update_secret)) + }; + + // If the local user is the sender, we return that update secret. + if sender == y_ii.my_id { + return Ok(( + y_ii, + ProcessOutput { + control_message: None, + direct_messages: Vec::new(), + sender_update_secret, + me_update_secret: None, + }, + )); + } + + // Otherwise, we need to acknowledge the "add" message, so we construct a control message + // of type "add-ack" to broadcast (note that add has its own acknowledgment type, whereas + // create, update and remove all use "ack"). + let control = ControlMessage::AddAck { + ack_sender: sender, + ack_seq: seq, + }; + + // We then use 2SM to encrypt our current ratchet state to send as a direct message to the + // added user, so that they can decrypt subsequent messages we send. + let (y_iii, ciphertext) = { + let chain_secret_bytes = y_ii + .ratchet + .get(&y_ii.my_id) + .ok_or(DcgkaError::MissingRatchetSecret)? + .as_bytes() + .to_vec(); + Self::encrypt_to(y_ii, &added, &chain_secret_bytes, rng)? + }; + let forward = DirectMessage { + recipient: added, + content: DirectMessageContent::Forward { ciphertext }, + }; + + // Finally, we call process_add_ack to compute the local user's update secret Ime, and + // return it with Isender. + let (y_iv, output) = { + let my_id = y_iii.my_id; + Self::process_add_ack(y_iii, my_id, (&sender, seq), None)? + }; + let me_update_secret = output.sender_update_secret; + + Ok(( + y_iv, + ProcessOutput { + control_message: Some(control), + direct_messages: vec![forward], + sender_update_secret, + me_update_secret, + }, + )) + } + + /// Called by both the sender and each recipient of an "add-ack" message, including the new + /// group member. + fn process_add_ack( + mut y: DcgkaState, + sender: ID, + ack: (&ID, OP), + direct_message: Option>, + ) -> DcgkaProcessResult { + // Add the acknowledgment to γ.history, like in process_ack. + y.dgm = DGM::ack(y.dgm, sender, ack.1).map_err(|err| DcgkaError::DgmOperation(err))?; + + // If the current user is the new group member, the "add_ack" message is accompanied by the + // direct message that we constructed in process_add; this direct message dmsg contains the + // encrypted ratchet state of the sender of the "add_ack", so we decrypt it. + let y_i = if let Some(direct_message) = direct_message { + if let DirectMessage { + recipient, + content: DirectMessageContent::Forward { ciphertext }, + .. + } = direct_message + { + if recipient != y.my_id { + return Err(DcgkaError::NotOurDirectMessage(y.my_id, recipient)); + } + + let (mut y_i, plaintext) = Self::decrypt_from(y, &sender, ciphertext)?; + let chain_secret = ChainSecret::try_from_bytes(&plaintext)?; + y_i.ratchet.insert(sender, chain_secret); + y_i + } else { + return Err(DcgkaError::UnexpectedDirectMessageType( + DirectMessageType::Forward, + direct_message.message_type(), + )); + } + } else { + y + }; + + // Check if the local user was already a group member at the time the "add_ack" was sent + // (which may not be the case when there are concurrent additions). + let is_concurrent = !Self::member_view(&y_i, &sender)? + .iter() + .any(|member| member == &y_i.my_id); + + if !is_concurrent { + // If so, we compute a new update secret I for the sender of the "add_ack" by calling + // update_ratchet with the constant string "add". In the case of the new member, the + // ratchet state was just previously initialized. This ratchet update allows all group + // members, including the new one, to derive each member's update secret for the add + // operation, but it prevents the new group member from obtaining any update secret + // from before they were added. + let (y_ii, sender_update_secret) = + Self::update_ratchet(y_i, &sender, ChainSecret::from_add())?; + return Ok(( + y_ii, + ProcessOutput { + control_message: None, + direct_messages: Vec::new(), + sender_update_secret: Some(sender_update_secret), + me_update_secret: None, + }, + )); + } + + Ok((y_i, ProcessOutput::default())) + } + + /// Second function called by a newly added group member (the first is the call to init that + /// sets up their state). + fn process_welcome( + mut y: DcgkaState, + sender: ID, + seq: OP, + history: DGM::State, + ciphertext: TwoPartyMessage, + ) -> DcgkaProcessResult { + // Adding user's copy of γ.history sent in their welcome message, which is used to + // initialize the added user's history. + // + // Note that we might receive multiple welcome messages when peers added us concurrently. A + // DGM implementation might want to account for this. + y.dgm = DGM::from_welcome(y.dgm, history).map_err(|err| DcgkaError::DgmOperation(err))?; + + // Add ourselves. + y.dgm = + DGM::add(y.dgm, sender, y.my_id, seq).map_err(|err| DcgkaError::DgmOperation(err))?; + + // Ciphertext of the adding user's ratchet state, which we decrypt. + let y_i = { + let (mut y_i, plaintext) = Self::decrypt_from(y, &sender, ciphertext)?; + let chain_secret = ChainSecret::try_from_bytes(&plaintext)?; + y_i.ratchet.insert(sender, chain_secret); + y_i + }; + + // After γ.ratchet[sender] is initialized, we can call update_ratchet twice with the + // constant strings "welcome" and "add": exactly the same ratchet operations as every other + // group member performs in process_add. + // + // As before, the result of the first update_ratchet call becomes the first member secret + // for the added user, and the second returns Isender, the update secret for the sender of + // the add operation. + let y_ii = { + let (mut y_ii, member_secret) = + Self::update_ratchet(y_i, &sender, ChainSecret::from_welcome())?; + y_ii.member_secrets + .insert((sender, seq, y_ii.my_id), ChainSecret::from(member_secret)); + y_ii + }; + + let (y_iii, sender_update_secret) = + Self::update_ratchet(y_ii, &sender, ChainSecret::from_add())?; + + // Finally, the new group member constructs an "ack" control message (not "add_ack") to + // broadcast and calls process_ack to compute their first update secret Ime. + let control = ControlMessage::Ack { + ack_sender: sender, + ack_seq: seq, + }; + + // process_ack works as described previously, reading from γ.memberSecret the member secret + // we just generated, and passing it to update_ratchet. + // + // The previous ratchet state for the new member is the empty string ε, as set up by init, + // so this step initializes the new member's ratchet. Every other group member, on + // receiving the new member's "ack", will initialize their copy of the new member's ratchet + // in the same way. By the end of process_welcome, the new group member has obtained update + // secrets for themselves and the user who added them. They then use those secrets to + // initialize the ratchets for application messages, allowing them to send messages and + // decrypt messages from the user who added them. The ratchets for other group members are + // initialized by process_add_ack. + let (y_iv, output) = { + let my_id = y_iii.my_id; + Self::process_ack(y_iii, my_id, (&sender, seq), None)? + }; + let me_update_secret = output.sender_update_secret; + + Ok(( + y_iv, + ProcessOutput { + control_message: Some(control), + direct_messages: Vec::new(), + sender_update_secret: Some(sender_update_secret), + me_update_secret: Some( + me_update_secret.expect("sender update secret from process_ack"), + ), + }, + )) + } + + /// Generates a seed secret using a secure source of random bits, then calls `encrypt_to` to + /// encrypt it for each other group member using the 2SM protocol. It returns the updated + /// protocol state and the set of direct messages to send. + fn generate_seed( + mut y: DcgkaState, + recipients: &[ID], + rng: &Rng, + ) -> GenerateSeedResult { + let mut direct_messages: Vec> = + Vec::with_capacity(recipients.len()); + + // Generate next seed. + let next_seed_bytes = rng.random_array()?; + y.next_seed = Some(NextSeed::from_bytes(next_seed_bytes)); + + let y_i = { + let mut y_loop = y; + for recipient in recipients { + // Skip ourselves. + if recipient == &y_loop.my_id { + continue; + } + + // Encrypt to every recipient. + let (y_next, ciphertext) = + Self::encrypt_to(y_loop, recipient, &next_seed_bytes, rng)?; + y_loop = y_next; + + direct_messages.push(DirectMessage { + recipient: *recipient, + content: DirectMessageContent::TwoParty { ciphertext }, + }); + } + y_loop + }; + + Ok((y_i, direct_messages)) + } + + /// Handle the next seed for the group, either generated locally by us or received as an + /// encrypted message by another member. + /// + /// We use the seed to derive independent member secrets for each group member by combining + /// the seed secret and each user ID using HKDF. + fn process_seed( + mut y: DcgkaState, + sender: &ID, + seq: OP, + direct_message: Option>, + rng: &Rng, + ) -> DcgkaProcessResult { + // Determine the set of users who were group members at the time the control message was + // sent, and hence the set of recipients of the message. + let recipients: Vec = Self::member_view(&y, sender)? + .into_iter() + .filter(|member| member != sender) + .collect(); + + // Attempt to obtain the seed secret. + let (mut y_i, next_seed) = if sender == &y.my_id { + // 1. If the control message was sent by the local user, the last call to generate_seed + // placed the seed secret in γ.nextSeed, so we read that variable and then delete + // its contents. + let next_seed = y.next_seed.take().expect("seed was generated before"); // FS + (y, next_seed) + } else if recipients.iter().any(|member| member == &y.my_id) { + // 2. If the control message was sent by another user, and the local user is one of its + // recipients, we use decrypt_from to decrypt the direct message containing the seed + // secret. + let Some(DirectMessage { + recipient, + content: DirectMessageContent::TwoParty { ciphertext }, + .. + }) = direct_message + else { + return match direct_message { + Some(direct_message) => Err(DcgkaError::UnexpectedDirectMessageType( + DirectMessageType::TwoParty, + direct_message.message_type(), + )), + None => Err(DcgkaError::MissingDirectMessage( + DirectMessageType::TwoParty, + )), + }; + }; + + if recipient != y.my_id { + return Err(DcgkaError::NotOurDirectMessage(y.my_id, recipient)); + } + + let (y_i, plaintext) = Self::decrypt_from(y, sender, ciphertext)?; + (y_i, NextSeed::try_from_bytes(&plaintext)?) + } else { + // 3. Otherwise we return an "ack" message without deriving an update secret. Case 3 + // may occur when a group member is added concurrently to other messages. + let control = ControlMessage::Ack { + ack_sender: *sender, + ack_seq: seq, + }; + return Ok(( + y, + ProcessOutput { + control_message: Some(control), + direct_messages: Vec::new(), + sender_update_secret: None, + me_update_secret: None, + }, + )); + }; + + // Derive independent member secrets for each group member from the seed secret by + // combining the seed secret and each user ID using HKDF. The secret for the sender of the + // message is stored in senderSecret, and those for the other group members are stored in + // γ.memberSecret; the latter are used when we receive acknowledgments from those users. + for recipient in &recipients { + let recipient_identity_key = PKI::identity_key(&y_i.pki, recipient) + .map_err(|err| DcgkaError::IdentityRegistry(err))? + .ok_or(DcgkaError::MissingIdentityKey(*recipient))?; + let recipient_member_secret: [u8; RATCHET_KEY_SIZE] = hkdf( + b"update", + &{ + let mut ikm = Vec::with_capacity(RATCHET_KEY_SIZE * 2); + ikm.extend_from_slice(next_seed.as_bytes()); + ikm.extend_from_slice(recipient_identity_key.as_bytes()); + ikm + }, + None, + )?; + y_i.member_secrets.insert( + (*sender, seq, *recipient), + ChainSecret::from_bytes(recipient_member_secret), + ); + } + + // The sender's member secret is used immediately to update their KDF ratchet and compute + // their update secret Isender, using update_ratchet. + let (y_ii, sender_update_secret) = { + let sender_identity_key = PKI::identity_key(&y_i.pki, sender) + .map_err(|err| DcgkaError::IdentityRegistry(err))? + .ok_or(DcgkaError::MissingIdentityKey(*sender))?; + let sender_member_secret: [u8; RATCHET_KEY_SIZE] = hkdf( + b"update", + &{ + let mut ikm = Vec::with_capacity(RATCHET_KEY_SIZE * 2); + ikm.extend_from_slice(next_seed.as_bytes()); + ikm.extend_from_slice(sender_identity_key.as_bytes()); + ikm + }, + None, + )?; + Self::update_ratchet(y_i, sender, ChainSecret::from_bytes(sender_member_secret))? + }; + + // We only store the member secrets, and not the seed secret, so that if the user's private + // state is compromised, the adversary obtains only those member secrets that have not yet + // been used. + drop(next_seed); // FS for "next_seed". + + // If the local user is the sender of the control message, we are now finished and return + // the update secret. + if sender == &y_ii.my_id { + return Ok(( + y_ii, + ProcessOutput { + control_message: None, + direct_messages: Vec::new(), + sender_update_secret: Some(sender_update_secret), + me_update_secret: None, + }, + )); + } + + // If we received the seed secret from another user, we construct an "ack" control message + // to broadcast, including the sender ID and sequence number of the message we are + // acknowledging. + let control = ControlMessage::Ack { + ack_sender: *sender, + ack_seq: seq, + }; + + // Care is required when an add operation occurs concurrently with an update, remove, or + // another add operation. We want all intended recipients to learn every update secret, + // since otherwise some users would not be able to decrypt some messages, despite being a + // group member. + // + // For example, consider a group with members {A, B, C}, and say A performs an update while + // concurrently C adds D to the group. When A distributes a new seed secret through + // 2SM-encrypted direct messages, D will not be a recipient of one of those direct + // messages, since A did not know about D's addition at the time of sending. D cannot + // derive any of the member secrets for this update. When B updates its KDF ratchet using + // A's seed secret, it will compute an update secret that D does not know, and D will not + // be able to decrypt B's subsequent application messages. + // + // In this example, B may receive the add and the update in either order. If B processes + // A's update first, the seed secret from A is already incorporated into B's ratchet state + // at the time of adding D; since B sends this ratchet state to D along with its "add-ack" + // message, no further action is needed. On the other hand, if B processes the addition of + // D first, then when B subsequently processes A's update, B must take the member secret it + // derives from A's seed secret and forward it to D, so that D can compute B's update + // secret for A's update. + // + // Recall that first we set recipients to be the set of group members at the time the + // update/remove was sent, except for the sender. We then compute the current set of + // members according to the local node. The set difference thus computes the set of users + // whose additions have been processed by the local user, but who were not yet known to + // the sender of the update. + // + // If there are any such users, we construct a direct message to each of them. One of the + // member secrets we computed before is the member secret for the local user. We + // 2SM-encrypt that member secret for each of the users who need it. This set forward is + // sent as direct messages along with the "ack". + let (y_iii, forward_messages) = { + let members: Vec = Self::member_view(&y_ii, &y_ii.my_id)? + .into_iter() + .filter(|member| member != sender && !recipients.contains(member)) + .collect(); + let mut forward_messages = Vec::with_capacity(members.len()); + + let mut y_loop = y_ii; + for member in members { + let member_secret_bytes = y_loop + .member_secrets + .get(&(*sender, seq, y_loop.my_id)) + .ok_or(DcgkaError::MissingMemberSecret(*sender, seq))? + .as_bytes() + .to_vec(); + let (y_next, ciphertext) = + Self::encrypt_to(y_loop, &member, &member_secret_bytes, rng)?; + y_loop = y_next; + forward_messages.push(DirectMessage { + recipient: member, + content: DirectMessageContent::Forward { ciphertext }, + }); + } + + (y_loop, forward_messages) + }; + + // Compute an update secret Ime for the local user. + let (y_iv, output) = { + let my_id = y_iii.my_id; + Self::process_ack(y_iii, my_id, (sender, seq), None)? + }; + let me_update_secret = output.sender_update_secret; + + Ok(( + y_iv, + ProcessOutput { + control_message: Some(control), + direct_messages: forward_messages, + sender_update_secret: Some(sender_update_secret), + me_update_secret, + }, + )) + } + + /// Uses 2SM to encrypt a direct message for another group member. The first time a message is + /// encrypted to a particular recipient ID, the 2SM protocol state is initialized and stored in + /// γ.2sm[ID]. We then use 2SM-Send to encrypt the message, and store the updated protocol + /// state in γ. + fn encrypt_to( + mut y: DcgkaState, + recipient: &ID, + plaintext: &[u8], + rng: &Rng, + ) -> DcgkaResult { + let y_2sm = match y.two_party.remove(recipient) { + Some(y_2sm) => y_2sm, + None => { + let (pki_i, prekey_bundle) = PKI::key_bundle(y.pki, recipient) + .map_err(|err| DcgkaError::PreKeyRegistry(err))?; + y.pki = pki_i; + let prekey_bundle = prekey_bundle.ok_or(DcgkaError::MissingPreKeys(*recipient))?; + TwoParty::::init_to_send(prekey_bundle) + } + }; + let (y_2sm_i, ciphertext) = + TwoParty::::send(y_2sm, &y.my_keys, plaintext, rng)?; + y.two_party.insert(*recipient, y_2sm_i); + Ok((y, ciphertext)) + } + + /// Is the reverse of encrypt_to. It similarly initializes the protocol state on first use, and + /// then uses 2SM-Receive to decrypt the ciphertext, with the protocol state stored in + /// γ.2sm[ID]. + fn decrypt_from( + mut y: DcgkaState, + sender: &ID, + ciphertext: TwoPartyMessage, + ) -> DcgkaResult> { + let y_2sm = match y.two_party.remove(sender) { + Some(y_2sm) => y_2sm, + None => { + let (pki_i, prekey_bundle) = PKI::key_bundle(y.pki, sender) + .map_err(|err| DcgkaError::PreKeyRegistry(err))?; + y.pki = pki_i; + let prekey_bundle = prekey_bundle.ok_or(DcgkaError::MissingPreKeys(*sender))?; + TwoParty::::init_to_send(prekey_bundle) + } + }; + let (y_2sm_i, y_my_keys_i, plaintext) = + TwoParty::::receive(y_2sm, y.my_keys, ciphertext)?; + y.my_keys = y_my_keys_i; + y.two_party.insert(*sender, y_2sm_i); + Ok((y, plaintext)) + } + + /// Generates the next update secret for group member ID. It implements the outer KDF of the + /// ratchet. The ratchet state is stored in γ.ratchet[ID]; we use an HMAC-based key derivation + /// function HKDF to combine the ratchet state with an input, producing an update secret and a + /// new ratchet state. + fn update_ratchet( + mut y: DcgkaState, + member: &ID, + member_secret: ChainSecret, + ) -> DcgkaResult { + let identity_key = PKI::identity_key(&y.pki, member) + .map_err(|err| DcgkaError::IdentityRegistry(err))? + .ok_or(DcgkaError::MissingIdentityKey(*member))?; + // Mix in the previous "outer" ratchet chain secret if it exists. + let previous_outer_ratchet_key = y.ratchet.get(member); + let update_secret: [u8; RATCHET_KEY_SIZE] = hkdf( + b"update", + &{ + let mut ikm = Vec::with_capacity(RATCHET_KEY_SIZE * 3); + if let Some(previous_outer_ratchet_key) = previous_outer_ratchet_key { + ikm.extend_from_slice(previous_outer_ratchet_key.as_bytes()); + } + ikm.extend_from_slice(member_secret.as_bytes()); + ikm.extend_from_slice(identity_key.as_bytes()); + ikm + }, + None, + )?; + let next_outer_ratchet_key: [u8; RATCHET_KEY_SIZE] = hkdf( + b"chain", + &{ + let mut ikm = Vec::with_capacity(RATCHET_KEY_SIZE * 3); + if let Some(previous_outer_ratchet_key) = previous_outer_ratchet_key { + ikm.extend_from_slice(previous_outer_ratchet_key.as_bytes()); + } + ikm.extend_from_slice(member_secret.as_bytes()); + ikm.extend_from_slice(identity_key.as_bytes()); + ikm + }, + None, + )?; + drop(member_secret); // FS for `member_secret` + y.ratchet + .insert(*member, ChainSecret::from_bytes(next_outer_ratchet_key)); + Ok((y, UpdateSecret::from_bytes(update_secret))) + } + + /// Computes the set of group members at the time of the most recent control message sent by + /// user ID. It works by filtering the set of group membership operations to contain only those + /// seen by ID, and then invoking the Decentralised Group Membership function DGM to compute + /// the group membership. + pub fn member_view( + y: &DcgkaState, + viewer: &ID, + ) -> Result, DcgkaError> { + let members = + DGM::members_view(&y.dgm, viewer).map_err(|err| DcgkaError::MembersView(err))?; + Ok(members) + } +} + +pub type GenerateSeedResult = Result< + ( + DcgkaState, + Vec>, + ), + DcgkaError, +>; + +pub type DcgkaResult = + Result<(DcgkaState, T), DcgkaError>; + +pub type DcgkaProcessResult = + DcgkaResult>; + +pub type DcgkaOperationResult = + DcgkaResult>; + +/// Message that should be broadcast to the group. +/// +/// The control message must be distributed to the other group members through Authenticated Causal +/// Broadcast, calling the process function on the recipient when they are delivered. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ControlMessage { + Create { initial_members: Vec }, + Ack { ack_sender: ID, ack_seq: OP }, + Update, + Remove { removed: ID }, + Add { added: ID }, + AddAck { ack_sender: ID, ack_seq: OP }, +} + +impl Display for ControlMessage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + ControlMessage::Create { .. } => "create", + ControlMessage::Ack { .. } => "ack", + ControlMessage::Update => "update", + ControlMessage::Remove { .. } => "remove", + ControlMessage::Add { .. } => "add", + ControlMessage::AddAck { .. } => "add_ack", + } + ) + } +} + +/// Arguments required to process a group operation received from another member. +#[derive(Clone, Debug)] +pub struct ProcessInput +where + DGM: AckedGroupMembership, +{ + /// Sequence number, which consecutively numbers successive control messages from the same + /// sender. + pub seq: OP, + + /// Author of this message. + pub sender: ID, + + /// Message received from this author. + pub control_message: ControlMessage, + + /// Optional direct message for us. + /// + /// Applications need to filter the direct message for the correct recipient before passing it + /// as an input. There can always only be max. 1 direct message per recipient. + pub direct_message: Option>, +} + +/// Calling "process" returns a 4-tuple `(control, dmsgs, Is, Ir)`, where `Is` is an update secret +/// for the sender of the message being processed, `Ir` is an update secret for the recipient. +#[derive(Debug)] +pub struct ProcessOutput +where + DGM: AckedGroupMembership, +{ + /// Control message that should be broadcast to the group. + pub control_message: Option>, + + /// Direct messages to be sent to specific members. + pub direct_messages: Vec>, + + /// Our next update key for the message ratchet for incoming messages from the sender. + pub sender_update_secret: Option, + + /// Our next update key for the message ratchet for outgoing messages to the group. + pub me_update_secret: Option, +} + +impl Default for ProcessOutput +where + DGM: AckedGroupMembership, +{ + fn default() -> Self { + Self { + control_message: None, + direct_messages: Vec::new(), + sender_update_secret: None, + me_update_secret: None, + } + } +} + +/// Calling "create", "add", "remove" and "update" return a tuple of three variables (`control`, +/// `dmsgs` and `I`) after changing the state for the current user. +/// +/// `control` is a control message that should be broadcast to the group, `dmsgs` is a set of `(u, +/// m)` pairs where `m` is a direct message that should be sent to user `u`, and `I` is a new +/// update secret for the current user. +pub struct OperationOutput +where + DGM: AckedGroupMembership, +{ + /// Control message that should be broadcast to the group. + pub control_message: ControlMessage, + + /// Set of messages directly to be sent to specific users. + pub direct_messages: Vec>, + + /// Our next update key for the message ratchet for outgoing messages to the group. + pub me_update_secret: Option, +} + +/// Direct message that should be sent to a single member. +/// +/// The direct message must be distributed to the other group members through Authenticated Causal +/// Broadcast, calling the process function on the recipient when they are delivered. +/// +/// If direct messages are sent along with a control message, we assume that the direct message for +/// the appropriate recipient is delivered in the same call to process. Our algorithm never sends a +/// direct message without an associated broadcast control message. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct DirectMessage +where + DGM: AckedGroupMembership, +{ + pub recipient: ID, + pub content: DirectMessageContent, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum DirectMessageContent +where + DGM: AckedGroupMembership, +{ + Welcome { + ciphertext: TwoPartyMessage, + history: DGM::State, + }, + TwoParty { + ciphertext: TwoPartyMessage, + }, + Forward { + ciphertext: TwoPartyMessage, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum DirectMessageType { + Welcome, + TwoParty, + Forward, +} + +impl Display for DirectMessageType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + DirectMessageType::Welcome => "welcome", + DirectMessageType::TwoParty => "2sm", + DirectMessageType::Forward => "forward", + } + ) + } +} + +impl DirectMessage +where + DGM: AckedGroupMembership, +{ + pub fn message_type(&self) -> DirectMessageType { + match self.content { + DirectMessageContent::Welcome { .. } => DirectMessageType::Welcome, + DirectMessageContent::TwoParty { .. } => DirectMessageType::TwoParty, + DirectMessageContent::Forward { .. } => DirectMessageType::Forward, + } + } +} + +/// Randomly generated seed we keep temporarily around when creating or updating a group or +/// removing a member. +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct NextSeed(Secret); + +impl NextSeed { + pub fn from_bytes(bytes: [u8; RATCHET_KEY_SIZE]) -> Self { + Self(Secret::from_bytes(bytes)) + } + + pub fn try_from_bytes( + bytes: &[u8], + ) -> Result> + where + PKI: IdentityRegistry + PreKeyRegistry, + DGM: AckedGroupMembership, + KMG: PreKeyManager, + { + let bytes: [u8; RATCHET_KEY_SIZE] = + bytes.try_into().map_err(|_| DcgkaError::InvalidKeySize)?; + Ok(Self::from_bytes(bytes)) + } + + pub(crate) fn as_bytes(&self) -> &[u8; RATCHET_KEY_SIZE] { + self.0.as_bytes() + } +} + +/// Chain secret for the "outer" key-agreement ratchet. +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct ChainSecret(Secret); + +impl ChainSecret { + pub fn from_welcome() -> Self { + // BLAKE3 hash of the byte-representation of the utf8 string "welcome". + Self::from_bytes([ + 168, 234, 241, 118, 147, 12, 137, 47, 48, 26, 61, 243, 183, 11, 158, 143, 99, 219, 142, + 131, 41, 18, 245, 167, 132, 195, 241, 26, 89, 106, 154, 134, + ]) + } + + pub fn from_add() -> Self { + // BLAKE3 hash of the byte-representation of the utf8 string "add". + Self::from_bytes([ + 58, 3, 204, 193, 45, 117, 68, 208, 41, 238, 11, 13, 169, 250, 180, 215, 22, 4, 43, 226, + 179, 34, 182, 188, 85, 49, 221, 39, 150, 98, 220, 156, + ]) + } + + pub fn from_bytes(bytes: [u8; RATCHET_KEY_SIZE]) -> Self { + Self(Secret::from_bytes(bytes)) + } + + pub fn try_from_bytes( + bytes: &[u8], + ) -> Result> + where + PKI: IdentityRegistry + PreKeyRegistry, + DGM: AckedGroupMembership, + KEY: PreKeyManager, + { + let bytes: [u8; RATCHET_KEY_SIZE] = + bytes.try_into().map_err(|_| DcgkaError::InvalidKeySize)?; + Ok(Self::from_bytes(bytes)) + } + + pub(crate) fn as_bytes(&self) -> &[u8; RATCHET_KEY_SIZE] { + self.0.as_bytes() + } +} + +impl From for ChainSecret { + fn from(value: UpdateSecret) -> Self { + Self(value.0) + } +} + +/// Chain secret for the "inner" message ratchet. +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct UpdateSecret(Secret); + +impl UpdateSecret { + pub fn from_bytes(bytes: [u8; RATCHET_KEY_SIZE]) -> Self { + Self(Secret::from_bytes(bytes)) + } + + pub fn try_from_bytes( + bytes: &[u8], + ) -> Result> + where + PKI: IdentityRegistry + PreKeyRegistry, + DGM: AckedGroupMembership, + KMG: PreKeyManager, + { + let bytes: [u8; RATCHET_KEY_SIZE] = + bytes.try_into().map_err(|_| DcgkaError::InvalidKeySize)?; + Ok(Self::from_bytes(bytes)) + } + + #[cfg(any(test, feature = "test_utils"))] + pub fn as_bytes(&self) -> &[u8; RATCHET_KEY_SIZE] { + self.0.as_bytes() + } +} + +impl From for Secret { + fn from(update_secret: UpdateSecret) -> Self { + update_secret.0 + } +} + +#[derive(Debug, Error)] +pub enum DcgkaError +where + PKI: IdentityRegistry + PreKeyRegistry, + DGM: AckedGroupMembership, + KMG: PreKeyManager, +{ + #[error("the given key does not match the required 32 byte length")] + InvalidKeySize, + + #[error("expected ratchet secret but couldn't find anything")] + MissingRatchetSecret, + + #[error("expected message secret for {0} at seq {1} but couldn't find anything")] + MissingMemberSecret(ID, OP), + + #[error("expected direct message of type \"{0}\" but got nothing instead")] + MissingDirectMessage(DirectMessageType), + + #[error("expected direct message of type \"{0}\" but got message of type \"{1}\" instead")] + UnexpectedDirectMessageType(DirectMessageType, DirectMessageType), + + #[error("direct message recipient mismatch, expected recipient: {1}, actual recipient: {0}")] + NotOurDirectMessage(ID, ID), + + #[error("computing members view from dgm failed: {0}")] + MembersView(DGM::Error), + + #[error("dgm operation failed: {0}")] + DgmOperation(DGM::Error), + + #[error("failed retrieving bundle from pre key registry: {0}")] + PreKeyRegistry(>::Error), + + #[error("failed retrieving identity from registry: {0}")] + IdentityRegistry(>::Error), + + #[error("missing key bundle for member {0}")] + MissingPreKeys(ID), + + #[error("missing identity key for member {0}")] + MissingIdentityKey(ID), + + #[error(transparent)] + Rng(#[from] RngError), + + #[error(transparent)] + KeyManager(KMG::Error), + + #[error(transparent)] + TwoParty(#[from] TwoPartyError), + + #[error(transparent)] + Hdkf(#[from] HkdfError), +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/group.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/group.rs new file mode 100644 index 0000000000..a2b6a13a4b --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/group.rs @@ -0,0 +1,725 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! API to manage groups using the "Message Encryption" scheme and process remote control- and +//! application messages. +#![allow(clippy::type_complexity)] +use std::collections::{HashMap, HashSet}; +use std::hash::Hash as StdHash; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::Rng; +use crate::crypto::aead::AeadError; +use crate::key_bundle::OneTimeKeyBundle; +use crate::message_scheme::dcgka::{ + ControlMessage, Dcgka, DcgkaError, DcgkaState, DirectMessage, OperationOutput, ProcessInput, +}; +use crate::message_scheme::message::{decrypt_message, encrypt_message}; +use crate::message_scheme::ratchet::{ + DecryptionRatchet, DecryptionRatchetState, Generation, RatchetError, RatchetSecret, + RatchetSecretState, +}; +use crate::traits::{ + AckedGroupMembership, ForwardSecureGroupMessage, ForwardSecureMessageContent, + ForwardSecureOrdering, IdentityHandle, IdentityManager, IdentityRegistry, OperationId, + PreKeyManager, PreKeyRegistry, +}; + +/// API to manage groups using the "Message Encryption" scheme with strong security guarantees. +pub struct MessageGroup { + _marker: PhantomData<(ID, OP, PKI, DGM, KMG, ORD)>, +} + +/// Group state for "Message Encryption" scheme. Serializable for persistence. +#[derive(Debug, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct GroupState +where + ID: IdentityHandle, + OP: OperationId, + PKI: IdentityRegistry + PreKeyRegistry, + PKI::State: Clone, + DGM: AckedGroupMembership, + KMG: IdentityManager + PreKeyManager, + KMG::State: Clone, + ORD: ForwardSecureOrdering, +{ + pub(crate) my_id: ID, + pub(crate) dcgka: DcgkaState, + pub(crate) orderer: ORD::State, + pub(crate) welcome: Option, + pub(crate) ratchet: Option, + pub(crate) decryption_ratchet: HashMap, + pub(crate) config: GroupConfig, +} + +impl MessageGroup +where + ID: IdentityHandle, + OP: OperationId, + PKI: IdentityRegistry + PreKeyRegistry, + PKI::State: Clone, + DGM: AckedGroupMembership, + KMG: IdentityManager + PreKeyManager, + KMG::State: Clone, + ORD: ForwardSecureOrdering, +{ + /// Returns initial state for messaging group. + /// + /// This needs to be called before creating or being added to a group. + pub fn init( + my_id: ID, + my_keys: KMG::State, + pki: PKI::State, + dgm: DGM::State, + orderer: ORD::State, + config: GroupConfig, + ) -> GroupState { + GroupState { + my_id, + dcgka: Dcgka::init(my_id, my_keys, pki, dgm), + orderer, + welcome: None, + ratchet: None, + decryption_ratchet: HashMap::new(), + config, + } + } + + /// Creates new group with initial set of members. + pub fn create( + mut y: GroupState, + initial_members: Vec, + rng: &Rng, + ) -> GroupResult { + // If we have an encryption ratchet we already established a group (either by creating or + // processing a "welcome" message in the past). + if y.ratchet.is_some() { + return Err(GroupError::GroupAlreadyEstablished); + } + + // Create new group with initial members. + let (y_dcgka_i, pre) = Dcgka::create(y.dcgka, initial_members, rng)?; + y.dcgka = y_dcgka_i; + + let (mut y_i, message) = Self::process_local(y, pre, rng)?; + + // Set our own "create" as the "welcome" message. + let y_orderer_i = ORD::set_welcome(y_i.orderer, &message).map_err(GroupError::Orderer)?; + y_i.orderer = y_orderer_i; + + Ok((y_i, message)) + } + + /// Adds new member to group. + pub fn add( + mut y: GroupState, + added: ID, + rng: &Rng, + ) -> GroupResult { + if y.ratchet.is_none() { + return Err(GroupError::GroupNotYetEstablished); + } + + if y.my_id == added { + return Err(GroupError::NotAddOurselves); + } + + if Self::members(&y)?.contains(&added) { + return Err(GroupError::AddedExistsAlready(added)); + } + + // Add a new member to the group. + let (y_dcgka_i, pre) = Dcgka::add(y.dcgka, added, rng)?; + y.dcgka = y_dcgka_i; + + Self::process_local(y, pre, rng) + } + + /// Removes member from group. It is possible to remove ourselves. + pub fn remove( + mut y: GroupState, + removed: ID, + rng: &Rng, + ) -> GroupResult { + if y.ratchet.is_none() { + return Err(GroupError::GroupNotYetEstablished); + } + + if !Self::members(&y)?.contains(&removed) { + return Err(GroupError::InexistentRemovedMember(removed)); + } + + // Remove a member from the group. + let (y_dcgka_i, pre) = Dcgka::remove(y.dcgka, removed, rng)?; + y.dcgka = y_dcgka_i; + + Self::process_local(y, pre, rng) + } + + /// Updates group secret and provides all members with fresh entropy. + pub fn update( + mut y: GroupState, + rng: &Rng, + ) -> GroupResult { + if y.ratchet.is_none() { + return Err(GroupError::GroupNotYetEstablished); + } + + // Update the group by generating a new seed. + let (y_dcgka_i, pre) = Dcgka::update(y.dcgka, rng)?; + y.dcgka = y_dcgka_i; + + Self::process_local(y, pre, rng) + } + + /// Handler for incoming, remote messages. + /// + /// This yields a list of "outputs" which can be either control messages which need to be + /// broadcast to all members in the group or decrypted application message payloads. + /// + /// If we got removed after processing a control message we will receive a "removed" output + /// signal. + pub fn receive( + mut y: GroupState, + message: &ORD::Message, + rng: &Rng, + ) -> GroupResult>, ID, OP, PKI, DGM, KMG, ORD> { + // Remember current members state so we can calculate a diff after processing these + // messages. + let members_pre = Self::members(&y)?; + + let message_type = message.content(); + let is_established = y.ratchet.is_some(); + let mut is_create_or_welcome = false; + + // Accept "create" control messages if we haven't established our state yet and if we are + // part of the initial members set. + if let ForwardSecureMessageContent::Control(ControlMessage::Create { + ref initial_members, + }) = message_type + { + if is_established { + return Err(GroupError::GroupAlreadyEstablished); + } + + if initial_members.contains(&y.my_id) { + is_create_or_welcome = true; + } + } + + // Accept "add" control messages if we are being added by it. + if let ForwardSecureMessageContent::Control(ControlMessage::Add { added }) = message_type + && !is_established + && added == y.my_id + { + is_create_or_welcome = true; + } + + let y_orderer_i = ORD::queue(y.orderer, message).map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + + if !is_established && !is_create_or_welcome { + // We're receiving control- and application messages for this group but we haven't + // joined yet. We keep these messages for later. We don't know yet when we will join + // the group and which of these messages we can process afterwards. + return Ok((y, None)); + } + + if !is_established && is_create_or_welcome { + // We've received a "create" or "add" (welcome) message for us and can join the group + // now. + let y_orderer_i = ORD::set_welcome(y.orderer, message).map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + + // Remember welcome message for later. + y.welcome = Some(message.clone()); + + // Always process welcome message first before anything else. + let (y_i, result) = Self::process_ready(y, message, rng)?; + + let members_post = Self::members(&y_i)?; + + return Ok(( + y_i, + result.map(|output| GroupOutput::new(vec![output], members_pre, members_post)), + )); + } + + let mut events = Vec::new(); + let mut y_loop = y; + + // Check if there's any correctly ordered messages ready to-be processed. + loop { + let (y_orderer_next, result) = + ORD::next_ready_message(y_loop.orderer).map_err(GroupError::Orderer)?; + y_loop.orderer = y_orderer_next; + + let Some(message) = result else { + // Orderer is done yielding "ready" messages, stop here and try again later when we + // receive new messages. + break; + }; + + if let Some(welcome) = &y_loop.welcome { + // Skip processing welcome again, we've already done that after receiving it. + if welcome.id() == message.id() { + continue; + } + } + + let (y_next, result) = Self::process_ready(y_loop, &message, rng)?; + y_loop = y_next; + if let Some(message) = result { + events.push(message); + } + } + + let members_post = Self::members(&y_loop)?; + + Ok(( + y_loop, + Some(GroupOutput::new(events, members_pre, members_post)), + )) + } + + /// Encrypts application message towards the current group. + /// + /// The returned message can then be broadcast to all members in the group. The underlying + /// protocol makes sure that all members will be able to decrypt this message. + pub fn send( + mut y: GroupState, + plaintext: &[u8], + ) -> GroupResult { + let Some(y_ratchet) = y.ratchet else { + return Err(GroupError::GroupNotYetEstablished); + }; + + // Encrypt application message. + let (y_ratchet_i, generation, ciphertext) = Self::encrypt(y_ratchet, plaintext)?; + y.ratchet = Some(y_ratchet_i); + + // Determine parameters for to-be-published application message. + let (y_orderer_i, message) = + ORD::next_application_message(y.orderer, generation, ciphertext) + .map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + + Ok((y, message)) + } + + /// Returns a list of all current members in this group from our perspective. + pub fn members( + y: &GroupState, + ) -> Result, GroupError> { + let members = Dcgka::member_view(&y.dcgka, &y.my_id)?; + Ok(members) + } + + /// Processes our own locally created control messages. + fn process_local( + mut y: GroupState, + output: OperationOutput, + rng: &Rng, + ) -> GroupResult { + // Determine parameters for to-be-published control message. + let (y_orderer_i, message) = + ORD::next_control_message(y.orderer, &output.control_message, &output.direct_messages) + .map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + + // Process control message locally to update our state. + let (y_dcgka_i, process) = Dcgka::process_local(y.dcgka, message.id(), output, rng)?; + y.dcgka = y_dcgka_i; + + // Update own encryption ratchet for sending application messages. + y.ratchet = Some(RatchetSecret::init( + process + .me_update_secret + .expect("local operation always yields an update secret for us") + .into(), + )); + + Ok((y, message)) + } + + /// Processes remote messages which have been marked as "ready" by the orderer. + fn process_ready( + y: GroupState, + message: &ORD::Message, + rng: &Rng, + ) -> GroupResult>, ID, OP, PKI, DGM, KMG, ORD> { + match message.content() { + ForwardSecureMessageContent::Control(control_message) => { + let direct_message = message + .direct_messages() + .into_iter() + .find(|dm| dm.recipient == y.my_id); + + let (y_i, output) = Self::process_remote( + y, + message.id(), + message.sender(), + control_message, + direct_message, + rng, + )?; + + // Check if processing this message removed us from the group. + let is_removed = !Self::members(&y_i)?.contains(&y_i.my_id); + if is_removed { + Ok((y_i, Some(GroupEvent::RemovedOurselves))) + } else { + Ok((y_i, output.map(|msg| GroupEvent::Control(msg)))) + } + } + ForwardSecureMessageContent::Application { + ciphertext, + generation, + } => { + let (y_i, plaintext) = Self::decrypt(y, message.sender(), ciphertext, generation)?; + Ok(( + y_i, + Some(GroupEvent::Application { + plaintext, + message_id: message.id(), + }), + )) + } + } + } + + /// Internal method to process remote control message. + fn process_remote( + mut y: GroupState, + seq: OP, + sender: ID, + control_message: ControlMessage, + direct_message: Option>, + rng: &Rng, + ) -> GroupResult, ID, OP, PKI, DGM, KMG, ORD> { + let (y_dcgka_i, output) = Dcgka::process_remote( + y.dcgka, + ProcessInput { + seq, + sender, + control_message, + direct_message, + }, + rng, + )?; + y.dcgka = y_dcgka_i; + + // Update own encryption ratchet for sending application messages. + if let Some(me_update_secret) = output.me_update_secret { + y.ratchet = Some(RatchetSecret::init(me_update_secret.into())); + } + + // Update decryption ratchet for receiving application messages from this sender. + if let Some(sender_update_secret) = output.sender_update_secret { + y.decryption_ratchet + .insert(sender, DecryptionRatchet::init(sender_update_secret.into())); + } + + if let Some(output_control_message) = output.control_message { + // Determine parameters for to-be-published control message. + let (y_orderer_i, output_message) = ORD::next_control_message( + y.orderer, + &output_control_message, + &output.direct_messages, + ) + .map_err(GroupError::Orderer)?; + y.orderer = y_orderer_i; + Ok((y, Some(output_message))) + } else { + Ok((y, None)) + } + } + + /// Encrypt message by using our ratchet. + fn encrypt( + y_ratchet: RatchetSecretState, + plaintext: &[u8], + ) -> Result<(RatchetSecretState, Generation, Vec), GroupError> + { + // Derive key material to encrypt message from our ratchet. + let (y_ratchet_i, generation, key_material) = + RatchetSecret::ratchet_forward(y_ratchet).map_err(GroupError::EncryptionRatchet)?; + + // Encrypt message. + let ciphertext = encrypt_message(plaintext, key_material)?; + + Ok((y_ratchet_i, generation, ciphertext)) + } + + /// Decrypt message by using the sender's ratchet. + fn decrypt( + mut y: GroupState, + sender: ID, + ciphertext: Vec, + generation: Generation, + ) -> GroupResult, ID, OP, PKI, DGM, KMG, ORD> { + let Some(y_decryption_ratchet) = y.decryption_ratchet.remove(&sender) else { + return Err(GroupError::DecryptionRachetUnavailable(sender, generation)); + }; + + // Try to derive required key material from ratchet. + let (y_decryption_ratchet_i, key_material) = DecryptionRatchet::secret_for_decryption( + y_decryption_ratchet, + generation, + y.config.maximum_forward_distance, + y.config.out_of_order_tolerance, + ) + .map_err(GroupError::DecryptionRatchet)?; + y.decryption_ratchet.insert(sender, y_decryption_ratchet_i); + + // Attempt to decrypt message. + let plaintext = decrypt_message(&ciphertext, key_material)?; + + Ok((y, plaintext)) + } +} + +pub type GroupResult = + Result<(GroupState, T), GroupError>; + +/// Result from processing a remote message or calling a local group operation. +#[derive(Clone, Default)] +pub struct GroupOutput +where + ID: Clone + Eq + PartialEq + StdHash, + DGM: AckedGroupMembership, + ORD: ForwardSecureOrdering, +{ + pub events: Vec>, + pub removed_members: HashSet, + pub added_members: HashSet, +} + +impl GroupOutput +where + ID: Clone + Eq + PartialEq + StdHash, + DGM: AckedGroupMembership, + ORD: ForwardSecureOrdering, +{ + pub(crate) fn new( + events: Vec>, + pre_members: HashSet, + post_members: HashSet, + ) -> Self { + let added_members = post_members.difference(&pre_members).cloned().collect(); + let removed_members = pre_members.difference(&post_members).cloned().collect(); + + GroupOutput { + events, + removed_members, + added_members, + } + } +} + +/// Dispatched event after processing a group message. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GroupEvent +where + DGM: AckedGroupMembership, + ORD: ForwardSecureOrdering, +{ + /// Control message for group encryption which should be broadcast to all members of the group. + Control(ORD::Message), + + /// Decrypted payload of message. + Application { plaintext: Vec, message_id: OP }, + + /// Signal that we've been removed from the group. + RemovedOurselves, +} + +/// Configuration for the message ratchets used in this group. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GroupConfig { + /// This parameter defines how many incoming messages can be skipped. This is useful if the + /// application drops messages. + pub maximum_forward_distance: u32, + + /// This parameter defines a window for which decryption secrets are kept. This is useful in + /// case the ratchet cannot guarantee that all application messages have total order within an + /// epoch. Use this carefully, since keeping decryption secrets affects forward secrecy within + /// an epoch. + pub out_of_order_tolerance: u32, +} + +impl Default for GroupConfig { + fn default() -> Self { + Self { + maximum_forward_distance: 1000, + out_of_order_tolerance: 100, + } + } +} + +#[derive(Debug, Error)] +pub enum GroupError +where + PKI: IdentityRegistry + PreKeyRegistry, + DGM: AckedGroupMembership, + KMG: PreKeyManager, + ORD: ForwardSecureOrdering, +{ + #[error(transparent)] + Dcgka(#[from] DcgkaError), + + #[error(transparent)] + Orderer(ORD::Error), + + #[error(transparent)] + EncryptionRatchet(RatchetError), + + #[error(transparent)] + DecryptionRatchet(RatchetError), + + #[error(transparent)] + Aead(#[from] AeadError), + + #[error("creating or joining a group is not possible, state is already established")] + GroupAlreadyEstablished, + + #[error("state is not ready yet, group needs to be created or joined first")] + GroupNotYetEstablished, + + #[error("can not add ourselves to the group")] + NotAddOurselves, + + #[error("received \"create\" or \"add\" message addressing us but no direct message attached")] + DirectMessageMissing, + + #[error("decryption ratchet not established yet to process the message from {0} @{1}")] + DecryptionRachetUnavailable(ID, Generation), + + #[error("to-be-added member {0} is already part of the group")] + AddedExistsAlready(ID), + + #[error("to-be-removed member {0} is not part of the group")] + InexistentRemovedMember(ID), +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + use crate::message_scheme::test_utils::network::Network; + + #[test] + fn simple_group() { + let alice = 0; + let bob = 1; + + let mut network = Network::new([alice, bob], Rng::from_seed([1; 32])); + + // Alice creates a group with Bob. + network.create(alice, vec![bob]); + + // Everyone processes each other's messages. + let results = network.process(); + assert!( + results.is_empty(), + "no decrypted application messages expected" + ); + + // Alice and Bob share the same members view. + for member in [alice, bob] { + assert_eq!(network.members(&member), vec![alice, bob]); + } + + // Alice sends a message to the group and Bob can decrypt it. + network.send(alice, b"Hello everyone!"); + assert_eq!( + network.process(), + vec![(alice, bob, b"Hello everyone!".to_vec())], + ); + } + + #[test] + fn welcome() { + let alice = 0; + let bob = 1; + let charlie = 2; + + let mut network = Network::new([alice, bob, charlie], Rng::from_seed([1; 32])); + + // Alice creates a group with Bob. + network.create(alice, vec![bob]); + network.process(); + + // Bob updates the group. + network.update(bob); + network.process(); + + // Bob sends a message to the group and Alice can decrypt it. + network.send(bob, b"Huhu"); + assert_eq!(network.process(), vec![(bob, alice, b"Huhu".to_vec())],); + + // Bob adds Charlie. Charlie will process their "welcome" message now to join. + network.add(bob, charlie); + network.process(); + + // Alice sends a message to the group and Bob and Charlie can decrypt it. + network.send(alice, b"Hello everyone!"); + assert_eq!( + network.process(), + vec![ + (alice, bob, b"Hello everyone!".to_vec()), + (alice, charlie, b"Hello everyone!".to_vec()), + ], + ); + } + + #[test] + fn concurrency() { + let alice = 0; + let bob = 1; + let charlie = 2; + + let mut network = Network::new([alice, bob, charlie], Rng::from_seed([1; 32])); + + // Alice creates a group with Bob. + network.create(alice, vec![bob]); + network.process(); + + // Bob updates the group and concurrently Alice adds Charlie. + network.update(bob); + network.add(alice, charlie); + network.process(); + + // Bob sends a message to the group and Alice and Charlie can decrypt it. + network.send(bob, b"Hello everyone!"); + assert_eq!( + network.process(), + vec![ + (bob, alice, b"Hello everyone!".to_vec()), + (bob, charlie, b"Hello everyone!".to_vec()), + ], + ); + } + + #[test] + fn removal() { + let alice = 0; + let bob = 1; + let charlie = 2; + + let mut network = Network::new([alice, bob, charlie], Rng::from_seed([1; 32])); + + network.create(alice, vec![alice, bob, charlie]); + network.process(); + + // Alice removes Bob. + network.remove(alice, bob); + network.process(); + + // Charlie removes themselves. + network.remove(charlie, charlie); + network.process(); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/message.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/message.rs new file mode 100644 index 0000000000..a4bed34129 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/message.rs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::crypto::aead::{AeadError, aead_decrypt, aead_encrypt}; +use crate::message_scheme::ratchet::RatchetKeyMaterial; + +pub fn encrypt_message( + plaintext: &[u8], + ratchet_secrets: RatchetKeyMaterial, +) -> Result, AeadError> { + let (key, nonce) = ratchet_secrets; + let ciphertext = aead_encrypt(key.as_bytes(), plaintext, nonce, None)?; + Ok(ciphertext) +} + +pub fn decrypt_message( + ciphertext: &[u8], + ratchet_secrets: RatchetKeyMaterial, +) -> Result, AeadError> { + let (key, nonce) = ratchet_secrets; + let plaintext = aead_decrypt(key.as_bytes(), ciphertext, nonce, None)?; + Ok(plaintext) +} + +#[cfg(test)] +mod tests { + use crate::Rng; + use crate::crypto::Secret; + use crate::message_scheme::{DecryptionRatchet, MESSAGE_KEY_SIZE, RatchetSecret}; + + use super::{decrypt_message, encrypt_message}; + + #[test] + fn message_ratcheting() { + let rng = Rng::from_seed([1; 32]); + + let update_secret = Secret::from_bytes(rng.random_array::().unwrap()); + + let ooo_tolerance = 4; + let max_forward = 10; + + let alice = RatchetSecret::init(update_secret.clone()); + let bob = DecryptionRatchet::init(update_secret); + + let (alice, generation_0, alice_secret_0) = RatchetSecret::ratchet_forward(alice).unwrap(); + let message_0 = encrypt_message(b"I scream, you scream!", alice_secret_0).unwrap(); + + let (bob, bob_secret_0) = + DecryptionRatchet::secret_for_decryption(bob, generation_0, max_forward, ooo_tolerance) + .unwrap(); + let receive_0 = decrypt_message(&message_0, bob_secret_0).unwrap(); + assert_eq!(receive_0, b"I scream, you scream!"); + + let (_alice, generation_1, alice_secret_1) = RatchetSecret::ratchet_forward(alice).unwrap(); + let message_1 = encrypt_message(b"We all scream for ice-cream!", alice_secret_1).unwrap(); + + let (_bob, bob_secret_1) = + DecryptionRatchet::secret_for_decryption(bob, generation_1, max_forward, ooo_tolerance) + .unwrap(); + let receive_1 = decrypt_message(&message_1, bob_secret_1).unwrap(); + assert_eq!(receive_1, b"We all scream for ice-cream!"); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/mod.rs new file mode 100644 index 0000000000..26a46715fc --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/mod.rs @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Message Encryption for groups offering a forward secure (FS) messaging ratchet, similar to +//! Signal's [Double Ratchet algorithm](https://en.wikipedia.org/wiki/Double_Ratchet_Algorithm). +//! +//! Since secret keys are always generated for each message, a user can not easily learn about +//! previously-created messages when getting hold of such a key. We believe that the latter scheme +//! will be used in more specialised applications, for example p2p group chats, as strong forward +//! secrecy comes with it's own UX requirements. We are nonetheless excited to offer a solution for +//! both worlds, depending on the application's needs. +//! +//! ## Messages +//! +//! Every group operation ([create](MessageGroup::create) or [update](MessageGroup::update) +//! group, [add](MessageGroup::add) or [remove](MessageGroup::remove) member) results in a +//! [`ControlMessage`] which is broadcast to the network for each group member and a set of direct +//! messages. +//! +//! A [`DirectMessage`] is sent to a specific group member and contains the group secrets encrypted +//! towards them for key agreement. +//! +//! Application messages contain the ciphertexts and parameters required to decrypt it using a +//! message ratchet. +//! +//! ## Message Ratchets +//! +//! The "inner" message ratchet derives a ChaCha20Poly1305 AEAD secret and nonce for message +//! encryption for each "generation". Each peer maintains their own [`RatchetSecret`] for sending +//! messages and keeps around one [`DecryptionRatchet`] per other member in the group to decrypt +//! received messages from them. +//! +//! Messages arriving out of order or getting lost are tolerated within the [configured +//! limits](group::GroupConfig). +//! +//! ## Key Agreement +//! +//! Extra care is required to keep the chain secrets, updating the "outer" ratchets in a strict, linearized +//! order. Consult the [DCGKA](dcgka) module for more information. +//! +//! ## Key bundles +//! +//! For initial key agreement (X3DH) peers need to publish key bundles into the network to allow +//! others to invite them into groups. For the "Message Encryption" scheme we're using one-time +//! pre-keys which bring additional requirements due to their "only use once" limitation. +//! +//! More on key bundles can be read [here](crate::key_bundle). +//! +//! ## Usage +//! +//! Check out the [`MessageGroup`] API for establishing and maintaining groups using the "Message +//! Encryption" scheme. +//! +//! Developers need to bring their own data types with [group message +//! interfaces](crate::traits::ForwardSecureGroupMessage), [decentralised group +//! membership](crate::traits::AckedGroupMembership) (DGM) and +//! [ordering](crate::traits::ForwardSecureOrdering) implementations when using this crate +//! directly, for easier use without this overhead it's recommended to look into higher-level +//! integrations using the p2panda stack. +pub mod dcgka; +pub mod group; +mod message; +pub mod ratchet; +#[cfg(any(test, feature = "test_utils"))] +pub mod test_utils; +#[cfg(test)] +mod tests; + +pub use dcgka::{ControlMessage, DirectMessage, DirectMessageContent, DirectMessageType}; +pub use group::{GroupError, GroupEvent, GroupOutput, GroupState, MessageGroup}; +pub use message::{decrypt_message, encrypt_message}; +pub use ratchet::{ + DecryptionRatchet, DecryptionRatchetState, Generation, MESSAGE_KEY_SIZE, RatchetError, + RatchetSecret, RatchetSecretState, +}; diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/ratchet.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/ratchet.rs new file mode 100644 index 0000000000..a2cdb94a5c --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/ratchet.rs @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Encryption and decryption ratches with lost or out-of-order messages. +use std::collections::VecDeque; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::Secret; +use crate::crypto::aead::AeadNonce; +use crate::crypto::hkdf::{HkdfError, hkdf}; + +/// 256-bit secret message key. +pub const MESSAGE_KEY_SIZE: usize = 32; + +/// Secret message key. +pub type RatchetKey = Secret; + +/// AEAD nonce to encrypt message. +pub type RatchetNonce = AeadNonce; + +/// AEAD parameters to encrypt message. +pub type RatchetKeyMaterial = (RatchetKey, RatchetNonce); + +/// Key generation of message ratchet. +pub type Generation = u32; + +/// Message ratchet that can output key material either for encryption or decryption. +#[derive(Debug)] +pub struct RatchetSecret; + +#[derive(Debug, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct RatchetSecretState { + secret: Secret, + generation: Generation, +} + +impl RatchetSecret { + pub fn init(secret: Secret) -> RatchetSecretState { + RatchetSecretState { + secret, + generation: 0, + } + } + + /// Consume the current ratchet secret to derive key material and establish a new secret for + /// the next generation. + pub fn ratchet_forward( + mut y: RatchetSecretState, + ) -> Result<(RatchetSecretState, Generation, RatchetKeyMaterial), RatchetError> { + let generation = y.generation; + + // Derive key material from current secret. + let nonce: AeadNonce = hkdf(b"nonce", y.secret.as_bytes(), None)?; + let key: [u8; MESSAGE_KEY_SIZE] = hkdf(b"key", y.secret.as_bytes(), None)?; + + // Ratchet forward. + y.generation += 1; + y.secret = Secret::from_bytes(hkdf(b"chain", y.secret.as_bytes(), None)?); + + Ok((y, generation, (Secret::from_bytes(key), nonce))) + } +} + +/// Message ratchet for decryption with support for handling lost or out-of-order messages. +/// +/// ## Out-of-order handling +/// +/// Out-of-order messages cause the ratchet to "jump" ahead and keep "unused" keys persisted until +/// they're used eventually. +/// +/// In this example our chain has a length of 2 at the moment a message for generation 4 arrives +/// out of order (we've expected generation 2). Now we pre-generate the keys for the "jumped" +/// messages (generation 2 and 3) and keep them persisted for later. We decrypt the new message for +/// generation 4 with the regular, now "latest", chain state. +/// +/// ```text +/// 0 +/// 1 <- Current chain "head" +/// 2 +/// 3 +/// 4 <- New chain "head" after receiving message @ generation 4 +/// ``` +/// +/// ## Tolerance limits +/// +/// Developers can and should set bounds to how much a decryption ratchet can tolerate messages +/// arriving out of order, that is, into the "future" and into the "past". Setting these "window" +/// limits has implications for the forward secrecy of an application as unused keys stay around +/// for a while. A setting should be picked wisely based on the network's reliability to deliver +/// and order messages and security requirements. +#[derive(Debug)] +pub struct DecryptionRatchet; + +#[derive(Debug, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct DecryptionRatchetState { + past_secrets: VecDeque>, + ratchet_head: RatchetSecretState, +} + +impl DecryptionRatchet { + pub fn init(secret: Secret) -> DecryptionRatchetState { + DecryptionRatchetState { + past_secrets: VecDeque::new(), + ratchet_head: RatchetSecret::init(secret), + } + } + + /// Returns a secret from the ratchet for decryption. Throws an error if requested secret is + /// out of bounds. + /// + /// ## Limits Configuration + /// + /// - Out-of-order (ooo) tolerance: + /// This parameter defines a window for which decryption secrets are kept. This is useful in + /// case the ratchet cannot guarantee that all application messages have total order within + /// an epoch. Use this carefully, since keeping decryption secrets affects forward secrecy + /// within an epoch. + /// - Maximum forward distance: + /// This parameter defines how many incoming messages can be skipped. This is useful if the + /// application drops messages. + pub fn secret_for_decryption( + mut y: DecryptionRatchetState, + generation: Generation, + maximum_forward_distance: u32, + ooo_tolerance: u32, + ) -> Result<(DecryptionRatchetState, RatchetKeyMaterial), RatchetError> { + let generation_head = y.ratchet_head.generation; + + // If generation is too distant in the future. + if generation_head < u32::MAX - maximum_forward_distance + && generation > generation_head + maximum_forward_distance + { + return Err(RatchetError::TooDistantInTheFuture); + } + + // If generation is too distant in the past. + if generation < generation_head && (generation_head - generation) > ooo_tolerance { + return Err(RatchetError::TooDistantInThePast); + } + + // If generation is the one the ratchet is currently at (regular case) or in the future. + if generation >= generation_head { + // Ratchet the chain forward as far as necessary. + for _ in 0..(generation - generation_head) { + // Derive the key material. + let (y_ratchet_head_i, _, ratchet_secrets) = + RatchetSecret::ratchet_forward(y.ratchet_head)?; + y.ratchet_head = y_ratchet_head_i; + // Add it to the front of the queue. + y.past_secrets.push_front(Some(ratchet_secrets)); + } + let (y_ratchet_head_i, _, ratchet_secrets) = + RatchetSecret::ratchet_forward(y.ratchet_head)?; + y.ratchet_head = y_ratchet_head_i; + // Add an entry to the past secrets queue to keep indexing consistent. + y.past_secrets.push_front(None); + // Remove persisted keys until it is within the bounds determined by the config. + y.past_secrets.truncate(ooo_tolerance as usize); + Ok((y, ratchet_secrets)) + } else { + // If the requested generation is within the window of past secrets, we should get a + // positive index. + let window_index = ((generation_head - generation) as i32) - 1; + // We might not have the key material (e.g. we might have discarded it when generating + // an encryption secret). + let index = if window_index >= 0 { + window_index as usize + } else { + return Err(RatchetError::TooDistantInThePast); + }; + // Get the relevant secrets from the past secrets queue. + let ratchet_secrets = y + .past_secrets + .get_mut(index) + .ok_or(RatchetError::IndexOutOfBounds)? + // We use take here to replace the entry in the `past_secrets` with `None`, thus + // achieving FS for that secret as soon as the caller of this function drops it. + .take() + // If the requested generation was used to decrypt a message earlier, throw an + // error. + .ok_or(RatchetError::SecretReuse)?; + Ok((y, ratchet_secrets)) + } + } +} + +#[derive(Debug, Error)] +pub enum RatchetError { + #[error(transparent)] + Hkdf(#[from] HkdfError), + + #[error("generation for message ratchet is too far into the future")] + TooDistantInTheFuture, + + #[error("generation for message ratchet is too far into the past")] + TooDistantInThePast, + + #[error("unknown message secret")] + IndexOutOfBounds, + + #[error("tried to re-use secret for same generation")] + SecretReuse, +} + +#[cfg(test)] +mod tests { + use crate::Rng; + use crate::crypto::Secret; + + use super::{DecryptionRatchet, MESSAGE_KEY_SIZE, RatchetError, RatchetSecret}; + + #[test] + fn ratchet_forward() { + let rng = Rng::from_seed([1; 32]); + + let update_secret = Secret::from_bytes(rng.random_array::().unwrap()); + + let ratchet = RatchetSecret::init(update_secret); + let (ratchet, generation, secret_0) = RatchetSecret::ratchet_forward(ratchet).unwrap(); + assert_eq!(generation, 0); + assert_eq!(ratchet.generation, 1); + + let (ratchet, generation, secret_1) = RatchetSecret::ratchet_forward(ratchet).unwrap(); + assert_eq!(generation, 1); + assert_eq!(ratchet.generation, 2); + + // Ratchet secrets do not match across generations. + assert_ne!(secret_0, secret_1); + } + + #[test] + fn forward_secrecy() { + let rng = Rng::from_seed([1; 32]); + + let update_secret = Secret::from_bytes(rng.random_array::().unwrap()); + + let ooo_tolerance = 4; + let max_forward = 100; + + let ratchet = DecryptionRatchet::init(update_secret); + + let (ratchet, secret) = + DecryptionRatchet::secret_for_decryption(ratchet, 0, max_forward, ooo_tolerance) + .unwrap(); + + // Generation should have increased. + assert_eq!(ratchet.ratchet_head.generation, 1); + + // No secrets have been kept. + assert_ne!(ratchet.ratchet_head.secret, secret.0); + assert!(!ratchet.past_secrets.iter().any(|secret| secret.is_some())); + + // Re-trying to retreive the secret for the same generation should fail. + std::assert_matches!( + DecryptionRatchet::secret_for_decryption( + ratchet.clone(), + 0, + max_forward, + ooo_tolerance + ), + Err(RatchetError::SecretReuse), + ); + + // Move the ratchet forwards a few generations. + let jump = 10; + let (mut ratchet, _) = + DecryptionRatchet::secret_for_decryption(ratchet, jump, max_forward, ooo_tolerance) + .unwrap(); + + // Now let's get a few keys. The first time we're trying to get the key of a given + // generation, it should work. The second time, we should get an error. + for generation in jump - ooo_tolerance + 1..jump { + let (ratchet_i, _) = DecryptionRatchet::secret_for_decryption( + ratchet, + generation, + max_forward, + ooo_tolerance, + ) + .unwrap(); + + std::assert_matches!( + DecryptionRatchet::secret_for_decryption( + ratchet_i.clone(), + generation, + max_forward, + ooo_tolerance + ), + Err(RatchetError::SecretReuse), + ); + + ratchet = ratchet_i; + } + + // No secrets have been kept. + assert!(!ratchet.past_secrets.iter().any(|secret| secret.is_some())); + } + + #[test] + fn out_of_order() { + let rng = Rng::from_seed([1; 32]); + + let update_secret = Secret::from_bytes(rng.random_array::().unwrap()); + + let max_forward = 3; + let ooo_tolerance = 3; + + let alice = RatchetSecret::init(update_secret.clone()); + let bob = DecryptionRatchet::init(update_secret); + + let (alice, _, alice_secret_0) = RatchetSecret::ratchet_forward(alice).unwrap(); + let (alice, _, _alice_secret_1) = RatchetSecret::ratchet_forward(alice).unwrap(); + let (alice, _, alice_secret_2) = RatchetSecret::ratchet_forward(alice).unwrap(); + let (alice, _, alice_secret_3) = RatchetSecret::ratchet_forward(alice).unwrap(); + let (alice, _, alice_secret_4) = RatchetSecret::ratchet_forward(alice).unwrap(); + assert_eq!(alice.generation, 5); + + // Bob derives the first secret for Alice's first message. + let (bob, bob_secret_0) = + DecryptionRatchet::secret_for_decryption(bob, 0, max_forward, ooo_tolerance).unwrap(); + assert_eq!(alice_secret_0, bob_secret_0); + + // Alice's messages arrive out-of-order, Bob derives them still. + let (bob, bob_secret_4) = + DecryptionRatchet::secret_for_decryption(bob, 4, max_forward, ooo_tolerance).unwrap(); + assert_eq!(alice_secret_4, bob_secret_4); + assert_eq!(bob.ratchet_head.generation, 5); + let (bob, bob_secret_3) = + DecryptionRatchet::secret_for_decryption(bob, 3, max_forward, ooo_tolerance).unwrap(); + assert_eq!(alice_secret_3, bob_secret_3); + let (bob, bob_secret_2) = + DecryptionRatchet::secret_for_decryption(bob, 2, max_forward, ooo_tolerance).unwrap(); + assert_eq!(alice_secret_2, bob_secret_2); + + // Alice's message from generation 1 arrives, but it's already outside of the tolerance + // window, we expect an error here. + std::assert_matches!( + DecryptionRatchet::secret_for_decryption(bob.clone(), 1, max_forward, ooo_tolerance), + Err(RatchetError::TooDistantInThePast) + ); + + // Bob receives a message very far into the future from Alice, but this is also outside the + // tolerated window, we expect an error here. + std::assert_matches!( + DecryptionRatchet::secret_for_decryption( + bob.clone(), + bob.ratchet_head.generation + max_forward + 1, + max_forward, + ooo_tolerance + ), + Err(RatchetError::TooDistantInTheFuture) + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/dcgka.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/dcgka.rs new file mode 100644 index 0000000000..6a231be24e --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/dcgka.rs @@ -0,0 +1,978 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::collections::{HashMap, HashSet}; + +use crate::Rng; +use crate::crypto::x25519::SecretKey; +use crate::key_bundle::Lifetime; +use crate::key_manager::KeyManager; +use crate::key_registry::KeyRegistry; +use crate::message_scheme::dcgka::{ + ControlMessage, Dcgka, DcgkaState, DirectMessage, DirectMessageType, OperationOutput, + ProcessOutput, UpdateSecret, +}; +use crate::message_scheme::test_utils::dgm::AckedTestDgm; +use crate::test_utils::{MemberId, MessageId}; +use crate::traits::{AckedGroupMembership, PreKeyManager}; + +pub type TestDcgkaState = DcgkaState< + MemberId, + MessageId, + KeyRegistry, + AckedTestDgm, + KeyManager, +>; + +/// Helper method returning initialised DCGKA state for each member of a test group. +/// +/// The method will automatically generate all required one-time pre-key bundles from each member +/// and register them for each other. +pub fn init_dcgka_state( + member_ids: [MemberId; N], + rng: &Rng, +) -> [TestDcgkaState; N] { + let mut key_bundles = HashMap::new(); + let mut key_managers = HashMap::new(); + + // Generate a pre-key bundle for each other member of the group. + for id in member_ids { + let identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let mut manager = + KeyManager::init_and_generate_prekey(&identity_secret, Lifetime::default(), rng) + .unwrap(); + + let mut bundle_list = Vec::with_capacity(member_ids.len()); + for _ in member_ids { + let (manager_i, key_bundle) = + KeyManager::generate_onetime_bundle(manager, rng).unwrap(); + bundle_list.push(key_bundle); + manager = manager_i; + } + + key_bundles.insert(id, bundle_list); + key_managers.insert(id, manager); + } + + // Register each other's pre-key bundles and initialise DCGKA state. + let mut result = Vec::with_capacity(member_ids.len()); + for id in member_ids { + let dgm = AckedTestDgm::init(id); + let registry = { + let mut state = KeyRegistry::init(); + for bundle_id in member_ids { + let bundle = key_bundles.get_mut(&bundle_id).unwrap().pop().unwrap(); + let state_i = KeyRegistry::add_onetime_bundle(state, bundle_id, bundle).unwrap(); + state = state_i; + } + state + }; + let manager = key_managers.remove(&id).unwrap(); + let dcgka: TestDcgkaState = Dcgka::init(id, manager, registry, dgm); + result.push(dcgka); + } + + result.try_into().unwrap() +} + +fn members_without(members: &[MemberId], without: &[MemberId]) -> Vec { + members + .iter() + .filter(|id| !without.contains(id)) + .cloned() + .collect() +} + +pub fn assert_direct_message( + direct_messages: &[DirectMessage>], + recipient: MemberId, +) -> DirectMessage> { + direct_messages + .iter() + .find(|message| message.recipient == recipient) + .cloned() + .unwrap_or_else(|| panic!("could not find direct message for {recipient:?}")) + .clone() +} + +pub struct ExpectedMembers<'a> { + pub viewer: &'a [MemberId], + pub expected: &'a [MemberId], +} + +pub fn assert_members_view(dcgka: &TestDcgkaState, assertions: &[ExpectedMembers]) { + for assertion in assertions { + for viewer in assertion.viewer { + assert_eq!( + AckedTestDgm::members_view(&dcgka.dgm, viewer).unwrap(), + HashSet::from_iter(assertion.expected.iter().cloned()), + "{} should have had members view {:?}", + viewer, + assertion.expected + ); + } + } +} + +/// Testing helper to verify DCGKA group operations and states. +pub struct AssertableDcgka { + /// Update secrets the DCGKA exported for "local member -> remote member". + update_secrets: HashMap<(MemberId, MemberId), UpdateSecret>, +} + +impl Default for AssertableDcgka { + fn default() -> Self { + Self::new() + } +} + +impl AssertableDcgka { + pub fn new() -> Self { + Self { + update_secrets: HashMap::new(), + } + } + + /// Expected local state after a member created a group. + pub fn assert_create( + &mut self, + dcgka: &TestDcgkaState, + output: &OperationOutput>, + creator_id: MemberId, // Group "creator" + expected_members: &[MemberId], // List of expected initial group members + seq: MessageId, // Id of "create" control message + ) { + // This is a local group operation and the group "creator" manages that state. + assert_eq!(dcgka.my_id, creator_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // Group "creator" broadcasts a "create" control message to everyone. + let ControlMessage::Create { + ref initial_members, + } = output.control_message + else { + panic!("expected \"create\" control message"); + }; + assert_eq!(initial_members, expected_members); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // Group "creator" sends direct 2SM messages to each other member of the group. + assert_eq!(output.direct_messages.len(), expected_members.len() - 1); + for (index, expected_member) in members_without(expected_members, &[creator_id]) + .iter() + .enumerate() + { + assert_eq!( + output.direct_messages.get(index).unwrap().message_type(), + DirectMessageType::TwoParty, + ); + assert_eq!( + output.direct_messages.get(index).unwrap().recipient, + *expected_member, + ); + } + + // Members view + // ~~~~~~~~~~~~ + + // Group "creator" considers that all members are part of the group now and every member + // has processed the "create" control message. + assert_members_view( + dcgka, + &[ExpectedMembers { + viewer: expected_members, + expected: expected_members, + }], + ); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // Group "creator" establishes the update secret for their own message ratchet. + assert!(output.me_update_secret.is_some()); + + // Remember group "creator's" update secret for later assertions. + self.update_secrets.insert( + (creator_id, creator_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed secret has been dropped after group got created (FS). + assert!(dcgka.next_seed.is_none()); + + // Group "creator" established member secrets for all expected members of the group. + assert_eq!(dcgka.member_secrets.len(), expected_members.len() - 1); + for member_id in members_without(expected_members, &[creator_id]) { + assert!( + dcgka + .member_secrets + .contains_key(&(creator_id, seq, member_id)) + ); + } + + // Outer-Ratchet holds only the secret for the group "creator" so far. + assert_eq!(dcgka.ratchet.len(), 1); + assert!(dcgka.ratchet.contains_key(&creator_id)); + } + + /// Expected local state after an invited member processed a "create" control message. + pub fn assert_process_create( + &mut self, + dcgka: &TestDcgkaState, + output: &ProcessOutput>, + processor_id: MemberId, // "Processor" who handles "create" control message + creator_id: MemberId, // Group "creator" + expected_members: &[MemberId], // List of expected members after processing "create" + seq: MessageId, // Id of "create" control message + ) { + // We're looking at the state of the "processor". + assert_eq!(dcgka.my_id, processor_id); + assert_ne!(creator_id, processor_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // "Processing" member of "create" message broadcasts an "ack" control message to everyone. + let Some(ControlMessage::Ack { + ack_sender, + ack_seq, + }) = output.control_message + else { + panic!("expected \"ack\" control message"); + }; + + // "Processing" member acknowledges the "create" message of the creator. + assert_eq!(ack_sender, creator_id); + assert_eq!(ack_seq, seq); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // No direct messages. + assert!(output.direct_messages.is_empty()); + + // Members view + // ~~~~~~~~~~~~ + + // "Processor" of "create" considers all members part of the group now and every member has + // processed the "create" control message. + assert_members_view( + dcgka, + &[ExpectedMembers { + viewer: expected_members, + expected: expected_members, + }], + ); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // "Processor" establishes the update secret for their own message ratchet. + assert!(output.me_update_secret.is_some()); + + // Processor establishes the update secret for creator's message ratchet. + assert!(output.sender_update_secret.is_some()); + + // Remember "processor's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, processor_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Remember "creator's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, creator_id), + output.sender_update_secret.as_ref().unwrap().clone(), + ); + + // Processor should be aware now of creator's update secret. + self.assert_update_secrets(processor_id, creator_id); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed was never used and should be none. + assert!(dcgka.next_seed.is_none()); + + // When joining a group freshly we have member secrets for every member who is not the + // "creator". + assert_eq!( + dcgka.member_secrets.len(), + members_without(expected_members, &[creator_id, processor_id]).len() + ); + + // Outer-Ratchet holds only the secret for the group "creator" and ourselves ("processor") so far. + assert_eq!(dcgka.ratchet.len(), 2); + assert!(dcgka.ratchet.contains_key(&creator_id)); + assert!(dcgka.ratchet.contains_key(&processor_id)); + } + + /// Expected local state after a member processed an "ack" control message. + pub fn assert_process_ack( + &mut self, + dcgka: &TestDcgkaState, + output: &ProcessOutput>, + processor_id: MemberId, // Member who "processes" the "ack" control message + acker_id: MemberId, // Author of the "ack" control message, + seq: MessageId, // Id of the "ack" message + ) { + // We're looking at the state of the "processor". + assert_eq!(dcgka.my_id, processor_id); + assert_ne!(acker_id, processor_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // No control messages. + assert!(output.control_message.is_none()); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // No direct messages. + assert!(output.direct_messages.is_empty()); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // No new update secret for acking member. + assert!(output.me_update_secret.is_none()); + + // Processor establishes the update secret for acking member's message ratchet. + assert!(output.sender_update_secret.is_some()); + + // Remember ackers's update secret for later assertions. + self.update_secrets.insert( + (processor_id, acker_id), + output.sender_update_secret.as_ref().unwrap().clone(), + ); + + // Processor should be aware now of acker's update secret. + self.assert_update_secrets(processor_id, acker_id); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed was never used and should be none. + assert!(dcgka.next_seed.is_none()); + + // Member secrets for "acker" has to be removed (FS). + assert!( + !dcgka + .member_secrets + .contains_key(&(acker_id, seq, processor_id)) + ); + + // Outer-Ratchet holds secrets for at least the "acker" and "processor" of the "ack". + assert!(dcgka.ratchet.contains_key(&acker_id)); + assert!(dcgka.ratchet.contains_key(&processor_id)); + } + + /// Expected local state after an member was added to the group. + pub fn assert_add( + &mut self, + dcgka: &TestDcgkaState, + output: &OperationOutput>, + adder_id: MemberId, // "Adder" who adds someone to the group + added_id: MemberId, // "Added" who will join the group + seq: MessageId, // Id of the "add" control message + ) { + // This is a local group operation, so we expect this to be the "adder". + assert_eq!(dcgka.my_id, adder_id); + assert_ne!(adder_id, added_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // "Adder" broadcasts an "add" control message to everyone. + let ControlMessage::Add { added } = output.control_message else { + panic!("expected \"add\" control message"); + }; + assert_eq!(added, added_id); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // One direct "welcome" message to "added" was generated. + assert_eq!(output.direct_messages.len(), 1); + assert_eq!( + output.direct_messages.first().unwrap().message_type(), + DirectMessageType::Welcome + ); + assert_eq!(output.direct_messages.first().unwrap().recipient, added_id); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // "Adder" establishes a new update secret for their own message ratchet. + assert!(output.me_update_secret.is_some()); + + // Remember "adders's" update secret for later assertions. + let previous = self.update_secrets.insert( + (adder_id, adder_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // The new update secret does not match the previous one. + assert_ne!( + previous.unwrap(), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed was never used and should be none. + assert!(dcgka.next_seed.is_none()); + + // Member secret for the "added" was established. + assert!( + dcgka + .member_secrets + .contains_key(&(adder_id, seq, added_id)) + ); + + // Outer-Ratchet holds secrets for at least the "adder". + assert!(dcgka.ratchet.contains_key(&adder_id)); + + // The added doesn't have a ratchet secret yet. + assert!(!dcgka.ratchet.contains_key(&added_id)); + } + + /// Expected local state after an invited member "added" processes the "add" message with a + /// direct "welcome" message addressing them. + pub fn assert_process_welcome( + &mut self, + dcgka: &TestDcgkaState, + output: &ProcessOutput>, + adder_id: MemberId, // Member who invited to the group + added_id: MemberId, // Member who was added to the group + expected_members: &[MemberId], // List of expected members after processing "add" + seq: MessageId, // Id of the "add" control message + ) { + // This control message is processed by the member who was added. + assert_eq!(dcgka.my_id, added_id); + assert_ne!(adder_id, added_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // Added broadcasts an "ack" control message to everyone, no direct messages. + let Some(ControlMessage::Ack { + ack_sender, + ack_seq, + }) = output.control_message + else { + panic!("expected \"ack\" control message"); + }; + + // "Added" acknowledges the "add" message of "adder". + assert_eq!(ack_sender, adder_id); + assert_eq!(ack_seq, seq); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // No direct messages. + assert!(output.direct_messages.is_empty()); + + // Members view + // ~~~~~~~~~~~~ + + // "Added" considers all members as part of the group now and that "adder" has the same + // view as them. + assert_members_view( + dcgka, + &[ExpectedMembers { + viewer: &[added_id, adder_id], + expected: expected_members, + }], + ); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // Remember "added's" update secret for later assertions. + self.update_secrets.insert( + (added_id, added_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Remember "adder's" update secret for later assertions. + self.update_secrets.insert( + (added_id, adder_id), + output.sender_update_secret.as_ref().unwrap().clone(), + ); + + // "Added" should be aware now of "adder's" update secret. + self.assert_update_secrets(added_id, adder_id); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed was never used and should be none. + assert!(dcgka.next_seed.is_none()); + + // Member secret for the "added" was dropped (FS). + assert!( + !dcgka + .member_secrets + .contains_key(&(adder_id, seq, added_id)) + ); + + // Outer-Ratchet holds secrets for at least the "adder" and "added". + assert!(dcgka.ratchet.contains_key(&adder_id)); + assert!(dcgka.ratchet.contains_key(&added_id)); + } + + /// Expected local state after a member who is _not_ invited processes an "add" control + /// message. + #[allow(clippy::too_many_arguments)] + pub fn assert_process_add( + &mut self, + dcgka: &TestDcgkaState, + output: &ProcessOutput>, + processor_id: MemberId, // "Processor" of the "add" control message + adder_id: MemberId, // Id of the member who invited the new member + added_id: MemberId, // Id of the member which got added + seq: MessageId, // Id of the "add" message which is processed + ) { + // This control message is processed by every member who is _not_ the "added" and _not_ the + // adder. + assert_eq!(dcgka.my_id, processor_id); + assert_ne!(adder_id, processor_id); + assert_ne!(added_id, processor_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // Processor broadcasts an "add-ack" control message to everyone. + let Some(ControlMessage::AddAck { + ack_sender, + ack_seq, + }) = output.control_message + else { + panic!("expected \"add-ack\" control message"); + }; + + // "Processor" acknowledges the "add" message of the "adder". + assert_eq!(ack_sender, adder_id); + assert_eq!(ack_seq, seq); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // "Processor" forwards a direct message to "added". It is required so the "added" member + // can decrypt subsequent messages of the "processing" member. + assert_eq!(output.direct_messages.len(), 1); + assert_eq!(output.direct_messages.first().unwrap().recipient, added_id); + assert_eq!( + output.direct_messages.first().unwrap().message_type(), + DirectMessageType::Forward + ); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // Remember "processor's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, processor_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Remember "adder's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, adder_id), + output.sender_update_secret.as_ref().unwrap().clone(), + ); + + // "Processor" should be aware now of "adder's" update secret. + self.assert_update_secrets(processor_id, adder_id); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed was never used and should be none. + assert!(dcgka.next_seed.is_none()); + + // Member secret for the "added" was established. + assert!( + dcgka + .member_secrets + .contains_key(&(adder_id, seq, added_id)) + ); + + // No ratchet secret exists yet for "added". + assert!(!dcgka.ratchet.contains_key(&added_id)); + } + + /// Expected local state after processing an "add-ack" control message. + pub fn assert_process_add_ack( + &mut self, + dcgka: &TestDcgkaState, + output: &ProcessOutput>, + processor_id: MemberId, // "Processor" of the "add-ack" control message + add_acker_id: MemberId, // Sender of the "add-ack" control message + ) { + // The given state is from the "processor" and not the sender of the "add-ack" message. + assert_eq!(dcgka.my_id, processor_id); + assert_ne!(add_acker_id, processor_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // No control messages. + assert!(output.control_message.is_none()); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // No direct messages. + assert!(output.direct_messages.is_empty()); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // No new update secret for "processor's" own message ratchet. + assert!(output.me_update_secret.is_none()); + + // "Processor" establishes the update secret for "add-acking" member's message ratchet. + assert!(output.sender_update_secret.is_some()); + + // Remember "add-ackers's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, add_acker_id), + output.sender_update_secret.as_ref().unwrap().clone(), + ); + + // "Processor" should be aware now of "add-acker's" update secret. + self.assert_update_secrets(processor_id, add_acker_id); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed was never used and should be none. + assert!(dcgka.next_seed.is_none()); + + // Ratchet secret exists for "add-ack". + assert!(dcgka.ratchet.contains_key(&add_acker_id)); + } + + /// Expected local state after removing a member from the group. + pub fn assert_remove( + &mut self, + dcgka: &TestDcgkaState, + output: &OperationOutput>, + remover_id: MemberId, // Author of the "remove" control message + removed_id: MemberId, // Member which gets "removed" + expected_members: &[MemberId], // List of expected members after removal + seq: MessageId, // Id of "remove" control message + ) { + // This is a local group operation, so we expect the state to be from the "remover". + assert_eq!(dcgka.my_id, remover_id); + assert_ne!(removed_id, remover_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // "Remover" broadcasts a "remove" control message to everyone. + let ControlMessage::Remove { removed } = output.control_message else { + panic!("expected \"remove\" control message"); + }; + assert_eq!(removed, removed_id); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // "Remover" sends a direct 2SM message to each other member of the group who is left. + assert_eq!( + output.direct_messages.len(), + members_without(expected_members, &[remover_id, removed_id]).len(), + ); + for (index, expected_member) in members_without(expected_members, &[remover_id, removed_id]) + .iter() + .enumerate() + { + assert_eq!( + output.direct_messages.get(index).unwrap().message_type(), + DirectMessageType::TwoParty, + "remove operation should yield a 2SM direct message" + ); + assert_eq!( + output.direct_messages.get(index).unwrap().recipient, + *expected_member, + "direct message should address expected member", + ); + } + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // "Remover" establishes a new update secret for their own message ratchet. + assert!(output.me_update_secret.is_some()); + + // Remember "remover's" update secret for later assertions. + self.update_secrets.insert( + (remover_id, remover_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed secret has been dropped after removal (FS). + assert!(dcgka.next_seed.is_none()); + + // "Remover" established member secrets for all expected members of the group. + assert_eq!( + dcgka.member_secrets.len(), + members_without(expected_members, &[remover_id, removed_id]).len() + ); + for member_id in members_without(expected_members, &[remover_id, removed_id]) { + assert!( + dcgka + .member_secrets + .contains_key(&(remover_id, seq, member_id)) + ); + } + } + + /// Expected local state after processing a "remove" control message. + pub fn assert_process_remove( + &mut self, + dcgka: &TestDcgkaState, + output: &ProcessOutput>, + processor_id: MemberId, + remover_id: MemberId, + seq: MessageId, + ) { + // We're looking at the state of the processor. + assert_eq!(dcgka.my_id, processor_id); + assert_ne!(remover_id, processor_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // "Processor" of "remove" message broadcasts an "ack" control message to everyone. + let Some(ControlMessage::Ack { + ack_sender, + ack_seq, + }) = output.control_message + else { + panic!("expected \"ack\" control message"); + }; + + // "Processor" acknowledges the "remove" message of the "remover". + assert_eq!(ack_sender, remover_id); + assert_eq!(ack_seq, seq); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // No direct messages. + assert!(output.direct_messages.is_empty()); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // "Processor" establishes the update secret for their own message ratchet. + assert!(output.me_update_secret.is_some()); + + // "Processor" establishes the update secret for "remover's" message ratchet. + assert!(output.sender_update_secret.is_some()); + + // Remember "processor's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, processor_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Remember "remover's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, remover_id), + output.sender_update_secret.as_ref().unwrap().clone(), + ); + + // "Processor" should be aware now of "remover's" update secret. + self.assert_update_secrets(processor_id, remover_id); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed was never used and should be none. + assert!(dcgka.next_seed.is_none()); + + // Update secret of "remover" was dropped after use. (FS) + assert!( + !dcgka + .member_secrets + .contains_key(&(remover_id, seq, processor_id)) + ); + + // Outer-Ratchet holds secrets for both "processor" and "remover". + assert!(dcgka.ratchet.contains_key(&processor_id)); + assert!(dcgka.ratchet.contains_key(&remover_id)); + } + + /// Expected local state after a member updated the group. + pub fn assert_update( + &mut self, + dcgka: &TestDcgkaState, + output: &OperationOutput>, + updater_id: MemberId, // Member updating the group + expected_members: &[MemberId], // List of expected members during update + seq: MessageId, // Id of the "update" control message + ) { + // This is a local group operation, so we expect the state to be from the "updater". + assert_eq!(dcgka.my_id, updater_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // "Updater" broadcasts an "update" control message to everyone. + let ControlMessage::Update = output.control_message else { + panic!("expected \"update\" control message"); + }; + + // "Updater" sends a direct 2SM message to each other member of the group. + assert_eq!(output.direct_messages.len(), expected_members.len() - 1); + for (index, expected_member) in members_without(expected_members, &[updater_id]) + .iter() + .enumerate() + { + assert_eq!( + output.direct_messages.get(index).unwrap().message_type(), + DirectMessageType::TwoParty, + ); + assert_eq!( + output.direct_messages.get(index).unwrap().recipient, + *expected_member, + ); + } + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // "Updater" establishes a new update secret for their own message ratchet. + assert!(output.me_update_secret.is_some()); + + // Remember "updater's" update secret for later assertions. + self.update_secrets.insert( + (updater_id, updater_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed secret has been dropped after update (FS). + assert!(dcgka.next_seed.is_none()); + + // "Updater" established member secrets for all expected members of the group. + assert_eq!( + dcgka.member_secrets.len(), + members_without(expected_members, &[updater_id]).len() + ); + for member_id in members_without(expected_members, &[updater_id]) { + assert!( + dcgka + .member_secrets + .contains_key(&(updater_id, seq, member_id)) + ); + } + + // Outer-Ratchet contains secret from "updater". + assert!(dcgka.ratchet.contains_key(&updater_id)); + } + + /// Expected state after processing an "update" control message. + pub fn assert_process_update( + &mut self, + dcgka: &TestDcgkaState, + output: &ProcessOutput>, + processor_id: MemberId, // Member processing the "update" control message + updater_id: MemberId, // Member who updated the group + seq: MessageId, // Id of the "update" control message + ) { + // We're looking at the state of the processor. + assert_eq!(dcgka.my_id, processor_id); + assert_ne!(updater_id, processor_id); + + // Control messages + // ~~~~~~~~~~~~~~~~ + + // Processor of "update" message broadcasts an "ack" control message to everyone. + let Some(ControlMessage::Ack { + ack_sender, + ack_seq, + }) = output.control_message + else { + panic!("expected \"ack\" control message"); + }; + + // "Processor" acknowledges the "update" message of the "updater". + assert_eq!(ack_sender, updater_id); + assert_eq!(ack_seq, seq); + + // Direct messages + // ~~~~~~~~~~~~~~~ + + // No direct messages. + assert!(output.direct_messages.is_empty()); + + // Update Secrets + // ~~~~~~~~~~~~~~ + + // "Processor" establishes the update secret for their own message ratchet. + assert!(output.me_update_secret.is_some()); + + // "Processor" establishes the update secret for "remover's" message ratchet. + assert!(output.sender_update_secret.is_some()); + + // Remember "processor's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, processor_id), + output.me_update_secret.as_ref().unwrap().clone(), + ); + + // Remember "updater's" update secret for later assertions. + self.update_secrets.insert( + (processor_id, updater_id), + output.sender_update_secret.as_ref().unwrap().clone(), + ); + + // "Processor" should be aware now of "updater's" update secret. + self.assert_update_secrets(processor_id, updater_id); + + // Key Material + // ~~~~~~~~~~~~ + + // Seed was never used and should be none. + assert!(dcgka.next_seed.is_none()); + + // Update secret of "updater" was dropped after use. (FS) + assert!( + !dcgka + .member_secrets + .contains_key(&(updater_id, seq, processor_id)) + ); + + // Outer-Ratchet holds secrets for both "processor" and "updater". + assert!(dcgka.ratchet.contains_key(&processor_id)); + assert!(dcgka.ratchet.contains_key(&updater_id)); + } + + /// Compare if member learned about the update secret from another member. + fn assert_update_secrets(&self, from: MemberId, to: MemberId) { + assert_eq!( + self.update_secrets.get(&(from, to)).unwrap().as_bytes(), + self.update_secrets.get(&(to, to)).unwrap().as_bytes(), + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/dgm.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/dgm.rs new file mode 100644 index 0000000000..523ccc3011 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/dgm.rs @@ -0,0 +1,1137 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::collections::{HashMap, HashSet}; +use std::fmt::Debug; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::traits::{AckedGroupMembership, IdentityHandle, OperationId}; + +/// Non-optimal "Acked" Decentralised Group Membership CRDT implementation for p2panda's +/// message encryption scheme. +/// +/// This does not support re-adding a member, is only used for testing and will be soon +/// replaced with an optimal implementation. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct AckedTestDgm { + _marker: PhantomData<(ID, OP)>, +} + +impl AckedTestDgm +where + ID: IdentityHandle + Serialize + for<'a> Deserialize<'a>, + OP: OperationId + Serialize + for<'a> Deserialize<'a>, +{ + pub fn init(my_id: ID) -> State { + State { + my_id, + members: HashSet::new(), + removed_members: HashSet::new(), + infos: HashMap::new(), + remove_infos: HashMap::new(), + adds_by_msg: HashMap::new(), + removes_by_msg: HashSet::new(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct State +where + ID: IdentityHandle, + OP: OperationId, +{ + my_id: ID, + members: HashSet, + removed_members: HashSet, + infos: HashMap>, + remove_infos: HashMap>, + adds_by_msg: HashMap, + removes_by_msg: HashSet, +} + +impl AckedGroupMembership for AckedTestDgm +where + ID: IdentityHandle + Serialize + for<'a> Deserialize<'a>, + OP: OperationId + Serialize + for<'a> Deserialize<'a>, +{ + type State = State; + + type Error = TestAckedGroupError; + + fn from_welcome( + mut y: Self::State, + y_welcome: Self::State, + ) -> Result { + // TODO: This does not handle scenarios well when the same members get concurrently added. + // Merge states. + y.members.extend(y_welcome.members); + y.removed_members.extend(y_welcome.removed_members); + y.infos.extend(y_welcome.infos); + y.remove_infos.extend(y_welcome.remove_infos); + y.adds_by_msg.extend(y_welcome.adds_by_msg); + y.removes_by_msg.extend(y_welcome.removes_by_msg); + Ok(y) + } + + fn create(my_id: ID, initial_members: &[ID]) -> Result { + let mut initial_members = initial_members.to_vec(); + if !initial_members.contains(&my_id) { + initial_members.push(my_id); + } + + let mut infos = HashMap::with_capacity(initial_members.len()); + let mut members = HashSet::with_capacity(initial_members.len()); + + for member in &initial_members { + infos.insert(*member, MemberInfo::new(*member, None, &initial_members)); + members.insert(*member); + } + + Ok(Self::State { + my_id, + members, + removed_members: HashSet::new(), + infos, + remove_infos: HashMap::new(), + adds_by_msg: HashMap::new(), + removes_by_msg: HashSet::new(), + }) + } + + /// Handles message adding a new member ("added") to the group by another member ("adder"). + /// Please note that a user can only be added to a group once. + fn add( + mut y: Self::State, + adder: ID, + added: ID, + message_id: OP, + ) -> Result { + let mut added_info = MemberInfo::new(added, Some(adder), &[]); + added_info.acks.insert(adder); + added_info.acks.insert(added); + added_info.acks.insert(y.my_id); + + // Is `actor` still a member of the group itself? + if y.members.contains(&adder) { + // TODO: How to handle adds when the member already exists? This de-duplicates the + // member, but overwrites the `added_info` with a new state? + y.members.insert(added); + y.infos.insert(added, added_info); + } else { + // `actor` has been removed by a remove messages concurrent to this add message. + // All the remove messages removing `actor` get credit for removing `added` as + // well. + let actor_info = y + .infos + .get_mut(&adder) + .ok_or(TestAckedGroupError::UnrecognizedMember(adder))?; + for remove_message_id in &actor_info.remove_messages { + let remove_info = y + .remove_infos + .get_mut(remove_message_id) + .expect("remove_infos values should be consistent with remove_messages"); + remove_info.removed.insert(added); + added_info.remove_messages.push(*remove_message_id); + } + y.removed_members.insert(added); + y.infos.insert(added, added_info); + } + + // If `actor` acknowledged adding or removing a member in the past, then we can be sure + // that `added` also acknowledges it as they must have been made aware of this history + // by receiving the welcome message from `actor`. + for member in &y.members { + let member_info = y + .infos + .get_mut(member) + .expect("infos values should be consistent with members keys"); + if member_info.acks.contains(&adder) { + member_info.acks.insert(added); + } + } + + for member in &y.removed_members { + let member_info = y + .infos + .get_mut(member) + .expect("infos values should be consistent with removed_members keys"); + if member_info.acks.contains(&adder) { + member_info.acks.insert(added); + } + } + + for message_id in &y.removes_by_msg { + let remove_info = y + .remove_infos + .get_mut(message_id) + .expect("remove_infos values should be consistent with removes_by_msg keys"); + if remove_info.acks.contains(&adder) { + remove_info.acks.insert(added); + } + } + + y.adds_by_msg.insert(message_id, added); + + Ok(y) + } + + fn remove( + mut y: Self::State, + remover: ID, + removed: &ID, + message_id: OP, + ) -> Result { + let removed: &[ID] = &[*removed]; + + let mut remove_result = Vec::new(); + + let mut remove_info = RemoveInfo::new(removed); + remove_info.acks.insert(remover); + remove_info.acks.insert(y.my_id); + + // Remove the users in removed (if needed) and mark them as removed by this message. + for removed_member in removed { + let has_removed_member = y.members.remove(removed_member); + if has_removed_member { + let member_info = y + .infos + .get_mut(removed_member) + .expect("infos values should be consistent with members keys"); + y.removed_members.insert(*removed_member); + member_info.remove_messages.push(message_id); + remove_result.push(*removed_member); + } else if y.removed_members.contains(removed_member) { + if let Some(member_info) = y.infos.get_mut(removed_member) { + // Member has already been removed. + member_info.remove_messages.push(message_id); + } else { + return Err(TestAckedGroupError::UnrecognizedMember(*removed_member)); + } + } else { + return Err(TestAckedGroupError::UnrecognizedMember(*removed_member)); + } + } + + y.removes_by_msg.insert(message_id); + y.remove_infos.insert(message_id, remove_info); + + // If a removed user performed an add concurrent to this message (i.e., not yet ack'd by + // actor), then the user added by that message is also considered removed by this + // message. This loop searches for such adds and removes their target. + // + // Since users removed in this fashion may themselves have added users, we have to apply + // this rule repeatedly until it stops making progress. + loop { + let remove_info = y + .remove_infos + .get_mut(&message_id) + .expect("infos values should be consistent with members keys"); + + let mut made_progress = false; + + for member in &y.members { + let member_info = y + .infos + .get_mut(member) + .expect("infos values should be consistent with members keys"); + let contains = member_info + .actor + .is_some_and(|actor| remove_info.removed.contains(&actor)); + if contains && !member_info.acks.contains(&remover) { + remove_result.push(*member); + y.removed_members.insert(*member); + member_info.remove_messages.push(message_id); + remove_info.removed.insert(*member); + made_progress = true; + } + } + + for removed_member in &remove_result { + y.members.remove(removed_member); + } + + // Loop through already removed users, adding this message to their list of remove + // messages if it applies. + for member in &y.removed_members { + let member_info = y + .infos + .get_mut(member) + .expect("infos values should be consistent with members keys"); + let contains = member_info + .actor + .is_some_and(|actor| remove_info.removed.contains(&actor)); + if contains + && member_info.acks.contains(&remover) + && member_info.remove_messages.contains(&message_id) + { + remove_info.removed.insert(*member); + made_progress = true; + } + } + + if !made_progress { + break; + } + } + + Ok(y) + } + + fn members_view(y: &Self::State, viewer: &ID) -> Result, Self::Error> { + if viewer.eq(&y.my_id) { + return Ok(y.members.clone()); + } + + let mut view = HashSet::new(); + + // Include current members whose add was acked by viewer. + for member in &y.members { + let member_info = y + .infos + .get(member) + .expect("infos values should be consistent with members keys"); + if member_info.acks.contains(viewer) { + view.insert(*member); + } + } + + // Also include removed members, none of whose removes have been acked by viewer. + for member in &y.removed_members { + let member_info = y + .infos + .get(member) + .expect("infos values should be consistent with removed_members keys"); + let any_acked = member_info.remove_messages.iter().any(|message_id| { + let remove_info = y + .remove_infos + .get(message_id) + .expect("remove_infos values should be consistent with remove_messages"); + remove_info.acks.contains(viewer) + }); + if !any_acked { + // Add the member to the view if the removal was not acked yet. + // + // It's possible that "removed_members" contains transitive removals (Charlie added + // Bob, but Alice removed Charlie, so we'll end up with Charlie AND Bob in the + // "removed_members" set). + // + // The viewer might still not have recognized that add of Bob, so we still need to + // check if they acked the "add" itself: + if member_info.acks.contains(viewer) { + view.insert(*member); + } + } + } + + Ok(view) + } + + fn ack(mut y: Self::State, acker: ID, message_id: OP) -> Result { + let added = y.adds_by_msg.get_mut(&message_id); + match added { + Some(added) => { + let member_info = y + .infos + .get_mut(added) + .expect("adds_by_msg values should be consistent with members keys"); + member_info.acks.insert(acker); + } + None => { + let remove_info = y.remove_infos.get_mut(&message_id); + match remove_info { + Some(remove_info) => { + if !remove_info.acks.insert(acker) { + return Err(TestAckedGroupError::AlreadyAcked); + } + + if remove_info.removed.contains(&acker) { + return Err(TestAckedGroupError::AckingOwnRemoval); + } + } + None => return Err(TestAckedGroupError::UnknownMessage(message_id)), + } + } + } + + Ok(y) + } + + fn is_add(y: &Self::State, message_id: OP) -> bool { + y.adds_by_msg.contains_key(&message_id) + } + + fn is_remove(y: &Self::State, message_id: OP) -> bool { + y.removes_by_msg.contains(&message_id) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +struct MemberInfo +where + ID: IdentityHandle, +{ + pub id: ID, + + /// Who added this member. + pub actor: Option, + + /// Remove messages that removed this member. + pub remove_messages: Vec, + + /// Users who have ack'd the message. + pub acks: HashSet, +} + +impl MemberInfo +where + ID: IdentityHandle, + OP: OperationId, +{ + fn new(id: ID, actor: Option, initial_acks: &[ID]) -> Self { + let mut acks = HashSet::with_capacity(initial_acks.len()); + for ack in initial_acks { + acks.insert(*ack); + } + + Self { + id, + actor, + remove_messages: Vec::new(), + acks, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +struct RemoveInfo +where + ID: IdentityHandle, +{ + /// Users removed by this message, including users who would have been removed except they were + /// removed previously. + pub removed: HashSet, + + /// Users who have ack'd the member. + pub acks: HashSet, +} + +impl RemoveInfo +where + ID: IdentityHandle, +{ + pub fn new(removed_members: &[ID]) -> Self { + let mut removed = HashSet::with_capacity(removed_members.len()); + for member in removed_members { + removed.insert(*member); + } + + Self { + removed, + acks: HashSet::new(), + } + } +} + +#[derive(Debug, Error)] +pub enum TestAckedGroupError { + #[error("tried to access unrecognized member")] + UnrecognizedMember(ID), + + #[error("already acked")] + AlreadyAcked, + + #[error("member acking their own removal")] + AckingOwnRemoval, + + #[error("message not recognized")] + UnknownMessage(OP), +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use crate::test_utils::MessageId; + use crate::traits::AckedGroupMembership; + + use super::AckedTestDgm; + + #[test] + fn concurrent_operations() { + let alice = 0; + let bob = 1; + let charlie = 2; + let daphne = 3; + + // Charlie creates a group (charlie: seq=0 "create"). + + let charlie_y = AckedTestDgm::create(charlie, &[charlie]).unwrap(); + + // Charlie adds Alice (charlie: seq=1 "add"). + + let charlie_y = AckedTestDgm::add( + charlie_y, + charlie, + alice, + MessageId { + sender: charlie, + seq: 1, + }, + ) + .unwrap(); + + // Alice processes the "add" of Charlie (alice: seq=0 "ack"). + + let alice_y = AckedTestDgm::init(alice); + let alice_y = AckedTestDgm::from_welcome(alice_y, charlie_y.clone()).unwrap(); + + // Charlie processes Alice's ack. + + let charlie_y = AckedTestDgm::ack( + charlie_y, + alice, + MessageId { + sender: charlie, + seq: 1, + }, + ) + .unwrap(); + + // They have the same view on the group. + + for id in [alice, charlie] { + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &id).unwrap(), + HashSet::from([alice, charlie]) + ); + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &id).unwrap(), + HashSet::from([alice, charlie]) + ); + } + + // ----------------- + + // Charlie adds Daphne (charlie: seq=2 "add"). + + let charlie_y = AckedTestDgm::add( + charlie_y, + charlie, + daphne, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &charlie).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + + // Daphne processes their add (daphne: seq=0 "ack"). + + let daphne_y = AckedTestDgm::init(daphne); + let daphne_y = AckedTestDgm::from_welcome(daphne_y, charlie_y.clone()).unwrap(); + + assert_eq!( + AckedTestDgm::members_view(&daphne_y, &daphne).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + + // Alice processes Charlie's "add" of Daphne (alice: seq=1 "ack"). + + let alice_y = AckedTestDgm::add( + alice_y, + charlie, + daphne, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &alice).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + + // Everyone processes each other's acks. + + let charlie_y = AckedTestDgm::ack( + charlie_y, + daphne, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + let alice_y = AckedTestDgm::ack( + alice_y, + daphne, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + let charlie_y = AckedTestDgm::ack( + charlie_y, + alice, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + let daphne_y = AckedTestDgm::ack( + daphne_y, + alice, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + + // Everyone should have the same members views. + + for id in [alice, charlie, daphne] { + assert_eq!( + AckedTestDgm::members_view(&alice_y, &id).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &id).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&daphne_y, &id).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + } + + // ---------------------- + + // Alice removes Charlie (alice: seq=2 "remove"). + + let alice_y = AckedTestDgm::remove( + alice_y, + alice, + &charlie, + MessageId { + sender: alice, + seq: 2, + }, + ) + .unwrap(); + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &alice).unwrap(), + HashSet::from([alice, daphne]) + ); + + // Charlie adds Bob concurrently (charlie: seq=3 "add"). + + let charlie_y = AckedTestDgm::add( + charlie_y, + charlie, + bob, + MessageId { + sender: charlie, + seq: 3, + }, + ) + .unwrap(); + + for id in [bob, charlie] { + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &id).unwrap(), + HashSet::from([alice, bob, charlie, daphne]) + ); + } + + for id in [alice, daphne] { + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &id).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + } + + // Bob processes their addition. + + let bob_y = AckedTestDgm::init(bob); + let bob_y = AckedTestDgm::from_welcome(bob_y, charlie_y.clone()).unwrap(); + + for id in [bob, charlie] { + assert_eq!( + AckedTestDgm::members_view(&bob_y, &id).unwrap(), + HashSet::from([alice, bob, charlie, daphne]) + ); + } + + // Everyone processes the removal of Charlie. + + let bob_y = AckedTestDgm::remove( + bob_y, + alice, + &charlie, + MessageId { + sender: alice, + seq: 2, + }, + ) + .unwrap(); + + let charlie_y = AckedTestDgm::remove( + charlie_y, + alice, + &charlie, + MessageId { + sender: alice, + seq: 2, + }, + ) + .unwrap(); + + let daphne_y = AckedTestDgm::remove( + daphne_y, + alice, + &charlie, + MessageId { + sender: alice, + seq: 2, + }, + ) + .unwrap(); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &bob).unwrap(), + HashSet::from([alice, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &charlie).unwrap(), + HashSet::from([alice, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&daphne_y, &daphne).unwrap(), + HashSet::from([alice, daphne]) + ); + + // Everyone else processes the add of Bob. + + let alice_y = AckedTestDgm::add( + alice_y, + charlie, + bob, + MessageId { + sender: charlie, + seq: 3, + }, + ) + .unwrap(); + + let daphne_y = AckedTestDgm::add( + daphne_y, + charlie, + bob, + MessageId { + sender: charlie, + seq: 3, + }, + ) + .unwrap(); + + // Because of the strong removal CRDT, Bob's add will not be recognized as the adder + // Charlie got removed by Alice. + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &alice).unwrap(), + HashSet::from([alice, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &charlie).unwrap(), + HashSet::from([alice, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&daphne_y, &daphne).unwrap(), + HashSet::from([alice, daphne]) + ); + + // Since nothing was ack'ed yet, all members should believe that the other's didn't do any + // changes to their member views yet. + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &daphne).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &alice).unwrap(), + HashSet::from([alice, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &charlie).unwrap(), + HashSet::from([alice, bob, charlie, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &daphne).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &daphne).unwrap(), + HashSet::from([alice, charlie, daphne]) + ); + } + + #[test] + fn members_view() { + let alice = 0; + let bob = 1; + let charlie = 2; + + // Alice creates a group with Charlie. + + let alice_y = AckedTestDgm::create(alice, &[alice, charlie]).unwrap(); + + let charlie_y = AckedTestDgm::init(charlie); + let charlie_y = AckedTestDgm::from_welcome(charlie_y, alice_y.clone()).unwrap(); + + // Alice adds Bob. + + let alice_y = AckedTestDgm::add( + alice_y, + alice, + bob, + MessageId { + sender: alice, + seq: 1, + }, + ) + .unwrap(); + + let bob_y = AckedTestDgm::init(bob); + let bob_y = AckedTestDgm::from_welcome(bob_y, alice_y.clone()).unwrap(); + + // Bob acks their own add, Charlie doesn't ack yet. + + let alice_y = AckedTestDgm::ack( + alice_y, + bob, + MessageId { + sender: alice, + seq: 1, + }, + ) + .unwrap(); + + // Both Alice and Bob consider all three members of the set. + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &alice).unwrap(), + HashSet::from([alice, bob, charlie]) + ); + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &bob).unwrap(), + HashSet::from([alice, bob, charlie]) + ); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &alice).unwrap(), + HashSet::from([alice, bob, charlie]) + ); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &bob).unwrap(), + HashSet::from([alice, bob, charlie]) + ); + + // Charlie didn't ack added Bob yet. + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &charlie).unwrap(), + HashSet::from([alice, charlie]) + ); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &charlie).unwrap(), + HashSet::from([alice, charlie]) + ); + + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &charlie).unwrap(), + HashSet::from([alice, charlie]) + ); + + // Charlie processes and acks added Bob. + + let charlie_y = AckedTestDgm::add( + charlie_y, + alice, + bob, + MessageId { + sender: alice, + seq: 1, + }, + ) + .unwrap(); + + let alice_y = AckedTestDgm::ack( + alice_y, + charlie, + MessageId { + sender: alice, + seq: 1, + }, + ) + .unwrap(); + + let bob_y = AckedTestDgm::ack( + bob_y, + charlie, + MessageId { + sender: alice, + seq: 1, + }, + ) + .unwrap(); + + // Everyone should have the same view. + + for id in [alice, bob, charlie] { + assert_eq!( + AckedTestDgm::members_view(&alice_y, &id).unwrap(), + HashSet::from([alice, bob, charlie]) + ); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &id).unwrap(), + HashSet::from([alice, bob, charlie]) + ); + + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &id).unwrap(), + HashSet::from([alice, bob, charlie]) + ); + } + + // Charlie removes Bob. + + let charlie_y = AckedTestDgm::remove( + charlie_y, + charlie, + &bob, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + + // Alice and Bob process the removal. + + let alice_y = AckedTestDgm::remove( + alice_y, + charlie, + &bob, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + + let bob_y = AckedTestDgm::remove( + bob_y, + charlie, + &bob, + MessageId { + sender: charlie, + seq: 2, + }, + ) + .unwrap(); + + // Everyone considers for themselves and for Charlie (the "remover") that Bob is removed + // from the group. + + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &charlie).unwrap(), + HashSet::from([alice, charlie]) + ); + + for id in [alice, charlie] { + assert_eq!( + AckedTestDgm::members_view(&alice_y, &id).unwrap(), + HashSet::from([alice, charlie]) + ); + } + + for id in [bob, charlie] { + assert_eq!( + AckedTestDgm::members_view(&bob_y, &id).unwrap(), + HashSet::from([alice, charlie]) + ); + } + + // .. but they assume so far that the other's still consider Bob part of the group (because + // no acks have been observed yet). + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &bob).unwrap(), + HashSet::from([alice, bob, charlie]), + ); + + assert_eq!( + AckedTestDgm::members_view(&bob_y, &alice).unwrap(), + HashSet::from([alice, bob, charlie]), + ); + + for id in [alice, bob] { + assert_eq!( + AckedTestDgm::members_view(&charlie_y, &id).unwrap(), + HashSet::from([alice, bob, charlie]), + "invalid members view from 2's perspective for {id}", + ); + } + } + + #[test] + fn strong_removal() { + let alice = 0; + let bob = 1; + let charlie = 2; + let daphne = 3; + + // Alice creates a group. + + let alice_y = AckedTestDgm::create(alice, &[alice]).unwrap(); + + // Alice adds Bob. + + let alice_y = AckedTestDgm::add( + alice_y, + alice, + bob, + MessageId { + sender: alice, + seq: 0, + }, + ) + .unwrap(); + + let bob_y = AckedTestDgm::init(bob); + let bob_y = AckedTestDgm::from_welcome(bob_y, alice_y.clone()).unwrap(); + + // Alice removes Bob. + + let alice_y = AckedTestDgm::remove( + alice_y, + alice, + &bob, + MessageId { + sender: alice, + seq: 0, + }, + ) + .unwrap(); + + // Concurrently Bob adds Charlie and Daphne. + + let bob_y = AckedTestDgm::add( + bob_y, + bob, + charlie, + MessageId { + sender: bob, + seq: 0, + }, + ) + .unwrap(); + + let bob_y = AckedTestDgm::add( + bob_y, + bob, + daphne, + MessageId { + sender: bob, + seq: 1, + }, + ) + .unwrap(); + + // Alice applies Bob's changes. + + let alice_y = AckedTestDgm::add( + alice_y, + bob, + charlie, + MessageId { + sender: bob, + seq: 0, + }, + ) + .unwrap(); + + let alice_y = AckedTestDgm::add( + alice_y, + bob, + daphne, + MessageId { + sender: bob, + seq: 1, + }, + ) + .unwrap(); + + // Bob applies Alice's changes. + + let bob_y = AckedTestDgm::remove( + bob_y, + alice, + &bob, + MessageId { + sender: alice, + seq: 1, + }, + ) + .unwrap(); + + assert_eq!( + AckedTestDgm::members_view(&alice_y, &alice).unwrap(), + AckedTestDgm::members_view(&bob_y, &bob).unwrap(), + ); + assert!( + !AckedTestDgm::members_view(&alice_y, &alice) + .unwrap() + .contains(&bob) + ); + assert!( + !AckedTestDgm::members_view(&alice_y, &alice) + .unwrap() + .contains(&charlie) + ); + assert!( + !AckedTestDgm::members_view(&alice_y, &alice) + .unwrap() + .contains(&daphne) + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/mod.rs new file mode 100644 index 0000000000..d4f3896ea2 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/mod.rs @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +pub mod dcgka; +pub mod dgm; +pub mod network; +pub mod ordering; diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/network.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/network.rs new file mode 100644 index 0000000000..a80ddb886e --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/network.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::collections::{HashMap, VecDeque}; + +use crate::Rng; +use crate::key_manager::KeyManager; +use crate::key_registry::KeyRegistry; +use crate::message_scheme::GroupError; +use crate::message_scheme::group::{GroupConfig, GroupEvent, GroupState, MessageGroup}; +use crate::message_scheme::test_utils::dcgka::init_dcgka_state; +use crate::message_scheme::test_utils::dgm::AckedTestDgm; +use crate::message_scheme::test_utils::ordering::{ForwardSecureOrderer, TestMessage}; +use crate::test_utils::{MemberId, MessageId}; +use crate::traits::ForwardSecureGroupMessage; + +pub type TestGroupState = GroupState< + MemberId, + MessageId, + KeyRegistry, + AckedTestDgm, + KeyManager, + ForwardSecureOrderer>, +>; + +pub type TestGroupError = GroupError< + MemberId, + MessageId, + KeyRegistry, + AckedTestDgm, + KeyManager, + ForwardSecureOrderer>, +>; + +pub fn init_group_state( + member_ids: [MemberId; N], + rng: &Rng, +) -> [TestGroupState; N] { + init_dcgka_state(member_ids, rng) + .into_iter() + .map(|dcgka| { + let orderer = + ForwardSecureOrderer::>::init(dcgka.my_id); + TestGroupState { + my_id: dcgka.my_id, + dcgka, + orderer, + welcome: None, + ratchet: None, + decryption_ratchet: HashMap::new(), + config: GroupConfig::default(), + } + }) + .collect::>() + .try_into() + .unwrap() +} + +pub struct Network { + rng: Rng, + members: HashMap, + queue: VecDeque>>, +} + +impl Network { + pub fn new(members: [MemberId; N], rng: Rng) -> Self { + let members = init_group_state(members, &rng); + Self { + members: HashMap::from_iter(members.into_iter().map(|state| (state.my_id, state))), + rng, + queue: VecDeque::new(), + } + } + + pub fn create(&mut self, creator: MemberId, initial_members: Vec) { + let y = self.get_y(&creator); + let (y_i, message) = MessageGroup::create(y, initial_members, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + } + + pub fn add(&mut self, adder: MemberId, added: MemberId) { + let y = self.get_y(&adder); + let (y_i, message) = MessageGroup::add(y, added, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + } + + pub fn remove(&mut self, remover: MemberId, removed: MemberId) { + let y = self.get_y(&remover); + let (y_i, message) = MessageGroup::remove(y, removed, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + self.get_y(&removed); + } + + pub fn update(&mut self, updater: MemberId) { + let y = self.get_y(&updater); + let (y_i, message) = MessageGroup::update(y, &self.rng).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + } + + pub fn send(&mut self, sender: MemberId, plaintext: &[u8]) { + let y = self.get_y(&sender); + let (y_i, message) = MessageGroup::send(y, plaintext).unwrap(); + self.queue.push_back(message); + self.set_y(y_i); + } + + pub fn process(&mut self) -> Vec<(MemberId, MemberId, Vec)> { + if self.queue.is_empty() { + return Vec::new(); + } + + let mut decrypted_messages = Vec::new(); + let member_ids: Vec = self.members.keys().cloned().collect(); + + while let Some(message) = self.queue.pop_front() { + for id in &member_ids { + // Do not process our own messages. + if &message.sender() == id { + continue; + } + + // Member processes each message broadcast to the group. + let y = self.get_y(id); + let (y_i, result) = MessageGroup::receive(y, &message, &self.rng).unwrap(); + self.set_y(y_i); + + let Some(result) = result else { + continue; + }; + + for event in result.events { + match event { + GroupEvent::Control(control_message) => { + // Processing messages might yield new ones, process these as well. + self.queue.push_back(control_message); + } + GroupEvent::Application { plaintext, .. } => decrypted_messages.push(( + message.sender(), // Sender + *id, // Receiver + plaintext, // Decrypted content + )), + GroupEvent::RemovedOurselves => (), + } + } + } + } + + decrypted_messages.sort(); + decrypted_messages + } + + pub fn members(&self, member: &MemberId) -> Vec { + let y = self.members.get(member).expect("member exists"); + let mut members = Vec::from_iter(MessageGroup::members(y).unwrap()); + members.sort(); + members + } + + fn get_y(&mut self, member: &MemberId) -> TestGroupState { + self.members.remove(member).expect("member exists") + } + + fn set_y(&mut self, y: TestGroupState) { + assert!( + self.members.insert(y.my_id, y).is_none(), + "state was removed before insertion" + ); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/ordering.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/ordering.rs new file mode 100644 index 0000000000..51a3ae7e02 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/test_utils/ordering.rs @@ -0,0 +1,300 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +// TODO: A complete ordering solution following the full ordering specification for the "message +// encryption" scheme will be provided as soon as "access control" work has been finished. +use std::collections::HashMap; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::message_scheme::{ControlMessage, DirectMessage, Generation}; +use crate::ordering::{Orderer, OrdererError, OrdererState}; +use crate::test_utils::{MemberId, MessageId}; +use crate::traits::{ + AckedGroupMembership, ForwardSecureGroupMessage, ForwardSecureMessageContent, + ForwardSecureOrdering, +}; + +/// Simplified orderer for testing the "message encryption" group APIs. +/// +/// NOTE: This orderer does _not_ fullfill the full specification for correct ordering. It's +/// assuming that peers process all messages after each member has published max. one control +/// or application message. On top it's very inefficient, as every published message points at +/// _every_ previously published messages from all peers. +/// +/// This is sufficient for the current testing setup but for anything "production ready" and +/// more robust for all concurrency scenarios, a more sophisticated solution will be required. +#[derive(Clone, Debug)] +pub struct ForwardSecureOrderer { + _marker: PhantomData, +} + +impl ForwardSecureOrderer +where + DGM: Clone + AckedGroupMembership, +{ + pub fn init(my_id: MemberId) -> ForwardSecureOrdererState { + ForwardSecureOrdererState { + next_message_seq: 0, + orderer: Orderer::init(), + my_id, + messages: HashMap::new(), + welcome_message: None, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ForwardSecureOrdererState +where + DGM: Clone + AckedGroupMembership, +{ + /// Sequence number of the next, message to-be published. + next_message_seq: usize, + + /// Our own member id. + my_id: MemberId, + + /// Internal helper to order messages based on their "previous" dependencies. + orderer: OrdererState, + + /// In-memory store of all messages. + messages: HashMap>, + + /// "Create" or "Add" message which got us into the group. + welcome_message: Option>, +} + +impl ForwardSecureOrdering for ForwardSecureOrderer +where + DGM: std::fmt::Debug + + Clone + + AckedGroupMembership + + Serialize + + for<'a> Deserialize<'a>, +{ + type State = ForwardSecureOrdererState; + + type Error = ForwardSecureOrdererError; + + type Message = TestMessage; + + fn next_control_message( + mut y: Self::State, + control_message: &ControlMessage, + direct_messages: &[DirectMessage], + ) -> Result<(Self::State, Self::Message), Self::Error> { + let seq = y.next_message_seq; + let sender = y.my_id; + + // This is a very naive implementation where every message points at _every_ known, + // previous message as an "dependency". This allows us to not write any code which tracks + // transitive dependencies. + let previous = y.messages.keys().cloned().collect(); + + let message = TestMessage { + seq, + sender, + previous, + content: TestMessageContent::System { + control_message: control_message.to_owned(), + direct_messages: direct_messages.to_owned(), + }, + }; + + y.messages.insert(message.id(), message.clone()); + y.next_message_seq += 1; + + Ok((y, message)) + } + + fn next_application_message( + mut y: Self::State, + generation: Generation, + ciphertext: Vec, + ) -> Result<(Self::State, Self::Message), Self::Error> { + let seq = y.next_message_seq; + let sender = y.my_id; + + // This is a very naive implementation where every message points at _every_ known, + // previous message as an "dependency". This allows us to not write any code which tracks + // transitive dependencies. + let previous = y.messages.keys().cloned().collect(); + + let message = TestMessage { + seq, + sender, + previous, + content: TestMessageContent::Application { + ciphertext, + generation, + }, + }; + + y.messages.insert(message.id(), message.clone()); + y.next_message_seq += 1; + + Ok((y, message)) + } + + fn queue(mut y: Self::State, message: &Self::Message) -> Result { + let id = message.id(); + + y.messages.insert(id, message.clone()); + + // Clear dependencies list from own messages, we didn't queue them as we know that we've + // seen and processed them. + let previous: Vec = message + .previous + .iter() + .filter(|id| id.sender != y.my_id) + .cloned() + .collect(); + + if !Orderer::ready(&y.orderer, &previous)? { + let (y_orderer_i, _) = Orderer::mark_pending(y.orderer, id, previous)?; + y.orderer = y_orderer_i; + return Ok(y); + } + + let (y_orderer_i, _) = Orderer::mark_ready(y.orderer, id)?; + let y_orderer_ii = Orderer::process_pending(y_orderer_i, id)?; + y.orderer = y_orderer_ii; + + Ok(y) + } + + fn set_welcome( + mut y: Self::State, + message: &Self::Message, + ) -> Result { + y.welcome_message = Some(message.clone()); + Ok(y) + } + + fn next_ready_message( + y: Self::State, + ) -> Result<(Self::State, Option), Self::Error> { + // We have not joined the group yet, don't process any messages yet. + let Some(welcome) = y.welcome_message.clone() else { + return Ok((y, None)); + }; + + let mut y_loop = y; + loop { + let (y_next, next_ready) = Orderer::take_next_ready(y_loop.orderer)?; + y_loop.orderer = y_next; + + let message = next_ready.map(|id| { + y_loop + .messages + .get(&id) + .expect("ids map consistently to messages") + .to_owned() + }); + + if let Some(message) = message { + // Don't forward welcome message, it was already processed. + if message.id() == welcome.id() { + continue; + } + + // Control messages can be ignored if message is before our welcome. Concurrent + // messages need to be processed. + // + // This is a naive implementation where we assume that every member processed every + // control message after one round and where every message points at _every_ + // previously-created message. + if let ForwardSecureMessageContent::Control { .. } = message.content() + && welcome.previous.contains(&message.id()) + { + continue; + } + + // Application messages can be ignored if before or concurrent to welcome. + if let ForwardSecureMessageContent::Application { .. } = message.content() + && !message.previous.contains(&welcome.id()) + { + continue; + } + + return Ok((y_loop, Some(message))); + } else { + return Ok((y_loop, None)); + } + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TestMessage +where + DGM: Clone + AckedGroupMembership, +{ + seq: usize, + sender: usize, + previous: Vec, + content: TestMessageContent, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum TestMessageContent +where + DGM: Clone + AckedGroupMembership, +{ + Application { + ciphertext: Vec, + generation: Generation, + }, + System { + control_message: ControlMessage, + direct_messages: Vec>, + }, +} + +impl ForwardSecureGroupMessage for TestMessage +where + DGM: Clone + AckedGroupMembership, +{ + fn id(&self) -> MessageId { + MessageId { + sender: self.sender, + seq: self.seq, + } + } + + fn sender(&self) -> MemberId { + self.sender + } + + fn content(&self) -> ForwardSecureMessageContent { + match &self.content { + TestMessageContent::Application { + ciphertext, + generation, + } => ForwardSecureMessageContent::Application { + ciphertext: ciphertext.to_owned(), + generation: *generation, + }, + TestMessageContent::System { + control_message, .. + } => ForwardSecureMessageContent::Control(control_message.to_owned()), + } + } + + fn direct_messages(&self) -> Vec> { + match &self.content { + TestMessageContent::Application { .. } => Vec::new(), + TestMessageContent::System { + direct_messages, .. + } => direct_messages.clone(), + } + } +} + +#[derive(Debug, Error)] +pub enum ForwardSecureOrdererError { + #[error(transparent)] + Orderer(#[from] OrdererError), +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/concurrency.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/concurrency.rs new file mode 100644 index 0000000000..4ae4e5193c --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/concurrency.rs @@ -0,0 +1,615 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::crypto::Rng; +use crate::message_scheme::dcgka::{Dcgka, DirectMessageType, ProcessInput}; +use crate::message_scheme::test_utils::dcgka::{ + ExpectedMembers, assert_direct_message, assert_members_view, init_dcgka_state, +}; +use crate::test_utils::MessageId; + +// From DCGKA paper (6.2.5): +// +// "In particular, care is required when an add operation occurs concurrently with an update, +// remove, or another add operation." +// +// "We want all intended recipients to learn every update secret, since otherwise some users would +// not be able to decrypt some messages, despite being a group member. For example, consider a +// group with members {A, B, C}, and say A performs an update while concurrently C adds D to the +// group. When A distributes a new seed secret through 2SM-encrypted direct messages, D will not be +// a recipient of one of those direct messages, since A did not know about D's addition at the time +// of sending." +// +// "D will therefore execute lines 6–7 of process-seed, and it cannot derive any of the member +// secrets for this update. When B updates its KDF ratchet using A's seed secret, it will compute +// an update secret that D does not know, and D will not be able to decrypt B's subsequent +// application messages." +// +// "In this example, B may receive the add and the update in either order. If B processes A's +// update first, the seed secret from A is already incorporated into B's ratchet state at time time +// of adding D; since B sends this ratchet state to D along with its "add-ack" message, no further +// action is needed. On the other hand, if B processes the addition of D first, then when B +// subsequently processes A's update, B must take the member secret it derives from A's seed secret +// and forward it to D, so that D can compute B's update secret for A's update." +#[test] +fn concurrent_operation() { + let rng = Rng::from_seed([1; 32]); + + let alice = 0; + let bob = 1; + let charlie = 2; + let dahlia = 3; + let emil = 4; + + // Generate key material for all members, register pre-keys and initialise DCGKA states. + let [ + alice_dcgka, + bob_dcgka, + charlie_dcgka, + dahlia_dcgka, + _emil_dcgka, + ] = init_dcgka_state([alice, bob, charlie, dahlia, emil], &rng); + + // Alice creates a group with Bob and Charlie (similar to the paper's example). + let (alice_dcgka, alice_output) = { + let (alice_dcgka_pre, alice_pre) = + Dcgka::create(alice_dcgka, vec![alice, bob, charlie], &rng).unwrap(); + Dcgka::process_local( + alice_dcgka_pre, + MessageId { + sender: alice, + seq: 0, + }, + alice_pre, + &rng, + ) + .unwrap() + }; + + // Bob and Charlie process the "create" message from Alice. + let (bob_dcgka, _bob_output) = Dcgka::process_remote( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + direct_message: Some(assert_direct_message(&alice_output.direct_messages, bob)), + control_message: alice_output.control_message.clone(), + }, + &rng, + ) + .unwrap(); + + let (charlie_dcgka, _charlie_output) = Dcgka::process_remote( + charlie_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + direct_message: Some(assert_direct_message( + &alice_output.direct_messages, + charlie, + )), + control_message: alice_output.control_message, + }, + &rng, + ) + .unwrap(); + + // Everybody should consider each other part of the group. + for dcgka in [&alice_dcgka, &bob_dcgka, &charlie_dcgka] { + assert_members_view( + dcgka, + &[ExpectedMembers { + viewer: &[alice, bob, charlie], + expected: &[alice, bob, charlie], + }], + ); + } + + // Charlie adds Dahlia to the group (similar to paper's example). + let (charlie_dcgka, charlie_output) = { + let (charlie_dcgka_pre, charlie_pre) = Dcgka::add(charlie_dcgka, dahlia, &rng).unwrap(); + Dcgka::process_local( + charlie_dcgka_pre, + MessageId { + sender: charlie, + seq: 1, + }, + charlie_pre, + &rng, + ) + .unwrap() + }; + + for dcgka in [&alice_dcgka, &bob_dcgka] { + assert_members_view( + dcgka, + &[ExpectedMembers { + viewer: &[alice, bob, charlie], + expected: &[alice, bob, charlie], + }], + ); + } + + assert_members_view( + &charlie_dcgka, + &[ExpectedMembers { + viewer: &[charlie, dahlia], + expected: &[alice, bob, charlie, dahlia], + }], + ); + + // Bob processes Dahlia's addition by Charlie. + let (bob_dcgka, bob_output) = Dcgka::process_remote( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: charlie, + seq: 1, + }, + sender: charlie, + direct_message: None, + control_message: charlie_output.control_message.clone(), + }, + &rng, + ) + .unwrap(); + + assert_eq!(bob_output.direct_messages.len(), 1); + assert_eq!( + bob_output.direct_messages.first().unwrap().recipient, + dahlia + ); + + assert_members_view( + &bob_dcgka, + &[ + ExpectedMembers { + viewer: &[bob, charlie, dahlia], + expected: &[alice, bob, charlie, dahlia], + }, + ExpectedMembers { + viewer: &[alice], + expected: &[alice, bob, charlie], + }, + ], + ); + + // Dahlia processes their addition by Charlie. + let (dahlia_dcgka, _dahlia_output) = Dcgka::process_remote( + dahlia_dcgka, + ProcessInput { + seq: MessageId { + sender: charlie, + seq: 1, + }, + sender: charlie, + direct_message: Some(assert_direct_message( + &charlie_output.direct_messages, + dahlia, + )), + control_message: charlie_output.control_message, + }, + &rng, + ) + .unwrap(); + + assert_members_view( + &dahlia_dcgka, + &[ + ExpectedMembers { + viewer: &[charlie, dahlia], + expected: &[alice, bob, charlie, dahlia], + }, + ExpectedMembers { + viewer: &[alice, bob], + expected: &[alice, bob, charlie], + }, + ], + ); + + // Dahlia processes the "ack" of Bob adding them and the direct message. + let (dahlia_dcgka, _dahlia_output) = Dcgka::process_remote( + dahlia_dcgka, + ProcessInput { + seq: MessageId { + sender: bob, + seq: 1, + }, + sender: bob, + direct_message: Some(assert_direct_message(&bob_output.direct_messages, dahlia)), + control_message: bob_output.control_message.as_ref().unwrap().clone(), + }, + &rng, + ) + .unwrap(); + + for action in ["update", "remove", "another_add"] { + // Concurrently Alice performs another group operation. + let (_alice_dcgka, alice_output) = { + let (alice_dcgka_pre, alice_pre) = match action { + // Alice updates the group seed. + "update" => Dcgka::update(alice_dcgka.clone(), &rng).unwrap(), + // Alice concurrently removes Charlie who wanted to add Dahlia. + "remove" => Dcgka::remove(alice_dcgka.clone(), charlie, &rng).unwrap(), + // Alice adds Emil to the group. + "another_add" => Dcgka::add(alice_dcgka.clone(), emil, &rng).unwrap(), + _ => unreachable!(), + }; + Dcgka::process_local( + alice_dcgka_pre, + MessageId { + sender: alice, + seq: 1, + }, + alice_pre, + &rng, + ) + .unwrap() + }; + + // Bob processes Alice's operation _after_ they accepted Charlie's add of Dahlia. + let (_bob_dcgka, bob_output) = Dcgka::process_remote( + bob_dcgka.clone(), + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + control_message: alice_output.control_message.clone(), + direct_message: { + if action == "another_add" { + None + } else if action == "update" || action == "remove" { + Some(assert_direct_message(&alice_output.direct_messages, bob)) + } else { + unreachable!() + } + }, + }, + &rng, + ) + .unwrap(); + + if action == "remove" { + // Bob processed the "remove" already, so they will not forward anything to Dahlia + // anymore. + assert_eq!(bob_output.direct_messages.len(), 0); + } else if action == "another_add" { + // Bob forwards a direct message to Emil as part of the regular "add" procedure. + assert_eq!(bob_output.direct_messages.len(), 1); + assert_eq!(bob_output.direct_messages.first().unwrap().recipient, emil); + assert_eq!( + bob_output.direct_messages.first().unwrap().message_type(), + DirectMessageType::Forward + ); + } else if action == "update" { + // Bob forwards a direct message to Dahlia to account for the concurrent group update + // of Alice. + assert_eq!(bob_output.direct_messages.len(), 1); + assert_eq!( + bob_output.direct_messages.first().unwrap().recipient, + dahlia + ); + assert_eq!( + bob_output.direct_messages.first().unwrap().message_type(), + DirectMessageType::Forward + ); + } + + // Dahlia processes the concurrent operation of Alice. + let (dahlia_dcgka, dahlia_output) = Dcgka::process_remote( + dahlia_dcgka.clone(), + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + control_message: alice_output.control_message, + // We don't expect any direct messages to Dahlia from Alice as Alice didn't know + // about them when they performed the group operation. + direct_message: None, + }, + &rng, + ) + .unwrap(); + + if action == "another_add" { + // During an add Dahlia could already derive the temporary update secret. + assert!(dahlia_output.me_update_secret.is_some()); + } else { + // .. otherwise they can't do much yet. + assert!(dahlia_output.me_update_secret.is_none()); + } + assert!(dahlia_output.sender_update_secret.is_none()); + + // Dahlia processes the direct "forward" message and "ack" of Bob. + if action == "update" { + let (_dahlia_dcgka, dahlia_output) = Dcgka::process_remote( + dahlia_dcgka, + ProcessInput { + seq: MessageId { + sender: bob, + seq: 2, + }, + sender: bob, + direct_message: Some(assert_direct_message( + &bob_output.direct_messages, + dahlia, + )), + control_message: bob_output.control_message.as_ref().unwrap().clone(), + }, + &rng, + ) + .unwrap(); + + // Dahlia's update secret matches the one of Bob after handling all concurrent actions. + assert_eq!( + dahlia_output.sender_update_secret.unwrap(), + bob_output.me_update_secret.unwrap() + ); + } + } +} + +// From DCGKA paper (6.2.5): +// +// "Another scenario that needs to be handled is when two users are concurrently added to the +// group." +// +// "For example, in a group consisting initially of {A, B}, say A adds C to the group, while +// concurrently B adds D. User C first processes its own addition and welcome message, and then +// processes B's addition of D. However, since C was not a group member at the time B sent its +// "add" message, C does not yet have B's ratchet state, so C cannot derive an update secret for +// B's "add" message. The condition on line 5 of process-add is false and so C does not derive an +// update secret on lines 6–8. When B finds out about the fact that A has added C, B sends C its +// ratchet state as usual (line 12 of process-add), so C can initialize its copy of B's ratchet as +// before (lines 4–5 of process-add-ack)." +// +// "Similarly, when D finds out about the fact that A has added C, D sends its ratchet state to C +// along with the "add-ack" message. The existing logic therefore handles the concurrent additions: +// after all acks have been delivered, C and D have both initialized their copies of all four +// ratchets, and so they are able to decrypt application messages that any group member sent after +// processing their addition." +#[test] +fn concurrent_adds() { + let rng = Rng::from_seed([1; 32]); + + let alice = 0; + let bob = 1; + let charlie = 2; + let dahlia = 3; + + // Generate key material for all members, register pre-keys and initialise DCGKA states. + let [alice_dcgka, bob_dcgka, charlie_dcgka, dahlia_dcgka] = + init_dcgka_state([alice, bob, charlie, dahlia], &rng); + + // Alice creates a group with Bob (similar to the paper's example). + let (alice_dcgka, alice_output) = { + let (alice_dcgka_pre, alice_pre) = + Dcgka::create(alice_dcgka, vec![alice, bob], &rng).unwrap(); + Dcgka::process_local( + alice_dcgka_pre, + MessageId { + sender: alice, + seq: 0, + }, + alice_pre, + &rng, + ) + .unwrap() + }; + + // Bob processes the "create" message from Alice. + let (bob_dcgka, bob_output) = Dcgka::process_remote( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 0, + }, + sender: alice, + direct_message: Some(assert_direct_message(&alice_output.direct_messages, bob)), + control_message: alice_output.control_message, + }, + &rng, + ) + .unwrap(); + + // Bob learned about Alice's update secret. + assert_eq!( + &alice_output.me_update_secret.unwrap(), + bob_output.sender_update_secret.as_ref().unwrap() + ); + + // Alice processing the "ack" of Bob. + let (alice_dcgka, alice_output) = Dcgka::process_remote( + alice_dcgka, + ProcessInput { + seq: MessageId { + sender: bob, + seq: 0, + }, + sender: bob, + direct_message: None, + control_message: bob_output.control_message.unwrap(), + }, + &rng, + ) + .unwrap(); + + // Alice learned about Bob's update secret. + assert_eq!( + alice_output.sender_update_secret.unwrap(), + bob_output.me_update_secret.unwrap() + ); + + // Everybody should consider each other part of the group. + for dcgka in [&alice_dcgka, &bob_dcgka] { + assert_members_view( + dcgka, + &[ExpectedMembers { + viewer: &[alice, bob], + expected: &[alice, bob], + }], + ); + } + + // Alice adds Charlie to the group (as example in paper). + let (_alice_dcgka, alice_output) = { + let (alice_dcgka_pre, alice_pre) = Dcgka::add(alice_dcgka, charlie, &rng).unwrap(); + Dcgka::process_local( + alice_dcgka_pre, + MessageId { + sender: alice, + seq: 1, + }, + alice_pre, + &rng, + ) + .unwrap() + }; + + // Bob concurrently adds Dahlia to the group (as example in paper). + let (bob_dcgka, bob_output) = { + let (bob_dcgka_pre, bob_pre) = Dcgka::add(bob_dcgka, dahlia, &rng).unwrap(); + Dcgka::process_local( + bob_dcgka_pre, + MessageId { + sender: bob, + seq: 1, + }, + bob_pre, + &rng, + ) + .unwrap() + }; + + // Charlie processes their own addition by Alice. + let (charlie_dcgka, _charlie_output) = Dcgka::process_remote( + charlie_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + direct_message: Some(assert_direct_message( + &alice_output.direct_messages, + charlie, + )), + control_message: alice_output.control_message.clone(), + }, + &rng, + ) + .unwrap(); + + // Dahlia processes their own add by Bob. + let (dahlia_dcgka, _dahlia_output) = Dcgka::process_remote( + dahlia_dcgka, + ProcessInput { + seq: MessageId { + sender: bob, + seq: 1, + }, + sender: bob, + direct_message: Some(assert_direct_message(&bob_output.direct_messages, dahlia)), + control_message: bob_output.control_message, + }, + &rng, + ) + .unwrap(); + + // Dahlia processes Alice's addition of Charlie. + let (dahlia_dcgka, _dahlia_output) = Dcgka::process_remote( + dahlia_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + direct_message: None, + control_message: alice_output.control_message.clone(), + }, + &rng, + ) + .unwrap(); + + assert_members_view( + &dahlia_dcgka, + &[ExpectedMembers { + viewer: &[dahlia], + expected: &[alice, bob, charlie, dahlia], + }], + ); + + // Bob processes Charlie's "add" by Alice and finally learns that this happenend concurrently + // to their own add of Dahlia. + let (bob_dcgka, bob_output) = Dcgka::process_remote( + bob_dcgka, + ProcessInput { + seq: MessageId { + sender: alice, + seq: 1, + }, + sender: alice, + direct_message: None, + control_message: alice_output.control_message, + }, + &rng, + ) + .unwrap(); + + assert_members_view( + &bob_dcgka, + &[ + ExpectedMembers { + viewer: &[bob], + expected: &[alice, bob, charlie, dahlia], + }, + ExpectedMembers { + viewer: &[charlie], + expected: &[alice, bob, charlie], + }, + ], + ); + + // Bob prepares a direct "forward" message to Charlie due to the concurrent operations. + assert_eq!(bob_output.direct_messages.len(), 1); + assert_eq!( + bob_output.direct_messages.first().unwrap().recipient, + charlie + ); + assert_eq!( + bob_output.direct_messages.first().unwrap().message_type(), + DirectMessageType::Forward + ); + + // Charlie processes the "add-ack" of Bob and handles the direct "forward" message. + let (_charlie_dcgka, charlie_output) = Dcgka::process_remote( + charlie_dcgka, + ProcessInput { + seq: MessageId { + sender: bob, + seq: 1, + }, + sender: bob, + direct_message: Some(assert_direct_message(&bob_output.direct_messages, charlie)), + control_message: bob_output.control_message.unwrap(), + }, + &rng, + ) + .unwrap(); + + assert_eq!( + bob_output.me_update_secret.unwrap(), + charlie_output.sender_update_secret.unwrap() + ); +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/group_operations.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/group_operations.rs new file mode 100644 index 0000000000..2cf3424575 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/group_operations.rs @@ -0,0 +1,738 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::Rng; +use crate::message_scheme::dcgka::{Dcgka, ProcessInput}; +use crate::message_scheme::test_utils::dcgka::{ + AssertableDcgka, ExpectedMembers, assert_direct_message, assert_members_view, init_dcgka_state, +}; +use crate::test_utils::MessageId; + +#[test] +fn group_operations() { + let rng = Rng::from_seed([1; 32]); + + let alice = 0; + let bob = 1; + let charlie = 2; + + // Generate key material for all members, register pre-keys and initialise DCGKA states. + let [alice_dcgka, bob_dcgka, charlie_dcgka] = init_dcgka_state([alice, bob, charlie], &rng); + + // Initialise stateful test-helper verifying DCGKA state. + let mut test = AssertableDcgka::new(); + + // ================================= + // 1. Alice creates a group with Bob + // ================================= + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) <-- + // [ ] Bob's Ratchet (0) + // + // Bob's perspective: + // + // [ ] Alice's Rachet (0) + // [ ] Bob's Ratchet (0) + // + // Note: The numbers in brackets eg. "(0)" represent the update secret epoch. It starts with 0 + // and increases by 1 on every key rotation ("group update"). + + let (alice_dcgka_0, alice_0_seq_0) = { + let (alice_dcgka_pre, alice_pre) = + Dcgka::create(alice_dcgka, vec![alice, bob], &rng).unwrap(); + let seq = MessageId { + sender: alice, + seq: 0, + }; + let (alice_dcgka_0, alice_0) = + Dcgka::process_local(alice_dcgka_pre, seq, alice_pre, &rng).unwrap(); + test.assert_create(&alice_dcgka_0, &alice_0, alice, &[alice, bob], seq); + (alice_dcgka_0, alice_0) + }; + + // =============================== + // 2. Bob processes Alice's Create + // =============================== + // + // Bob processes the "invitation" and establishes the same state for Alice's ratchet. Bob + // "acks" the "create" of Alice and returns it as a control message. + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Bob's Ratchet (0) + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) <-- + // [x] Bob's Ratchet (0) <-- + + let (bob_dcgka_0, bob_0_seq_0) = { + let seq = MessageId { + sender: alice, + seq: 0, + }; + let (bob_dcgka_0, bob_0) = Dcgka::process_remote( + bob_dcgka, + ProcessInput { + seq, + sender: alice, + direct_message: Some(assert_direct_message(&alice_0_seq_0.direct_messages, bob)), + control_message: alice_0_seq_0.control_message, + }, + &rng, + ) + .unwrap(); + test.assert_process_create(&bob_dcgka_0, &bob_0, bob, alice, &[alice, bob], seq); + (bob_dcgka_0, bob_0) + }; + + // ============================ + // 3. Alice processes Bob's Ack + // ============================ + // + // Alice processes the ack of Bob and establishes the same state for Bob's ratchet. + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [x] Bob's Ratchet (0) <-- + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) + // [x] Bob's Ratchet (0) + + let (alice_dcgka_1, _alice_1) = { + let seq = MessageId { + sender: bob, + seq: 0, + }; + let (alice_dcgka_1, alice_1) = Dcgka::process_remote( + alice_dcgka_0, + ProcessInput { + seq, + sender: bob, + direct_message: None, + control_message: bob_0_seq_0.control_message.unwrap(), + }, + &rng, + ) + .unwrap(); + test.assert_process_ack(&alice_dcgka_1, &alice_1, alice, bob, seq); + assert_members_view( + &alice_dcgka_1, + &[ExpectedMembers { + viewer: &[alice, bob], + expected: &[alice, bob], + }], + ); + (alice_dcgka_1, alice_1) + }; + + // ================================ + // 4. Bob adds Charlie to the group + // ================================ + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [ ] Bob's Ratchet (1) + // [ ] Charlie's Ratchet (0) + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) <-- + // [ ] Charlie's Ratchet (0) + // + // Charlie's perspective: + // + // [ ] Alice's Rachet (1) + // [ ] Bob's Ratchet (1) + // [ ] Charlie's Ratchet (0) + + let (bob_dcgka_1, bob_1_seq_1) = { + let (bob_dcgka_pre, bob_pre) = Dcgka::add(bob_dcgka_0, charlie, &rng).unwrap(); + let seq = MessageId { + sender: bob, + seq: 1, + }; + let (bob_dcgka_1, bob_1) = Dcgka::process_local(bob_dcgka_pre, seq, bob_pre, &rng).unwrap(); + test.assert_add(&bob_dcgka_1, &bob_1, bob, charlie, seq); + assert_members_view( + &bob_dcgka_1, + &[ + ExpectedMembers { + viewer: &[bob, charlie], + expected: &[alice, bob, charlie], + }, + ExpectedMembers { + viewer: &[alice], + expected: &[alice, bob], + }, + ], + ); + (bob_dcgka_1, bob_1) + }; + + // ======================================== + // 5. Charlie processes Bob's Add & Welcome + // ======================================== + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [ ] Bob's Ratchet (1) + // [ ] Charlie's Ratchet (0) + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [ ] Charlie's Ratchet (0) + // + // Charlie's perspective: + // + // [ ] Alice's Rachet (1) + // [x] Bob's Ratchet (1) <-- + // [x] Charlie's Ratchet (0) <-- + + let (charlie_dcgka_0, charlie_0_seq_0) = { + let seq = MessageId { + sender: bob, + seq: 1, + }; + let (charlie_dcgka_0, charlie_0) = Dcgka::process_remote( + charlie_dcgka, + ProcessInput { + seq, + sender: bob, + direct_message: Some(assert_direct_message(&bob_1_seq_1.direct_messages, charlie)), + control_message: bob_1_seq_1.control_message.clone(), + }, + &rng, + ) + .unwrap(); + test.assert_process_welcome( + &charlie_dcgka_0, + &charlie_0, + bob, + charlie, + &[alice, bob, charlie], + seq, + ); + (charlie_dcgka_0, charlie_0) + }; + + // ======================================= + // 6. Alice processes Bob's Add of Charlie + // ======================================= + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [x] Alice's Ratchet (1) <-- + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) <-- + // [ ] Charlie's Ratchet (0) + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [ ] Charlie's Ratchet (0) + // + // Charlie's perspective: + // + // [ ] Alice's Rachet (1) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + + let (alice_dcgka_2, alice_2_seq_1) = { + let seq = MessageId { + sender: bob, + seq: 1, + }; + let (alice_dcgka_2, alice_2) = Dcgka::process_remote( + alice_dcgka_1, + ProcessInput { + seq, + sender: bob, + direct_message: None, + control_message: bob_1_seq_1.control_message, + }, + &rng, + ) + .unwrap(); + test.assert_process_add(&alice_dcgka_2, &alice_2, alice, bob, charlie, seq); + assert_members_view( + &alice_dcgka_2, + &[ExpectedMembers { + viewer: &[alice, bob, charlie], + expected: &[alice, bob, charlie], + }], + ); + (alice_dcgka_2, alice_2) + }; + + // ============================== + // 7. Bob processes Charlie's Ack + // ============================== + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [x] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [ ] Charlie's Ratchet (0) + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) <-- + // + // Charlie's perspective: + // + // [ ] Alice's Rachet (1) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + + let (bob_dcgka_2, _bob_2) = { + let seq = MessageId { + sender: charlie, + seq: 0, + }; + let (bob_dcgka_2, bob_2) = Dcgka::process_remote( + bob_dcgka_1, + ProcessInput { + seq, + sender: charlie, + direct_message: None, + control_message: charlie_0_seq_0.control_message.as_ref().unwrap().clone(), + }, + &rng, + ) + .unwrap(); + test.assert_process_ack(&bob_dcgka_2, &bob_2, bob, charlie, seq); + (bob_dcgka_2, bob_2) + }; + + // ================================ + // 8. Alice processes Charlie's Ack + // ================================ + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [x] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) <-- + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + // + // Charlie's perspective: + // + // [ ] Alice's Rachet (1) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + + let (_alice_dcgka_3, _alice_3) = { + let seq = MessageId { + sender: charlie, + seq: 0, + }; + let (alice_dcgka_3, alice_3) = Dcgka::process_remote( + alice_dcgka_2, + ProcessInput { + seq, + sender: charlie, + direct_message: None, + control_message: charlie_0_seq_0.control_message.unwrap(), + }, + &rng, + ) + .unwrap(); + test.assert_process_ack(&alice_dcgka_3, &alice_3, alice, charlie, seq); + (alice_dcgka_3, alice_3) + }; + + // =================================== + // 9. Charlie processes Alice's AddAck + // =================================== + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [x] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) + // [ ] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + // + // Charlie's perspective: + // + // [x] Alice's Rachet (1) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + + let (charlie_dcgka_1, _charlie_1) = { + let seq = MessageId { + sender: alice, + seq: 1, + }; + let (charlie_dcgka_1, charlie_1) = Dcgka::process_remote( + charlie_dcgka_0, + ProcessInput { + seq, + sender: alice, + direct_message: Some(assert_direct_message( + &alice_2_seq_1.direct_messages, + charlie, + )), + control_message: alice_2_seq_1.control_message.as_ref().unwrap().clone(), + }, + &rng, + ) + .unwrap(); + test.assert_process_add_ack(&charlie_dcgka_1, &charlie_1, charlie, alice); + (charlie_dcgka_1, charlie_1) + }; + + // ================================ + // 10. Bob processes Alice's AddAck + // ================================ + // + // Alice's perspective: + // + // [x] Alice's Rachet (0) + // [x] Alice's Ratchet (1) + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + // + // Bob's perspective: + // + // [x] Alice's Rachet (0) + // [x] Alice's Ratchet (1) <-- + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + // + // Charlie's perspective: + // + // [x] Alice's Rachet (1) + // [x] Bob's Ratchet (1) + // [x] Charlie's Ratchet (0) + + let (bob_dcgka_3, _bob_3) = { + let seq = MessageId { + sender: alice, + seq: 1, + }; + let (bob_dcgka_3, bob_3) = Dcgka::process_remote( + bob_dcgka_2, + ProcessInput { + seq, + sender: alice, + direct_message: None, + control_message: alice_2_seq_1.control_message.as_ref().unwrap().clone(), + }, + &rng, + ) + .unwrap(); + test.assert_process_add_ack(&bob_dcgka_3, &bob_3, bob, alice); + (bob_dcgka_3, bob_3) + }; + + // ========================= + // 11. Charlie removes Alice + // ========================= + // + // Bob's perspective: + // + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [ ] Bob's Ratchet (2) + // [x] Charlie's Ratchet (0) + // [ ] Charlie's Ratchet (1) + // + // Charlie's perspective: + // + // [x] Bob's Ratchet (1) + // [ ] Bob's Ratchet (2) + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) <-- + + let (charlie_dcgka_2, charlie_2_seq_1) = { + let (charlie_dcgka_pre, charlie_pre) = Dcgka::remove(charlie_dcgka_1, alice, &rng).unwrap(); + let seq = MessageId { + sender: charlie, + seq: 1, + }; + let (charlie_dcgka_2, charlie_2) = + Dcgka::process_local(charlie_dcgka_pre, seq, charlie_pre, &rng).unwrap(); + test.assert_remove( + &charlie_dcgka_2, + &charlie_2, + charlie, + alice, + &[bob, charlie], + seq, + ); + assert_members_view( + &charlie_dcgka_2, + &[ + ExpectedMembers { + viewer: &[charlie], + expected: &[bob, charlie], + }, + ExpectedMembers { + viewer: &[alice, bob], + expected: &[alice, bob, charlie], + }, + ], + ); + (charlie_dcgka_2, charlie_2) + }; + + // =========================================== + // 12. Bob processes Charlie's Remove of Alice + // =========================================== + // + // Bob's perspective: + // + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) <-- + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) <-- + // + // Charlie's perspective: + // + // [x] Bob's Ratchet (1) + // [ ] Bob's Ratchet (2) + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + + let (bob_dcgka_4, bob_4_seq_2) = { + let seq = MessageId { + sender: charlie, + seq: 1, + }; + let (bob_dcgka_4, bob_4) = Dcgka::process_remote( + bob_dcgka_3, + ProcessInput { + seq, + sender: charlie, + direct_message: Some(assert_direct_message(&charlie_2_seq_1.direct_messages, bob)), + control_message: charlie_2_seq_1.control_message, + }, + &rng, + ) + .unwrap(); + test.assert_process_remove(&bob_dcgka_4, &bob_4, bob, charlie, seq); + assert_members_view( + &bob_dcgka_4, + &[ + ExpectedMembers { + viewer: &[bob, charlie], + expected: &[bob, charlie], + }, + ExpectedMembers { + viewer: &[alice], + expected: &[alice, bob, charlie], + }, + ], + ); + (bob_dcgka_4, bob_4) + }; + + // =============================== + // 13. Charlie processes Bob's Ack + // =============================== + // + // Bob's perspective: + // + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + // + // Charlie's perspective: + // + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) <-- + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + + let (charlie_dcgka_3, _charlie_3) = { + let seq = MessageId { + sender: bob, + seq: 2, + }; + let (charlie_dcgka_3, charlie_3) = Dcgka::process_remote( + charlie_dcgka_2, + ProcessInput { + seq, + sender: bob, + direct_message: None, + control_message: bob_4_seq_2.control_message.unwrap(), + }, + &rng, + ) + .unwrap(); + test.assert_process_ack(&charlie_dcgka_3, &charlie_3, charlie, bob, seq); + (charlie_dcgka_3, charlie_3) + }; + + // =================================== + // 14. Bob updates the group's secrets + // =================================== + // + // Bob's perspective: + // + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) + // [x] Bob's Ratchet (3) <-- + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + // [ ] Charlie's Ratchet (2) + // + // Charlie's perspective: + // + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) + // [ ] Bob's Ratchet (3) + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + // [ ] Charlie's Ratchet (2) + + let (bob_dcgka_5, bob_5_seq_3) = { + let (bob_dcgka_pre, bob_pre) = Dcgka::update(bob_dcgka_4, &rng).unwrap(); + let seq = MessageId { + sender: bob, + seq: 3, + }; + let (bob_dcgka_5, bob_5) = Dcgka::process_local(bob_dcgka_pre, seq, bob_pre, &rng).unwrap(); + test.assert_update(&bob_dcgka_5, &bob_5, bob, &[bob, charlie], seq); + (bob_dcgka_5, bob_5) + }; + + // ================================== + // 15. Charlie processes Bob's Update + // ================================== + // + // Bob's perspective: + // + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) + // [x] Bob's Ratchet (3) + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + // [ ] Charlie's Ratchet (2) + // + // Charlie's perspective: + // + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) + // [x] Bob's Ratchet (3) <-- + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + // [x] Charlie's Ratchet (2) <-- + + let (_charlie_dcgka_4, charlie_4_seq_2) = { + let seq = MessageId { + sender: bob, + seq: 3, + }; + let (charlie_dcgka_4, charlie_4) = Dcgka::process_remote( + charlie_dcgka_3, + ProcessInput { + seq, + sender: bob, + direct_message: Some(assert_direct_message(&bob_5_seq_3.direct_messages, charlie)), + control_message: bob_5_seq_3.control_message, + }, + &rng, + ) + .unwrap(); + test.assert_process_update(&charlie_dcgka_4, &charlie_4, charlie, bob, seq); + (charlie_dcgka_4, charlie_4) + }; + + // =============================== + // 16. Bob processes Charlie's Ack + // =============================== + // + // Bob's perspective: + // + // [x] Bob's Ratchet (0) + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) + // [x] Bob's Ratchet (3) + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + // [x] Charlie's Ratchet (2) <-- + // + // Charlie's perspective: + // + // [x] Bob's Ratchet (1) + // [x] Bob's Ratchet (2) + // [x] Bob's Ratchet (3) + // [x] Charlie's Ratchet (0) + // [x] Charlie's Ratchet (1) + // [x] Charlie's Ratchet (2) + + let (_bob_dcgka_6, _bob_6) = { + let seq = MessageId { + sender: charlie, + seq: 2, + }; + let (bob_dcgka_6, bob_6) = Dcgka::process_remote( + bob_dcgka_5, + ProcessInput { + seq, + sender: charlie, + direct_message: None, + control_message: charlie_4_seq_2.control_message.unwrap(), + }, + &rng, + ) + .unwrap(); + test.assert_process_ack(&bob_dcgka_6, &bob_6, bob, charlie, seq); + (bob_dcgka_6, bob_6) + }; +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/mod.rs new file mode 100644 index 0000000000..360ae9ed0b --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/message_scheme/tests/mod.rs @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +mod concurrency; +mod group_operations; diff --git a/pkgs/id/vendor/p2panda-encryption/src/ordering.rs b/pkgs/id/vendor/p2panda-encryption/src/ordering.rs new file mode 100644 index 0000000000..56992a834e --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/ordering.rs @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::hash::Hash as StdHash; +use std::marker::PhantomData; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +/// Queue which checks if dependencies are met for an item and returning it as "ready". +/// +/// Internally this assumes a structure where items can point at others as "dependencies", forming +/// an DAG (Directed Acyclic Graph). The "orderer" monitors incoming items, asserts if the +/// dependencies are met and yields a linearized sequence of "dependency checked" items. +/// +/// Note that this is only used for fuzzing and testing purposes. A more robust implementation +/// would need to take file-system persistence and atomic transactions into account. +#[derive(Debug)] +pub struct Orderer { + _marker: PhantomData, +} + +impl Orderer +where + T: PartialEq + Eq + StdHash, +{ + pub fn init() -> OrdererState { + OrdererState { + ready: HashSet::new(), + ready_queue: VecDeque::new(), + pending: HashMap::new(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct OrdererState +where + T: PartialEq + Eq + StdHash, +{ + ready: HashSet, + ready_queue: VecDeque, + pending: HashMap)>>, +} + +impl Orderer +where + T: Copy + Clone + PartialEq + Eq + StdHash, +{ + pub fn mark_ready( + mut y: OrdererState, + key: T, + ) -> Result<(OrdererState, bool), OrdererError> { + let result = y.ready.insert(key); + if result { + y.ready_queue.push_back(key); + } + Ok((y, result)) + } + + pub fn mark_pending( + mut y: OrdererState, + key: T, + dependencies: Vec, + ) -> Result<(OrdererState, bool), OrdererError> { + let insert_occured = false; + for dep_key in &dependencies { + if y.ready.contains(dep_key) { + continue; + } + + let dependents = y.pending.entry(*dep_key).or_default(); + dependents.insert((key, dependencies.clone())); + } + + Ok((y, insert_occured)) + } + + #[allow(clippy::type_complexity)] + pub fn get_next_pending( + y: &OrdererState, + key: T, + ) -> Result)>>, OrdererError> { + Ok(y.pending.get(&key).cloned()) + } + + pub fn take_next_ready( + mut y: OrdererState, + ) -> Result<(OrdererState, Option), OrdererError> { + let result = y.ready_queue.pop_front(); + Ok((y, result)) + } + + pub fn remove_pending( + mut y: OrdererState, + key: T, + ) -> Result<(OrdererState, bool), OrdererError> { + let result = y.pending.remove(&key).is_some(); + Ok((y, result)) + } + + pub fn ready(y: &OrdererState, dependencies: &[T]) -> Result { + let deps_set = HashSet::from_iter(dependencies.iter().cloned()); + let result = y.ready.is_superset(&deps_set); + Ok(result) + } + + pub fn process_pending(y: OrdererState, key: T) -> Result, OrdererError> { + // Get all items which depend on the passed key. + let Some(dependents) = Self::get_next_pending(&y, key)? else { + return Ok(y); + }; + + // For each dependent check if it has all it's dependencies met, if not then we do nothing + // as it is still in a pending state. + let mut y_loop = y; + for (next_key, next_deps) in dependents { + if !Self::ready(&y_loop, &next_deps)? { + continue; + } + + let (y_next, _) = Self::mark_ready(y_loop, next_key)?; + y_loop = y_next; + + // Recurse down the dependency graph by now checking any pending items which depend on + // the current item. + let y_next = Self::process_pending(y_loop, next_key)?; + y_loop = y_next; + } + + // Finally remove this item from the pending items queue. + let (y_i, _) = Self::remove_pending(y_loop, key)?; + + Ok(y_i) + } +} + +#[derive(Debug, Error)] +pub enum OrdererError { + // TODO: For now the orderer API is infallible, but we keep the error type around for later, as + // in it's current form the orderer would need to keep too much memory around for processing + // and we'll probably start to introduce a persistence backend (which can fail). +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/test_utils.rs b/pkgs/id/vendor/p2panda-encryption/src/test_utils.rs new file mode 100644 index 0000000000..725ed950f8 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/test_utils.rs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Internal helpers for writing (fuzz-) tests against `p2panda-encryption`. +use std::fmt::Display; + +use serde::{Deserialize, Serialize}; + +use crate::traits::OperationId; + +// Re-export private types for fuzz tests when `test_utils` feature flag is enabled. +pub mod crypto { + pub use crate::crypto::x25519::SecretKey; +} + +pub mod data_scheme { + pub use crate::data_scheme::test_utils::*; +} + +pub mod message_scheme { + pub use crate::message_scheme::test_utils::*; +} + +/// Simple member id for tests. +pub type MemberId = usize; + +/// Simple message id for tests with monotonically incrementing sequence numbers per peer. +/// +/// This contains the sender again as we need unique message ids and just using the sequence number +/// would not be sufficient. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct MessageId { + pub sender: MemberId, + pub seq: usize, +} + +impl MessageId { + pub fn new(my_id: MemberId) -> Self { + Self { + sender: my_id, + seq: 0, + } + } + + pub fn inc(&self) -> Self { + Self { + sender: self.sender, + seq: self.seq + 1, + } + } +} + +impl Display for MessageId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "[id={}, seq={}]", self.sender, self.seq) + } +} + +impl OperationId for MessageId {} diff --git a/pkgs/id/vendor/p2panda-encryption/src/traits/dgm.rs b/pkgs/id/vendor/p2panda-encryption/src/traits/dgm.rs new file mode 100644 index 0000000000..0b27bf4614 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/traits/dgm.rs @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +/// Decentralised group membership (DGM) algorithm with acknowledgements. +/// +/// Tracking acknowledgements is required for understanding concurrent group operations and +/// handling possible cases where members would otherwise miss out on crucial state to set up their +/// ratchets (see DCGKA implementation and paper for handling concurrency cases for more info). +/// +/// This is the DGM interface for p2panda's "message encryption" scheme. +#[cfg(any(test, feature = "message_scheme"))] +pub trait AckedGroupMembership { + type State: Clone + std::fmt::Debug + serde::Serialize + for<'a> serde::Deserialize<'a>; + + type Error: std::error::Error; + + /// Creates a new group. + fn create(my_id: ID, initial_members: &[ID]) -> Result; + + /// Processes the received DGM state from a welcome message. + /// + /// Implementations might want to take the state of the remote peer (sent via a welcome + /// message) and only keep their own id. We might receive multiple welcome messages as peers + /// might add us concurrently, in this case we might want to "merge" the states into one. + fn from_welcome(y: Self::State, y_welcome: Self::State) -> Result; + + /// Adds a member to the group. + fn add( + y: Self::State, + adder: ID, + added: ID, + operation_id: OP, + ) -> Result; + + /// Removes a member from a group. + fn remove( + y: Self::State, + remover: ID, + removed: &ID, + operation_id: OP, + ) -> Result; + + /// Member acknowledged a group operation. + fn ack(y: Self::State, acker: ID, operation_id: OP) -> Result; + + /// Returns the list of current members in the group from the perspective of a "viewer". + /// + /// Membership operations like adding or removing are only recognized by a member when they + /// have been explicitly acknowledged by them. This is why different members can have different + /// "views" on the same group. Note that we are still looking at all of that from our knowledge + /// horizon aka the messages we could observe on the network. + fn members_view( + y: &Self::State, + viewer: &ID, + ) -> Result, Self::Error>; + + /// Returns true if given group operation added a member. + fn is_add(y: &Self::State, operation_id: OP) -> bool; + + /// Returns true if given group operation removed a member. + fn is_remove(y: &Self::State, operation_id: OP) -> bool; +} + +/// Decentralised group membership (DGM) algorithm. +/// +/// This is the DGM interface for p2panda's "data encryption" scheme. +#[cfg(any(test, feature = "data_scheme"))] +pub trait GroupMembership { + type State: Clone + + std::fmt::Debug + + PartialEq + + Eq + + serde::Serialize + + for<'a> serde::Deserialize<'a>; + + type Error: std::error::Error; + + /// Creates a new group. + fn create(my_id: ID, initial_members: &[ID]) -> Result; + + /// Processes the received DGM state from a welcome message. + fn from_welcome(my_id: ID, y: Self::State) -> Result; + + /// Adds a member to the group. + fn add( + y: Self::State, + adder: ID, + added: ID, + operation_id: OP, + ) -> Result; + + /// Removes a member from a group. + fn remove( + y: Self::State, + remover: ID, + removed: &ID, + operation_id: OP, + ) -> Result; + + /// Returns the list of current members in the group. + fn members(y: &Self::State) -> Result, Self::Error>; +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/traits/key_bundle.rs b/pkgs/id/vendor/p2panda-encryption/src/traits/key_bundle.rs new file mode 100644 index 0000000000..2445618baf --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/traits/key_bundle.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::crypto::x25519::PublicKey; +use crate::key_bundle::{KeyBundleError, Lifetime, OneTimePreKeyId}; + +/// Key bundle holding data to establish a X3DH key-agreement. +pub trait KeyBundle { + fn identity_key(&self) -> &PublicKey; + + fn signed_prekey(&self) -> &PublicKey; + + fn onetime_prekey(&self) -> Option<&PublicKey>; + + fn onetime_prekey_id(&self) -> Option; + + fn lifetime(&self) -> &Lifetime; + + fn verify(&self) -> Result<(), KeyBundleError>; +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/traits/key_manager.rs b/pkgs/id/vendor/p2panda-encryption/src/traits/key_manager.rs new file mode 100644 index 0000000000..c95a8053bf --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/traits/key_manager.rs @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::error::Error; +use std::fmt::Debug; + +use serde::{Deserialize, Serialize}; + +use crate::crypto::Rng; +use crate::crypto::x25519::SecretKey; +use crate::key_bundle::{Lifetime, LongTermKeyBundle, OneTimeKeyBundle, OneTimePreKeyId, PreKeyId}; + +/// Manages our own identity secret. +pub trait IdentityManager { + fn identity_secret(y: &Y) -> &SecretKey; +} + +/// Manages our own pre-key secrets to generate public key bundles. +pub trait PreKeyManager { + type State: Debug + Serialize + for<'a> Deserialize<'a>; + + type Error: Error; + + fn prekey_secret<'a>( + y: &'a Self::State, + id: &'a PreKeyId, + ) -> Result<&'a SecretKey, Self::Error>; + + fn rotate_prekey( + y: Self::State, + lifetime: Lifetime, + rng: &Rng, + ) -> Result; + + fn prekey_bundle(y: &Self::State) -> Result; + + fn generate_onetime_bundle( + y: Self::State, + rng: &Rng, + ) -> Result<(Self::State, OneTimeKeyBundle), Self::Error>; + + fn use_onetime_secret( + y: Self::State, + id: OneTimePreKeyId, + ) -> Result<(Self::State, Option), Self::Error>; +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/traits/key_registry.rs b/pkgs/id/vendor/p2panda-encryption/src/traits/key_registry.rs new file mode 100644 index 0000000000..179ac07cbf --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/traits/key_registry.rs @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::error::Error; +use std::fmt::Debug; + +use serde::{Deserialize, Serialize}; + +use crate::crypto::x25519::PublicKey; + +/// Manages public identity keys of other members. +pub trait IdentityRegistry { + type Error: Error; + + fn identity_key(y: &Y, id: &ID) -> Result, Self::Error>; +} + +/// Manages public key bundles of other members. +pub trait PreKeyRegistry { + type State: Debug + Serialize + for<'a> Deserialize<'a>; + + type Error: Error; + + fn key_bundle(y: Self::State, id: &ID) -> Result<(Self::State, Option), Self::Error>; +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/traits/message.rs b/pkgs/id/vendor/p2panda-encryption/src/traits/message.rs new file mode 100644 index 0000000000..eda2b0daca --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/traits/message.rs @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +#[cfg(any(test, feature = "data_scheme"))] +use crate::crypto::xchacha20::XAeadNonce; +#[cfg(any(test, feature = "data_scheme"))] +use crate::data_scheme::{self, GroupSecretId}; +#[cfg(any(test, feature = "message_scheme"))] +use crate::message_scheme::{self, Generation}; +#[cfg(any(test, feature = "message_scheme"))] +use crate::traits::AckedGroupMembership; +#[cfg(any(test, feature = "data_scheme"))] +use crate::traits::GroupMembership; + +/// Interface to express required information from messages following the "data encryption" +/// protocol for groups. +/// +/// Applications implementing these traits should authenticate the original sender of each message. +/// +/// Messages, except of the direct ones, need to be broadcast to the whole group. +#[cfg(any(test, feature = "data_scheme"))] +pub trait GroupMessage +where + DGM: GroupMembership, +{ + /// Unique identifier of this message. + fn id(&self) -> OP; + + /// Unique identifier of the sender of this message. + fn sender(&self) -> ID; + + /// Returns content of either a control- or application message. + fn content(&self) -> GroupMessageContent; + + /// Returns optional list of direct messages. + fn direct_messages(&self) -> Vec>; +} + +#[cfg(any(test, feature = "data_scheme"))] +#[derive(Debug)] +pub enum GroupMessageContent { + /// Control message managing encryption group. + Control(data_scheme::ControlMessage), + + /// Encrypted application payload indicating which AEAD key and nonce was used. + Application { + /// Identifier of the used AEAD key (group secret). + group_secret_id: GroupSecretId, + + /// AEAD nonce. + nonce: XAeadNonce, + + /// Payload encrypted with AEAD. + ciphertext: Vec, + }, +} + +#[cfg(any(test, feature = "data_scheme"))] +impl std::fmt::Display for GroupMessageContent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + Self::Control(control_message) => control_message.to_string(), + Self::Application { + group_secret_id, .. + } => format!("application @{}", hex::encode(group_secret_id)), + } + ) + } +} + +/// Interface to express required information from messages following the "message encryption" +/// protocol for groups. +/// +/// Applications implementing these traits should authenticate the original sender of each message. +/// +/// Messages, except for the direct ones, need to be broadcast to the whole group. +#[cfg(any(test, feature = "message_scheme"))] +pub trait ForwardSecureGroupMessage +where + DGM: AckedGroupMembership, +{ + /// Unique identifier of this message. + fn id(&self) -> OP; + + /// Unique identifier of the sender of this message. + fn sender(&self) -> ID; + + /// Returns data required to manage group encryption and receive decrypted application messages. + fn content(&self) -> ForwardSecureMessageContent; + + /// Returns optional list of direct messages. + /// + /// Direct messages do not need to be encoded as part of one broadcast message. Applications + /// can also decide to keep control messages and direct messages detached and use + /// `ForwardSecureMessage` as a way to express which control message belonged to this set of + /// direct messages. + fn direct_messages(&self) -> Vec>; +} + +#[cfg(any(test, feature = "message_scheme"))] +#[derive(Debug)] +pub enum ForwardSecureMessageContent { + /// Control message managing messaging encryption group. + Control(message_scheme::ControlMessage), + + /// Encrypted application message payload indicating which ratchet generation was used. + Application { + ciphertext: Vec, + generation: Generation, + }, +} + +#[cfg(any(test, feature = "message_scheme"))] +impl std::fmt::Display for ForwardSecureMessageContent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + Self::Control(control_message) => control_message.to_string(), + Self::Application { generation, .. } => format!("application @{generation}"), + } + ) + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/traits/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/traits/mod.rs new file mode 100644 index 0000000000..196fae0787 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/traits/mod.rs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Interfaces to integrate `p2panda-encryption` into custom data- and messaging types, group +//! management- and ordering strategies. +use std::fmt::Debug; +use std::hash::Hash as StdHash; + +mod dgm; +mod key_bundle; +mod key_manager; +mod key_registry; +mod message; +mod ordering; + +#[cfg(any(test, feature = "message_scheme"))] +pub use dgm::AckedGroupMembership; +#[cfg(any(test, feature = "data_scheme"))] +pub use dgm::GroupMembership; +pub use key_bundle::KeyBundle; +pub use key_manager::{IdentityManager, PreKeyManager}; +pub use key_registry::{IdentityRegistry, PreKeyRegistry}; +#[cfg(any(test, feature = "message_scheme"))] +pub use message::{ForwardSecureGroupMessage, ForwardSecureMessageContent}; +#[cfg(any(test, feature = "data_scheme"))] +pub use message::{GroupMessage, GroupMessageContent}; +#[cfg(any(test, feature = "message_scheme"))] +pub use ordering::ForwardSecureOrdering; +#[cfg(any(test, feature = "data_scheme"))] +pub use ordering::Ordering; + +/// Handle to identify a group member. +/// +/// Note that this needs to be unique within a group, can be a username, number or preferably a +/// long byte string. +pub trait IdentityHandle: Copy + Debug + PartialEq + Eq + StdHash {} + +impl IdentityHandle for p2panda_core::VerifyingKey {} + +#[cfg(any(test, feature = "test_utils"))] +impl IdentityHandle for &str {} + +#[cfg(any(test, feature = "test_utils"))] +impl IdentityHandle for usize {} + +/// Identifier for each group membership operation. +/// +/// Operations trigger changes of the group state and are usually sent in form of messages over the +/// network. Each operation needs to be uniquely identifiable, preferably by a collision-resistant +/// hash. +pub trait OperationId: Copy + Debug + PartialEq + Eq + StdHash {} + +impl OperationId for p2panda_core::Hash {} + +#[cfg(any(test, feature = "test_utils"))] +impl OperationId for (usize, usize) {} // (ID, Seq) + +#[cfg(any(test, feature = "test_utils"))] +impl OperationId for usize {} diff --git a/pkgs/id/vendor/p2panda-encryption/src/traits/ordering.rs b/pkgs/id/vendor/p2panda-encryption/src/traits/ordering.rs new file mode 100644 index 0000000000..c57155121c --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/traits/ordering.rs @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Peers need to make sure that messages arrive "in order" to be processed correctly. +//! +//! We require three things: +//! +//! 1. Define a way to partially order our messages (for example through a vector clock), like this +//! we can sort events "after" or "before" each other, or identify messages which arrived "at +//! the same time". +//! 2. Define a way to declare "dependencies", that is, messages which are required to be processed +//! _before_ we can process this message. This is slightly different from a vector clock as we +//! do not only declare which message we've observed "before" to help with partial ordering, but +//! also point at additional requirements to fullfil the protocol. +//! 3. Define a set of rules, the "protocol", peers need to follow whenever they publish new +//! messages: What information do they need to mention for other peers to correctly order and +//! process messages from us? +//! +//! An "ordering" interface allows us to implement these requirements for our custom application +//! data types. +#[cfg(any(test, feature = "data_scheme"))] +use crate::crypto::xchacha20::XAeadNonce; +#[cfg(any(test, feature = "data_scheme"))] +use crate::data_scheme::{self, GroupSecretId}; +#[cfg(any(test, feature = "message_scheme"))] +use crate::message_scheme::{self, Generation}; +#[cfg(any(test, feature = "message_scheme"))] +use crate::traits::{AckedGroupMembership, ForwardSecureGroupMessage}; +#[cfg(any(test, feature = "data_scheme"))] +use crate::traits::{GroupMembership, GroupMessage}; + +/// Ordering protocol for p2panda's "data encryption" scheme. +/// +/// When publishing a message peers need to make sure to provide the following informations: +/// +/// 1. "create" control messages do not have any dependencies as they are the first messages in a +/// group. +/// 2. When an "add", "update" or "remove" control message gets published, that message needs to +/// point at all the last known, previously processed control messages (by us and others). +/// 3. Every application message needs to point at the control message which generated the used +/// secret. Usually applications always use the "latest" group secret. In this case it's enough +/// to point at the last known control messages (similar to point 2). +/// +/// When a peer processes a "welcome" message (they got added to a group) then all previously seen +/// control and application messages can be re-processed. +/// +/// Applications can choose to remove secrets from their group bundles for forward secrecy. In this +/// case additional logic is required to "jump" over these "outdated" application messages. +/// Ignoring these messages can take place when processing the "welcome" message. +#[cfg(any(test, feature = "data_scheme"))] +pub trait Ordering +where + DGM: GroupMembership, +{ + type State; + + type Error: std::error::Error; + + type Message: GroupMessage; + + fn next_control_message( + y: Self::State, + control_message: &data_scheme::ControlMessage, + direct_messages: &[data_scheme::DirectMessage], + ) -> Result<(Self::State, Self::Message), Self::Error>; + + fn next_application_message( + y: Self::State, + group_secret_id: GroupSecretId, + nonce: XAeadNonce, + ciphertext: Vec, + ) -> Result<(Self::State, Self::Message), Self::Error>; + + fn queue(y: Self::State, message: &Self::Message) -> Result; + + fn set_welcome(y: Self::State, message: &Self::Message) -> Result; + + #[allow(clippy::type_complexity)] + fn next_ready_message( + y: Self::State, + ) -> Result<(Self::State, Option), Self::Error>; +} + +/// Ordering protocol for p2panda's "message encryption" scheme. Extra care is required here, since +/// the strong forward secrecy guarantees makes ordering more strict. +/// +/// When publishing a message peers need to make sure to provide the following information: +/// +/// 1. "create" control messages do not have any dependencies as they are the first messages in a +/// group. +/// 2. When an "add", "update" or "remove" control message gets published, that message needs to +/// point at a) the last known, previously processed control messages (by us and others), b) if +/// any application messages were sent by us, the last sent message. The latter helps with peers +/// understanding that they might miss a message when they switch to a new ratchet, they can +/// decide to ignore this message "dependency", but will also then potentially lose it. This +/// can be useful to do if messages get lost and peers otherwise get "stuck". +/// 3. "ack" control messages need to point at the regarding "create", "add", "update" or "remove" +/// control message they are acknowledging. +/// 4. The first application message written during a new "ratchet epoch" needs to point at the +/// "ack" or "create", "add", "update" or "remove" message which initiated that epoch. +/// 5. Every subsequent application message needs to point at the previous application message. +/// +/// In this example a user "Alice" creates a group with Bob. Both of them send messages into the +/// group ("Message 1", "Messsage 2" etc.) based on the established ratchet secrets. At some point +/// Alice decides to renew the group's seed with an "update", and at the same time (concurrently) +/// Bob "adds" Charlie. After processing all messages in the correct order and meeting all +/// dependencies Alice and Bob will be able to read all sent messages by each other. +/// +/// ```text +/// Alice +/// ──────── +/// ┌──────┐ +/// │CREATE│ +/// └──────┘ Bob +/// ▲ ▲ ▲ ───── +/// │ │ │ ┌───┐ +/// │ │ └───────────────────┤ACK│ +/// │ │ ┌►└───┘ +/// │ │ │ ▲ ▲ +/// │ │ │ │ +/// Message 1 │ ┌─────────────────┘ │ +/// ▲ │ │ │ Message 1 +/// │ │ │ │ ▲ +/// │ │ │ │ +/// Message 2 │ │ │ +/// ▲ │ │ │ Message 2 +/// │ │ │ │ ▲ +/// │ │ │ │ │ +/// ┌┴─┴─┴─┐ ┌┴─┴┐ +/// │UPDATE│ Concurrent! │ADD│ +/// └──────┘ ┌►└───┘ +/// ▲ ▲ ▲ │ ▲ ▲ Charlie +/// │ │ │ │ │ │ ───────── +/// │ ├─┼─────────────────┘ │ ├──────────────────────┐ +/// │ │ │ │ │ +/// Message 3 │ └────────────────────┤ │ │ +/// ▲ │ │ │ +/// │ │ │ Message 3 │ +/// │ │ ▲ │ +/// Message 4 │ │ │ │ +/// │ │ │ │ +/// ┌─┴─┐ ┌┴─┴┐ ┌─┴─┐ +/// │ACK│ │ACK│ │ACK│ +/// └───┘ └───┘ └───┘ +/// ``` +/// +/// When a peer processes a "welcome" message (they got added to a group, like "Charlie" in our +/// example), then the following steps take place: +/// +/// 1. Control and application messages before the "welcome" message (the "add" which added us) can +/// be ignored. +/// 2. Control messages after or concurrent to the "welcome" message need to be processed +/// regularly like all other messages. +/// 3. Application messages concurrent to the "welcome" message can be ignored (as they can not be +/// decrypted). +/// +/// All of this "welcome" processing needs to be done before we can move on processing future +/// messages. +/// +/// In the previously given example "Charlie" would be added to the group by Bob's "add" control +/// message. Charlie would process their "welcome", acknowledge it and look at all other messages +/// now. They identified that Alice's "update" happened concurrently to the "add", so they also +/// process this message. They ignore the "create" as it took place before the "add". They ignore +/// "Message 1", "Message 2", "Message 3" and "Message 4" of Alice and "Message 1" and "Message 2" +/// of Bob, as they would not be able to decrypt them. Afterwards they would be able to decrypt +/// "Message 3" of Bob as this message was created with Charlie in mind. +/// +/// Note that Charlie will _not_ be able to decrypt older messages of Alice and Bob as they have +/// been encrypted by Alice prior to their knowledge that Charlie was already in the group then. As +/// soon as Alice will learn that Charlie was added they will "forward" their ratchet state to +/// Charlie, but this will only be used for future messages. +#[cfg(any(test, feature = "message_scheme"))] +pub trait ForwardSecureOrdering +where + DGM: AckedGroupMembership, +{ + type State: Clone + std::fmt::Debug + serde::Serialize + for<'a> serde::Deserialize<'a>; + + type Error: std::error::Error; + + type Message: Clone + + ForwardSecureGroupMessage + + serde::Serialize + + for<'a> serde::Deserialize<'a>; + + fn next_control_message( + y: Self::State, + control_message: &message_scheme::ControlMessage, + direct_messages: &[message_scheme::DirectMessage], + ) -> Result<(Self::State, Self::Message), Self::Error>; + + fn next_application_message( + y: Self::State, + generation: Generation, + ciphertext: Vec, + ) -> Result<(Self::State, Self::Message), Self::Error>; + + fn queue(y: Self::State, message: &Self::Message) -> Result; + + fn set_welcome(y: Self::State, message: &Self::Message) -> Result; + + #[allow(clippy::type_complexity)] + fn next_ready_message( + y: Self::State, + ) -> Result<(Self::State, Option), Self::Error>; +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/two_party/mod.rs b/pkgs/id/vendor/p2panda-encryption/src/two_party/mod.rs new file mode 100644 index 0000000000..7339cbb8b2 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/two_party/mod.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Protocols for secure key-agreement between two members ("two party"). +//! +//! Group encryption is concerned around delivering a secure message from a single sender to a +//! whole group with potentially many receivers. To achieve this "broadcast" topology of such +//! system we need to establish secret key material with each member of the group before. This +//! takes places in form of a pair-wise, secure key-agreement protocol between two members of the +//! group. +//! +//! The "two party secure messaging" key-agreement protocol (2SM) is specified in the paper "Key +//! Agreement for Decentralized Secure Group Messaging with Strong Security Guarantees" (2020). +//! +//! At its core, the 2SM protocol uses Public-Key Encryption (PKE) to encrypt messages, with +//! frequent key rotation to provide PCS and FS. Initially, each party encrypts messages using the +//! key-bundle input for X3DH. Afterwards, to achieve PCS, each time a party sends a message, it +//! also updates its public key. Finally, to avoid reusing public keys (which would make FS +//! impossible), whenever a party sends a message, it also updates the other party's public key. To +//! do so, it sends a new secret key along with its message, then deletes its own copy, storing +//! only the public key. +//! +//! +#[allow(clippy::module_inception)] +mod two_party; +mod x3dh; + +pub use two_party::{ + LongTermTwoParty, OneTimeTwoParty, TwoParty, TwoPartyCiphertext, TwoPartyError, + TwoPartyMessage, TwoPartyState, +}; +pub use x3dh::{X3dhCiphertext, X3dhError, x3dh_decrypt, x3dh_encrypt}; diff --git a/pkgs/id/vendor/p2panda-encryption/src/two_party/two_party.rs b/pkgs/id/vendor/p2panda-encryption/src/two_party/two_party.rs new file mode 100644 index 0000000000..0ea826a1dc --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/two_party/two_party.rs @@ -0,0 +1,767 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Two-Party Secure Messaging (2SM) Key Agreement Protocol. +use std::collections::HashMap; +use std::marker::PhantomData; + +use p2panda_core::cbor::{DecodeError, EncodeError, decode_cbor, encode_cbor}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::hpke::{HpkeCiphertext, HpkeError, hpke_open, hpke_seal}; +use crate::crypto::x25519::{PublicKey, SecretKey, X25519Error}; +use crate::crypto::{Rng, RngError}; +use crate::key_bundle::{LongTermKeyBundle, OneTimeKeyBundle, PreKeyId}; +use crate::key_manager::KeyManager; +use crate::traits::{IdentityManager, KeyBundle, PreKeyManager}; +use crate::two_party::{X3dhCiphertext, X3dhError, x3dh_decrypt, x3dh_encrypt}; + +/// Two-Party Secure Messaging (2SM) Key Agreement Protocol as specified in the paper "Key +/// Agreement for Decentralized Secure Group Messaging with Strong Security Guarantees" (2020). +/// +/// 2SM is used for key-agreement as part of the DCGKA protocol allowing all members to learn about +/// the "seed" for establishing new secret state. 2SM is pair-wise between all members of an +/// encrypted group. p2panda uses 2SM for both "data-" and "message encryption" schemes. +/// +/// ## Protocol +/// +/// An initiator "Alice" of a 2SM session uses the pre-keys of "Bob" to send the first encrypted +/// message using the X3DH protocol. This only takes place once and the pre-keys can be considered +/// "used" afterwards (which is especially important for one-time pre-keys). +/// +/// All subsequent messages sent between Alice and Bob are encrypted using the HPKE protocol. For +/// each round the sender uses the previous keys for HPKE and generates and attaches to the payload +/// a new key-pair for future rounds. +/// +/// To avoid reusing public keys (which would make FS impossible), whenever a party sends a +/// message, it also updates the other party's public key. To do so, it sends a new secret key +/// along with its message, then deletes its own copy, storing only the public key. +/// +/// To accommodate for messages arriving "late", the secret key is kept until it or a newer secret +/// has been used. In the case of a newer secret being used, all "previous" secret keys will be +/// dropped. +/// +/// ## Forward secrecy +/// +/// During the initial 2SM "round" using X3DH the forward secrecy is defined by the lifetime of the +/// used pre-keys. For strong security guarantees it is recommended to use one-time pre-keys. If +/// this requirement can be relaxed it is possible to use long-term pre-keys, with a lifetime +/// defined by the application. +/// +/// Each subsequent 2SM HPKE round uses exactly one secret key, which is then dropped and replaced +/// by a newly-generated key-pair. This gives the key-agreement protocol strong forward secrecy +/// guarantees for each round, independent of the used pre-keys. +/// +/// ## Cost of key-agreements +/// +/// To make a group aware of a new secret key we could encrypt the secret pairwise with public-key +/// encryption (PKE) towards each member of the group, resulting in an O(n^2) overhead as every +/// member needs to share their secret with every other. The paper proposes an alternative approach +/// with 2SM where a member prepares the next encryption keys not only for themselves but also for +/// the other party, resulting in a more optimal O(n) cost when rotating keys. This allows us to +/// "heal" the group in less steps after a member is removed. +/// +/// ## Message Ordering +/// +/// 2SM assumes that all messages are received in the order they have been sent. The application or +/// underlying networking protocol needs to handle ordering. This is handled for us by the DCGKA +/// protocol (as specified in the paper) and causally-ordered, authenticated broadcast in p2panda +/// itself. +/// +/// +pub struct TwoParty { + _marker: PhantomData<(KMG, KB)>, +} + +/// 2SM protocol with one-time pre-keys. +pub type OneTimeTwoParty = TwoParty; + +/// 2SM protocol with long-term pre-keys (with a specified lifetime). +pub type LongTermTwoParty = TwoParty; + +/// State of 2SM session between two members. +/// +/// All 2SM methods are expressed as "pure functions" without any side-effects, returning an +/// updated state object. This allows applications to be more crash-resiliant, persisting the final +/// state only when all processes have successfully completed. +/// +/// The state is serializable and can be used to persist 2SM sessions. +#[derive(Debug, Serialize, Deserialize)] +#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))] +pub struct TwoPartyState { + /// Index of key we will use during next send. The receiver can use the public key and refer to + /// it through that index when they want to encrypt a message back to us. + our_next_key_index: u64, + + /// Index of the last key which was used by the other peer to encrypt a message towards us. We + /// keep it around to understand which secret keys we can remove. + our_min_key_index: u64, + + /// List of all secret keys we generated ourselves. We sent the public counterpart to the other + /// peer. + our_secret_keys: HashMap, + + /// Last secret key the other peer generated for us. This is part of the 2SM protocol and an + /// optimization where the remote end can _also_ generate secrets for us. + our_received_secret_key: Option, + + /// Which key we use to decrypt the next incoming message. + their_next_key_used: KeyUsed, + + /// Key-material we need to encrypt the first message with the help of X3DH and prekeys. + their_prekey_bundle: Option, + + /// Last known public key of the other peer. We use it to encrypt a message towards them. + their_verifying_key: Option, +} + +// Public methods. + +impl TwoParty +where + KMG: IdentityManager + PreKeyManager, + KB: KeyBundle, +{ + /// Initialise new 2SM state to send a message to this receiver for the first time using the + /// other party's pre-key bundle. + pub fn init_to_send(their_prekey_bundle: KB) -> TwoPartyState { + TwoPartyState { + our_next_key_index: 1, + our_min_key_index: 1, + our_secret_keys: HashMap::new(), + our_received_secret_key: None, + their_verifying_key: None, + their_next_key_used: KeyUsed::PreKey, + their_prekey_bundle: Some(their_prekey_bundle), + } + } + + /// Initialise new 2SM state to receive a message from any sender for the first time. + pub fn init_to_receive() -> TwoPartyState { + TwoPartyState { + our_next_key_index: 1, + our_min_key_index: 1, + our_secret_keys: HashMap::new(), + our_received_secret_key: None, + their_verifying_key: None, + their_next_key_used: KeyUsed::PreKey, + their_prekey_bundle: None, + } + } + + /// Securely send a `plaintext` message to the other party. + pub fn send( + y: TwoPartyState, + y_manager: &KMG::State, + plaintext: &[u8], + rng: &Rng, + ) -> TwoPartyResult<(TwoPartyState, TwoPartyMessage)> { + let (for_us, for_them) = Self::generate_keys(rng)?; + + let plaintext_message = TwoPartyPlaintext { + plaintext: plaintext.to_vec(), + receiver_new_secret: for_them.their_new_secret.clone(), + sender_new_verifying_key: for_them.our_new_verifying_key, + sender_next_index: y.our_next_key_index, + }; + let plaintext_bytes = plaintext_message.to_bytes()?; + + let (mut y_i, ciphertext) = Self::encrypt(y, y_manager, &plaintext_bytes, rng)?; + + let message = TwoPartyMessage { + ciphertext, + key_used: y_i.their_next_key_used, + }; + + y_i.our_secret_keys + .insert(y_i.our_next_key_index, for_us.our_new_secret); + y_i.our_next_key_index += 1; + + y_i.their_verifying_key = Some(for_us.their_new_verifying_key); + + y_i.their_next_key_used = KeyUsed::ReceivedKey; + + Ok((y_i, message)) + } + + /// Handle receiving a secure message from the other party. + pub fn receive( + y: TwoPartyState, + y_manager: KMG::State, + message: TwoPartyMessage, + ) -> TwoPartyResult<(TwoPartyState, KMG::State, Vec)> { + let (mut y_i, y_manager_i, plaintext_bytes) = + Self::decrypt(y, y_manager, message.ciphertext, message.key_used)?; + let plaintext_message = TwoPartyPlaintext::from_bytes(&plaintext_bytes)?; + + y_i.their_verifying_key = Some(plaintext_message.sender_new_verifying_key); + y_i.their_next_key_used = KeyUsed::OwnKey(plaintext_message.sender_next_index); + y_i.our_received_secret_key = Some(plaintext_message.receiver_new_secret); + + Ok((y_i, y_manager_i, plaintext_message.plaintext)) + } +} + +/// 2SM states indicating which key material was used. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[allow(clippy::enum_variant_names)] +pub enum KeyUsed { + /// Previously published keys ("prekeys") for X3DH. + PreKey, + + /// Key the receiving peer received last time from the sending peer for HPKE. + ReceivedKey, + + /// Key the receiving peer generated themselves at some time. We can refer to the exact key by + /// it's index. + OwnKey(u64), +} + +/// 2SM message to be sent over the network. +/// +/// Note that this does not contain any additional information about the sender and receiver. This +/// information needs to be added in applications. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TwoPartyMessage { + ciphertext: TwoPartyCiphertext, + key_used: KeyUsed, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum TwoPartyCiphertext { + /// Message was encrypted using X3DH pre-keys (initial round). + PreKey(X3dhCiphertext), + + /// Message was encrypted using HPKE. + Hpke(HpkeCiphertext), +} + +/// Payload from sender which will be encrypted containing the actual message `plaintext` and +/// meta-data we need for the 2SM protocol. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TwoPartyPlaintext { + /// Secret message for the receiver. + plaintext: Vec, + + /// Newly generated secret for the receiver, to be used in future 2SM rounds. + receiver_new_secret: SecretKey, + + /// Newly generated public key of the sender, to be used in future 2SM rounds. + sender_new_verifying_key: PublicKey, + + /// Index of the newly generated key of the sender, the receiver refers to it when using it in + /// future 2SM rounds. + sender_next_index: u64, +} + +impl TwoPartyPlaintext { + pub fn from_bytes(bytes: &[u8]) -> Result { + decode_cbor(bytes) + } + + pub fn to_bytes(&self) -> Result, EncodeError> { + encode_cbor(&self) + } +} + +// Private methods. + +impl TwoParty +where + KMG: IdentityManager + PreKeyManager, + KB: KeyBundle, +{ + /// Encrypt a message toward the other party using X3DH when it is the first round or HPKE for + /// subsequent rounds. + fn encrypt( + mut y: TwoPartyState, + y_manager: &KMG::State, + plaintext: &[u8], + rng: &Rng, + ) -> TwoPartyResult<(TwoPartyState, TwoPartyCiphertext)> { + let ciphertext = match &y.their_verifying_key { + None => { + // Establish secret via X3DH from prekey when no secret is given yet. + let their_prekey_bundle = y + .their_prekey_bundle + .take() + .ok_or(TwoPartyError::PreKeyReuse)?; + let ciphertext = x3dh_encrypt( + plaintext, + KMG::identity_secret(y_manager), + &their_prekey_bundle, + rng, + )?; + TwoPartyCiphertext::PreKey(ciphertext) + } + Some(their_verifying_key) => { + let ciphertext = hpke_seal(their_verifying_key, None, None, plaintext)?; + TwoPartyCiphertext::Hpke(ciphertext) + } + }; + + Ok((y, ciphertext)) + } + + /// Decrypt a message from the other party using X3DH when it is the first round or HPKE for + /// subsequent rounds. + fn decrypt( + mut y: TwoPartyState, + y_manager: KMG::State, + ciphertext: TwoPartyCiphertext, + key_used: KeyUsed, + ) -> TwoPartyResult<(TwoPartyState, KMG::State, Vec)> { + let (y_manager_i, plaintext) = match key_used { + KeyUsed::PreKey => { + let TwoPartyCiphertext::PreKey(ciphertext) = ciphertext else { + return Err(TwoPartyError::InvalidCiphertextType); + }; + + // If the underlying key manager provides a one-time secret, we use it here. + let (y_manager_i, onetime_secret) = match ciphertext.onetime_prekey_id { + Some(onetime_prekey_id) => { + let (y_manager_i, onetime_secret) = + KMG::use_onetime_secret(y_manager, onetime_prekey_id) + .map_err(|_| TwoPartyError::PreKeyReuse)?; + (y_manager_i, onetime_secret) + } + None => (y_manager, None), + }; + + let plaintext = x3dh_decrypt( + &ciphertext, + KMG::identity_secret(&y_manager_i), + KMG::prekey_secret(&y_manager_i, &ciphertext.prekey_id) + // Fails when sender used an invalid / expired pre-key for initial X3DH. + .map_err(|_| TwoPartyError::UnknownPreKeyUsed(ciphertext.prekey_id))?, + onetime_secret.as_ref(), + )?; + + (y_manager_i, plaintext) + } + KeyUsed::ReceivedKey => { + let TwoPartyCiphertext::Hpke(ciphertext) = ciphertext else { + return Err(TwoPartyError::InvalidCiphertextType); + }; + + let Some(our_received_secret_key) = &y.our_received_secret_key else { + return Err(TwoPartyError::UnknownSecretUsed(0)); + }; + + let plaintext = hpke_open(&ciphertext, our_received_secret_key, None, None)?; + (y_manager, plaintext) + } + KeyUsed::OwnKey(index) => { + let TwoPartyCiphertext::Hpke(ciphertext) = ciphertext else { + return Err(TwoPartyError::InvalidCiphertextType); + }; + + let plaintext = match y.our_secret_keys.get(&index) { + Some(secret) => hpke_open(&ciphertext, secret, None, None)?, + None => return Err(TwoPartyError::UnknownSecretUsed(index)), + }; + + for i in y.our_min_key_index..index + 1 { + y.our_secret_keys.remove(&i); + } + y.our_min_key_index = index + 1; + + (y_manager, plaintext) + } + }; + + Ok((y, y_manager_i, plaintext)) + } +} + +impl TwoParty { + /// Generate fresh key material for us and the other party for future 2SM rounds. + /// + /// This material is sent as part of the encrypted ciphertext, attached next to the actual + /// secret message. Each party prepares the received keys to be available for future rounds. + fn generate_keys(rng: &Rng) -> TwoPartyResult<(NewKeysForUs, NewKeysForThem)> { + let our_new_secret = SecretKey::from_bytes(rng.random_array()?); + let our_new_verifying_key = our_new_secret.verifying_key()?; + + let their_new_secret = SecretKey::from_bytes(rng.random_array()?); + let their_new_verifying_key = their_new_secret.verifying_key()?; + + Ok(( + NewKeysForUs { + our_new_secret, + their_new_verifying_key, + }, + NewKeysForThem { + our_new_verifying_key, + their_new_secret, + }, + )) + } +} + +struct NewKeysForUs { + our_new_secret: SecretKey, + their_new_verifying_key: PublicKey, +} + +struct NewKeysForThem { + our_new_verifying_key: PublicKey, + their_new_secret: SecretKey, +} + +pub type TwoPartyResult = Result; + +#[derive(Debug, Error)] +pub enum TwoPartyError { + #[error(transparent)] + Hpke(#[from] HpkeError), + + #[error(transparent)] + X3dh(#[from] X3dhError), + + #[error(transparent)] + Rng(#[from] RngError), + + #[error(transparent)] + Encode(#[from] EncodeError), + + #[error(transparent)] + Decode(#[from] DecodeError), + + #[error(transparent)] + X25519(#[from] X25519Error), + + #[error("prekeys have already been used")] + PreKeyReuse, + + #[error("tried to decrypt with unknown 2SM secret at index {0}")] + UnknownSecretUsed(u64), + + #[error("tried to decrypt with unknown initial X3DH pre-key {0}")] + UnknownPreKeyUsed(PreKeyId), + + #[error("invalid ciphertext for message type")] + InvalidCiphertextType, +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + use crate::crypto::x25519::SecretKey; + use crate::key_bundle::Lifetime; + use crate::key_manager::KeyManager; + use crate::traits::PreKeyManager; + + use super::{KeyUsed, LongTermTwoParty, OneTimeTwoParty, TwoPartyError}; + + #[test] + fn two_party_secret_messaging_protocol() { + let rng = Rng::from_seed([1; 32]); + + // Alice generates their key material. + + let alice_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let alice_manager = + KeyManager::init_and_generate_prekey(&alice_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + // Bob generates their key material. + + let bob_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let bob_manager = + KeyManager::init_and_generate_prekey(&bob_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let (bob_manager, bob_prekey_bundle) = + KeyManager::generate_onetime_bundle(bob_manager, &rng).unwrap(); + + // Alice and Bob set up the 2SM protocol handlers for each other. + + let alice_2sm = OneTimeTwoParty::init_to_send(bob_prekey_bundle); + + // Alice doesn't have any secret HPKE keys yet and will use Bob's pre-keys for X3DH. + assert_eq!(alice_2sm.our_secret_keys.len(), 0); + assert_eq!(alice_2sm.our_min_key_index, 1); + assert_eq!(alice_2sm.our_next_key_index, 1); + assert_eq!(alice_2sm.their_next_key_used, KeyUsed::PreKey); + + let bob_2sm = OneTimeTwoParty::init_to_receive(); + + // Bob doesn't have any secret HPKE keys yet and will wait for Alice reaching out. + assert_eq!(bob_2sm.our_secret_keys.len(), 0); + assert_eq!(bob_2sm.our_min_key_index, 1); + assert_eq!(bob_2sm.our_next_key_index, 1); + assert_eq!(bob_2sm.their_next_key_used, KeyUsed::PreKey); + + // They start exchanging "secret messages" to each other. + + // 1. Alice sends a message to Bob using their pre-keys for X3DH. + let (alice_2sm, message_1) = + OneTimeTwoParty::send(alice_2sm, &alice_manager, b"Hello, Bob!", &rng).unwrap(); + + // Alice generated their own secret key and sends the public part to Bob for future rounds. + assert_eq!(alice_2sm.our_secret_keys.len(), 1); + assert_eq!(alice_2sm.our_min_key_index, 1); + assert_eq!(alice_2sm.our_next_key_index, 2); + + // Alice also generated the secret key for Bob, so Alice also knows their public key + // for the future already. + assert!(alice_2sm.their_verifying_key.is_some()); + + // Alice didn't receive anything from Bob yet. + assert!(alice_2sm.our_received_secret_key.is_none()); + + // In the future Alice would use the key they just generated to decrypt messages from Bob. + assert_eq!(alice_2sm.their_next_key_used, KeyUsed::ReceivedKey); + + // Alice dropped the now-used pre-keys of Bob. + assert!(alice_2sm.their_prekey_bundle.is_none()); + + // 2. Bob receives Alice's message. + let (bob_2sm, bob_manager, receive_1) = + OneTimeTwoParty::receive(bob_2sm, bob_manager, message_1).unwrap(); + + // Bob still doesn't have any generated keys yet. + assert_eq!(bob_2sm.our_secret_keys.len(), 0); + assert_eq!(bob_2sm.our_min_key_index, 1); + assert_eq!(bob_2sm.our_next_key_index, 1); + + // Bob learned about the new public key (1) of Alice. + assert_eq!( + bob_2sm + .their_verifying_key + .expect("bob learned about public key of alice"), + alice_2sm + .our_secret_keys + .get(&1) + .expect("alice has one secret key") + .verifying_key() + .unwrap() + ); + + // Bob got their new secret key from Alice. + assert!(bob_2sm.our_received_secret_key.is_some()); + + // Bob would use Alice's new secret key for decrypting future messages. + assert_eq!(bob_2sm.their_next_key_used, KeyUsed::OwnKey(1)); + + // Bob still doesn't have Alice's pre-key bundle. + assert!(bob_2sm.their_prekey_bundle.is_none()); + + // 3. Alice sends another message to Bob and they receive it. + let (alice_2sm, message_2) = + OneTimeTwoParty::send(alice_2sm, &alice_manager, b"How are you doing?", &rng).unwrap(); + let (bob_2sm, bob_manager, receive_2) = + OneTimeTwoParty::receive(bob_2sm, bob_manager, message_2).unwrap(); + + // Alice generated another secret and keeps now two of them around as Bob didn't reply yet. + assert_eq!(alice_2sm.our_secret_keys.len(), 2); + assert_eq!(alice_2sm.our_min_key_index, 1); + assert_eq!(alice_2sm.our_next_key_index, 3); + + // The secret keys are unique for each round. + assert_ne!( + alice_2sm.our_secret_keys.get(&1).unwrap(), + alice_2sm.our_secret_keys.get(&2).unwrap(), + ); + + // Bob learned about the new public key (2) of Alice. + assert_eq!( + bob_2sm + .their_verifying_key + .expect("bob learned about public key of alice"), + alice_2sm + .our_secret_keys + .get(&2) + .expect("alice has one secret key") + .verifying_key() + .unwrap() + ); + + // 4. Bob answers to Alice. + let (bob_2sm, message_3) = + OneTimeTwoParty::send(bob_2sm, &bob_manager, b"I'm alright. Thank you!", &rng).unwrap(); + + // Bob used Alice's latest public key (2) to encrypt this message. + assert_eq!(message_3.key_used, KeyUsed::OwnKey(2)); + + // Bob generated their own secret key and sends the public part to Alice for future rounds. + assert_eq!(bob_2sm.our_secret_keys.len(), 1); + assert_eq!(bob_2sm.our_min_key_index, 1); + assert_eq!(bob_2sm.our_next_key_index, 2); + + // Bob assumes now that Alice will use Bob's secret key for future messages. + assert_eq!(bob_2sm.their_next_key_used, KeyUsed::ReceivedKey); + + // 5. Alice receives the message from Bob. + let (alice_2sm, alice_manager, receive_3) = + OneTimeTwoParty::receive(alice_2sm, alice_manager, message_3).unwrap(); + + // Alice removed the used secret key of this message (2) and all previous secrets as well + // (1) for forward secrecy. + assert_eq!(alice_2sm.our_secret_keys.len(), 0); + assert_eq!(alice_2sm.our_min_key_index, 3); + assert_eq!(alice_2sm.our_next_key_index, 3); + + // 6. Both parties continue chatting with each other .. + let (bob_2sm, message_4) = + OneTimeTwoParty::send(bob_2sm, &bob_manager, b"How are you?", &rng).unwrap(); + let (alice_2sm, alice_manager, receive_4) = + OneTimeTwoParty::receive(alice_2sm, alice_manager, message_4).unwrap(); + + let (alice_2sm, message_5) = + OneTimeTwoParty::send(alice_2sm, &alice_manager, b"I'm bored.", &rng).unwrap(); + let (bob_2sm, bob_manager, receive_5) = + OneTimeTwoParty::receive(bob_2sm, bob_manager, message_5).unwrap(); + + // Messages can be correctly decrypted. + assert_eq!(receive_1, b"Hello, Bob!"); + assert_eq!(receive_2, b"How are you doing?"); + assert_eq!(receive_3, b"I'm alright. Thank you!"); + assert_eq!(receive_4, b"How are you?"); + assert_eq!(receive_5, b"I'm bored."); + + // 7. They write a message to each other at the same time. + let (bob_2sm, message_6) = + OneTimeTwoParty::send(bob_2sm, &bob_manager, b":-(", &rng).unwrap(); + let (alice_2sm, message_7) = + OneTimeTwoParty::send(alice_2sm, &alice_manager, b"Oh wait.", &rng).unwrap(); + + let (alice_2sm, _, receive_6) = + OneTimeTwoParty::receive(alice_2sm, alice_manager, message_6).unwrap(); + let (bob_2sm, _, receive_7) = + OneTimeTwoParty::receive(bob_2sm, bob_manager, message_7).unwrap(); + + assert_eq!(receive_6, b":-("); + assert_eq!(receive_7, b"Oh wait."); + + // Both Alice and Bob still only have one secret key and all other keys have been removed. + assert_eq!(alice_2sm.our_secret_keys.len(), 1); + assert_eq!(bob_2sm.our_secret_keys.len(), 1); + } + + #[test] + fn long_term_prekeys() { + let rng = Rng::from_seed([1; 32]); + + // Alice generates their long-term key material. + + let alice_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let alice_manager = + KeyManager::init_and_generate_prekey(&alice_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + // Bob generates their long-term key material. + + let bob_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let bob_manager = + KeyManager::init_and_generate_prekey(&bob_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let bob_prekey_bundle = KeyManager::prekey_bundle(&bob_manager).unwrap(); + + // Alice and Bob set up the 2SM protocol handlers for each other. + + let alice_2sm_a = LongTermTwoParty::init_to_send(bob_prekey_bundle.clone()); + let bob_2sm_a = LongTermTwoParty::init_to_receive(); + + // They start exchanging "secret messages" to each other in Group A. + + let (alice_2sm_a, message_1) = + LongTermTwoParty::send(alice_2sm_a, &alice_manager, b"Hello, Bob!", &rng).unwrap(); + + // Public key of "Bob" for the first round in Group A. + let bob_verifying_key_1 = alice_2sm_a.their_verifying_key; + + let (bob_2sm_a, bob_manager, receive_1) = + LongTermTwoParty::receive(bob_2sm_a, bob_manager, message_1).unwrap(); + + let (_bob_2sm_a, message_2) = + LongTermTwoParty::send(bob_2sm_a, &bob_manager, b"Hello, Alice!", &rng).unwrap(); + let (_alice_2sm_a, alice_manager, receive_2) = + LongTermTwoParty::receive(alice_2sm_a, alice_manager, message_2).unwrap(); + + assert_eq!(receive_1, b"Hello, Bob!"); + assert_eq!(receive_2, b"Hello, Alice!"); + + // Sometime later they start another group B with the same long-term pre-keys. + + let alice_2sm_b = LongTermTwoParty::init_to_send(bob_prekey_bundle); + let bob_2sm_b = LongTermTwoParty::init_to_receive(); + + // They start exchanging "secret messages" to each other. + + let (alice_2sm_b, message_1) = + LongTermTwoParty::send(alice_2sm_b, &alice_manager, b"Hello, again, Bob!", &rng) + .unwrap(); + + // Public key of "Bob" for the first round in Group B. + let bob_verifying_key_2 = alice_2sm_b.their_verifying_key; + + let (bob_2sm_b, bob_manager, receive_1) = + LongTermTwoParty::receive(bob_2sm_b, bob_manager, message_1).unwrap(); + + let (_bob_2sm_b, message_2) = + LongTermTwoParty::send(bob_2sm_b, &bob_manager, b"Hello, again, Alice!", &rng).unwrap(); + let (_alice_2sm_b, _alice_manager, receive_2) = + LongTermTwoParty::receive(alice_2sm_b, alice_manager, message_2).unwrap(); + + assert_eq!(receive_1, b"Hello, again, Bob!"); + assert_eq!(receive_2, b"Hello, again, Alice!"); + + // The keys for the first round should be different across groups. + + assert_ne!(bob_verifying_key_1, bob_verifying_key_2); + } + + #[test] + fn invalid_replayed_messages() { + let rng = Rng::from_seed([1; 32]); + + // Alice generates their key material. + + let alice_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let alice_manager = + KeyManager::init_and_generate_prekey(&alice_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + // Bob generates their key material. + + let bob_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let bob_manager = + KeyManager::init_and_generate_prekey(&bob_identity_secret, Lifetime::default(), &rng) + .unwrap(); + + let (bob_manager, bob_prekey_bundle) = + KeyManager::generate_onetime_bundle(bob_manager, &rng).unwrap(); + + // Alice and Bob set up the 2SM protocol handlers for each other. + + let alice_2sm = OneTimeTwoParty::init_to_send(bob_prekey_bundle); + let bob_2sm = OneTimeTwoParty::init_to_receive(); + + // Alice sends a message to Bob. + + let (alice_2sm, message_1) = + OneTimeTwoParty::send(alice_2sm, &alice_manager, b"Hello, Bob!", &rng).unwrap(); + let (bob_2sm, bob_manager, _receive_1) = + OneTimeTwoParty::receive(bob_2sm, bob_manager, message_1.clone()).unwrap(); + + // Bob receives the same message again. + + let result = OneTimeTwoParty::receive(bob_2sm.clone(), bob_manager.clone(), message_1); + std::assert_matches!(result, Err(TwoPartyError::PreKeyReuse)); + + // Alice sends another message to Bob. + + let (_alice_2sm, message_2) = + OneTimeTwoParty::send(alice_2sm, &alice_manager, b"Hello, again, Bob!", &rng).unwrap(); + let (bob_2sm, bob_manager, _receive_2) = + OneTimeTwoParty::receive(bob_2sm, bob_manager, message_2.clone()).unwrap(); + + // Bob receives the same message again. + + let result = OneTimeTwoParty::receive(bob_2sm, bob_manager, message_2); + std::assert_matches!(result, Err(TwoPartyError::Hpke(_))); + } +} diff --git a/pkgs/id/vendor/p2panda-encryption/src/two_party/x3dh.rs b/pkgs/id/vendor/p2panda-encryption/src/two_party/x3dh.rs new file mode 100644 index 0000000000..378cdf5185 --- /dev/null +++ b/pkgs/id/vendor/p2panda-encryption/src/two_party/x3dh.rs @@ -0,0 +1,288 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Extended Triple Diffie-Hellman (X3DH) key agreement protocol as specified by Signal. +//! +//! X3DH establishes a shared secret key between two parties who mutually authenticate each other +//! based on public keys. X3DH provides forward secrecy and cryptographic deniability. +//! +//! X3DH is designed for asynchronous settings where one user ("Bob") is offline but has published +//! public key bundles in the network. Another user ("Alice") wants to use that information to send +//! encrypted data to Bob, and also establish a shared secret key for future communication. +//! +//! +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::crypto::aead::{AeadError, AeadNonce, aead_decrypt, aead_encrypt}; +use crate::crypto::hkdf::{HkdfError, hkdf}; +use crate::crypto::x25519::{PublicKey, SecretKey, X25519Error}; +use crate::crypto::{Rng, RngError}; +use crate::key_bundle::{KeyBundleError, OneTimePreKeyId, PreKeyId}; +use crate::traits::KeyBundle; + +/// ASCII string identifying the application as specified in X3DH used for KDF. +const KDF_INFO: &[u8; 7] = b"p2panda"; + +/// Message containing encrypted payload and X3DH session-data to be delivered from sender to +/// receiver. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct X3dhCiphertext { + /// Identity of the sender. + pub identity_key: PublicKey, + + /// Identifier of the used one-time pre-key. Is none when no one-time key was used (for example + /// in long-term key bundles). + pub onetime_prekey_id: Option, + + /// Identifier of the used long-term pre-key. + pub prekey_id: PreKeyId, + + /// Encrypted payload for the receiver. + pub ciphertext: Vec, + + /// Ephemeral public key used for this session. + pub ephemeral_key: PublicKey, +} + +/// Encrypt message towards a receiver using X3DH protocol with their public pre-key material. +pub fn x3dh_encrypt( + plaintext: &[u8], + our_identity_secret: &SecretKey, + their_prekey_bundle: &KB, + rng: &Rng, +) -> Result { + // Ensure we're not using an expired bundle of receiver. + their_prekey_bundle.verify()?; + + let our_identity_key = our_identity_secret.verifying_key()?; + + let our_ephemeral_secret = SecretKey::from_bytes(rng.random_array()?); + let our_ephemeral_key = our_ephemeral_secret.verifying_key()?; + + let mut ikm = Vec::with_capacity({ + if their_prekey_bundle.onetime_prekey().is_none() { + 32 * 4 + } else { + 32 * 5 + } + }); + + ikm.extend_from_slice(&[0xFFu8; 32]); // "discontinuity bytes" + + // DH1 = DH(IKA, SPKB) + ikm.extend_from_slice( + &our_identity_secret.calculate_agreement(their_prekey_bundle.signed_prekey())?, + ); + + // DH2 = DH(EKA, IKB) + ikm.extend_from_slice( + &our_ephemeral_secret.calculate_agreement(their_prekey_bundle.identity_key())?, + ); + + // DH3 = DH(EKA, SPKB) + ikm.extend_from_slice( + &our_ephemeral_secret.calculate_agreement(their_prekey_bundle.signed_prekey())?, + ); + + // DH4 = DH(EKA, OPKB) + if let Some(onetime_prekey) = their_prekey_bundle.onetime_prekey() { + ikm.extend_from_slice(&our_ephemeral_secret.calculate_agreement(onetime_prekey)?); + } + + // SK = KDF(DH1 || DH2 || DH3 || DH4) + let sk: [u8; 32] = { + let salt = vec![0_u8; 32]; + hkdf(&salt, &ikm, Some(KDF_INFO))? + }; + + drop(our_ephemeral_secret); + drop(ikm); + + // AD = Encode(IKA) || Encode(IKB) + let ad = { + let mut buf = Vec::new(); + buf.extend_from_slice(our_identity_key.as_bytes()); + buf.extend_from_slice(their_prekey_bundle.identity_key().as_bytes()); + buf + }; + + let nonce: AeadNonce = hkdf(b"", &sk, None)?; + let ciphertext = aead_encrypt(&sk, plaintext, nonce, Some(&ad))?; + + Ok(X3dhCiphertext { + ciphertext, + ephemeral_key: our_ephemeral_key, + identity_key: our_identity_key, + prekey_id: *their_prekey_bundle.signed_prekey(), + onetime_prekey_id: their_prekey_bundle.onetime_prekey_id(), + }) +} + +/// Decrypt message using the X3DH protocol and the secrets of the key material the sender used to +/// encrypt the payload towards us. +/// +/// Note that an application using X3DH should reject the received ciphertext when an expired +/// pre-key or already used one-time pre-key was used by the sender. +pub fn x3dh_decrypt( + their_ciphertext: &X3dhCiphertext, + our_identity_secret: &SecretKey, + our_prekey_secret: &SecretKey, + our_onetime_secret: Option<&SecretKey>, +) -> Result, X3dhError> { + let our_identity_key = our_identity_secret.verifying_key()?; + + let mut ikm = Vec::with_capacity(if our_onetime_secret.is_none() { + 32 * 4 + } else { + 32 * 5 + }); + + ikm.extend_from_slice(&[0xFFu8; 32]); // "discontinuity bytes" + + // DH1 = DH(IKA, SPKB) + ikm.extend_from_slice(&our_prekey_secret.calculate_agreement(&their_ciphertext.identity_key)?); + + // DH2 = DH(EKA, IKB) + ikm.extend_from_slice( + &our_identity_secret.calculate_agreement(&their_ciphertext.ephemeral_key)?, + ); + + // DH3 = DH(EKA, SPKB) + ikm.extend_from_slice(&our_prekey_secret.calculate_agreement(&their_ciphertext.ephemeral_key)?); + + // DH4 = DH(EKA, OPKB) + if let Some(our_onetime_secret) = our_onetime_secret { + ikm.extend_from_slice( + &our_onetime_secret.calculate_agreement(&their_ciphertext.ephemeral_key)?, + ); + } + + // SK = KDF(DH1 || DH2 || DH3 || DH4) + let sk: [u8; 32] = { + let salt = vec![0_u8; 32]; + hkdf(&salt, &ikm, Some(KDF_INFO))? + }; + + drop(ikm); + + // AD = Encode(IKA) || Encode(IKB) + let ad = { + let mut buf = Vec::new(); + buf.extend_from_slice(their_ciphertext.identity_key.as_bytes()); + buf.extend_from_slice(our_identity_key.as_bytes()); + buf + }; + + let nonce: AeadNonce = hkdf(b"", &sk, None)?; + let plaintext = aead_decrypt(&sk, &their_ciphertext.ciphertext, nonce, Some(&ad))?; + + Ok(plaintext) +} + +#[derive(Debug, Error)] +pub enum X3dhError { + #[error(transparent)] + Rng(#[from] RngError), + + #[error(transparent)] + Aead(#[from] AeadError), + + #[error(transparent)] + Hkdf(#[from] HkdfError), + + #[error(transparent)] + X25519(#[from] X25519Error), + + #[error(transparent)] + KeyBundle(#[from] KeyBundleError), +} + +#[cfg(test)] +mod tests { + use crate::crypto::Rng; + use crate::crypto::x25519::SecretKey; + use crate::key_bundle::{Lifetime, LongTermKeyBundle, OneTimeKeyBundle, OneTimePreKey, PreKey}; + + use super::{x3dh_decrypt, x3dh_encrypt}; + + #[test] + fn encrypt_decrypt() { + let rng = Rng::from_seed([1; 32]); + + let bob_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let bob_prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let bob_signed_prekey = PreKey::new( + bob_prekey_secret.verifying_key().unwrap(), + Lifetime::default(), + ); + + let bob_onetime_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let bob_onetime_prekey = OneTimePreKey::new(bob_onetime_secret.verifying_key().unwrap(), 2); + + let bob_prekey_signature = bob_signed_prekey.sign(&bob_identity_secret, &rng).unwrap(); + + let bob_prekey_bundle = OneTimeKeyBundle::new( + bob_identity_secret.verifying_key().unwrap(), + bob_signed_prekey, + bob_prekey_signature, + Some(bob_onetime_prekey), + ); + + let alice_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let ciphertext = x3dh_encrypt( + b"Hello, Panda!", + &alice_identity_secret, + &bob_prekey_bundle, + &rng, + ) + .unwrap(); + + let plaintext = x3dh_decrypt( + &ciphertext, + &bob_identity_secret, + &bob_prekey_secret, + Some(&bob_onetime_secret), + ) + .unwrap(); + + assert_eq!(b"Hello, Panda!", plaintext.as_slice()); + } + + #[test] + fn longterm_key_bundle() { + let rng = Rng::from_seed([1; 32]); + + let bob_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let bob_prekey_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + let bob_signed_prekey = PreKey::new( + bob_prekey_secret.verifying_key().unwrap(), + Lifetime::default(), + ); + + let bob_prekey_signature = bob_signed_prekey.sign(&bob_identity_secret, &rng).unwrap(); + + let bob_prekey_bundle = LongTermKeyBundle::new( + bob_identity_secret.verifying_key().unwrap(), + bob_signed_prekey, + bob_prekey_signature, + ); + + let alice_identity_secret = SecretKey::from_bytes(rng.random_array().unwrap()); + + let ciphertext = x3dh_encrypt( + b"Hello, Panda!", + &alice_identity_secret, + &bob_prekey_bundle, + &rng, + ) + .unwrap(); + + let plaintext = + x3dh_decrypt(&ciphertext, &bob_identity_secret, &bob_prekey_secret, None).unwrap(); + + assert_eq!(b"Hello, Panda!", plaintext.as_slice()); + } +} From daa4f20098d4185f331d7cb17d42d4abadf269e4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 09:52:40 -0500 Subject: [PATCH 04/21] feat(rust): from_join with immediate update and withholding [P4.3] Session::add_from_join welcomes a joiner with no earlier secret (the fork's EncryptionGroup::add_from_join) and follows it with an immediate update, so the group has a secret the joiner learns. The joiner does not read a message sent before its join: process withholds an application message whose group secret the device does not hold, and gives the crate only the rest. Tests: a joiner cannot read a message from before its join, nor one sent between the add and the update, and reads one sent after the update. A property over random joins (from_join and full add), removals, updates and sends checks that members agree on the roster and epoch, read the newest message, and that removed members are refused it. --- pkgs/id/src/encryption/scheme.rs | 22 ++++ pkgs/id/src/encryption/tests.rs | 183 +++++++++++++++++++++++++++++++ 2 files changed, 205 insertions(+) diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index 92c3f8f73e..f9f7f9a130 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -158,6 +158,28 @@ impl Session { Ok(message) } + /// Adds `added` by a join: a welcome that carries no earlier secret, then an immediate update. + /// + /// The joiner learns nothing the group had before the add, so it cannot read messages sent + /// before its join. The update gives the group a secret the joiner does learn, and it must be + /// delivered too. Returns the add and the update, in the order they are delivered. + pub fn add_from_join( + &mut self, + model: &BTreeSet, + added: Key, + rng: &Rng, + ) -> Result, SchemeError> { + self.ensure_welcomed()?; + if !model.contains(&added) { + return Err(SchemeError::NotInModel(short(added))); + } + let added_key = member_of(added)?; + let add = self.step(|y| EncryptionGroup::add_from_join(y, added_key, rng))?; + let update = self.step(|y| EncryptionGroup::update(y, rng))?; + self.check_roster(model)?; + Ok(vec![add, update]) + } + /// Removes `removed`, which `model` must no longer list. The removal rotates the epoch. pub fn remove( &mut self, diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index e85ee9ae8a..c206c82da9 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -13,6 +13,7 @@ use p2panda_encryption::data_scheme::group_secret::GroupSecretId; use p2panda_encryption::key_bundle::Lifetime; use p2panda_encryption::key_manager::KeyManagerState; use p2panda_encryption::traits::GroupMessage; +use proptest::prelude::*; use super::*; use crate::groups::Key; @@ -99,6 +100,17 @@ impl Cast { .expect("remove") } + /// A join through `add_from_join`: the add, then the immediate update. + fn join(&mut self, by: u8, who: u8) -> Vec { + self.model.insert(id(who)); + let model = self.model.clone(); + self.sessions + .get_mut(&id(by)) + .expect("session") + .add_from_join(&model, id(who), &self.rng) + .expect("add_from_join") + } + fn update(&mut self, by: u8) -> Envelope { self.sessions .get_mut(&id(by)) @@ -417,3 +429,174 @@ fn test_five_members_converge_through_add_update_and_remove() { ); assert_eq!(cast.members_of(5), cast.model); } + +// --- from_join (P4.3) ----------------------------------------------------------------------------- + +#[test] +fn test_from_join_rejects_a_key_the_model_does_not_list() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + + let model = cast.model.clone(); + let rng = Rng::default(); + let result = cast + .sessions + .get_mut(&id(1)) + .expect("session") + .add_from_join(&model, id(4), &rng); + assert!(matches!(result, Err(SchemeError::NotInModel(_)))); + assert_eq!(cast.members_of(1), cast.model, "the roster is untouched"); +} + +#[test] +fn test_from_join_welcomes_the_joiner_into_a_new_epoch() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + let before = cast.epoch(1); + + let messages = cast.join(1, 4); + assert_eq!( + messages.len(), + 2, + "the join is an add and an immediate update" + ); + cast.deliver(&messages[0], &[2, 3, 4]); + cast.deliver(&messages[1], &[2, 3, 4]); + + assert!(cast.session(4).is_welcomed(), "the joiner is welcomed"); + assert_eq!( + cast.members_of(4), + cast.model, + "the joiner's roster matches the model" + ); + assert_ne!( + cast.epoch(4), + before, + "the joiner holds the epoch the join started" + ); + assert_eq!(cast.epoch(4), cast.epoch(1)); +} + +#[test] +fn test_joiner_cannot_read_a_message_from_before_its_join_and_reads_one_after() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + let before = cast.send(2, "before the join"); + cast.deliver(&before, &[1, 3]); + + let messages = cast.join(1, 4); + cast.deliver(&messages[0], &[2, 3, 4]); + + let gap = cast.send(2, "between the add and the update"); + assert_eq!( + cast.deliver(&gap, &[4]), + vec![vec![Received::Withheld(gap.id())]], + "a message sent before the update is under the old epoch, and is withheld" + ); + + cast.deliver(&messages[1], &[2, 3, 4]); + let after = cast.send(2, "after the update"); + assert_eq!( + cast.deliver(&after, &[4]), + vec![vec![text("after the update")]] + ); + + assert_eq!( + cast.deliver(&before, &[4]), + vec![vec![Received::Withheld(before.id())]], + "the joiner does not read a message sent before its join" + ); +} + +// --- property ------------------------------------------------------------------------------------- + +/// The seeds of the people the group model lists. +fn current_seeds(cast: &Cast, people: &[u8]) -> Vec { + people + .iter() + .copied() + .filter(|seed| cast.model.contains(&id(*seed))) + .collect() +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(24))] + + /// Random joins (from_join and full add), removals, updates and sends. At the end every member + /// agrees on the roster and the epoch, every member reads the newest message, and every removed + /// member is refused it. + #[test] + fn test_random_operations_keep_members_in_agreement( + ops in proptest::collection::vec((0u8..5, any::()), 1..16), + ) { + const PEOPLE: [u8; 5] = [1, 2, 3, 4, 5]; + let mut cast = Cast::new(&PEOPLE); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4, 5]); + + let mut waiting: Vec = vec![4, 5]; + let mut removed: Vec = Vec::new(); + for (step, (kind, pick)) in ops.into_iter().enumerate() { + let current = current_seeds(&cast, &PEOPLE); + let by = current[usize::from(pick) % current.len()]; + // Control messages reach everyone not removed, so a joiner has the history it needs. + let audience: Vec = PEOPLE + .iter() + .copied() + .filter(|seed| *seed != by && !removed.contains(seed)) + .collect(); + match kind { + 0 if !waiting.is_empty() => { + let who = waiting.remove(0); + let messages = cast.join(by, who); + cast.deliver(&messages[0], &audience); + cast.deliver(&messages[1], &audience); + } + 1 if !waiting.is_empty() => { + let who = waiting.remove(0); + let add = cast.add(by, who); + cast.deliver(&add, &audience); + } + 2 if current.len() > 2 => { + let others: Vec = current.iter().copied().filter(|seed| *seed != by).collect(); + let victim = others[usize::from(pick) % others.len()]; + let remove = cast.remove(by, victim); + cast.deliver(&remove, &audience); + removed.push(victim); + } + 3 => { + let update = cast.update(by); + cast.deliver(&update, &audience); + } + _ => { + let text = format!("message {step}"); + let message = cast.send(by, &text); + let readers: Vec = current.iter().copied().filter(|seed| *seed != by).collect(); + for read in cast.deliver(&message, &readers) { + prop_assert_eq!(read, vec![Received::Plaintext(text.as_bytes().to_vec())]); + } + } + } + } + + let members = current_seeds(&cast, &PEOPLE); + for who in &members { + prop_assert_eq!(cast.members_of(*who), cast.model.clone(), "member {} roster", who); + } + let epochs: BTreeSet<_> = members.iter().map(|who| cast.epoch(*who)).collect(); + prop_assert_eq!(epochs.len(), 1, "every member holds the same epoch"); + + let last = cast.send(members[0], "last"); + let readers: Vec = members.iter().copied().filter(|seed| *seed != members[0]).collect(); + for read in cast.deliver(&last, &readers) { + prop_assert_eq!(read, vec![text("last")]); + } + for gone in &removed { + let read = cast.deliver(&last, &[*gone]); + prop_assert_eq!(read, vec![vec![Received::Withheld(last.id())]], "removed member {}", gone); + } + } +} From 205a5483d39339d4a51ed32efab1bb419e0e494a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:02:10 -0500 Subject: [PATCH 05/21] feat(rust): rotation only on removal and update, PCS recovery procedure [P4.8] --- pkgs/id/src/encryption/mod.rs | 14 ++- pkgs/id/src/encryption/scheme.rs | 43 +++++++++ pkgs/id/src/encryption/tests.rs | 148 ++++++++++++++++++++++++++++++- 3 files changed, 198 insertions(+), 7 deletions(-) diff --git a/pkgs/id/src/encryption/mod.rs b/pkgs/id/src/encryption/mod.rs index e3a31231c7..109211d506 100644 --- a/pkgs/id/src/encryption/mod.rs +++ b/pkgs/id/src/encryption/mod.rs @@ -1,14 +1,17 @@ -//! Group encryption on the `DataScheme` of `p2panda-encryption` (Phase 4, P4.1 to P4.3). +//! Group encryption on the `DataScheme` of `p2panda-encryption` (Phase 4, P4.1 to P4.3 and P4.8). //! //! - [`scheme`]: the adapter. One [`Session`] per device and group, with create, add, remove, -//! update, send and process. Membership comes from the group model: the caller passes the member -//! set the model holds after the event. +//! update, recover, send and process. Membership comes from the group model: the caller passes +//! the member set the model holds after the event. //! - [`roster`]: the membership the crate keeps. The adapter checks it against the model after each //! local membership change. //! - [`ordering`]: causal delivery, and the [`Envelope`] messages travel in. //! //! A group member is the key the group model holds (`crate::groups::Key`). The crate's identity is //! the matching `p2panda_core::VerifyingKey`. +//! +//! The epoch rotates only on create, update, add by join, remove and recovery. No timer rotates it +//! (N7): the module takes no clock. pub mod ordering; pub mod roster; @@ -16,7 +19,10 @@ pub mod scheme; pub use ordering::{Envelope, Orderer, OrdererError}; pub use roster::Roster; -pub use scheme::{Received, SchemeError, Session, key_bundle, key_of, new_keys, registry}; +pub use scheme::{ + RECOVERY_STEPS, Received, Recovery, SchemeError, Session, key_bundle, key_of, new_keys, + registry, +}; #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index f9f7f9a130..be8a361327 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -55,6 +55,25 @@ pub enum Received { Withheld(Hash), } +/// What the recovery procedure (N8) did. The CLI prints [`RECOVERY_STEPS`] next to it. +#[derive(Clone, Debug)] +pub struct Recovery { + /// The removal. It rotates the epoch, so the device no longer holds the new secrets. + pub removal: Envelope, + /// The re-add: the welcome and the immediate update, in delivery order (P4.3). + pub readd: Vec, + /// The epoch before the procedure. + pub epoch_before: Option, + /// The epoch after the procedure. It differs from `epoch_before`. + pub epoch_after: Option, +} + +/// The steps of the recovery procedure, in the order [`Session::recover`] runs them. +pub const RECOVERY_STEPS: [&str; 2] = [ + "remove the device: the group rotates its secret, and the device cannot read what follows", + "add the device back by a join: it reads messages from the new epoch, and nothing before it", +]; + /// What the adapter can fail with. #[derive(Debug, Error)] pub enum SchemeError { @@ -203,6 +222,30 @@ impl Session { self.step(|y| EncryptionGroup::update(y, rng)) } + /// Recovers `device` from a suspected compromise (N8): removes it, then adds it back by a join. + /// + /// `without` is the model after the removal and `with` the model after the re-add, so `with` + /// is `without` plus `device`. The removal rotates the epoch, so the device loses the secret it + /// held. The re-add welcomes it into the new epoch without any earlier secret (P4.3). This + /// session must be a manager's: the caller is the device that performs the procedure. + pub fn recover( + &mut self, + without: &BTreeSet, + with: &BTreeSet, + device: Key, + rng: &Rng, + ) -> Result { + let epoch_before = self.epoch(); + let removal = self.remove(without, device, rng)?; + let readd = self.add_from_join(with, device, rng)?; + Ok(Recovery { + removal, + readd, + epoch_before, + epoch_after: self.epoch(), + }) + } + /// Encrypts `plaintext` under the current epoch. pub fn send(&mut self, plaintext: &[u8], rng: &Rng) -> Result { self.ensure_welcomed()?; diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index c206c82da9..774a4ec184 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -12,6 +12,7 @@ use p2panda_encryption::crypto::x25519::SecretKey as IdentitySecret; use p2panda_encryption::data_scheme::group_secret::GroupSecretId; use p2panda_encryption::key_bundle::Lifetime; use p2panda_encryption::key_manager::KeyManagerState; +use p2panda_encryption::key_registry::KeyRegistryState; use p2panda_encryption::traits::GroupMessage; use proptest::prelude::*; @@ -37,6 +38,9 @@ struct Cast { sessions: BTreeMap, /// The member set the group model holds after the last operation. model: BTreeSet, + /// Each person's identity and keys, kept so a device can be rebuilt with the same keys. + keys: BTreeMap, + registry: KeyRegistryState, } impl Cast { @@ -53,19 +57,27 @@ impl Cast { } let registry = registry(&bundles).expect("registry"); let sessions = keys - .into_iter() + .iter() .map(|(key, (verifying, state))| { - let session = Session::init(verifying, state, registry.clone()); - (key, session) + let session = Session::init(*verifying, state.clone(), registry.clone()); + (*key, session) }) .collect(); Self { rng, sessions, model: BTreeSet::new(), + keys, + registry, } } + /// A fresh session for `who` with the keys it was created with. It holds no group secret. + fn reinstall(&self, who: u8) -> Session { + let (verifying, state) = self.keys.get(&id(who)).expect("keys"); + Session::init(*verifying, state.clone(), self.registry.clone()) + } + fn session(&self, who: u8) -> &Session { self.sessions.get(&id(who)).expect("session") } @@ -317,6 +329,136 @@ fn test_remove_rejects_a_member_the_model_still_lists() { // --- integration: three members ------------------------------------------------------------------- +// --- rotation (P4.8) ------------------------------------------------------------------------------ + +#[test] +fn test_the_epoch_rotates_on_create_update_and_remove_and_not_on_send() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + let created = cast.epoch(1); + + let message = cast.send(1, "no rotation"); + cast.deliver(&message, &[2, 3]); + assert_eq!(cast.epoch(1), created, "a send keeps the epoch"); + + let update = cast.update(1); + cast.deliver(&update, &[2, 3]); + let updated = cast.epoch(1); + assert_ne!(updated, created, "an explicit update rotates"); + + let remove = cast.remove(1, 3); + cast.deliver(&remove, &[2, 3]); + assert_ne!(cast.epoch(1), updated, "a removal rotates"); + assert_eq!( + cast.epoch(1), + cast.epoch(2), + "the members agree on the epoch" + ); +} + +#[test] +fn test_an_idle_group_keeps_its_epoch_over_a_simulated_year() { + // The adapter takes no clock and runs no timer, so the only thing that moves an epoch is a call + // to create, update, add or remove. Each simulated hour below is a tick with no call at all. + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + let epoch = cast.epoch(1); + + for hour in 0..(24 * 365) { + for who in [1, 2, 3] { + assert_eq!(cast.epoch(who), epoch, "member {who} at hour {hour}"); + } + } + + let update = cast.update(1); + cast.deliver(&update, &[2, 3]); + assert_ne!( + cast.epoch(1), + epoch, + "the group still rotates when it is asked to" + ); +} + +#[test] +fn test_recovery_puts_the_device_back_and_its_compromised_copy_cannot_read() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + // The attacker's copy of device 3 holds the state it had before the compromise was found. + let mut compromised = cast.sessions.remove(&id(3)).expect("session"); + let without: BTreeSet = [id(1), id(2)].into(); + let with = cast.model.clone(); + let before = cast.epoch(1); + + let recovery = cast + .sessions + .get_mut(&id(1)) + .expect("session") + .recover(&without, &with, id(3), &cast.rng) + .expect("recover"); + assert_eq!(recovery.epoch_before, before); + assert_ne!( + recovery.epoch_after, before, + "the procedure rotates the epoch" + ); + assert_eq!(recovery.readd.len(), 2, "a welcome and an immediate update"); + + // The device comes back as a new session with its own keys and no group secret. + let fresh = cast.reinstall(3); + cast.sessions.insert(id(3), fresh); + cast.model = with; + cast.deliver(&create, &[3]); + cast.deliver(&recovery.removal, &[2, 3]); + cast.deliver(&recovery.readd[0], &[2, 3]); + cast.deliver(&recovery.readd[1], &[2, 3]); + assert!( + cast.session(3).is_welcomed(), + "the re-add welcomes the device" + ); + assert_eq!( + cast.members_of(3), + cast.model, + "the device's roster matches" + ); + + let message = cast.send(1, "after the recovery"); + assert_eq!( + cast.deliver(&message, &[2, 3]), + vec![ + vec![text("after the recovery")], + vec![text("after the recovery")] + ] + ); + + assert_eq!(compromised.epoch(), recovery.epoch_before); + assert_eq!( + compromised.process(&message).expect("process"), + vec![Received::Withheld(message.id())], + "the compromised copy cannot read a message sent after the recovery" + ); +} + +#[test] +fn test_recovery_rejects_a_removal_that_leaves_the_device_in_the_model() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + let model = cast.model.clone(); + let result = + cast.sessions + .get_mut(&id(1)) + .expect("session") + .recover(&model, &model, id(3), &cast.rng); + assert!( + matches!(result, Err(SchemeError::StillInModel(_))), + "a device the model still lists is not removed" + ); +} + #[test] fn test_three_members_create_send_update_and_remove_in_step() { let mut cast = Cast::new(&[1, 2, 3]); From 6b2a9005713e4374c048cafd463ec1d372f48071 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:02:40 -0500 Subject: [PATCH 06/21] feat(rust): recent:N welcomes and history modes [P4.5] A welcome carries the secrets its history mode allows: every secret for full, the newest N for recent:N. The adapter cuts the bundle before Dcgka::add, so the crate never sees a secret outside the window. Presets are 32 and 128. A world sets its mode through the policy's History::Recent. --- pkgs/id/src/encryption/history.rs | 187 ++++++++++++++++++++++++++++++ pkgs/id/src/encryption/mod.rs | 3 + pkgs/id/src/encryption/scheme.rs | 27 ++++- pkgs/id/src/encryption/tests.rs | 71 ++++++++++++ pkgs/id/src/groups/policy.rs | 3 + 5 files changed, 290 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/src/encryption/history.rs diff --git a/pkgs/id/src/encryption/history.rs b/pkgs/id/src/encryption/history.rs new file mode 100644 index 0000000000..a1f0c7f721 --- /dev/null +++ b/pkgs/id/src/encryption/history.rs @@ -0,0 +1,187 @@ +//! History modes: how much of the group's past a joiner is welcomed with (P4.5). +//! +//! 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`. +//! +//! 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` +//! joins. See `explainers.md` section 4. + +use std::cmp::Reverse; +use std::fmt; +use std::str::FromStr; + +use p2panda_encryption::data_scheme::group_secret::{GroupSecret, SecretBundle, SecretBundleState}; +use thiserror::Error; + +use crate::groups::policy::History; + +/// The window of a preset that keeps a join small: 32 epochs (5.3 KB per join with the stock +/// encoding, 1.7 KB with serde_bytes, at 1,000 rotations; round 2 `welcome-recent`). +pub const RECENT_SMALL: u32 = 32; + +/// The window of a preset for churn-heavy worlds that want a longer memory: 128 epochs. +pub const RECENT_LARGE: u32 = 128; + +/// How much of the group's past a joiner is welcomed with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HistoryMode { + /// Every secret the adder holds. + Full, + /// The newest `n` secrets by timestamp. `n` is at least 1. + Recent(u32), +} + +/// A history mode that cannot be used. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum HistoryModeError { + /// The text is neither `full` nor `recent:N`. + #[error("unknown history mode {0:?}: use \"full\" or \"recent:N\"")] + Unknown(String), + /// A window of zero epochs would welcome nothing. + #[error("a recent window must hold at least one epoch")] + EmptyWindow, +} + +impl HistoryMode { + /// A window of the newest `epochs` secrets. + pub const fn recent(epochs: u32) -> Result { + if epochs == 0 { + return Err(HistoryModeError::EmptyWindow); + } + Ok(Self::Recent(epochs)) + } + + /// The mode a world's policy names. `from_join` and `causal` are not welcome bundles, so they + /// have no mode here. + pub fn from_policy(history: History) -> Option { + match history { + History::Full => Some(Self::Full), + History::Recent(epochs) => Self::recent(epochs).ok(), + History::FromJoin | History::Causal => None, + } + } + + /// The bundle a welcome carries under this mode: every secret in `secrets` for `Full`, and the + /// newest `n` for `Recent(n)`. + pub fn welcome_bundle(self, secrets: &SecretBundleState) -> SecretBundleState { + let mut newest: Vec = secrets.secrets().cloned().collect(); + newest.sort_by_key(|secret| Reverse((secret.timestamp(), secret.id()))); + if let Self::Recent(epochs) = self { + newest.truncate(usize::try_from(epochs).unwrap_or(usize::MAX)); + } + SecretBundle::from_secrets(newest) + } +} + +impl FromStr for HistoryMode { + type Err = HistoryModeError; + + fn from_str(text: &str) -> Result { + if text == "full" { + return Ok(Self::Full); + } + let epochs = text + .strip_prefix("recent:") + .and_then(|count| count.parse::().ok()) + .ok_or_else(|| HistoryModeError::Unknown(text.to_string()))?; + Self::recent(epochs) + } +} + +impl fmt::Display for HistoryMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Full => write!(f, "full"), + Self::Recent(epochs) => write!(f, "recent:{epochs}"), + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use p2panda_encryption::crypto::Rng; + + use super::*; + + /// `count` secrets in the order they were generated. Each one is newer than the last, since + /// `generate` moves a timestamp past the latest secret it sees. + fn generated(count: usize) -> (Vec, SecretBundleState) { + let rng = Rng::default(); + let mut bundle = SecretBundle::init(); + let mut secrets = Vec::new(); + for _ in 0..count { + let secret = SecretBundle::generate(&bundle, &rng).expect("generate"); + secrets.push(secret.clone()); + bundle = SecretBundle::insert(bundle, secret); + } + (secrets, bundle) + } + + #[test] + fn test_history_mode_parses_and_prints() { + assert_eq!("full".parse::(), Ok(HistoryMode::Full)); + assert_eq!( + "recent:32".parse::(), + Ok(HistoryMode::Recent(RECENT_SMALL)) + ); + assert_eq!(HistoryMode::Recent(RECENT_LARGE).to_string(), "recent:128"); + assert_eq!(HistoryMode::Full.to_string(), "full"); + } + + #[test] + fn test_history_mode_refuses_an_empty_window_and_unknown_text() { + assert_eq!( + "recent:0".parse::(), + Err(HistoryModeError::EmptyWindow) + ); + assert!(matches!( + "all".parse::(), + Err(HistoryModeError::Unknown(_)) + )); + assert!(matches!( + "recent:x".parse::(), + Err(HistoryModeError::Unknown(_)) + )); + } + + #[test] + fn test_policy_history_maps_to_a_welcome_mode() { + assert_eq!( + HistoryMode::from_policy(History::Full), + Some(HistoryMode::Full) + ); + assert_eq!( + HistoryMode::from_policy(History::Recent(RECENT_LARGE)), + Some(HistoryMode::Recent(RECENT_LARGE)) + ); + assert_eq!(HistoryMode::from_policy(History::Recent(0)), None); + assert_eq!(HistoryMode::from_policy(History::FromJoin), None); + assert_eq!(HistoryMode::from_policy(History::Causal), None); + } + + #[test] + fn test_recent_welcome_carries_the_newest_secrets_by_timestamp() { + let (secrets, held) = generated(5); + + let recent = HistoryMode::Recent(2).welcome_bundle(&held); + assert_eq!(recent.len(), 2); + assert_eq!(recent.latest().map(GroupSecret::id), Some(secrets[4].id())); + assert!(recent.contains(&secrets[4].id())); + assert!(recent.contains(&secrets[3].id())); + assert!(!recent.contains(&secrets[2].id())); + + let full = HistoryMode::Full.welcome_bundle(&held); + assert_eq!(full.len(), 5); + } + + #[test] + fn test_recent_window_larger_than_the_bundle_carries_everything() { + let (_, held) = generated(2); + let welcome = HistoryMode::Recent(RECENT_LARGE).welcome_bundle(&held); + assert_eq!(welcome.len(), 2); + } +} diff --git a/pkgs/id/src/encryption/mod.rs b/pkgs/id/src/encryption/mod.rs index e3a31231c7..3e5830efa3 100644 --- a/pkgs/id/src/encryption/mod.rs +++ b/pkgs/id/src/encryption/mod.rs @@ -6,14 +6,17 @@ //! - [`roster`]: the membership the crate keeps. The adapter checks it against the model after each //! local membership change. //! - [`ordering`]: causal delivery, and the [`Envelope`] messages travel in. +//! - [`history`]: the history modes a welcome is cut to (`full` or `recent:N`). //! //! A group member is the key the group model holds (`crate::groups::Key`). The crate's identity is //! the matching `p2panda_core::VerifyingKey`. +pub mod history; pub mod ordering; pub mod roster; pub mod scheme; +pub use history::{HistoryMode, HistoryModeError}; pub use ordering::{Envelope, Orderer, OrdererError}; pub use roster::Roster; pub use scheme::{Received, SchemeError, Session, key_bundle, key_of, new_keys, registry}; diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index f9f7f9a130..465cb19e43 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -33,6 +33,7 @@ use p2panda_encryption::key_registry::{KeyRegistry, KeyRegistryState}; use p2panda_encryption::traits::{GroupMessage, GroupMessageContent, Ordering as _, PreKeyManager}; use thiserror::Error; +use super::history::HistoryMode; use super::ordering::{Envelope, Orderer}; use super::roster::Roster; use crate::groups::Key; @@ -119,6 +120,11 @@ impl Session { self.state.as_ref()?.secrets.latest().map(GroupSecret::id) } + /// How many group secrets this device holds, so how many epochs it can read. + pub fn epoch_count(&self) -> usize { + self.state.as_ref().map_or(0, |y| y.secrets.len()) + } + /// The members the crate's roster holds, as group-model keys. pub fn members(&self) -> Result, SchemeError> { let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; @@ -143,14 +149,33 @@ impl Session { model: &BTreeSet, added: Key, rng: &Rng, + ) -> Result { + self.add_with_history(model, added, HistoryMode::Full, rng) + } + + /// Adds `added`, which `model` must already list, with a welcome that carries the secrets + /// `mode` allows: every secret for `Full`, the newest N for `Recent(N)` (P4.5). + /// + /// The bundle is cut here, before `Dcgka::add`, so the crate never sees a secret outside the + /// window. The joiner then holds exactly the window and refuses older messages. + pub fn add_with_history( + &mut self, + model: &BTreeSet, + added: Key, + mode: HistoryMode, + rng: &Rng, ) -> Result { self.ensure_welcomed()?; if !model.contains(&added) { return Err(SchemeError::NotInModel(short(added))); } let added_key = member_of(added)?; + let bundle = { + let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; + mode.welcome_bundle(&y.secrets) + }; let message = self.step(|mut y| { - let (dcgka, output) = Dcgka::add(y.dcgka, added_key, &y.secrets, rng)?; + let (dcgka, output) = Dcgka::add(y.dcgka, added_key, &bundle, rng)?; y.dcgka = dcgka; publish(y, output) })?; diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index c206c82da9..14f42498e1 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -100,6 +100,17 @@ impl Cast { .expect("remove") } + /// An add that welcomes the joiner with the secrets `mode` allows. + fn add_with_history(&mut self, by: u8, who: u8, mode: HistoryMode) -> Envelope { + self.model.insert(id(who)); + let model = self.model.clone(); + self.sessions + .get_mut(&id(by)) + .expect("session") + .add_with_history(&model, id(who), mode, &self.rng) + .expect("add_with_history") + } + /// A join through `add_from_join`: the add, then the immediate update. fn join(&mut self, by: u8, who: u8) -> Vec { self.model.insert(id(who)); @@ -239,6 +250,66 @@ fn test_add_rejects_a_key_the_model_does_not_list() { assert_eq!(cast.members_of(1), cast.model, "the roster is untouched"); } +// --- history modes ------------------------------------------------------------------------------- + +/// Every window size and epoch count: a `recent:N` welcome succeeds, the joiner holds the newest +/// `min(N, K + 1)` epochs, and it reads a message sent after the join. +#[test] +fn test_recent_welcome_succeeds_for_every_window_and_epoch_count() { + for window in [1, 8, 32, 128, 512] { + for rotations in [0, 1, 5, 40] { + let mode = HistoryMode::Recent(window); + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + for _ in 0..rotations { + let update = cast.update(1); + cast.deliver(&update, &[2, 3, 4]); + } + + let add = cast.add_with_history(1, 4, mode); + cast.deliver(&add, &[2, 3, 4]); + let case = format!("{mode} after {rotations} rotations"); + assert!(cast.session(4).is_welcomed(), "{case}: welcomed"); + assert_eq!(cast.members_of(4), cast.model, "{case}: roster"); + assert_eq!(cast.epoch(4), cast.epoch(1), "{case}: newest epoch"); + let epochs = usize::try_from(window).expect("window").min(rotations + 1); + assert_eq!(cast.session(4).epoch_count(), epochs, "{case}: window"); + + let message = cast.send(2, "after the join"); + assert_eq!( + cast.deliver(&message, &[1, 3, 4]), + vec![ + vec![text("after the join")], + vec![text("after the join")], + vec![text("after the join")] + ], + "{case}: the joiner reads after its join" + ); + } + } +} + +/// A full welcome carries every epoch, and the joiner holds all of them. +#[test] +fn test_full_welcome_carries_every_epoch() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + for _ in 0..5 { + let update = cast.update(1); + cast.deliver(&update, &[2, 3, 4]); + } + + let add = cast.add_with_history(1, 4, HistoryMode::Full); + cast.deliver(&add, &[2, 3, 4]); + assert_eq!( + cast.session(4).epoch_count(), + 6, + "every epoch the adder holds" + ); +} + // --- update --------------------------------------------------------------------------------------- #[test] diff --git a/pkgs/id/src/groups/policy.rs b/pkgs/id/src/groups/policy.rs index 25e5552ad9..40fbbb6955 100644 --- a/pkgs/id/src/groups/policy.rs +++ b/pkgs/id/src/groups/policy.rs @@ -57,6 +57,9 @@ pub enum History { /// The whole history. #[default] Full, + /// The last N epochs (P4.5). A joiner reads older messages only by asking a member (P4.6). + /// N is at least 1. + Recent(u32), /// Only what came after the join. FromJoin, /// Causal history (deferred). From 4b82eff2b1d399c63a60627dcf3575b89c7b2e1f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:03:05 -0500 Subject: [PATCH 07/21] feat(rust): local warnings at 96, 128 and 1000 and on churn [P4.9] --- pkgs/id/src/encryption/mod.rs | 4 +- pkgs/id/src/encryption/warnings.rs | 340 +++++++++++++++++++++++++++++ 2 files changed, 343 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/src/encryption/warnings.rs diff --git a/pkgs/id/src/encryption/mod.rs b/pkgs/id/src/encryption/mod.rs index 109211d506..2278649fa1 100644 --- a/pkgs/id/src/encryption/mod.rs +++ b/pkgs/id/src/encryption/mod.rs @@ -1,4 +1,4 @@ -//! Group encryption on the `DataScheme` of `p2panda-encryption` (Phase 4, P4.1 to P4.3 and P4.8). +//! Group encryption on the `DataScheme` of `p2panda-encryption` (Phase 4, P4.1 to P4.3, P4.8 to P4.11). //! //! - [`scheme`]: the adapter. One [`Session`] per device and group, with create, add, remove, //! update, recover, send and process. Membership comes from the group model: the caller passes @@ -6,6 +6,7 @@ //! - [`roster`]: the membership the crate keeps. The adapter checks it against the model after each //! local membership change. //! - [`ordering`]: causal delivery, and the [`Envelope`] messages travel in. +//! - [`warnings`]: the server's local warnings about a group's size and re-add churn (P4.9). //! //! A group member is the key the group model holds (`crate::groups::Key`). The crate's identity is //! the matching `p2panda_core::VerifyingKey`. @@ -16,6 +17,7 @@ pub mod ordering; pub mod roster; pub mod scheme; +pub mod warnings; pub use ordering::{Envelope, Orderer, OrdererError}; pub use roster::Roster; diff --git a/pkgs/id/src/encryption/warnings.rs b/pkgs/id/src/encryption/warnings.rs new file mode 100644 index 0000000000..ef404c7788 --- /dev/null +++ b/pkgs/id/src/encryption/warnings.rs @@ -0,0 +1,340 @@ +//! Local warnings about a client-made group's size and re-add churn (P4.9, N11 and N34). +//! +//! The server evaluates each client-made group. A warning fires when the group's member count +//! reaches 96, 128 or 1,000, and when its devices are re-added in bursts (a re-add is the N8 +//! recovery, so a burst is worth a look). The warnings are local to the server: they go to its log +//! through [`log`], and the same text goes to the CLI status line through [`Warning::message`]. No +//! warning blocks an operation, and no group is refused for its size (decision 9). +//! +//! A warning fires once per crossing. The evaluator keeps each group's high-water mark, so a group +//! that shrinks below a threshold and grows back does not warn again. Churn re-arms only once the +//! window falls to [`CHURN_CLEAR`], so a count that flaps around [`CHURN_THRESHOLD`] warns once. + +use std::collections::BTreeMap; + +use p2panda_core::Hash; + +/// The member counts that warn (N11). +pub const SIZE_THRESHOLDS: [usize; 3] = [96, 128, 1_000]; + +/// The re-add window, in seconds: one day. +pub const CHURN_WINDOW_SECS: u64 = 24 * 60 * 60; + +/// The re-adds in the window that warn (N34). +pub const CHURN_THRESHOLD: usize = 4; + +/// The window count at or below which churn re-arms: half the threshold. A count that flaps +/// between the two does not re-arm, so it does not warn twice. +pub const CHURN_CLEAR: usize = 2; + +/// One warning about a group. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Warning { + /// The group reached `threshold` members, and has `members` now. + Size { + /// The threshold crossed. + threshold: usize, + /// The member count when it was crossed. + members: usize, + }, + /// The group had `readds` device re-adds in the last [`CHURN_WINDOW_SECS`]. + Churn { + /// The re-adds in the window. + readds: usize, + }, +} + +impl Warning { + /// The text for the server log and the CLI status line. + pub fn message(&self) -> String { + match self { + Self::Size { threshold, members } => format!( + "group reached {threshold} members ({members} now): each update is sent to every member, so its cost grows with the group" + ), + Self::Churn { readds } => format!( + "{readds} device re-adds in the last 24 hours: each re-add is a compromise recovery, so check the devices" + ), + } + } +} + +/// What the server knows about one group when it evaluates it. +#[derive(Clone, Copy, Debug)] +pub struct Observation<'a> { + /// The group. + pub group: Hash, + /// Whether a client made the group. Groups provisioned from a server config are not warned + /// about. + pub client_made: bool, + /// The member count, from the fold. + pub members: usize, + /// When each device was re-added, in Unix seconds, from the group's events. + pub readds: &'a [u64], +} + +/// Tracks each group's warnings between evaluations. It holds no clock: the caller passes `now`. +#[derive(Debug, Default)] +pub struct Evaluator { + groups: BTreeMap, +} + +/// What an evaluator remembers about one group. +#[derive(Debug)] +struct Tracked { + /// How many of [`SIZE_THRESHOLDS`] the group has warned for. It never goes down. + crossed: usize, + /// Whether churn may warn. It disarms on a warning and re-arms at [`CHURN_CLEAR`]. + churn_armed: bool, +} + +impl Default for Tracked { + fn default() -> Self { + Self { + crossed: 0, + churn_armed: true, + } + } +} + +impl Evaluator { + /// Evaluates one group at `now` (Unix seconds). It returns the warnings this observation adds, + /// and never fails: nothing here blocks an operation. + pub fn observe(&mut self, observation: &Observation<'_>, now: u64) -> Vec { + if !observation.client_made { + return Vec::new(); + } + let tracked = self.groups.entry(observation.group).or_default(); + let mut warnings = Vec::new(); + + let reached = SIZE_THRESHOLDS + .iter() + .filter(|threshold| **threshold <= observation.members) + .count(); + for threshold in SIZE_THRESHOLDS.iter().take(reached).skip(tracked.crossed) { + warnings.push(Warning::Size { + threshold: *threshold, + members: observation.members, + }); + } + tracked.crossed = tracked.crossed.max(reached); + + let readds = window_count(observation.readds, now); + if readds <= CHURN_CLEAR { + tracked.churn_armed = true; + } else if readds >= CHURN_THRESHOLD && tracked.churn_armed { + tracked.churn_armed = false; + warnings.push(Warning::Churn { readds }); + } + warnings + } +} + +/// The re-adds in the window that ends at `now`. A re-add later than `now` is not counted yet. +fn window_count(readds: &[u64], now: u64) -> usize { + readds + .iter() + .filter(|at| **at <= now && now - **at < CHURN_WINDOW_SECS) + .count() +} + +/// Writes each warning to the server log, against the group it is about. +pub fn log(group: &Hash, warnings: &[Warning]) { + for warning in warnings { + tracing::warn!(group = %group.to_hex(), "{}", warning.message()); + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use proptest::prelude::*; + + use super::*; + + fn group() -> Hash { + Hash::digest(b"a client-made group") + } + + fn observe( + evaluator: &mut Evaluator, + members: usize, + readds: &[u64], + now: u64, + ) -> Vec { + let observation = Observation { + group: group(), + client_made: true, + members, + readds, + }; + evaluator.observe(&observation, now) + } + + fn size(threshold: usize, members: usize) -> Warning { + Warning::Size { threshold, members } + } + + #[test] + fn test_each_threshold_warns_at_its_count_and_not_one_below() { + // A new group that starts at `members` has crossed every threshold at or below it. + for (members, expected) in [ + (95, vec![]), + (96, vec![size(96, 96)]), + (127, vec![size(96, 127)]), + (128, vec![size(96, 128), size(128, 128)]), + (999, vec![size(96, 999), size(128, 999)]), + ( + 1_000, + vec![size(96, 1_000), size(128, 1_000), size(1_000, 1_000)], + ), + ] { + let warnings = observe(&mut Evaluator::default(), members, &[], 0); + assert_eq!(warnings, expected, "at {members} members"); + } + } + + #[test] + fn test_a_group_warns_once_per_crossing_as_it_grows() { + let mut evaluator = Evaluator::default(); + let mut seen = Vec::new(); + for members in [95, 96, 96, 97, 127, 128, 128, 999, 1_000, 1_001] { + seen.extend(observe(&mut evaluator, members, &[], 0)); + } + assert_eq!(seen, vec![size(96, 96), size(128, 128), size(1_000, 1_000)]); + } + + #[test] + fn test_one_jump_past_several_thresholds_warns_for_each_in_order() { + let warnings = observe(&mut Evaluator::default(), 1_200, &[], 0); + assert_eq!( + warnings, + vec![size(96, 1_200), size(128, 1_200), size(1_000, 1_200)] + ); + } + + #[test] + fn test_flapping_across_a_threshold_warns_once() { + let mut evaluator = Evaluator::default(); + let mut seen = Vec::new(); + for members in [96, 95, 96, 95, 96, 94, 96] { + seen.extend(observe(&mut evaluator, members, &[], 0)); + } + assert_eq!( + seen, + vec![size(96, 96)], + "the shrink and regrow do not repeat" + ); + } + + #[test] + fn test_churn_warns_at_the_threshold_and_then_rearms_when_the_window_clears() { + let mut evaluator = Evaluator::default(); + let mut readds = vec![0, 1, 2, 3]; + assert_eq!( + observe(&mut evaluator, 10, &readds, 3), + vec![Warning::Churn { readds: 4 }] + ); + + readds.push(4); + assert!( + observe(&mut evaluator, 10, &readds, 4).is_empty(), + "one warning per burst" + ); + + // Every re-add has aged out of the window, so churn re-arms. + let later = CHURN_WINDOW_SECS + 4; + assert!(observe(&mut evaluator, 10, &readds, later).is_empty()); + + let burst = later + 10; + readds.extend([burst, burst + 1, burst + 2, burst + 3]); + assert_eq!( + observe(&mut evaluator, 10, &readds, burst + 3), + vec![Warning::Churn { readds: 4 }], + "a new burst warns again" + ); + } + + #[test] + fn test_churn_flapping_around_the_threshold_warns_once() { + let mut evaluator = Evaluator::default(); + let mut readds = vec![1, 2, 3, 4]; + let mut seen = observe(&mut evaluator, 10, &readds, 4); + + // Re-add 1 ages out, so the count drops to 3, which is above CHURN_CLEAR and does not + // re-arm. Then a new re-add brings it back to 4. + let mut now = CHURN_WINDOW_SECS + 1; + seen.extend(observe(&mut evaluator, 10, &readds, now)); + readds.push(now); + seen.extend(observe(&mut evaluator, 10, &readds, now)); + now += 1; + seen.extend(observe(&mut evaluator, 10, &readds, now)); + readds.push(now); + seen.extend(observe(&mut evaluator, 10, &readds, now)); + + assert_eq!(seen, vec![Warning::Churn { readds: 4 }]); + } + + #[test] + fn test_a_group_that_is_not_client_made_is_never_warned_about() { + let observation = Observation { + group: group(), + client_made: false, + members: 1_000, + readds: &[1, 2, 3, 4], + }; + assert!(Evaluator::default().observe(&observation, 4).is_empty()); + } + + #[test] + fn test_each_group_keeps_its_own_warnings() { + let mut evaluator = Evaluator::default(); + let other = Hash::digest(b"another group"); + assert_eq!(observe(&mut evaluator, 96, &[], 0), vec![size(96, 96)]); + let observation = Observation { + group: other, + client_made: true, + members: 96, + readds: &[], + }; + assert_eq!(evaluator.observe(&observation, 0), vec![size(96, 96)]); + } + + #[test] + fn test_the_message_names_the_threshold_and_the_churn() { + assert!(size(96, 96).message().contains("96")); + assert!( + Warning::Churn { readds: 4 } + .message() + .contains("4 device re-adds") + ); + } + + proptest! { + /// Over any path of sizes, the warnings a group has earned are the thresholds its largest + /// size has reached, and the count never falls along the way. + #[test] + fn test_a_groups_warning_count_follows_its_largest_size( + sizes in proptest::collection::vec(0usize..1_500, 1..40), + ) { + let mut evaluator = Evaluator::default(); + let mut total = 0; + let mut peak = 0; + for members in sizes { + peak = peak.max(members); + let warned = observe(&mut evaluator, members, &[], 0).len(); + total += warned; + let reached = SIZE_THRESHOLDS.iter().filter(|t| **t <= peak).count(); + prop_assert_eq!(total, reached); + } + } + + /// A bigger group never has fewer warnings than a smaller one. + #[test] + fn test_warnings_are_monotone_in_size(a in 0usize..1_500, b in 0usize..1_500) { + let (small, large) = (a.min(b), a.max(b)); + let small_count = observe(&mut Evaluator::default(), small, &[], 0).len(); + let large_count = observe(&mut Evaluator::default(), large, &[], 0).len(); + prop_assert!(small_count <= large_count); + } + } +} From a95c52ae9c2b828369c21f504ae2b1c16d0f9302 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:03:26 -0500 Subject: [PATCH 08/21] feat(rust): scheme none notice [P4.10] --- pkgs/id/src/encryption/mod.rs | 2 + pkgs/id/src/encryption/notice.rs | 75 ++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 pkgs/id/src/encryption/notice.rs diff --git a/pkgs/id/src/encryption/mod.rs b/pkgs/id/src/encryption/mod.rs index 2278649fa1..fd91e9698b 100644 --- a/pkgs/id/src/encryption/mod.rs +++ b/pkgs/id/src/encryption/mod.rs @@ -7,6 +7,7 @@ //! local membership change. //! - [`ordering`]: causal delivery, and the [`Envelope`] messages travel in. //! - [`warnings`]: the server's local warnings about a group's size and re-add churn (P4.9). +//! - [`notice`]: the "scheme: none" notice for a group made without a scheme (P4.10). //! //! A group member is the key the group model holds (`crate::groups::Key`). The crate's identity is //! the matching `p2panda_core::VerifyingKey`. @@ -14,6 +15,7 @@ //! The epoch rotates only on create, update, add by join, remove and recovery. No timer rotates it //! (N7): the module takes no clock. +pub mod notice; pub mod ordering; pub mod roster; pub mod scheme; diff --git a/pkgs/id/src/encryption/notice.rs b/pkgs/id/src/encryption/notice.rs new file mode 100644 index 0000000000..fec3144f9b --- /dev/null +++ b/pkgs/id/src/encryption/notice.rs @@ -0,0 +1,75 @@ +//! The "scheme: none" notice (P4.10, decision 8). +//! +//! A group created without a key-agreement scheme says so in its metadata and in the status string +//! the UI and the CLI show. The notice is information, not a gate: the group works as it did +//! before. Every group carries the field, so a reader never has to infer the scheme from silence. + +use crate::groups::{Policy, Scheme}; + +/// The metadata key and the status-string prefix for a group's scheme. +pub const SCHEME_KEY: &str = "scheme"; + +/// The value for a group with no scheme. +pub const NO_SCHEME: &str = "none"; + +/// The scheme's value in the metadata: `none`, or the scheme's name and version. +pub fn scheme_value(policy: &Policy) -> String { + match &policy.scheme { + None => NO_SCHEME.to_owned(), + Some(Scheme { name, version }) => format!("{name} v{version}"), + } +} + +/// The group's metadata, as key and value pairs. It always has the scheme field. +pub fn metadata(policy: &Policy) -> Vec<(&'static str, String)> { + vec![(SCHEME_KEY, scheme_value(policy))] +} + +/// The status string for the UI and the CLI, such as `scheme: none`. +pub fn status(policy: &Policy) -> String { + format!("{SCHEME_KEY}: {}", scheme_value(policy)) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn test_a_group_created_without_encryption_carries_the_notice_in_its_metadata() { + let policy = Policy::default(); + assert_eq!( + metadata(&policy), + vec![("scheme", "none".to_owned())], + "the metadata names the missing scheme" + ); + } + + #[test] + fn test_the_status_string_says_scheme_none() { + assert_eq!(status(&Policy::default()), "scheme: none"); + } + + #[test] + fn test_a_group_with_a_scheme_names_it_in_the_metadata_and_the_status() { + let policy = Policy { + scheme: Some(Scheme { + name: "data-scheme".to_owned(), + version: 1, + }), + ..Policy::default() + }; + assert_eq!( + metadata(&policy), + vec![("scheme", "data-scheme v1".to_owned())] + ); + assert_eq!(status(&policy), "scheme: data-scheme v1"); + } + + #[test] + fn test_the_notice_is_not_a_gate_for_the_group_policy() { + // The notice describes the policy. A group without a scheme is still valid and can take + // members, so nothing here may make the policy invalid. + assert!(Policy::default().is_valid()); + } +} From 2a3de9a9221fb5287df1719edb8fe4af3fa2a9e4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:04:09 -0500 Subject: [PATCH 09/21] test(rust): DataScheme update cost measurement [P4.11] --- pkgs/id/src/encryption/tests.rs | 111 ++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index 774a4ec184..bed5d4007a 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -5,6 +5,7 @@ //! to the members who may read them. use std::collections::{BTreeMap, BTreeSet}; +use std::time::Instant; use p2panda_core::{SigningKey, VerifyingKey}; use p2panda_encryption::crypto::Rng; @@ -742,3 +743,113 @@ proptest! { } } } + +// --- cost (P4.11) --------------------------------------------------------------------------------- + +/// The `index`th person of a benchmark group. [`person`] takes a one-byte seed, which runs out at +/// 256 people, so the benchmark spreads the index over the key bytes. +fn benchmark_person(index: usize) -> (Key, VerifyingKey) { + let mut bytes = [0_u8; 32]; + bytes[..8].copy_from_slice(&(index as u64).to_le_bytes()); + let verifying = SigningKey::from_bytes(&bytes).verifying_key(); + (key_of(verifying), verifying) +} + +/// The committer's cost for one group size: the create, and the mean of a few updates. +#[derive(Debug)] +struct UpdateCost { + members: usize, + create_bytes: usize, + create_ms: f64, + update_bytes: usize, + update_ms: f64, + updates: usize, +} + +impl UpdateCost { + fn report(&self) -> String { + format!( + "members {:>5}: create {:>9} B in {:>9.1} ms; update {:>9} B, {:>8.2} ms (mean of {})", + self.members, + self.create_bytes, + self.create_ms, + self.update_bytes, + self.update_ms, + self.updates, + ) + } +} + +/// Builds a group of `members` on one committer's device, and measures the committer's side. The +/// other members are not built, since the cost of an update is the committer's to pay: it encrypts +/// the new secret to each member and processes its own message. The bytes are the postcard size of +/// the envelope, which is what a transport would carry. +fn measure_update_cost(members: usize, updates: usize) -> UpdateCost { + let rng = Rng::default(); + let mut bundles = Vec::with_capacity(members); + let mut model = BTreeSet::new(); + let mut committer = None; + for index in 0..members { + let (key, verifying) = benchmark_person(index); + let identity = IdentitySecret::from_rng(&rng).expect("identity"); + let state = new_keys(&identity, Lifetime::default(), &rng).expect("keys"); + bundles.push((verifying, key_bundle(&state).expect("bundle"))); + model.insert(key); + if index == 0 { + committer = Some((verifying, state)); + } + } + let (me, keys) = committer.expect("a committer"); + let mut session = Session::init(me, keys, registry(&bundles).expect("registry")); + + let started = Instant::now(); + let create = session.create(&model, &rng).expect("create"); + let create_ms = started.elapsed().as_secs_f64() * 1_000.0; + let create_bytes = wire_bytes(&create); + + // One update before the timed ones, so the first-commit cost is not counted twice. + session.update(&rng).expect("warm-up update"); + let mut sent = Vec::with_capacity(updates); + let started = Instant::now(); + for _ in 0..updates { + sent.push(session.update(&rng).expect("update")); + } + let count = f64::from(u32::try_from(updates).expect("a few updates")); + let update_ms = started.elapsed().as_secs_f64() * 1_000.0 / count; + let update_bytes = sent.iter().map(wire_bytes).sum::() / updates; + + UpdateCost { + members, + create_bytes, + create_ms, + update_bytes, + update_ms, + updates, + } +} + +fn wire_bytes(envelope: &Envelope) -> usize { + postcard::to_allocvec(envelope).expect("encode").len() +} + +#[test] +fn test_the_update_cost_measurement_grows_with_the_members() { + let small = measure_update_cost(4, 1); + let large = measure_update_cost(8, 1); + assert!(small.update_bytes > 0, "an update is sent"); + assert!( + large.update_bytes > small.update_bytes, + "an update carries a message for each member" + ); +} + +/// P4.11: what one `DataScheme` update costs the committer at 100, 1,000 and 5,000 members, with our +/// adapter. It records the numbers and fails on none of them. Run it in release: +/// `cargo test --release --lib encryption::tests::bench_update_cost -- --ignored --nocapture`. +#[test] +#[ignore = "release benchmark for P4.11: cargo test --release --lib encryption::tests::bench_update_cost -- --ignored --nocapture"] +fn bench_update_cost() { + for members in [100, 1_000, 5_000] { + println!("{}", measure_update_cost(members, 5).report()); + } +} From d22f6987a703887624217ab4042bd4fa29c0b592 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:06:27 -0500 Subject: [PATCH 10/21] feat(rust): scheme v1 with the version bound to the signed policy [P4.4] The fork encodes the two byte fields as serde_bytes and writes the bundle sorted by (timestamp, id). The version is the group policy's scheme field. The session negotiates it at start and refuses a policy it does not speak, so a stock group is refused, not migrated. Each envelope carries the version in its header and in every direct message, and the session checks both before the crate reads a message, so a relay cannot downgrade. --- pkgs/id/src/encryption/mod.rs | 5 +- pkgs/id/src/encryption/ordering.rs | 68 +++++- pkgs/id/src/encryption/scheme.rs | 78 ++++++- pkgs/id/src/encryption/tests.rs | 193 +++++++++++++++++- pkgs/id/vendor/README.md | 10 +- .../src/data_scheme/group_secret.rs | 28 ++- .../src/two_party/two_party.rs | 2 + .../p2panda-encryption/src/two_party/x3dh.rs | 2 + 8 files changed, 366 insertions(+), 20 deletions(-) diff --git a/pkgs/id/src/encryption/mod.rs b/pkgs/id/src/encryption/mod.rs index e3a31231c7..917d30126e 100644 --- a/pkgs/id/src/encryption/mod.rs +++ b/pkgs/id/src/encryption/mod.rs @@ -16,7 +16,10 @@ pub mod scheme; pub use ordering::{Envelope, Orderer, OrdererError}; pub use roster::Roster; -pub use scheme::{Received, SchemeError, Session, key_bundle, key_of, new_keys, registry}; +pub use scheme::{ + DATASCHEME, Received, SCHEME_V1, SchemeError, Session, key_bundle, key_of, negotiate, new_keys, + registry, +}; #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] diff --git a/pkgs/id/src/encryption/ordering.rs b/pkgs/id/src/encryption/ordering.rs index 313f94db89..79867f0467 100644 --- a/pkgs/id/src/encryption/ordering.rs +++ b/pkgs/id/src/encryption/ordering.rs @@ -26,9 +26,11 @@ use super::roster::Roster; /// message. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Envelope { - /// Hash of the sequence number, the sender, the names and the content. + /// Hash of the sequence number, the sender, the scheme, the names and the content. id: Hash, sender: VerifyingKey, + /// The scheme version the message was encoded under: a copy of the group's signed policy (P4.4). + scheme: u32, /// The last control message seen from each author when this was published. previous: Vec, content: Content, @@ -38,7 +40,7 @@ pub struct Envelope { enum Content { Control { control: ControlMessage, - direct: Vec>, + direct: Vec, }, Application { group_secret_id: GroupSecretId, @@ -47,22 +49,60 @@ enum Content { }, } +/// A direct message with the scheme version it was encoded under. The copy lets a recipient check +/// the version before the crate reads the message. A joiner has no group state yet, so the welcome +/// copy is the only check it has. +#[derive(Clone, Debug, Serialize, Deserialize)] +struct Direct { + scheme: u32, + message: DirectMessage, +} + impl Envelope { fn new( seq: u64, sender: VerifyingKey, + scheme: u32, previous: Vec, content: Content, ) -> Result { - let bytes = encode_cbor(&(seq, sender, &previous, &content)) + let bytes = encode_cbor(&(seq, sender, scheme, &previous, &content)) .map_err(|err| OrdererError::Encode(err.to_string()))?; Ok(Self { id: Hash::digest(&bytes), sender, + scheme, previous, content, }) } + + /// The scheme version in the header. + pub const fn scheme(&self) -> u32 { + self.scheme + } + + /// The scheme version copied into each direct message, in order. Empty for an application + /// message. + pub fn direct_schemes(&self) -> Vec { + match &self.content { + Content::Control { direct, .. } => direct.iter().map(|copy| copy.scheme).collect(), + Content::Application { .. } => Vec::new(), + } + } + + /// Rewrites the header and the direct copies, as a relay's edit would. The ID is kept, so the + /// refusal tests check the copies alone. + #[cfg(test)] + pub(crate) fn with_scheme(mut self, header: u32, copy: u32) -> Self { + self.scheme = header; + if let Content::Control { direct, .. } = &mut self.content { + for entry in direct { + entry.scheme = copy; + } + } + self + } } impl GroupMessage for Envelope { @@ -91,7 +131,9 @@ impl GroupMessage for Envelope { fn direct_messages(&self) -> Vec> { match &self.content { - Content::Control { direct, .. } => direct.clone(), + Content::Control { direct, .. } => { + direct.iter().map(|copy| copy.message.clone()).collect() + } Content::Application { .. } => Vec::new(), } } @@ -110,10 +152,11 @@ pub enum OrdererError { pub struct Orderer; impl Orderer { - /// The state before a create or a welcome. - pub const fn init(my_id: VerifyingKey) -> OrdererState { + /// The state before a create or a welcome. Every message this state publishes carries `scheme`. + pub const fn init(my_id: VerifyingKey, scheme: u32) -> OrdererState { OrdererState { my_id, + scheme, next_seq: 0, previous: BTreeMap::new(), messages: BTreeMap::new(), @@ -130,6 +173,8 @@ impl Orderer { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct OrdererState { my_id: VerifyingKey, + /// The scheme version of every message this device publishes. + scheme: u32, next_seq: u64, /// The last control message delivered from each author, including our own. previous: BTreeMap, @@ -152,7 +197,7 @@ impl OrdererState { let seq = self.next_seq; self.next_seq += 1; let previous = self.previous.values().copied().collect(); - let envelope = Envelope::new(seq, self.my_id, previous, content)?; + let envelope = Envelope::new(seq, self.my_id, self.scheme, previous, content)?; self.ready.insert(envelope.id); Ok(envelope) } @@ -186,9 +231,16 @@ impl Ordering for Orderer { control_message: &ControlMessage, direct_messages: &[DirectMessage], ) -> Result<(Self::State, Self::Message), Self::Error> { + let direct = direct_messages + .iter() + .map(|message| Direct { + scheme: y.scheme, + message: message.clone(), + }) + .collect(); let content = Content::Control { control: control_message.clone(), - direct: direct_messages.to_vec(), + direct, }; let envelope = y.publish(content)?; y.previous.insert(y.my_id, envelope.id); diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index f9f7f9a130..a2caf0d105 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -5,6 +5,11 @@ //! each local membership change the adapter checks the crate's roster against that set, so the two //! cannot drift apart without an error. //! +//! The scheme version (P4.4) is the `scheme` of the group's signed policy. [`negotiate`] maps it to +//! the version this build speaks, and the session refuses any message whose header or direct copy +//! names another version. The stock layout (v0) is not shipped, so a stock group is refused, not +//! migrated (scheme-serde RESULTS). +//! //! An add calls `Dcgka::add` with the full secret bundle, then runs the local steps that //! `EncryptionGroup::add` runs. The crate keeps those steps private, and the lower-level call is //! what a smaller bundle (`recent:N`) needs. @@ -35,7 +40,26 @@ use thiserror::Error; use super::ordering::{Envelope, Orderer}; use super::roster::Roster; -use crate::groups::Key; +use crate::groups::{Key, Policy}; + +/// The name the group policy gives this scheme. +pub const DATASCHEME: &str = "datascheme"; + +/// The scheme version this build speaks: `serde_bytes` on the two byte fields of the vendored +/// crate (P4.4). Its welcome costs 40 bytes per epoch, where the stock layout costs 146.5. +pub const SCHEME_V1: u32 = 1; + +/// The scheme version a group's signed policy names, if this build speaks it. +pub fn negotiate(policy: &Policy) -> Result { + match &policy.scheme { + None => Err(SchemeError::NoScheme), + Some(scheme) if scheme.name == DATASCHEME && scheme.version == SCHEME_V1 => Ok(SCHEME_V1), + Some(scheme) => Err(SchemeError::UnsupportedScheme { + name: scheme.name.clone(), + version: scheme.version, + }), + } +} type Pki = KeyRegistry; @@ -79,34 +103,60 @@ pub enum SchemeError { /// The crate's roster and the group model hold different members. #[error("the encryption roster disagrees with the group model: {0}")] RosterMismatch(String), + /// The group's policy names no scheme, so the group is not encrypted. + #[error("the group's policy names no scheme")] + NoScheme, + /// The group's policy names a scheme this build does not speak. A stock group (v0) is refused + /// this way, and nothing is migrated. + #[error("the group's policy names scheme {name} v{version}, which this build does not speak")] + UnsupportedScheme { + /// The scheme's name. + name: String, + /// The version the policy names. + version: u32, + }, + /// A message's header or direct copy names a version other than the group's signed policy. + #[error("the message names scheme v{found}, but the group's signed policy names v{expected}")] + SchemeMismatch { + /// The version the signed policy names. + expected: u32, + /// The version the message names. + found: u32, + }, } /// One device's encryption state for one group. #[derive(Debug)] pub struct Session { me: VerifyingKey, + /// The scheme version the group's signed policy names. + scheme: u32, state: Option, } impl Session { /// A device's state before it creates or joins the group. `registry` must hold the long-term - /// bundles of every member who may take part. + /// bundles of every member who may take part. `policy` is the group's signed policy, and the + /// session refuses a policy that names no scheme or one this build does not speak. pub fn init( me: VerifyingKey, keys: KeyManagerState, registry: KeyRegistryState, - ) -> Self { + policy: &Policy, + ) -> Result { + let scheme = negotiate(policy)?; let state: Group = EncryptionGroup::init( me, keys, registry, Roster::initial_state(), - Orderer::init(me), + Orderer::init(me, scheme), ); - Self { + Ok(Self { me, + scheme, state: Some(state), - } + }) } /// Whether this device has created or joined the group. @@ -212,6 +262,7 @@ impl Session { /// Handles a message from the group. An application message whose secret this device does not /// hold is withheld and not given to the crate (P4.3). pub fn process(&mut self, message: &Envelope) -> Result, SchemeError> { + self.check_scheme(message)?; if let GroupMessageContent::Application { group_secret_id, .. } = message.content() @@ -249,6 +300,21 @@ impl Session { Ok(value) } + /// Refuses a message whose header or any direct copy names another version than the policy. + /// The check runs before the crate sees the message, so a refusal leaves the state as it was. + fn check_scheme(&self, message: &Envelope) -> Result<(), SchemeError> { + let found = std::iter::once(message.scheme()) + .chain(message.direct_schemes()) + .find(|found| *found != self.scheme); + match found { + None => Ok(()), + Some(found) => Err(SchemeError::SchemeMismatch { + expected: self.scheme, + found, + }), + } + } + fn check_roster(&self, model: &BTreeSet) -> Result<(), SchemeError> { let roster = self.members()?; if roster == *model { diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index c206c82da9..24fc5e4a6b 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -6,6 +6,7 @@ use std::collections::{BTreeMap, BTreeSet}; +use p2panda_core::cbor::{decode_cbor, encode_cbor}; use p2panda_core::{SigningKey, VerifyingKey}; use p2panda_encryption::crypto::Rng; use p2panda_encryption::crypto::x25519::SecretKey as IdentitySecret; @@ -16,7 +17,7 @@ use p2panda_encryption::traits::GroupMessage; use proptest::prelude::*; use super::*; -use crate::groups::Key; +use crate::groups::{Key, Policy, Scheme}; fn person(seed: u8) -> (Key, VerifyingKey) { let verifying = SigningKey::from_bytes(&[seed; 32]).verifying_key(); @@ -31,6 +32,17 @@ fn text(message: &str) -> Received { Received::Plaintext(message.as_bytes().to_vec()) } +/// A group policy that names the `datascheme` scheme at `version`. +fn scheme_policy(version: u32) -> Policy { + Policy { + scheme: Some(Scheme { + name: DATASCHEME.to_owned(), + version, + }), + ..Policy::default() + } +} + /// Every person's keys and one session per person, all sharing one registry of bundles. struct Cast { rng: Rng, @@ -55,7 +67,13 @@ impl Cast { let sessions = keys .into_iter() .map(|(key, (verifying, state))| { - let session = Session::init(verifying, state, registry.clone()); + let session = Session::init( + verifying, + state, + registry.clone(), + &scheme_policy(SCHEME_V1), + ) + .expect("session"); (key, session) }) .collect(); @@ -511,6 +529,177 @@ fn test_joiner_cannot_read_a_message_from_before_its_join_and_reads_one_after() ); } +// --- wire (P4.4) ---------------------------------------------------------------------------------- + +/// The CBOR length of the add that welcomes a fourth member after `rotations` updates. Each update +/// adds one secret, and the welcome carries every secret the group holds. +fn add_welcome_len(rotations: usize) -> usize { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + for _ in 0..rotations { + let update = cast.update(1); + cast.deliver(&update, &[2, 3]); + } + let add = cast.add(1, 4); + encode_cbor(&add).expect("encode the add").len() +} + +#[test] +fn test_each_epoch_adds_about_forty_bytes_to_the_welcome() { + // S12: serde_bytes on the two byte fields costs 40.0 bytes per epoch. The stock integer arrays + // cost 146.5. + let grown = add_welcome_len(110) - add_welcome_len(10); + assert!( + (3950..=4050).contains(&grown), + "100 epochs grew the welcome by {grown} bytes, expected about 4000" + ); +} + +#[test] +fn test_v1_bytes_decode_and_the_joiner_reads_them() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + + let add = cast.add(1, 4); + let bytes = encode_cbor(&add).expect("encode the add"); + let received: Envelope = decode_cbor(bytes.as_slice()).expect("decode the add"); + cast.deliver(&received, &[4]); + assert!( + cast.session(4).is_welcomed(), + "the decoded welcome welcomes" + ); + + let message = cast.send(2, "over the wire"); + let bytes = encode_cbor(&message).expect("encode the message"); + let received: Envelope = decode_cbor(bytes.as_slice()).expect("decode the message"); + assert_eq!( + cast.deliver(&received, &[4]), + vec![vec![text("over the wire")]] + ); +} + +#[test] +fn test_an_envelope_re_encodes_to_the_same_bytes() { + // The bundle is sorted inside the welcome, so a decoded envelope is encoded again unchanged. + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + for _ in 0..3 { + let update = cast.update(1); + cast.deliver(&update, &[2, 3]); + } + let add = cast.add(1, 4); + let first = encode_cbor(&add).expect("encode the add"); + let decoded: Envelope = decode_cbor(first.as_slice()).expect("decode the add"); + assert_eq!(encode_cbor(&decoded).expect("encode again"), first); +} + +#[test] +fn test_a_welcome_with_a_v0_copy_is_refused() { + // A relay that rewrites the welcome's copy to the stock version. The header still names v1. + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + let forged = cast.add(1, 4).with_scheme(SCHEME_V1, 0); + + let result = cast + .sessions + .get_mut(&id(4)) + .expect("session") + .process(&forged); + assert!( + matches!( + result, + Err(SchemeError::SchemeMismatch { + expected: SCHEME_V1, + found: 0 + }) + ), + "the welcome's copy is checked against the signed policy: {result:?}" + ); + assert!( + !cast.session(4).is_welcomed(), + "the refused welcome leaves the joiner unwelcomed" + ); +} + +#[test] +fn test_a_header_that_disagrees_with_the_policy_is_refused() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + let message = cast.send(1, "downgraded"); + let forged = message.with_scheme(0, 0); + + let result = cast + .sessions + .get_mut(&id(2)) + .expect("session") + .process(&forged); + assert!( + matches!( + result, + Err(SchemeError::SchemeMismatch { + expected: SCHEME_V1, + found: 0 + }) + ), + "the header is checked against the signed policy: {result:?}" + ); +} + +#[test] +fn test_the_policy_names_the_scheme_this_build_speaks() { + assert!(matches!( + negotiate(&scheme_policy(SCHEME_V1)), + Ok(SCHEME_V1) + )); + assert!(matches!( + negotiate(&Policy::default()), + Err(SchemeError::NoScheme) + )); + assert!(matches!( + negotiate(&scheme_policy(0)), + Err(SchemeError::UnsupportedScheme { version: 0, .. }) + )); + assert!(matches!( + negotiate(&scheme_policy(2)), + Err(SchemeError::UnsupportedScheme { version: 2, .. }) + )); + let other = Policy { + scheme: Some(Scheme { + name: "other".to_owned(), + version: SCHEME_V1, + }), + ..Policy::default() + }; + assert!(matches!( + negotiate(&other), + Err(SchemeError::UnsupportedScheme { .. }) + )); +} + +#[test] +fn test_a_stock_group_is_refused_not_migrated() { + // The stock layout (v0) is not shipped, so a group that names it is refused when a device + // starts its session. Nothing is migrated (scheme-serde RESULTS, the recommendation). + let (_, verifying) = person(1); + let rng = Rng::default(); + let identity = IdentitySecret::from_rng(&rng).expect("identity"); + let keys = new_keys(&identity, Lifetime::default(), &rng).expect("keys"); + let registry = registry(&[]).expect("registry"); + let result = Session::init(verifying, keys, registry, &scheme_policy(0)); + assert!( + matches!( + result, + Err(SchemeError::UnsupportedScheme { version: 0, .. }) + ), + "a stock group is refused when the session starts" + ); +} + // --- property ------------------------------------------------------------------------------------- /// The seeds of the people the group model lists. diff --git a/pkgs/id/vendor/README.md b/pkgs/id/vendor/README.md index 8f737762aa..3293b94d59 100644 --- a/pkgs/id/vendor/README.md +++ b/pkgs/id/vendor/README.md @@ -48,7 +48,15 @@ git -C "$SRC/.." rev-parse HEAD # 3e84cac48bba05c6857cce2ec433862 - `Cargo.toml`: every `workspace = true` is replaced by the root's value, since this copy is outside the p2panda workspace. `[lints] workspace = true` is removed. `p2panda-core` is the same git source and rev, with `default-features = false`, as upstream's workspace declares it. `[dev-dependencies]` is unchanged (none). - `LICENSES/` is added. -**Size.** `src/` differs from upstream by 63 lines added and 2 removed (3 files); `Cargo.toml` by 13 changed lines. +**Scheme v1 (P4.4).** The encoding this fork ships is DataScheme scheme v1, named in the group's signed policy (`src/groups/policy.rs`, `Scheme`). Three changes, all in the fork: + +- `src/two_party/two_party.rs`: `#[serde(with = "serde_bytes")]` on `TwoPartyPlaintext.plaintext`. The stock layout is an array of integers, 146.5 bytes per epoch in the welcome. With it, 40.0 bytes per epoch. +- `src/two_party/x3dh.rs`: the same attribute on `X3dhCiphertext.ciphertext`. Together with the one above, the two fields are byte strings. +- `src/data_scheme/group_secret.rs`: `SecretBundleState` serializes its secrets sorted by (timestamp, ID), not in `HashMap` order. The bundle is encrypted inside the welcome, and sorting keeps its plaintext stable. The test is `bundle_bytes_do_not_depend_on_hash_map_order`. + +v1 and the stock layout do not decode each other. The stock layout is not shipped, so a group whose policy names it is refused when a session starts (`pkgs/id/src/encryption/scheme.rs`, `negotiate`), and nothing is migrated. Source: `doc/2026-10-11T11-08-42Z_design_remaining_work/research-round2/scheme-serde/RESULTS.md`. + +**Size.** `src/` differs from upstream in 6 files, 83 lines added and 4 removed. The S3 patch is 63 added and 2 removed in three files, and scheme v1 is the rest (20 added, 2 removed, in three files). `Cargo.toml` differs by 13 changed lines. **Features.** `data_scheme` on, `test_utils` and `message_scheme` off. The `test_utils` tests in the fork use the crate's own `Network` and `TestDgm`, which the test cfg enables. diff --git a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group_secret.rs b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group_secret.rs index 9e8e4f2b64..e8e8b7307b 100644 --- a/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group_secret.rs +++ b/pkgs/id/vendor/p2panda-encryption/src/data_scheme/group_secret.rs @@ -176,8 +176,12 @@ impl Serialize for SecretBundleState { where S: serde::Serializer, { - let mut s = serializer.serialize_seq(Some(self.secrets.len()))?; - for secret in self.secrets.values() { + // Scheme v1 (P4.4): sorted by timestamp, then ID, so the bytes do not depend on the map's + // iteration order. The bundle is encrypted inside the welcome, and sorting keeps it stable. + let mut secrets: Vec<&GroupSecret> = self.secrets.values().collect(); + secrets.sort_by_cached_key(|secret| (secret.timestamp(), secret.id())); + let mut s = serializer.serialize_seq(Some(secrets.len()))?; + for secret in secrets { s.serialize_element(secret)?; } s.end() @@ -319,10 +323,30 @@ pub enum GroupSecretError { #[cfg(test)] mod tests { + use p2panda_core::cbor::encode_cbor; + use crate::Rng; use super::{GroupSecret, SecretBundle}; + #[test] + fn bundle_bytes_do_not_depend_on_hash_map_order() { + // Scheme v1 (P4.4): the secrets are written sorted by (timestamp, id), so the bytes are the + // same whichever order the map iterates in. Each map has its own random hasher, so the + // unsorted encoding would differ between these builds. + let secrets: Vec = (1..=8u8) + .map(|n| GroupSecret::new([n; 32], u64::from(n % 3))) + .collect(); + let mut sorted = secrets.clone(); + sorted.sort_by_key(|secret| (secret.timestamp(), secret.id())); + let expected = encode_cbor(&sorted).expect("encode the sorted secrets"); + + for _ in 0..16 { + let bundle = SecretBundle::from_secrets(secrets.clone()); + assert_eq!(bundle.to_bytes().expect("encode the bundle"), expected); + } + } + #[test] fn group_secret_bundle() { let rng = Rng::from_seed([1; 32]); diff --git a/pkgs/id/vendor/p2panda-encryption/src/two_party/two_party.rs b/pkgs/id/vendor/p2panda-encryption/src/two_party/two_party.rs index 0ea826a1dc..15907025e2 100644 --- a/pkgs/id/vendor/p2panda-encryption/src/two_party/two_party.rs +++ b/pkgs/id/vendor/p2panda-encryption/src/two_party/two_party.rs @@ -241,6 +241,8 @@ pub enum TwoPartyCiphertext { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TwoPartyPlaintext { /// Secret message for the receiver. + // Scheme v1 (P4.4): a byte string on the wire, not an array of integers. + #[serde(with = "serde_bytes")] plaintext: Vec, /// Newly generated secret for the receiver, to be used in future 2SM rounds. diff --git a/pkgs/id/vendor/p2panda-encryption/src/two_party/x3dh.rs b/pkgs/id/vendor/p2panda-encryption/src/two_party/x3dh.rs index 378cdf5185..5953b97db5 100644 --- a/pkgs/id/vendor/p2panda-encryption/src/two_party/x3dh.rs +++ b/pkgs/id/vendor/p2panda-encryption/src/two_party/x3dh.rs @@ -38,6 +38,8 @@ pub struct X3dhCiphertext { pub prekey_id: PreKeyId, /// Encrypted payload for the receiver. + // Scheme v1 (P4.4): a byte string on the wire, not an array of integers. + #[serde(with = "serde_bytes")] pub ciphertext: Vec, /// Ephemeral public key used for this session. From 67207adde0fe3fccba67a775b7ba31dd83a8c1ce Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:06:54 -0500 Subject: [PATCH 11/21] fix(rust): pre-welcome history stays outside the crate [P4.5] The crate fails a whole call on a group secret it does not hold, and a welcome that receives such a message fails with it. Round 2 saw that in 80 of 120 runs. The adapter now keeps every application message it cannot read in arrival order, outside the crate. A welcome or a later secret releases the messages it unlocks, and the call that does so returns them. The reproduction is a test: the crate refuses 6 of 18 welcomes, exactly where the window leaves an epoch out. --- pkgs/id/src/encryption/history.rs | 4 +- pkgs/id/src/encryption/scheme.rs | 74 +++++++++++++++--- pkgs/id/src/encryption/tests.rs | 121 ++++++++++++++++++++++++++++-- 3 files changed, 179 insertions(+), 20 deletions(-) diff --git a/pkgs/id/src/encryption/history.rs b/pkgs/id/src/encryption/history.rs index a1f0c7f721..5ba9f5ba82 100644 --- a/pkgs/id/src/encryption/history.rs +++ b/pkgs/id/src/encryption/history.rs @@ -19,7 +19,7 @@ use thiserror::Error; use crate::groups::policy::History; /// The window of a preset that keeps a join small: 32 epochs (5.3 KB per join with the stock -/// encoding, 1.7 KB with serde_bytes, at 1,000 rotations; round 2 `welcome-recent`). +/// encoding, 1.7 KB with `serde_bytes`, at 1,000 rotations; round 2 `welcome-recent`). pub const RECENT_SMALL: u32 = 32; /// The window of a preset for churn-heavy worlds that want a longer memory: 128 epochs. @@ -86,7 +86,7 @@ impl FromStr for HistoryMode { let epochs = text .strip_prefix("recent:") .and_then(|count| count.parse::().ok()) - .ok_or_else(|| HistoryModeError::Unknown(text.to_string()))?; + .ok_or_else(|| HistoryModeError::Unknown(text.to_owned()))?; Self::recent(epochs) } } diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index 465cb19e43..609705c93c 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -51,8 +51,8 @@ pub enum Received { Plaintext(Vec), /// A removal that took this device out of the group. Removed, - /// An application message whose group secret this device does not hold. It was not given to the - /// crate, so it can be offered again later, once a welcome or an update brings the secret. + /// An application message whose group secret this device does not hold. The adapter keeps it, + /// and reads it once the secret arrives: a welcome or an update, or lazy history (P4.6). Withheld(Hash), } @@ -87,6 +87,9 @@ pub enum SchemeError { pub struct Session { me: VerifyingKey, state: Option, + /// Application messages this device cannot read yet, in arrival order. They stay out of the + /// crate until their group secret arrives (P4.5). + held: Vec, } impl Session { @@ -107,6 +110,7 @@ impl Session { Self { me, state: Some(state), + held: Vec::new(), } } @@ -234,19 +238,55 @@ impl Session { self.step(|y| EncryptionGroup::send(y, plaintext, rng)) } - /// Handles a message from the group. An application message whose secret this device does not - /// hold is withheld and not given to the crate (P4.3). + /// Handles a message from the group. + /// + /// An application message whose secret this device does not hold is kept here, outside the + /// crate, and reported as [`Received::Withheld`] (P4.3). The crate fails a whole call on a secret + /// it does not hold, so it is never given such a message. A welcome brings the secrets, and the + /// call that does so also reads the held messages it unlocks, in the order they arrived (P4.5). pub fn process(&mut self, message: &Envelope) -> Result, SchemeError> { - if let GroupMessageContent::Application { - group_secret_id, .. - } = message.content() - { - // The crate fails the whole call, and loses the state, on a secret it does not hold. - let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; - if !y.secrets.contains(&group_secret_id) { - return Ok(vec![Received::Withheld(message.id())]); + let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; + if !Self::can_read(y, message) { + if !self.held.iter().any(|held| held.id() == message.id()) { + self.held.push(message.clone()); } + return Ok(vec![Received::Withheld(message.id())]); + } + let mut read = self.receive(message)?; + read.extend(self.release()?); + Ok(read) + } + + /// Whether the crate may take `message` now: a control message always, an application message + /// once the device holds its group secret. + fn can_read(y: &Group, message: &Envelope) -> bool { + match message.content() { + GroupMessageContent::Control(_) => true, + GroupMessageContent::Application { + group_secret_id, .. + } => y.secrets.contains(&group_secret_id), } + } + + /// Gives the crate each held message whose secret the device now holds, in arrival order. + fn release(&mut self) -> Result, SchemeError> { + let held = std::mem::take(&mut self.held); + let (ready, waiting): (Vec, Vec) = match self.state.as_ref() { + Some(y) => held + .into_iter() + .partition(|message| Self::can_read(y, message)), + None => (Vec::new(), held), + }; + self.held = waiting; + let mut read = Vec::new(); + for message in &ready { + read.extend(self.receive(message)?); + } + Ok(read) + } + + /// Hands `message` to the crate and reads its outputs. + fn receive(&mut self, message: &Envelope) -> Result, SchemeError> { let outputs = self.step(|y| EncryptionGroup::receive(y, message))?; Ok(outputs .into_iter() @@ -266,6 +306,16 @@ impl Session { } } + /// Hands `message` to the crate with no secret check. The check is what keeps pre-welcome history + /// out of the crate (P4.5), so only the reproduction of the crate's refusal uses this. + #[cfg(test)] + pub(super) fn process_unchecked( + &mut self, + message: &Envelope, + ) -> Result, SchemeError> { + self.receive(message) + } + /// Runs one crate call. On error the state is gone, so the session is poisoned. fn step(&mut self, op: impl FnOnce(Group) -> Step) -> Result { let y = self.state.take().ok_or(SchemeError::Poisoned)?; diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index 14f42498e1..5b7686a740 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -269,12 +269,12 @@ fn test_recent_welcome_succeeds_for_every_window_and_epoch_count() { let add = cast.add_with_history(1, 4, mode); cast.deliver(&add, &[2, 3, 4]); - let case = format!("{mode} after {rotations} rotations"); - assert!(cast.session(4).is_welcomed(), "{case}: welcomed"); - assert_eq!(cast.members_of(4), cast.model, "{case}: roster"); - assert_eq!(cast.epoch(4), cast.epoch(1), "{case}: newest epoch"); + let label = format!("{mode} after {rotations} rotations"); + assert!(cast.session(4).is_welcomed(), "{label}: welcomed"); + assert_eq!(cast.members_of(4), cast.model, "{label}: roster"); + assert_eq!(cast.epoch(4), cast.epoch(1), "{label}: newest epoch"); let epochs = usize::try_from(window).expect("window").min(rotations + 1); - assert_eq!(cast.session(4).epoch_count(), epochs, "{case}: window"); + assert_eq!(cast.session(4).epoch_count(), epochs, "{label}: window"); let message = cast.send(2, "after the join"); assert_eq!( @@ -284,7 +284,7 @@ fn test_recent_welcome_succeeds_for_every_window_and_epoch_count() { vec![text("after the join")], vec![text("after the join")] ], - "{case}: the joiner reads after its join" + "{label}: the joiner reads after its join" ); } } @@ -310,6 +310,115 @@ fn test_full_welcome_carries_every_epoch() { ); } +/// Builds `rotations` epochs for the group of 1, 2 and 3, and sends one message under each epoch. +/// Members 2 and 3 take every message as it goes. Returns every group message in send order, and +/// the application messages alone, oldest first. +fn history(cast: &mut Cast, rotations: usize) -> (Vec, Vec) { + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + let mut all = vec![create]; + let mut apps = Vec::new(); + for epoch in 0..=rotations { + let message = cast.send(1, &format!("epoch {epoch}")); + cast.deliver(&message, &[2, 3]); + all.push(message.clone()); + apps.push(message); + if epoch < rotations { + let update = cast.update(1); + cast.deliver(&update, &[2, 3]); + all.push(update); + } + } + (all, apps) +} + +/// The crate's refusal, reproduced. A joiner handed its pre-welcome history with no secret check +/// (the crate receives every message) fails its welcome whenever the window leaves an epoch out: +/// `recent:N` with N no larger than the rotations. Round 2 saw this in 80 of 120 runs, and never +/// in a run where the window held every epoch (P4.5, round 2 `welcome-recent` §E6). +#[test] +fn test_crate_refuses_the_welcome_when_pre_welcome_history_names_an_unknown_secret() { + let windows = [Some(1), Some(8), Some(32), Some(128), Some(512), None]; + let mut runs = 0; + let mut refused = 0; + for rotations in [4, 20, 40] { + for window in windows { + let mode = window.map_or(HistoryMode::Full, HistoryMode::Recent); + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (all, _) = history(&mut cast, rotations); + for message in &all { + cast.sessions + .get_mut(&id(4)) + .expect("session") + .process_unchecked(message) + .expect("pre-welcome message"); + } + let add = cast.add_with_history(1, 4, mode); + let welcome = cast + .sessions + .get_mut(&id(4)) + .expect("session") + .process_unchecked(&add); + + runs += 1; + let label = format!("{mode} after {rotations} rotations"); + let expect_refused = + window.is_some_and(|n| usize::try_from(n).expect("window") <= rotations); + assert_eq!(welcome.is_err(), expect_refused, "{label}"); + if let Err(err) = welcome { + refused += 1; + assert!( + matches!(&err, SchemeError::Crate(text) if text.contains("unknown group secret")), + "{label}: {err}" + ); + } + } + } + assert_eq!( + (refused, runs), + (6, 18), + "refused welcomes out of runs, by the pattern above" + ); +} + +/// A recent joiner reads the window of history it was handed before its welcome, in the order it +/// arrived, and refuses the older messages. The welcome releases the window (P4.5). Every window +/// and epoch count is tried. +#[test] +fn test_recent_joiner_reads_its_window_of_history_handed_over_before_the_welcome() { + for window in [1, 8, 32, 128, 512] { + for rotations in [0, 1, 5, 40] { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (all, apps) = history(&mut cast, rotations); + for message in &all { + cast.deliver(message, &[4]); + } + + let add = cast.add_with_history(1, 4, HistoryMode::Recent(window)); + let read = cast + .sessions + .get_mut(&id(4)) + .expect("session") + .process(&add) + .expect("welcome"); + + let epochs = usize::try_from(window).expect("window").min(rotations + 1); + let label = format!("recent:{window} after {rotations} rotations"); + let expected: Vec = (rotations + 1 - epochs..=rotations) + .map(|epoch| text(&format!("epoch {epoch}"))) + .collect(); + assert_eq!(read, expected, "{label}: the window is released"); + if epochs <= rotations { + assert_eq!( + cast.deliver(&apps[0], &[4]), + vec![vec![Received::Withheld(apps[0].id())]], + "{label}: the oldest epoch stays refused" + ); + } + } + } +} + // --- update --------------------------------------------------------------------------------------- #[test] From 25d7d8143afc56dbeccec709c2a03ea9c1664bbf Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:10:02 -0500 Subject: [PATCH 12/21] feat(rust): lazy full history from a member [P4.6] A joiner that holds messages it cannot read asks a member for the secrets they need. The member answers only if both it and the requester are in its roster. The secrets are sealed with HPKE to the requester's identity key, with the request as associated data, so an answer opens only for its request. A request with no answer ends in a timeout, not a hang. --- pkgs/id/src/encryption/history.rs | 78 +++++++++++++++- pkgs/id/src/encryption/scheme.rs | 101 ++++++++++++++++++++- pkgs/id/src/encryption/tests.rs | 146 ++++++++++++++++++++++++++++++ 3 files changed, 321 insertions(+), 4 deletions(-) diff --git a/pkgs/id/src/encryption/history.rs b/pkgs/id/src/encryption/history.rs index 5ba9f5ba82..8960938ea7 100644 --- a/pkgs/id/src/encryption/history.rs +++ b/pkgs/id/src/encryption/history.rs @@ -11,13 +11,89 @@ use std::cmp::Reverse; use std::fmt; +use std::future::Future; use std::str::FromStr; +use std::time::Duration; -use p2panda_encryption::data_scheme::group_secret::{GroupSecret, SecretBundle, SecretBundleState}; +use p2panda_core::VerifyingKey; +use p2panda_encryption::crypto::hpke::HpkeCiphertext; +use p2panda_encryption::data_scheme::group_secret::{ + GroupSecret, GroupSecretId, SecretBundle, SecretBundleState, +}; +use serde::{Deserialize, Serialize}; use thiserror::Error; use crate::groups::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); + +/// A joiner's request for group secrets. It names the secrets its held messages need and no key +/// it does not need, and it names the requester, whose identity key the answer is sealed to. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoryRequest { + pub(super) requester: VerifyingKey, + /// The secrets asked for, by ID, sorted. + pub(super) wanted: Vec, +} + +impl HistoryRequest { + pub(super) const fn new(requester: VerifyingKey, wanted: Vec) -> Self { + Self { requester, wanted } + } +} + +/// A member's answer: the secrets it holds among those asked for, sealed to the requester's +/// identity key. Only the requester can open it, and only for the request it answers. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoryAnswer { + sealed: HpkeCiphertext, +} + +impl HistoryAnswer { + pub(super) const fn new(sealed: HpkeCiphertext) -> Self { + Self { sealed } + } + + pub(super) const fn sealed(&self) -> &HpkeCiphertext { + &self.sealed + } +} + +/// A history request that got no usable answer. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum HistoryError { + /// No member answered in time. A member that is offline never answers. + #[error("no member answered the history request within {0:?}")] + Timeout(Duration), + /// The member that answered holds none of the secrets, or is not in the group, or the requester + /// is not in the group. + #[error( + "no member would answer: the requester is not in the group, or no member holds the secrets asked for" + )] + Refused, +} + +/// Sends `request` through `ask`, and waits up to `wait` for the answer. +/// +/// `ask` is the transport: it reaches a member and returns that member's answer, or `None` when the +/// member refuses. A member that never answers ends the wait in [`HistoryError::Timeout`] (P4.6). +pub async fn ask_member( + request: HistoryRequest, + ask: F, + wait: Duration, +) -> Result +where + F: FnOnce(HistoryRequest) -> Fut, + Fut: Future>, +{ + match tokio::time::timeout(wait, ask(request)).await { + Ok(Some(answer)) => Ok(answer), + Ok(None) => Err(HistoryError::Refused), + Err(_) => Err(HistoryError::Timeout(wait)), + } +} + /// The window of a preset that keeps a join small: 32 epochs (5.3 KB per join with the stock /// encoding, 1.7 KB with `serde_bytes`, at 1,000 rotations; round 2 `welcome-recent`). pub const RECENT_SMALL: u32 = 32; diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index 609705c93c..4c0e7d58ca 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -19,21 +19,25 @@ use std::collections::BTreeSet; +use p2panda_core::cbor::{decode_cbor, encode_cbor}; use p2panda_core::{Hash, VerifyingKey}; use p2panda_encryption::crypto::Rng; +use p2panda_encryption::crypto::hpke::{hpke_open, hpke_seal}; use p2panda_encryption::crypto::x25519::SecretKey; use p2panda_encryption::data_scheme::dcgka::{Dcgka, OperationOutput, ProcessInput}; use p2panda_encryption::data_scheme::group::{ EncryptionGroup, GroupError, GroupOutput, GroupResult, GroupState, }; -use p2panda_encryption::data_scheme::group_secret::{GroupSecret, GroupSecretId}; +use p2panda_encryption::data_scheme::group_secret::{GroupSecret, GroupSecretId, SecretBundle}; use p2panda_encryption::key_bundle::{Lifetime, LongTermKeyBundle}; use p2panda_encryption::key_manager::{KeyManager, KeyManagerState}; use p2panda_encryption::key_registry::{KeyRegistry, KeyRegistryState}; -use p2panda_encryption::traits::{GroupMessage, GroupMessageContent, Ordering as _, PreKeyManager}; +use p2panda_encryption::traits::{ + GroupMessage, GroupMessageContent, IdentityRegistry, Ordering as _, PreKeyManager, +}; use thiserror::Error; -use super::history::HistoryMode; +use super::history::{HistoryAnswer, HistoryMode, HistoryRequest}; use super::ordering::{Envelope, Orderer}; use super::roster::Roster; use crate::groups::Key; @@ -74,6 +78,9 @@ pub enum SchemeError { /// The key is not a member in the group model, so it cannot be added. #[error("{0} is not in the group model, so it cannot be added")] NotInModel(String), + /// An answer carried a secret the request did not ask for, so it is refused. + #[error("the history answer carries a secret the request did not ask for")] + UnaskedSecret, /// The key is still a member in the group model, so it cannot be removed. #[error("{0} is still in the group model, so it cannot be removed")] StillInModel(String), @@ -257,6 +264,91 @@ impl Session { Ok(read) } + /// The secrets this device holds messages for but cannot read, as a request to a member (P4.6). + /// `None` when nothing held is unreadable for want of a secret. + pub fn request_history(&self) -> Option { + let y = self.state.as_ref()?; + let mut wanted = BTreeSet::new(); + for message in &self.held { + if let GroupMessageContent::Application { + group_secret_id, .. + } = message.content() + && !y.secrets.contains(&group_secret_id) + { + wanted.insert(group_secret_id); + } + } + (!wanted.is_empty()).then(|| HistoryRequest::new(self.me, wanted.into_iter().collect())) + } + + /// Answers a joiner's request with the secrets this device holds among those asked for, sealed + /// to the requester's identity key (P4.6). + /// + /// Only a member answers, and only for a member: a device outside the group, or a request from + /// outside the roster, gets `None`. So does a request for no secret this device holds. + pub fn answer_history( + &self, + request: &HistoryRequest, + ) -> Result, SchemeError> { + let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; + let roster = self.members()?; + if !roster.contains(&key_of(self.me)) || !roster.contains(&key_of(request.requester)) { + return Ok(None); + } + let Some(identity) = >::identity_key( + &y.dcgka.pki, + &request.requester, + ) + .map_err(crate_error)? + else { + return Ok(None); + }; + let secrets: Vec = request + .wanted + .iter() + .filter_map(|id| y.secrets.get(id).cloned()) + .collect(); + if secrets.is_empty() { + return Ok(None); + } + let plaintext = encode_cbor(&secrets).map_err(crate_error)?; + let aad = encode_cbor(request).map_err(crate_error)?; + let sealed = hpke_seal(&identity, Some(HISTORY_INFO), Some(&aad), &plaintext) + .map_err(crate_error)?; + Ok(Some(HistoryAnswer::new(sealed))) + } + + /// Opens a member's answer to `request` with this device's identity key, and holds the secrets it + /// carries (P4.6). Returns what the held messages now read. + /// + /// An answer for another request does not open, and a secret the request did not name is + /// refused before anything is held. + pub fn open_history( + &mut self, + request: &HistoryRequest, + answer: &HistoryAnswer, + identity: &SecretKey, + ) -> Result, SchemeError> { + self.ensure_welcomed()?; + let aad = encode_cbor(request).map_err(crate_error)?; + let plaintext = hpke_open(answer.sealed(), identity, Some(HISTORY_INFO), Some(&aad)) + .map_err(crate_error)?; + let secrets: Vec = decode_cbor(plaintext.as_slice()).map_err(crate_error)?; + if secrets + .iter() + .any(|secret| !request.wanted.contains(&secret.id())) + { + return Err(SchemeError::UnaskedSecret); + } + self.step(|y| { + let y = EncryptionGroup::update_secrets(y, |bundle| { + secrets.into_iter().fold(bundle, SecretBundle::insert) + }); + Ok((y, ())) + })?; + self.release() + } + /// Whether the crate may take `message` now: a control message always, an application message /// once the device holds its group secret. fn can_read(y: &Group, message: &Envelope) -> bool { @@ -358,6 +450,9 @@ fn publish(mut y: Group, output: OperationOutput) -> Ok((y, message)) } +/// The associated text of every history answer, so an answer opens only as one (P4.6). +const HISTORY_INFO: &[u8] = b"id/history-answer/v1"; + /// A device's long-term keys: its identity and one pre-key. pub fn new_keys( identity: &SecretKey, diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index 5b7686a740..5127ed9cfd 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -5,6 +5,7 @@ //! to the members who may read them. use std::collections::{BTreeMap, BTreeSet}; +use std::time::Duration; use p2panda_core::{SigningKey, VerifyingKey}; use p2panda_encryption::crypto::Rng; @@ -15,6 +16,7 @@ use p2panda_encryption::key_manager::KeyManagerState; use p2panda_encryption::traits::GroupMessage; use proptest::prelude::*; +use super::history::{HISTORY_WAIT, HistoryAnswer, HistoryError, ask_member}; use super::*; use crate::groups::Key; @@ -35,6 +37,8 @@ fn text(message: &str) -> Received { struct Cast { rng: Rng, sessions: BTreeMap, + /// Each person's identity secret, to open the answers sealed to them. + identities: BTreeMap, /// The member set the group model holds after the last operation. model: BTreeSet, } @@ -44,12 +48,14 @@ impl Cast { let rng = Rng::default(); let mut bundles = Vec::new(); let mut keys: BTreeMap = BTreeMap::new(); + let mut identities = BTreeMap::new(); for seed in seeds { let (key, verifying) = person(*seed); let identity = IdentitySecret::from_rng(&rng).expect("identity"); let state = new_keys(&identity, Lifetime::default(), &rng).expect("keys"); bundles.push((verifying, key_bundle(&state).expect("bundle"))); keys.insert(key, (verifying, state)); + identities.insert(key, identity); } let registry = registry(&bundles).expect("registry"); let sessions = keys @@ -62,6 +68,7 @@ impl Cast { Self { rng, sessions, + identities, model: BTreeSet::new(), } } @@ -70,6 +77,14 @@ impl Cast { self.sessions.get(&id(who)).expect("session") } + fn session_mut(&mut self, who: u8) -> &mut Session { + self.sessions.get_mut(&id(who)).expect("session") + } + + fn identity(&self, who: u8) -> &IdentitySecret { + self.identities.get(&id(who)).expect("identity") + } + fn create(&mut self, by: u8, members: &[u8]) -> Envelope { self.model = members.iter().map(|seed| id(*seed)).collect(); let model = self.model.clone(); @@ -419,6 +434,137 @@ fn test_recent_joiner_reads_its_window_of_history_handed_over_before_the_welcome } } +// --- lazy history --------------------------------------------------------------------------------- + +/// A joiner with a `recent:N` welcome asks a member for the older epochs it was handed and cannot +/// read. The member answers, and the joiner reads them. A key sealed to someone else does not open. +#[test] +fn test_joiner_gets_its_older_epochs_from_a_member() { + let mut cast = Cast::new(&[1, 2, 3, 4, 5]); + let (all, _) = history(&mut cast, 10); + for message in &all { + cast.deliver(message, &[4]); + } + let add = cast.add_with_history(1, 4, HistoryMode::Recent(4)); + cast.deliver(&add, &[4]); + assert_eq!(cast.session(4).epoch_count(), 4, "the window"); + + let request = cast.session(4).request_history().expect("older epochs"); + assert_eq!(request.wanted.len(), 7, "epochs 0 to 6, outside the window"); + + let answer = cast + .session(1) + .answer_history(&request) + .expect("answer") + .expect("a member answers"); + let outsider = cast.identity(5).clone(); + assert!( + cast.session_mut(4) + .open_history(&request, &answer, &outsider) + .is_err(), + "an answer does not open with another identity" + ); + + let identity = cast.identity(4).clone(); + let read = cast + .session_mut(4) + .open_history(&request, &answer, &identity) + .expect("open"); + let expected: Vec = (0..=6) + .map(|epoch| text(&format!("epoch {epoch}"))) + .collect(); + assert_eq!(read, expected, "the older messages, in send order"); + assert_eq!(cast.session(4).epoch_count(), 11, "every epoch now"); + assert!( + cast.session(4).request_history().is_none(), + "nothing left to ask for" + ); +} + +/// Only a member answers, and only a member may ask. A device outside the group gets nothing, and a +/// member refuses a request from outside its roster. +#[test] +fn test_a_non_member_gets_no_history_and_a_non_member_answers_nothing() { + let mut cast = Cast::new(&[1, 2, 3, 4, 5]); + let (all, _) = history(&mut cast, 6); + for message in &all { + cast.deliver(message, &[4, 5]); + } + let add = cast.add_with_history(1, 4, HistoryMode::Recent(2)); + cast.deliver(&add, &[4]); + + let outsider_request = cast + .session(5) + .request_history() + .expect("5 holds messages it cannot read"); + assert!( + cast.session(1) + .answer_history(&outsider_request) + .expect("answer") + .is_none(), + "a member refuses a request from outside its roster" + ); + + let joiner_request = cast.session(4).request_history().expect("4 asks"); + assert!( + cast.session(5) + .answer_history(&joiner_request) + .expect("answer") + .is_none(), + "a device outside the group answers nothing" + ); +} + +/// The answer comes back through the transport, within the wait. +#[tokio::test] +async fn test_a_member_answers_through_the_transport() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (all, _) = history(&mut cast, 3); + for message in &all { + cast.deliver(message, &[4]); + } + let add = cast.add_with_history(1, 4, HistoryMode::Recent(1)); + cast.deliver(&add, &[4]); + let request = cast.session(4).request_history().expect("older epochs"); + + let member = cast.session(1); + let answer = ask_member( + request.clone(), + |asked| std::future::ready(member.answer_history(&asked).expect("answer")), + HISTORY_WAIT, + ) + .await + .expect("answered"); + let identity = cast.identity(4).clone(); + let read = cast + .session_mut(4) + .open_history(&request, &answer, &identity) + .expect("open"); + assert_eq!(read.len(), 3, "the three older epochs"); +} + +/// A member that is offline never answers, and the wait ends in a timeout rather than a hang. +#[tokio::test] +async fn test_a_request_with_no_answer_times_out_cleanly() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (all, _) = history(&mut cast, 2); + for message in &all { + cast.deliver(message, &[4]); + } + let request = cast.session(4).request_history().expect("older epochs"); + + let outcome = ask_member( + request, + |_| std::future::pending::>(), + Duration::from_millis(20), + ) + .await; + assert_eq!( + outcome, + Err(HistoryError::Timeout(Duration::from_millis(20))) + ); +} + // --- update --------------------------------------------------------------------------------------- #[test] From a39cc8344401c3304a0de3897421619c1ab375f6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:11:08 -0500 Subject: [PATCH 13/21] feat(rust): adapter roster follows the group fold [P4.13] The session takes the group's GroupView from groups::fold, and its members are the roster the crate must hold after each local membership change. A mismatch is a refusal, and the session is poisoned rather than kept with a roster the fold does not give. A view whose policy names another scheme is refused before the crate runs. --- .../plan-phases.md | 29 +-- pkgs/id/src/encryption/scheme.rs | 108 +++++--- pkgs/id/src/encryption/tests.rs | 234 ++++++++++++++++-- 3 files changed, 295 insertions(+), 76 deletions(-) diff --git a/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md b/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md index e88cf47dfa..70e3b5beb4 100644 --- a/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md +++ b/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md @@ -135,20 +135,21 @@ Goal: range sync and LogSync on the store, blob gating, and relay defaults that Goal: group encryption on DataScheme, with the history modes, the heads rule, warnings, and the scheme v1. -| Step | What | Blocked by | Parallel with | Tests | -| ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -| P4.1 | DataScheme adapter around the crate: create, add, remove, update, process | Phase 1, P2.1 | P4.4, P4.8, P4.10 | unit; multi-member integration | -| P4.2 | Our DGM and the from_join membership fix, in our fork (decision 18) | P4.1 | P4.4 | regression: a joiner reads messages after joining; the fork's patch has its own test | -| P4.3 | from_join: immediate update, and the withholding rule for pre-join application messages | P4.1, P4.2 | P4.4, P4.5 | integration: a joiner cannot read pre-join messages but reads post-join ones | -| P4.4 | Scheme v1: `serde_bytes` on the two fields, the version bound to the signed policy and copied in the header and welcome envelope, and welcomes sorted before signing (owner question 2) | P4.1 | P4.3, P4.5 | interop: v0 and v1 do not decode each other (verified); size tests (40.0 B per epoch); determinism test: sorted bytes are stable | -| P4.5 | `recent:N` and `full`: the adapter checks the group secret ID before `receive`, and keeps pre-welcome history outside the crate. The reproduction of the 80-of-120 failure comes first, as a red test | P4.1, P3.1 (transport) | P4.3, P4.4 | integration: a `recent:N` joiner reads the last N epochs, is refused older ones, and the welcome succeeds for every N and K combination | -| P4.6 | Lazy full history: a joiner asks a member for older epoch secrets, sent encrypted to the joiner | P4.5 | P4.7 | integration: the request returns the older keys; a non-member gets nothing | -| P4.7 | Heads rule: cap 32, the author's latest event always named, merge when the heads would exceed the cap | P4.1, P1.3 | P4.8 | the S10 scenarios as tests; adversarial order tests | -| P4.8 | Rotation policy (no periodic rotation, N7). PCS recovery is a CLI procedure: remove and re-add (N8) | P4.1, P6.7 (CLI) | P4.7 | integration: a compromised member is replaced and cannot read new epochs | -| P4.9 | Warnings: 96, 128 and 1,000 members (N11); churn warnings (N34); local emission from the server; surfaces in logs and CLI status | P4.1 (counts) | P4.7, P4.8, P4.10 | unit: thresholds; e2e: the server warns at a threshold | -| P4.10 | "scheme: none" notice in the UI and in group metadata (decision 8) | P4.1 | P4.9 | e2e | -| P4.11 | Measure DataScheme update cost at 100, 1,000 and 5,000 members with our adapter, for the BeeKEM comparison | P4.1 | P4.4 to P4.10 | recorded in the phase document; no pass or fail | -| P4.12 | Welcome size budget: chunking above the frame cap (owner question 4) | P4.5 | P4.6 | a `full` welcome above the cap is chunked and reassembled | +| Step | What | Blocked by | Parallel with | Tests | +| ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| P4.1 | DataScheme adapter around the crate: create, add, remove, update, process | Phase 1, P2.1 | P4.4, P4.8, P4.10 | unit; multi-member integration | +| P4.2 | Our DGM and the from_join membership fix, in our fork (decision 18) | P4.1 | P4.4 | regression: a joiner reads messages after joining; the fork's patch has its own test | +| P4.3 | from_join: immediate update, and the withholding rule for pre-join application messages | P4.1, P4.2 | P4.4, P4.5 | integration: a joiner cannot read pre-join messages but reads post-join ones | +| P4.4 | Scheme v1: `serde_bytes` on the two fields, the version bound to the signed policy and copied in the header and welcome envelope, and welcomes sorted before signing (owner question 2) | P4.1 | P4.3, P4.5 | interop: v0 and v1 do not decode each other (verified); size tests (40.0 B per epoch); determinism test: sorted bytes are stable | +| P4.5 | `recent:N` and `full`: the adapter checks the group secret ID before `receive`, and keeps pre-welcome history outside the crate. The reproduction of the 80-of-120 failure comes first, as a red test | P4.1, P3.1 (transport) | P4.3, P4.4 | integration: a `recent:N` joiner reads the last N epochs, is refused older ones, and the welcome succeeds for every N and K combination | +| P4.6 | Lazy full history: a joiner asks a member for older epoch secrets, sent encrypted to the joiner | P4.5 | P4.7 | integration: the request returns the older keys; a non-member gets nothing | +| P4.7 | Heads rule: cap 32, the author's latest event always named, merge when the heads would exceed the cap | P4.1, P1.3 | P4.8 | the S10 scenarios as tests; adversarial order tests | +| P4.8 | Rotation policy (no periodic rotation, N7). PCS recovery is a CLI procedure: remove and re-add (N8) | P4.1, P6.7 (CLI) | P4.7 | integration: a compromised member is replaced and cannot read new epochs | +| P4.9 | Warnings: 96, 128 and 1,000 members (N11); churn warnings (N34); local emission from the server; surfaces in logs and CLI status | P4.1 (counts) | P4.7, P4.8, P4.10 | unit: thresholds; e2e: the server warns at a threshold | +| P4.10 | "scheme: none" notice in the UI and in group metadata (decision 8) | P4.1 | P4.9 | e2e | +| P4.11 | Measure DataScheme update cost at 100, 1,000 and 5,000 members with our adapter, for the BeeKEM comparison | P4.1 | P4.4 to P4.10 | recorded in the phase document; no pass or fail | +| P4.12 | Welcome size budget: chunking above the frame cap (owner question 4) | P4.5 | P4.6 | a `full` welcome above the cap is chunked and reassembled | +| P4.13 | Membership source: the adapter takes its members from the group fold (`GroupView.members` from `groups::fold`), not from the caller. After each local membership change the crate's roster equals the fold's set. A mismatch is a refusal and poisons the session. Remote control messages are not checked yet | P4.1, P2.4 | P4.5, P4.7 | integration: a membership change through the group path updates the roster; a mismatch is refused; property over random changes: the roster equals the fold after each step | ## 10. Phase 5: tags, documents, search diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index a2caf0d105..48a3869939 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -1,9 +1,10 @@ //! The `DataScheme` adapter: one device's encryption state for one group, over `p2panda-encryption`. //! -//! Membership comes from the group model. The caller passes the member set the model holds after -//! the event (the `members` of [`crate::groups::GroupView`], from [`crate::groups::fold`]). After -//! each local membership change the adapter checks the crate's roster against that set, so the two -//! cannot drift apart without an error. +//! Membership comes from the group model. The caller passes the [`crate::groups::GroupView`] the +//! fold ([`crate::groups::fold`]) gives after the event, and the adapter takes its members from +//! that view. After each local membership change the adapter checks the crate's roster against the +//! view's members. A mismatch is a refusal, and it poisons the session, so the two cannot drift +//! apart without an error. //! //! The scheme version (P4.4) is the `scheme` of the group's signed policy. [`negotiate`] maps it to //! the version this build speaks, and the session refuses any message whose header or direct copy @@ -40,7 +41,7 @@ use thiserror::Error; use super::ordering::{Envelope, Orderer}; use super::roster::Roster; -use crate::groups::{Key, Policy}; +use crate::groups::{GroupView, Key, Policy}; /// The name the group policy gives this scheme. pub const DATASCHEME: &str = "datascheme"; @@ -172,40 +173,36 @@ impl Session { /// The members the crate's roster holds, as group-model keys. pub fn members(&self) -> Result, SchemeError> { let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; - let members = EncryptionGroup::members(y).map_err(crate_error)?; - Ok(members.into_iter().map(key_of).collect()) + roster_of(y) } - /// Creates the group with `model` as its members. This device must be one of them. - pub fn create(&mut self, model: &BTreeSet, rng: &Rng) -> Result { - if !model.contains(&key_of(self.me)) { + /// Creates the group with the members `view` lists, as the group fold gives them. This device + /// must be one of them. + pub fn create(&mut self, view: &GroupView, rng: &Rng) -> Result { + if !view.members.contains_key(&key_of(self.me)) { return Err(SchemeError::NotInModel(short(key_of(self.me)))); } - let initial: Vec = members_of(model)?; - let message = self.step(|y| EncryptionGroup::create(y, initial, rng))?; - self.check_roster(model)?; - Ok(message) + let initial: Vec = members_of(&model_of(view))?; + self.change(view, |y| EncryptionGroup::create(y, initial, rng)) } - /// Adds `added`, which `model` must already list, with a welcome that carries the full bundle. + /// Adds `added`, which `view` must already list, with a welcome that carries the full bundle. pub fn add( &mut self, - model: &BTreeSet, + view: &GroupView, added: Key, rng: &Rng, ) -> Result { self.ensure_welcomed()?; - if !model.contains(&added) { + if !view.members.contains_key(&added) { return Err(SchemeError::NotInModel(short(added))); } let added_key = member_of(added)?; - let message = self.step(|mut y| { + self.change(view, |mut y| { let (dcgka, output) = Dcgka::add(y.dcgka, added_key, &y.secrets, rng)?; y.dcgka = dcgka; publish(y, output) - })?; - self.check_roster(model)?; - Ok(message) + }) } /// Adds `added` by a join: a welcome that carries no earlier secret, then an immediate update. @@ -215,36 +212,33 @@ impl Session { /// delivered too. Returns the add and the update, in the order they are delivered. pub fn add_from_join( &mut self, - model: &BTreeSet, + view: &GroupView, added: Key, rng: &Rng, ) -> Result, SchemeError> { self.ensure_welcomed()?; - if !model.contains(&added) { + if !view.members.contains_key(&added) { return Err(SchemeError::NotInModel(short(added))); } let added_key = member_of(added)?; - let add = self.step(|y| EncryptionGroup::add_from_join(y, added_key, rng))?; - let update = self.step(|y| EncryptionGroup::update(y, rng))?; - self.check_roster(model)?; + let add = self.change(view, |y| EncryptionGroup::add_from_join(y, added_key, rng))?; + let update = self.change(view, |y| EncryptionGroup::update(y, rng))?; Ok(vec![add, update]) } - /// Removes `removed`, which `model` must no longer list. The removal rotates the epoch. + /// Removes `removed`, which `view` must no longer list. The removal rotates the epoch. pub fn remove( &mut self, - model: &BTreeSet, + view: &GroupView, removed: Key, rng: &Rng, ) -> Result { self.ensure_welcomed()?; - if model.contains(&removed) { + if view.members.contains_key(&removed) { return Err(SchemeError::StillInModel(short(removed))); } let removed_key = member_of(removed)?; - let message = self.step(|y| EncryptionGroup::remove(y, removed_key, rng))?; - self.check_roster(model)?; - Ok(message) + self.change(view, |y| EncryptionGroup::remove(y, removed_key, rng)) } /// Rotates the epoch by giving every current member a new secret. @@ -315,15 +309,42 @@ impl Session { } } - fn check_roster(&self, model: &BTreeSet) -> Result<(), SchemeError> { - let roster = self.members()?; - if roster == *model { + /// Refuses a view whose policy names another scheme than the session's. A scheme change needs a + /// new epoch (task-05 item 6), which is not built yet, so the session does not follow it. + fn check_policy(&self, view: &GroupView) -> Result<(), SchemeError> { + let scheme = negotiate(&view.policy)?; + if scheme == self.scheme { return Ok(()); } + Err(SchemeError::SchemeMismatch { + expected: self.scheme, + found: scheme, + }) + } + + /// Runs one membership change, then checks the crate's roster against the fold's members. The + /// state is taken, as in [`Self::step`]. A mismatch therefore leaves the session poisoned: it + /// cannot go on with a roster the fold does not give (P4.13). + fn change( + &mut self, + view: &GroupView, + op: impl FnOnce(Group) -> Step, + ) -> Result { + self.check_policy(view)?; + let y = self.state.take().ok_or(SchemeError::Poisoned)?; + let (y, value) = op(y).map_err(crate_error)?; + let roster = roster_of(&y)?; + let model = model_of(view); + if roster == model { + self.state = Some(y); + return Ok(value); + } + let only_roster: Vec = roster.difference(&model).map(|key| short(*key)).collect(); + let only_fold: Vec = model.difference(&roster).map(|key| short(*key)).collect(); Err(SchemeError::RosterMismatch(format!( - "the roster has {} members, the model {}", - roster.len(), - model.len() + "in the roster only: [{}]; in the fold only: [{}]", + only_roster.join(", "), + only_fold.join(", ") ))) } } @@ -380,6 +401,17 @@ pub fn key_of(member: VerifyingKey) -> Key { *member.as_bytes() } +/// The members the crate's roster holds, as group-model keys. +fn roster_of(y: &Group) -> Result, SchemeError> { + let members = EncryptionGroup::members(y).map_err(crate_error)?; + Ok(members.into_iter().map(key_of).collect()) +} + +/// The members the group fold gives: the keys of [`GroupView::members`]. +fn model_of(view: &GroupView) -> BTreeSet { + view.members.keys().copied().collect() +} + fn member_of(key: Key) -> Result { VerifyingKey::from_bytes(&key).map_err(|err| SchemeError::InvalidKey(err.to_string())) } diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index 24fc5e4a6b..58394e2190 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, BTreeSet}; use p2panda_core::cbor::{decode_cbor, encode_cbor}; -use p2panda_core::{SigningKey, VerifyingKey}; +use p2panda_core::{Hash, SigningKey, VerifyingKey}; use p2panda_encryption::crypto::Rng; use p2panda_encryption::crypto::x25519::SecretKey as IdentitySecret; use p2panda_encryption::data_scheme::group_secret::GroupSecretId; @@ -17,7 +17,9 @@ use p2panda_encryption::traits::GroupMessage; use proptest::prelude::*; use super::*; -use crate::groups::{Key, Policy, Scheme}; +use crate::groups::{ + Body, Create, Event, GroupView, Key, MemberOp, Policy, Role, Scheme, Template, fold, +}; fn person(seed: u8) -> (Key, VerifyingKey) { let verifying = SigningKey::from_bytes(&[seed; 32]).verifying_key(); @@ -43,10 +45,24 @@ fn scheme_policy(version: u32) -> Policy { } } +/// A view that lists `members` as Admins. For the checks that run before any fold. +fn view_of(members: &BTreeSet) -> GroupView { + GroupView { + policy: scheme_policy(SCHEME_V1), + members: members.iter().map(|key| (*key, Role::Admin)).collect(), + friendship: None, + present: BTreeSet::new(), + dissolved_by: None, + } +} + /// Every person's keys and one session per person, all sharing one registry of bundles. struct Cast { rng: Rng, sessions: BTreeMap, + /// The group's signed events, in order. The first is the create, and the group model is their + /// fold. + events: Vec, /// The member set the group model holds after the last operation. model: BTreeSet, } @@ -80,6 +96,7 @@ impl Cast { Self { rng, sessions, + events: Vec::new(), model: BTreeSet::new(), } } @@ -88,44 +105,101 @@ impl Cast { self.sessions.get(&id(who)).expect("session") } + /// The group's view as the fold gives it after the events so far. + fn view(&self) -> GroupView { + let create = self.events.first().expect("a create").id; + let projection = fold(&self.events).expect("fold"); + projection.group(&create).expect("the group").clone() + } + + /// Appends a membership event by `by` to the group's log, and returns the view after it. + fn log(&mut self, by: u8, body: Body) -> GroupView { + let group = self.events.first().map(|create| create.id); + let after = self.events.last().map(|last| last.id).into_iter().collect(); + let name = format!("event {}", self.events.len()); + self.events.push(Event { + id: Hash::digest(name.as_bytes()), + author: id(by), + after, + group, + body, + }); + let view = self.view(); + self.model = view.members.keys().copied().collect(); + view + } + fn create(&mut self, by: u8, members: &[u8]) -> Envelope { - self.model = members.iter().map(|seed| id(*seed)).collect(); - let model = self.model.clone(); + let others = members + .iter() + .filter(|seed| **seed != by) + .map(|seed| (id(*seed), Role::Admin)) + .collect(); + let create = Event { + id: Hash::digest(b"event 0"), + author: id(by), + after: Vec::new(), + group: None, + body: Body::Create(Create { + template: Template::Custom, + policy: scheme_policy(SCHEME_V1), + members: others, + admins_on_create: false, + }), + }; + self.events = vec![create]; + let view = self.view(); + self.model = view.members.keys().copied().collect(); self.sessions .get_mut(&id(by)) .expect("session") - .create(&model, &self.rng) + .create(&view, &self.rng) .expect("create") } fn add(&mut self, by: u8, who: u8) -> Envelope { - self.model.insert(id(who)); - let model = self.model.clone(); + let view = self.log( + by, + Body::Member(MemberOp::Add { + member: id(who), + role: Role::Admin, + }), + ); self.sessions .get_mut(&id(by)) .expect("session") - .add(&model, id(who), &self.rng) + .add(&view, id(who), &self.rng) .expect("add") } fn remove(&mut self, by: u8, who: u8) -> Envelope { - self.model.remove(&id(who)); - let model = self.model.clone(); + let view = self.log( + by, + Body::Member(MemberOp::Remove { + member: id(who), + successor: None, + }), + ); self.sessions .get_mut(&id(by)) .expect("session") - .remove(&model, id(who), &self.rng) + .remove(&view, id(who), &self.rng) .expect("remove") } /// A join through `add_from_join`: the add, then the immediate update. fn join(&mut self, by: u8, who: u8) -> Vec { - self.model.insert(id(who)); - let model = self.model.clone(); + let view = self.log( + by, + Body::Member(MemberOp::Add { + member: id(who), + role: Role::Admin, + }), + ); self.sessions .get_mut(&id(by)) .expect("session") - .add_from_join(&model, id(who), &self.rng) + .add_from_join(&view, id(who), &self.rng) .expect("add_from_join") } @@ -186,13 +260,13 @@ fn test_create_gives_every_member_the_model_roster() { #[test] fn test_create_rejects_a_device_outside_the_model() { let mut cast = Cast::new(&[1, 2]); - let model: BTreeSet = std::iter::once(id(2)).collect(); + let view = view_of(&std::iter::once(id(2)).collect()); let rng = Rng::default(); let result = cast .sessions .get_mut(&id(1)) .expect("session") - .create(&model, &rng); + .create(&view, &rng); assert!(matches!(result, Err(SchemeError::NotInModel(_)))); assert!( !cast.session(1).is_welcomed(), @@ -213,9 +287,9 @@ fn test_operations_before_create_are_rejected_without_poisoning() { session.update(&rng), Err(SchemeError::NotWelcomed) )); - let create_model: BTreeSet = [id(1), id(2)].into_iter().collect(); + let view = view_of(&[id(1), id(2)].into_iter().collect()); assert!( - session.create(&create_model, &rng).is_ok(), + session.create(&view, &rng).is_ok(), "the session still creates" ); } @@ -246,13 +320,13 @@ fn test_add_rejects_a_key_the_model_does_not_list() { let create = cast.create(1, &[1, 2]); cast.deliver(&create, &[2]); - let model = cast.model.clone(); + let view = cast.view(); let rng = Rng::default(); let result = cast .sessions .get_mut(&id(1)) .expect("session") - .add(&model, id(3), &rng); + .add(&view, id(3), &rng); assert!(matches!(result, Err(SchemeError::NotInModel(_)))); assert_eq!(cast.members_of(1), cast.model, "the roster is untouched"); } @@ -323,13 +397,13 @@ fn test_remove_rejects_a_member_the_model_still_lists() { let create = cast.create(1, &[1, 2, 3]); cast.deliver(&create, &[2, 3]); - let model = cast.model.clone(); + let view = cast.view(); let rng = Rng::default(); let result = cast .sessions .get_mut(&id(1)) .expect("session") - .remove(&model, id(3), &rng); + .remove(&view, id(3), &rng); assert!(matches!(result, Err(SchemeError::StillInModel(_)))); } @@ -456,13 +530,13 @@ fn test_from_join_rejects_a_key_the_model_does_not_list() { let create = cast.create(1, &[1, 2, 3]); cast.deliver(&create, &[2, 3, 4]); - let model = cast.model.clone(); + let view = cast.view(); let rng = Rng::default(); let result = cast .sessions .get_mut(&id(1)) .expect("session") - .add_from_join(&model, id(4), &rng); + .add_from_join(&view, id(4), &rng); assert!(matches!(result, Err(SchemeError::NotInModel(_)))); assert_eq!(cast.members_of(1), cast.model, "the roster is untouched"); } @@ -700,6 +774,118 @@ fn test_a_stock_group_is_refused_not_migrated() { ); } +// --- the roster follows the fold (P4.13) ---------------------------------------------------------- + +#[test] +fn test_a_membership_change_through_the_group_path_updates_the_roster() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2]); + cast.deliver(&create, &[2]); + assert_eq!(cast.members_of(1), [id(1), id(2)].into_iter().collect()); + + cast.add(1, 3); + assert_eq!( + cast.members_of(1), + [id(1), id(2), id(3)].into_iter().collect(), + "an add through the fold reaches the roster" + ); + + cast.remove(1, 2); + assert_eq!( + cast.members_of(1), + [id(1), id(3)].into_iter().collect(), + "a removal through the fold reaches the roster" + ); +} + +#[test] +fn test_a_view_that_disagrees_with_the_roster_is_refused_and_poisons_the_session() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2]); + cast.deliver(&create, &[2]); + + // The fold lists 4 as well, but the crate is only asked to add 3. + let mut view = cast.view(); + view.members.insert(id(3), Role::Admin); + view.members.insert(id(4), Role::Admin); + let rng = Rng::default(); + let result = cast + .sessions + .get_mut(&id(1)) + .expect("session") + .add(&view, id(3), &rng); + assert!( + matches!(result, Err(SchemeError::RosterMismatch(_))), + "a mismatch is refused: {result:?}" + ); + assert!( + matches!(cast.session(1).members(), Err(SchemeError::Poisoned)), + "the session does not keep a roster the fold disagrees with" + ); + assert!(matches!( + cast.sessions + .get_mut(&id(1)) + .expect("session") + .send(b"after", &rng), + Err(SchemeError::Poisoned) + )); +} + +#[test] +fn test_a_view_whose_policy_names_no_scheme_is_refused_without_poisoning() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2]); + cast.deliver(&create, &[2]); + + let mut view = cast.view(); + view.policy = Policy::default(); + view.members.insert(id(3), Role::Admin); + let rng = Rng::default(); + let result = cast + .sessions + .get_mut(&id(1)) + .expect("session") + .add(&view, id(3), &rng); + assert!(matches!(result, Err(SchemeError::NoScheme)), "{result:?}"); + assert_eq!( + cast.members_of(1), + [id(1), id(2)].into_iter().collect(), + "the refused change left the roster as it was" + ); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(32))] + + /// Random adds, joins and removes through the group path. After each one, the creator's roster + /// is the set of members the fold gives. + #[test] + fn test_roster_follows_the_fold_through_random_changes( + ops in proptest::collection::vec((0u8..3, 2u8..6), 1..24), + ) { + let mut cast = Cast::new(&[1, 2, 3, 4, 5]); + let create = cast.create(1, &[1, 2]); + cast.deliver(&create, &[2]); + for (kind, who) in ops { + let present = cast.model.contains(&id(who)); + match kind { + 0 if !present => { + cast.add(1, who); + } + 1 if !present => { + cast.join(1, who); + } + 2 if present => { + cast.remove(1, who); + } + _ => continue, + } + let folded: BTreeSet = cast.view().members.keys().copied().collect(); + prop_assert_eq!(cast.members_of(1), folded, "after {} of {}", kind, who); + } + } +} + // --- property ------------------------------------------------------------------------------------- /// The seeds of the people the group model lists. From 3b671bb40ee4d6c1cb70b960e8ab1b4ae565a7f1 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:12:36 -0500 Subject: [PATCH 14/21] fix(rust): encode the scheme copies as pairs, within the 5 to 12 byte budget [P4.4] A named struct costs 17 bytes per direct message in CBOR (a map header and two text keys). A pair costs 2, so the header copy (8 bytes) and one welcome copy (2 bytes) come to 10 bytes. --- pkgs/id/src/encryption/ordering.rs | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/pkgs/id/src/encryption/ordering.rs b/pkgs/id/src/encryption/ordering.rs index 79867f0467..e7edb195c5 100644 --- a/pkgs/id/src/encryption/ordering.rs +++ b/pkgs/id/src/encryption/ordering.rs @@ -51,12 +51,9 @@ enum Content { /// A direct message with the scheme version it was encoded under. The copy lets a recipient check /// the version before the crate reads the message. A joiner has no group state yet, so the welcome -/// copy is the only check it has. +/// copy is the only check it has. It is a pair, so the copy costs two bytes on the wire (P4.4). #[derive(Clone, Debug, Serialize, Deserialize)] -struct Direct { - scheme: u32, - message: DirectMessage, -} +struct Direct(u32, DirectMessage); impl Envelope { fn new( @@ -86,7 +83,7 @@ impl Envelope { /// message. pub fn direct_schemes(&self) -> Vec { match &self.content { - Content::Control { direct, .. } => direct.iter().map(|copy| copy.scheme).collect(), + Content::Control { direct, .. } => direct.iter().map(|copy| copy.0).collect(), Content::Application { .. } => Vec::new(), } } @@ -98,7 +95,7 @@ impl Envelope { self.scheme = header; if let Content::Control { direct, .. } = &mut self.content { for entry in direct { - entry.scheme = copy; + entry.0 = copy; } } self @@ -131,9 +128,7 @@ impl GroupMessage for Envelope { fn direct_messages(&self) -> Vec> { match &self.content { - Content::Control { direct, .. } => { - direct.iter().map(|copy| copy.message.clone()).collect() - } + Content::Control { direct, .. } => direct.iter().map(|copy| copy.1.clone()).collect(), Content::Application { .. } => Vec::new(), } } @@ -233,10 +228,7 @@ impl Ordering for Orderer { ) -> Result<(Self::State, Self::Message), Self::Error> { let direct = direct_messages .iter() - .map(|message| Direct { - scheme: y.scheme, - message: message.clone(), - }) + .map(|message| Direct(y.scheme, message.clone())) .collect(); let content = Content::Control { control: control_message.clone(), From c38e6a39a97e2034f145df1039c18c43263b1a28 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:14:14 -0500 Subject: [PATCH 15/21] feat(rust): chunked welcomes above the frame cap [P4.12] A welcome above one world frame is split into chunks. Each chunk carries its position, the total, the digest of the whole and a check on its own bytes. The reassembly refuses an altered chunk as it arrives, a chunk out of sequence, a chunk of another welcome, and a whole that does not match its digest. The envelope is decoded only once the whole checks out. A chunk's payload is the frame less a 256-byte header budget (1 MiB frame: 1,048,320 bytes). --- pkgs/id/src/encryption/mod.rs | 6 +- pkgs/id/src/encryption/tests.rs | 160 +++++++++++++++++++++- pkgs/id/src/encryption/welcome.rs | 212 ++++++++++++++++++++++++++++++ 3 files changed, 375 insertions(+), 3 deletions(-) create mode 100644 pkgs/id/src/encryption/welcome.rs diff --git a/pkgs/id/src/encryption/mod.rs b/pkgs/id/src/encryption/mod.rs index 3e5830efa3..f0d83ed839 100644 --- a/pkgs/id/src/encryption/mod.rs +++ b/pkgs/id/src/encryption/mod.rs @@ -1,4 +1,4 @@ -//! Group encryption on the `DataScheme` of `p2panda-encryption` (Phase 4, P4.1 to P4.3). +//! Group encryption on the `DataScheme` of `p2panda-encryption` (Phase 4, P4.1 to P4.6 and P4.12). //! //! - [`scheme`]: the adapter. One [`Session`] per device and group, with create, add, remove, //! update, send and process. Membership comes from the group model: the caller passes the member @@ -6,7 +6,8 @@ //! - [`roster`]: the membership the crate keeps. The adapter checks it against the model after each //! local membership change. //! - [`ordering`]: causal delivery, and the [`Envelope`] messages travel in. -//! - [`history`]: the history modes a welcome is cut to (`full` or `recent:N`). +//! - [`history`]: the history modes a welcome is cut to (`full` or `recent:N`), and lazy history. +//! - [`welcome`]: a welcome above the frame cap, split into checked chunks. //! //! A group member is the key the group model holds (`crate::groups::Key`). The crate's identity is //! the matching `p2panda_core::VerifyingKey`. @@ -15,6 +16,7 @@ pub mod history; pub mod ordering; pub mod roster; pub mod scheme; +pub mod welcome; pub use history::{HistoryMode, HistoryModeError}; pub use ordering::{Envelope, Orderer, OrdererError}; diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index 5127ed9cfd..2498335ab0 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -7,7 +7,8 @@ use std::collections::{BTreeMap, BTreeSet}; use std::time::Duration; -use p2panda_core::{SigningKey, VerifyingKey}; +use p2panda_core::cbor::encode_cbor; +use p2panda_core::{Hash, SigningKey, VerifyingKey}; use p2panda_encryption::crypto::Rng; use p2panda_encryption::crypto::x25519::SecretKey as IdentitySecret; use p2panda_encryption::data_scheme::group_secret::GroupSecretId; @@ -17,6 +18,7 @@ use p2panda_encryption::traits::GroupMessage; use proptest::prelude::*; use super::history::{HISTORY_WAIT, HistoryAnswer, HistoryError, ask_member}; +use super::welcome::{CHUNK_HEADER_BYTES, Reassembly, WelcomeError, split}; use super::*; use crate::groups::Key; @@ -565,6 +567,162 @@ async fn test_a_request_with_no_answer_times_out_cleanly() { ); } +// --- welcome chunks ------------------------------------------------------------------------------- + +/// A frame small enough that a welcome of a few epochs needs several chunks. A chunk is then +/// `FRAME - CHUNK_HEADER_BYTES` bytes of payload. +const SMALL_FRAME: usize = 512; + +/// The group of 1, 2 and 3 after `rotations` updates, with 4 holding every control message. Returns +/// the full welcome for 4, and the update that was sent last. +fn full_welcome(cast: &mut Cast, rotations: usize) -> (Envelope, Envelope) { + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + let mut last = create; + for _ in 0..rotations { + last = cast.update(1); + cast.deliver(&last, &[2, 3, 4]); + } + (cast.add(1, 4), last) +} + +/// A full welcome above the frame cap is split into checked chunks, reassembled, and processed. +#[test] +fn test_a_full_welcome_above_the_cap_is_split_and_reassembled() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (add, _) = full_welcome(&mut cast, 20); + + let chunks = split(&add, SMALL_FRAME).expect("split"); + assert!(chunks.len() > 1, "a full welcome above the cap is split"); + for chunk in &chunks { + let encoded = encode_cbor(chunk).expect("encode").len(); + assert!( + encoded <= SMALL_FRAME, + "chunk {} fits the frame", + chunk.index + ); + assert!( + encoded - chunk.bytes.len() <= CHUNK_HEADER_BYTES, + "the header of chunk {} is within its budget", + chunk.index + ); + } + + let mut joiner = Reassembly::default(); + let mut whole = None; + for chunk in chunks { + if let Some(envelope) = joiner.push(&chunk).expect("in order and intact") { + whole = Some(envelope); + } + } + let whole = whole.expect("the last chunk completes the welcome"); + joiner.finish().expect("complete"); + + assert_eq!( + cast.sessions + .get_mut(&id(4)) + .expect("session") + .process(&whole) + .expect("welcome"), + Vec::new() + ); + assert!( + cast.session(4).is_welcomed(), + "the reassembled welcome welcomes" + ); + assert_eq!(cast.session(4).epoch_count(), 21, "every epoch"); +} + +/// A welcome that fits one frame is one chunk, so every welcome takes the same path. +#[test] +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"); + assert_eq!(chunks.len(), 1); + let mut joiner = Reassembly::default(); + assert!(joiner.push(&chunks[0]).expect("one chunk").is_some()); +} + +/// A chunk whose bytes were altered in transit is refused as it arrives. +#[test] +fn test_a_corrupted_chunk_is_refused() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (add, _) = full_welcome(&mut cast, 20); + let mut chunks = split(&add, SMALL_FRAME).expect("split"); + chunks[1].bytes[0] ^= 0x01; + + let mut joiner = Reassembly::default(); + assert!(joiner.push(&chunks.remove(0)).expect("chunk 0").is_none()); + assert_eq!( + joiner.push(&chunks.remove(0)).err(), + Some(WelcomeError::AlteredChunk { index: 1 }) + ); +} + +/// A missing chunk is refused: the next one that arrives is out of sequence, and a reassembly that +/// ends early is incomplete. +#[test] +fn test_a_missing_chunk_is_refused() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (add, _) = full_welcome(&mut cast, 20); + let mut chunks = split(&add, SMALL_FRAME).expect("split"); + assert!(chunks.len() >= 3, "the test needs a middle chunk"); + + let mut joiner = Reassembly::default(); + assert!(joiner.push(&chunks.remove(0)).expect("chunk 0").is_none()); + let skipped = chunks.remove(0); + assert_eq!(skipped.index, 1); + assert_eq!( + joiner.push(&chunks.remove(0)).err(), + Some(WelcomeError::OutOfSequence { + expected: 1, + got: 2 + }) + ); + assert!(matches!( + joiner.finish(), + Err(WelcomeError::Incomplete { received: 1, .. }) + )); +} + +/// A chunk that checks and keeps its own digest, but carries altered bytes, passes each check and +/// fails the whole. The welcome is refused before it is decoded. +#[test] +fn test_an_altered_welcome_with_consistent_checks_is_refused_before_decoding() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (add, _) = full_welcome(&mut cast, 20); + let mut chunks = split(&add, SMALL_FRAME).expect("split"); + let last = chunks.len() - 1; + chunks[last].bytes[0] ^= 0x01; + chunks[last].check = Hash::digest(&chunks[last].bytes); + + let mut joiner = Reassembly::default(); + let mut outcome = Ok(None); + for chunk in chunks { + outcome = joiner.push(&chunk); + } + assert_eq!(outcome.err(), Some(WelcomeError::AlteredWelcome)); +} + +/// A chunk of another welcome does not join this one. +#[test] +fn test_a_chunk_of_another_welcome_is_refused() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let (add, update) = full_welcome(&mut cast, 20); + let mut chunks = split(&add, SMALL_FRAME).expect("split"); + let other = split(&update, SMALL_FRAME).expect("split"); + + let mut joiner = Reassembly::default(); + assert!(joiner.push(&chunks.remove(0)).expect("chunk 0").is_none()); + assert_eq!( + joiner + .push(&other.into_iter().nth(1).expect("chunk 1 of the other")) + .err(), + Some(WelcomeError::OtherWelcome) + ); +} + // --- update --------------------------------------------------------------------------------------- #[test] diff --git a/pkgs/id/src/encryption/welcome.rs b/pkgs/id/src/encryption/welcome.rs new file mode 100644 index 0000000000..6cf717df8e --- /dev/null +++ b/pkgs/id/src/encryption/welcome.rs @@ -0,0 +1,212 @@ +//! Welcome chunking above the frame cap (P4.12). +//! +//! A welcome is the envelope that adds a member, and it grows with the epochs it carries: about 40 +//! bytes an epoch with `serde_bytes`. A full welcome passes one world frame of +//! [`MAX_FRAME_BYTES`] at about 26,000 rotations (round 2 `welcome-recent`, extrapolated). Past +//! that, the welcome goes as chunks. +//! +//! [`split`] cuts the encoded envelope into chunks that each fit a frame. Every chunk names its +//! position, the total, the digest of the whole welcome, and a check on its own bytes. The +//! [`Reassembly`] on the joiner's side refuses an altered chunk as it arrives, refuses a chunk out +//! of sequence, and refuses the whole when its digest does not match. The envelope is decoded only +//! after the whole checks out. + +use std::num::TryFromIntError; + +use p2panda_core::Hash; +use p2panda_core::cbor::{decode_cbor, encode_cbor}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use super::ordering::Envelope; +use crate::world_session::MAX_FRAME_BYTES; + +/// Bytes a chunk spends on everything but its payload: its position, the total, the two digests +/// and their CBOR framing. +/// +/// Generous, so a chunk of payload `frame_cap - CHUNK_HEADER_BYTES` fits a frame of `frame_cap` +/// bytes. +pub const CHUNK_HEADER_BYTES: usize = 256; + +/// The payload one chunk carries in a world frame: the frame less its header budget. +pub const CHUNK_PAYLOAD_BYTES: usize = MAX_FRAME_BYTES - CHUNK_HEADER_BYTES; + +/// One part of a welcome. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Chunk { + /// This chunk's position, from 0. + pub(super) index: u32, + /// How many chunks the welcome has. Never zero. + pub(super) total: u32, + /// Digest of the whole encoded envelope. + pub(super) digest: Hash, + /// Digest of this chunk's bytes, so an altered chunk is refused as it arrives. + pub(super) check: Hash, + #[serde(with = "byte_string")] + pub(super) bytes: Vec, +} + +/// The payload as one CBOR byte string. A `Vec` would encode as an array of integers, nearly +/// twice the size. +mod byte_string { + use std::fmt; + + use serde::de::Visitor; + use serde::{Deserializer, Serializer}; + + pub fn serialize(bytes: &[u8], serializer: S) -> Result { + serializer.serialize_bytes(bytes) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + struct Bytes; + + impl Visitor<'_> for Bytes { + type Value = Vec; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a byte string") + } + + fn visit_bytes(self, value: &[u8]) -> Result, E> { + Ok(value.to_vec()) + } + } + + deserializer.deserialize_bytes(Bytes) + } +} + +/// A welcome that cannot be split, or that does not reassemble. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum WelcomeError { + /// The frame is too small to carry a chunk's header and any payload. + #[error("a frame of {0} bytes cannot carry a welcome chunk")] + FrameTooSmall(usize), + /// The welcome has more chunks than a `u32` can count. + #[error("the welcome has more chunks than a u32 can count: {0}")] + TooManyChunks(#[source] TryFromIntError), + /// The envelope could not be encoded. + #[error("cannot encode the welcome: {0}")] + Encode(String), + /// The reassembled bytes are not an envelope. + #[error("cannot decode the reassembled welcome: {0}")] + Decode(String), + /// A chunk's bytes do not match its check. + #[error("chunk {index} was altered in transit")] + AlteredChunk { + /// The position of the altered chunk. + index: u32, + }, + /// A chunk arrived where another was due, so a chunk is missing or out of order. + #[error("chunk {got} arrived where chunk {expected} was due")] + OutOfSequence { + /// The position the reassembly waits for. + expected: u32, + /// The position of the chunk that arrived. + got: u32, + }, + /// A chunk claims no chunks at all. + #[error("a chunk claims a welcome of no chunks")] + NoChunks, + /// A chunk names a different welcome from the one being reassembled. + #[error("the chunk belongs to a different welcome")] + OtherWelcome, + /// Every chunk checks, but the whole does not match its digest. + #[error("the reassembled welcome does not match its digest")] + AlteredWelcome, + /// The reassembly ended before the last chunk. + #[error("the welcome is incomplete: {received} of {total} chunks arrived")] + Incomplete { + /// The chunks that arrived. + received: u32, + /// The chunks the welcome has, or zero when none arrived. + total: u32, + }, +} + +/// Splits `envelope` into chunks that each fit a world frame of `frame_cap` bytes. An envelope that +/// fits one frame is one chunk, so the joiner takes one path for every welcome (P4.12). +pub fn split(envelope: &Envelope, frame_cap: usize) -> Result, WelcomeError> { + let payload_bytes = frame_cap + .checked_sub(CHUNK_HEADER_BYTES) + .filter(|bytes| *bytes > 0) + .ok_or(WelcomeError::FrameTooSmall(frame_cap))?; + let payload = encode_cbor(envelope).map_err(|err| WelcomeError::Encode(err.to_string()))?; + let digest = Hash::digest(&payload); + let parts: Vec<&[u8]> = payload.chunks(payload_bytes).collect(); + let total = u32::try_from(parts.len()).map_err(WelcomeError::TooManyChunks)?; + let mut chunks = Vec::with_capacity(parts.len()); + for (index, bytes) in parts.into_iter().enumerate() { + chunks.push(Chunk { + index: u32::try_from(index).map_err(WelcomeError::TooManyChunks)?, + total, + digest, + check: Hash::digest(bytes), + bytes: bytes.to_vec(), + }); + } + Ok(chunks) +} + +/// The chunks of one welcome, as they arrive. Chunks come in order, and each one is checked before +/// it is kept. +#[derive(Debug, Default)] +pub struct Reassembly { + /// The total and the digest, once the first chunk has been accepted. + whole: Option<(u32, Hash)>, + /// How many chunks have been accepted, and so the index the next must have. + next: u32, + payload: Vec, +} + +impl Reassembly { + /// Takes the next chunk. Returns the envelope when the last chunk arrives and the whole matches + /// its digest. Until then, and on every error, nothing is decoded. + pub fn push(&mut self, chunk: &Chunk) -> Result, WelcomeError> { + if Hash::digest(&chunk.bytes) != chunk.check { + return Err(WelcomeError::AlteredChunk { index: chunk.index }); + } + if chunk.total == 0 { + return Err(WelcomeError::NoChunks); + } + if let Some((total, digest)) = self.whole + && (chunk.total != total || chunk.digest != digest) + { + return Err(WelcomeError::OtherWelcome); + } + let expected = self.next; + if chunk.index != expected || expected >= chunk.total { + return Err(WelcomeError::OutOfSequence { + expected, + got: chunk.index, + }); + } + + self.whole = Some((chunk.total, chunk.digest)); + self.payload.extend_from_slice(&chunk.bytes); + self.next += 1; + if self.next < chunk.total { + return Ok(None); + } + + if Hash::digest(&self.payload) != chunk.digest { + return Err(WelcomeError::AlteredWelcome); + } + decode_cbor(self.payload.as_slice()) + .map(Some) + .map_err(|err| WelcomeError::Decode(err.to_string())) + } + + /// Ends the reassembly, and fails if the welcome is not complete. + pub fn finish(self) -> Result<(), WelcomeError> { + let total = self.whole.map_or(0, |(total, _)| total); + if self.next == 0 || self.next < total { + return Err(WelcomeError::Incomplete { + received: self.next, + total, + }); + } + Ok(()) + } +} From f5dc80410e12a6fd6cc2238b76a1a2736372d94d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:33:43 -0500 Subject: [PATCH 16/21] docs(id): record P4.8 to P4.11 and the DataScheme update cost [phase 4] --- ...-12T14-33-36Z_phase_4_groups_encryption.md | 72 ++++++++++++++----- 1 file changed, 54 insertions(+), 18 deletions(-) diff --git a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md index 37996833de..9f4fc82952 100644 --- a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md +++ b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md @@ -7,37 +7,73 @@ ## Steps -| Step | Track | Status | Commits | Tests | Notes | -| ------------------------------------- | ------- | ------ | ------- | ----- | --------------- | -| P4.1 DataScheme adapter | adapter | todo | | | blocks the rest | -| P4.2 Our DGM and the from_join fork | adapter | todo | | | | -| P4.3 from_join withholding rule | adapter | todo | | | | -| P4.4 Scheme v1 | scheme | todo | | | | -| P4.5 recent:N and full | history | todo | | | | -| P4.6 Lazy full history | history | todo | | | | -| P4.7 Heads rule | heads | todo | | | | -| P4.8 Rotation policy and PCS recovery | warn | todo | | | | -| P4.9 Warnings | warn | todo | | | | -| P4.10 scheme none notice | warn | todo | | | | -| P4.11 DataScheme cost measurement | warn | todo | | | | -| P4.12 Welcome chunking | history | todo | | | | +| Step | Track | Status | Commits | Tests | Notes | +| ------------------------------------- | ------- | ------ | -------- | ------------------------------------- | ---------------------------------------- | +| P4.1 DataScheme adapter | adapter | todo | | | blocks the rest | +| P4.2 Our DGM and the from_join fork | adapter | todo | | | | +| P4.3 from_join withholding rule | adapter | todo | | | | +| P4.4 Scheme v1 | scheme | todo | | | | +| P4.5 recent:N and full | history | todo | | | | +| P4.6 Lazy full history | history | todo | | | | +| P4.7 Heads rule | heads | todo | | | | +| P4.8 Rotation policy and PCS recovery | warn | done | 205a5483 | 4 rotation and recovery tests | `Session::recover`; no CLI command yet | +| P4.9 Warnings | warn | done | 4b82eff2 | 11 warning tests (9 unit, 2 property) | pure evaluator; not yet wired into serve | +| P4.10 scheme none notice | warn | done | a95c52ae | 4 notice tests | function only; no UI yet | +| P4.11 DataScheme cost measurement | warn | done | 2a3de9a9 | 1 smoke test; benchmark ignored | numbers below | +| P4.12 Welcome chunking | history | todo | | | | ## Decisions - See the decisions above and the index. +- Rotation (P4.8): the epoch rotates on create, update, removal, and the update that follows a join. Nothing else moves it, and the module takes no clock. An idle group keeps its epoch over a simulated year (`test_an_idle_group_keeps_its_epoch_over_a_simulated_year`). +- PCS recovery (P4.8, N8): `Session::recover` removes the device, then re-adds it by `add_from_join`, so the device joins the new epoch with no earlier secret. It returns the envelopes and the epoch before and after. `RECOVERY_STEPS` holds the two steps the CLI prints. The re-added device keeps its long-term identity and its registered bundle; rotating its pre-key is not part of the procedure yet. +- Warning thresholds (P4.9, N11): 96, 128 and 1,000 members. A group that jumps past several warns for each, in order. +- Churn (P4.9, N34): a warning when a client-made group has 4 device re-adds in the last 24 hours. Churn re-arms only when the window falls to 2, so a count that flaps around 4 warns once. Size warnings keep a high-water mark, so a group that shrinks and regrows does not warn again. +- Warnings never block an operation, and they apply only to client-made groups. Provisioned groups are not warned about. +- The "scheme: none" notice (P4.10, decision 8): the metadata field `scheme` is `none` for a group with no scheme, and the status string is `scheme: none`. A group with a scheme shows its name and version. ## Open questions -- None yet. +- The warnings are not yet wired into `id serve` or the CLI status line. The evaluator is pure and takes `now` and the member count from the caller. The serve path does not yet have a client-made group event feed to evaluate. +- The notice is not yet shown in the web UI. The status string is the source for it. +- The recovery procedure is a function. The CLI command that runs it (P6.7) is not written. +- The churn window and count (24 hours, 4) and the size thresholds are first choices. The P4.11 numbers are the input for revisiting them. +- The re-added device's pre-key rotation (see Decisions) needs a decision before the CLI runs the procedure. ## Changes to the plan -- None yet. +- None to the plan itself. The P4.8 test ("a compromised member is replaced and cannot read new epochs") runs over three devices in the adapter's test cast, not over the CLI, since the CLI command is not written yet. + +## P4.11: DataScheme update cost (measured) + +Run: `cargo test --release --lib encryption::tests::bench_update_cost -- --ignored --nocapture`, on an AMD Ryzen 7 7840U (16 threads), Rust 1.99.0, release profile, one thread. The benchmark builds one committer's device for a group of N members, creates the group, runs one warm-up update, then times 5 updates and reports the mean. Bytes are the postcard size of the envelope. The benchmark measures the committer only: receivers, removals, and the transport framing are not in the numbers. + +| Members | Create bytes | Create ms | Update bytes | Update ms (mean of 5) | Update bytes per member | Update CPU per member | +| ------: | -----------: | --------: | -----------: | --------------------: | ----------------------: | --------------------: | +| 100 | 40,496 | 26.9 | 30,654 | 9.71 | 307 | 97 µs | +| 1,000 | 408,697 | 267.0 | 309,993 | 101.2 | 310 | 101 µs | +| 5,000 | 2,049,696 | 1,333 | 1,543,795 | 596.5 | 309 | 119 µs | + +Against the BeeKEM spike (the table in the BeeKEM assessment, section 2): + +| Members | BeeKEM update (one copy) | DataScheme update | Ratio (bytes) | BeeKEM CPU | DataScheme CPU | Ratio (CPU) | +| ------: | --------------------------: | ----------------: | ------------: | ------------: | -------------: | -------------: | +| 100 | 2.8 KB | 30.7 KB | 11x | 0.6 to 0.8 ms | 9.71 ms | 12x to 16x | +| 1,000 | 3.9 KB | 310 KB | 80x | 0.6 to 0.8 ms | 101.2 ms | 126x to 169x | +| 5,000 | about 5.0 KB (extrapolated) | 1.54 MB | about 309x | not given | 596.5 ms | not computable | + +The BeeKEM CPU in the spike is given without a size, so the CPU ratios assume it is flat. The first commit after a bulk create is 408.7 KB at 1,000 members for DataScheme, against 122 KB for BeeKEM (the BeeKEM table). + +Fan-out break-even: a BeeKEM operation goes out once, and DataScheme sends about 309 bytes to each member. So BeeKEM wins on bytes from about 9 members (at 2.8 KB) to about 16 members (at 5.0 KB). The BeeKEM assessment states 11 to 17 from a per-message estimate, which it marks as not measured. The measured figure puts the lower end at 9. The assessment is not edited here; the owner should decide whether to update it. + +Reading: DataScheme's update cost is linear in the members, at about 309 bytes and 100 µs of committer CPU per member, so it grows as the table predicts. At 1,000 members a single update is 310 KB, which is the "update exceeds an agreed budget" trigger in BeeKEM's conditions (section 4, item 4). No budget has been agreed, so this is a number, not a finding that a condition holds. ## Review notes and regression tests -- To be filled. +- The rotation tests are `test_the_epoch_rotates_on_create_update_and_remove_and_not_on_send` and `test_an_idle_group_keeps_its_epoch_over_a_simulated_year`. +- The recovery tests are `test_recovery_puts_the_device_back_and_its_compromised_copy_cannot_read` and `test_recovery_rejects_a_removal_that_leaves_the_device_in_the_model`. The compromised copy is the removed device's session, which holds the state from before the removal. It is withheld from every message under the new epoch. +- The warning tests cover each threshold (95, 96, 127, 128, 999, 1000), flapping on size and churn, the non-client-made case, and two properties: the warning count follows the largest size, and it is monotone in size. ## End -- Pending. +- P4.8 to P4.11 done on `p4-warn`. Commits: 205a5483, 4b82eff2, a95c52ae, 2a3de9a9. Not pushed. From 29d65e7b4e6ca7ee51c18960033256fe99f40e51 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:39:38 -0500 Subject: [PATCH 17/21] docs(id): phase 4 status table after merging the tracks [phase 4] --- ...-12T14-33-36Z_phase_4_groups_encryption.md | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md index 9f4fc82952..ea6e03d1bb 100644 --- a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md +++ b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md @@ -7,20 +7,21 @@ ## Steps -| Step | Track | Status | Commits | Tests | Notes | -| ------------------------------------- | ------- | ------ | -------- | ------------------------------------- | ---------------------------------------- | -| P4.1 DataScheme adapter | adapter | todo | | | blocks the rest | -| P4.2 Our DGM and the from_join fork | adapter | todo | | | | -| P4.3 from_join withholding rule | adapter | todo | | | | -| P4.4 Scheme v1 | scheme | todo | | | | -| P4.5 recent:N and full | history | todo | | | | -| P4.6 Lazy full history | history | todo | | | | -| P4.7 Heads rule | heads | todo | | | | -| P4.8 Rotation policy and PCS recovery | warn | done | 205a5483 | 4 rotation and recovery tests | `Session::recover`; no CLI command yet | -| P4.9 Warnings | warn | done | 4b82eff2 | 11 warning tests (9 unit, 2 property) | pure evaluator; not yet wired into serve | -| P4.10 scheme none notice | warn | done | a95c52ae | 4 notice tests | function only; no UI yet | -| P4.11 DataScheme cost measurement | warn | done | 2a3de9a9 | 1 smoke test; benchmark ignored | numbers below | -| P4.12 Welcome chunking | history | todo | | | | +| Step | Track | Status | Commits | Tests | Notes | +| ------------------------------------- | ------- | ------ | ------------------ | ------------------------------------- | ---------------------------------------- | +| P4.1 DataScheme adapter | adapter | done | a630a440 | | blocks the rest | +| P4.2 Our DGM and the from_join fork | adapter | done | e57c1223 | | | +| P4.3 from_join withholding rule | adapter | done | daa4f200 | | | +| P4.4 Scheme v1 | scheme | done | d22f6987, 3b671bb4 | | | +| P4.5 recent:N and full | history | done | 6b2a9005, 67207add | | | +| P4.6 Lazy full history | history | done | 25d7d814 | | | +| P4.7 Heads rule | heads | todo | | | | +| P4.8 Rotation policy and PCS recovery | warn | done | 205a5483 | 4 rotation and recovery tests | `Session::recover`; no CLI command yet | +| P4.9 Warnings | warn | done | 4b82eff2 | 11 warning tests (9 unit, 2 property) | pure evaluator; not yet wired into serve | +| P4.10 scheme none notice | warn | done | a95c52ae | 4 notice tests | function only; no UI yet | +| P4.11 DataScheme cost measurement | warn | done | 2a3de9a9 | 1 smoke test; benchmark ignored | numbers below | +| P4.12 Welcome chunking | history | done | c38e6a39 | | | +| P4.13 Roster follows the group fold | scheme | done | a39cc834 | 11 scheme tests (incl. fold property) | mismatch poisons the session | ## Decisions From 6001cfdd27e2c08a5fd068f3bdc9c888de46086a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:52:47 -0500 Subject: [PATCH 18/21] test(rust): concurrent membership changes converge [P4.7] Two admins adding members from the same view, with a third member ordering the two adds, left the joiner with an empty roster: the orderer delivered an add that was ready before the joiner's welcome, and the crate applied it before the joiner was welcomed. The orderer now delivers a welcome after its own past and before any other pending message. A welcome that is not yet ready holds delivery. Properties (16 cases each): concurrent updates and sends, and a concurrent add with sends. Each member hears the others' changes in its own shuffled order. Every member must end with the same roster and epoch set, and read every send by another member. Open: an update made without knowing a concurrent add never reaches the joiner, so the joiner holds one epoch fewer. The shape is pinned by test_open_a_joiner_misses_an_update_made_without_knowing_it. Adds Scheme::epoch_set, the IDs of every secret a device holds. --- pkgs/id/src/encryption/ordering.rs | 45 +++++- pkgs/id/src/encryption/scheme.rs | 8 + pkgs/id/src/encryption/tests.rs | 252 ++++++++++++++++++++++++++++- 3 files changed, 302 insertions(+), 3 deletions(-) diff --git a/pkgs/id/src/encryption/ordering.rs b/pkgs/id/src/encryption/ordering.rs index e7edb195c5..c0f9f67e92 100644 --- a/pkgs/id/src/encryption/ordering.rs +++ b/pkgs/id/src/encryption/ordering.rs @@ -159,6 +159,7 @@ impl Orderer { waiting: BTreeMap::new(), deliverable: VecDeque::new(), welcomed: false, + welcome: None, } } } @@ -184,9 +185,29 @@ pub struct OrdererState { deliverable: VecDeque, /// Set by a create or a welcome. Nothing is delivered before it. welcomed: bool, + /// The create or welcome that opened delivery. It is delivered before any pending message that + /// is not in its own past (P4.7). + welcome: Option, } impl OrdererState { + /// The messages `id` names, directly or through the messages they name. + fn past_of(&self, id: Hash) -> BTreeSet { + let mut past = BTreeSet::new(); + let mut pending = vec![id]; + while let Some(next) = pending.pop() { + let Some(envelope) = self.messages.get(&next) else { + continue; + }; + for named in &envelope.previous { + if past.insert(*named) { + pending.push(*named); + } + } + } + past + } + /// Publishes our own message. It names the control messages we have seen, and it is ready. fn publish(&mut self, content: Content) -> Result { let seq = self.next_seq; @@ -276,9 +297,10 @@ impl Ordering for Orderer { fn set_welcome( mut y: Self::State, - _message: &Self::Message, + message: &Self::Message, ) -> Result { y.welcomed = true; + y.welcome = Some(message.id); Ok(y) } @@ -288,7 +310,26 @@ impl Ordering for Orderer { if !y.welcomed { return Ok((y, None)); } - let Some(id) = y.deliverable.pop_front() else { + // The welcome comes after its own past and before anything else. A control message that is + // concurrent with the join would otherwise reach the crate before the joiner is welcomed, + // and the crate would apply it to a roster that is still empty (P4.7). + let next = match y.welcome { + Some(welcome) if !y.ready.contains(&welcome) => return Ok((y, None)), + Some(welcome) if y.deliverable.contains(&welcome) => { + let past = y.past_of(welcome); + let index = y + .deliverable + .iter() + .position(|id| past.contains(id)) + .or_else(|| y.deliverable.iter().position(|id| *id == welcome)); + let Some(index) = index else { + return Ok((y, None)); + }; + y.deliverable.remove(index) + } + _ => y.deliverable.pop_front(), + }; + let Some(id) = next else { return Ok((y, None)); }; let Some(envelope) = y.messages.get(&id).cloned() else { diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index 70cae693ae..23cf732612 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -206,6 +206,14 @@ impl Session { self.state.as_ref().map_or(0, |y| y.secrets.len()) } + /// The IDs of every group secret this device holds. Two members agree on the epochs when these + /// sets are equal, even if their latest epoch differs (concurrent changes, P4.7). + pub fn epoch_set(&self) -> BTreeSet { + self.state + .as_ref() + .map_or_else(BTreeSet::new, |y| y.secrets.ids().copied().collect()) + } + /// The members the crate's roster holds, as group-model keys. pub fn members(&self) -> Result, SchemeError> { let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index 2315abdf95..59bbec75c3 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -4,7 +4,7 @@ //! cast, since a joiner needs the control history to take the welcome. Application messages go only //! to the members who may read them. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::time::{Duration, Instant}; use p2panda_core::cbor::{decode_cbor, encode_cbor}; @@ -17,6 +17,7 @@ use p2panda_encryption::key_manager::KeyManagerState; use p2panda_encryption::key_registry::KeyRegistryState; use p2panda_encryption::traits::GroupMessage; use proptest::prelude::*; +use proptest::test_runner::TestCaseResult; use super::history::{HISTORY_WAIT, HistoryAnswer, HistoryError, ask_member}; use super::welcome::{CHUNK_HEADER_BYTES, Reassembly, WelcomeError, split}; @@ -289,6 +290,10 @@ impl Cast { fn epoch(&self, who: u8) -> Option { self.session(who).epoch() } + + fn epoch_set(&self, who: u8) -> BTreeSet { + self.session(who).epoch_set() + } } // --- create --------------------------------------------------------------------------------------- @@ -1624,6 +1629,251 @@ proptest! { } } +// --- concurrency (P4.7) --------------------------------------------------------------------------- + +/// `by` adds `who` from the group as `members` lists it, with nothing else delivered. The add is +/// concurrent with any other change made the same way. +fn concurrent_add(cast: &mut Cast, by: u8, who: u8, members: &[u8]) -> Envelope { + let members: BTreeSet = members.iter().map(|seed| id(*seed)).collect(); + let rng = Rng::default(); + cast.session_mut(by) + .add(&view_of(&members), id(who), &rng) + .expect("concurrent add") +} + +#[test] +fn test_two_concurrent_adds_converge_for_a_third_member() { + let everyone: BTreeSet = [1, 2, 3, 4, 5].into_iter().map(id).collect(); + for order in [[0, 1], [1, 0]] { + let mut cast = Cast::new(&[1, 2, 3, 4, 5]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4, 5]); + + // Admins 2 and 3 each add a member from the same view, so neither add names the other. + let adds = [ + concurrent_add(&mut cast, 2, 4, &[1, 2, 3, 4]), + concurrent_add(&mut cast, 3, 5, &[1, 2, 3, 5]), + ]; + let authors = [2, 3]; + + // Member 1 is the third member and orders the two adds in `order`. The others hear them in + // the other order, so no two members see the same arrival order. + for member in [1, 2, 3, 4, 5] { + let turn = if member == 2 || member == 5 { + [order[1], order[0]] + } else { + order + }; + for index in turn { + if authors[index] != member { + cast.deliver(&adds[index], &[member]); + } + } + } + + for who in [1, 2, 3, 4, 5] { + assert_eq!( + cast.members_of(who), + everyone, + "member {who} roster, order {order:?}" + ); + assert_eq!( + cast.epoch_set(who), + cast.epoch_set(1), + "member {who} epochs, order {order:?}" + ); + } + + let message = cast.send(4, "after both adds"); + for read in cast.deliver(&message, &[1, 2, 3, 5]) { + assert_eq!(read, vec![text("after both adds")]); + } + } +} + +/// A seeded shuffle, so a proptest case replays one delivery order. +fn shuffled(items: Vec, seed: u64) -> Vec { + let mut keyed: Vec<(u64, T)> = items + .into_iter() + .enumerate() + .map(|(index, item)| (splitmix(seed ^ (index as u64)), item)) + .collect(); + keyed.sort_by_key(|(key, _)| *key); + keyed.into_iter().map(|(_, item)| item).collect() +} + +fn splitmix(seed: u64) -> u64 { + let x = seed.wrapping_add(0x9E37_79B9_7F4A_7C15); + let x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + let x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^ (x >> 31) +} + +/// One change an admin makes in a round of concurrent changes. +#[derive(Clone, Copy, Debug)] +enum Change { + Update, + Send, + /// The add of member 4. A round has at most one. + Add, +} + +/// Admins 1 to `admins` each make one change from the group as it was, before any of them hears +/// from another. Then each member hears the changes it did not make, one at a time, in its own +/// shuffled order, with the members taking turns. Afterwards every member must have the same roster +/// and epoch set, and read every send by another member. A refused message fails the round. +fn check_concurrent_round(changes: &[Change], shuffles: &[u64]) -> TestCaseResult { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + + let mut made: Vec<(u8, Envelope)> = Vec::new(); + let mut sends: Vec<(u8, Vec)> = Vec::new(); + let mut joined = false; + for (author, change) in [1_u8, 2, 3].into_iter().zip(changes) { + let envelope = match change { + Change::Add if !joined => { + joined = true; + concurrent_add(&mut cast, author, 4, &[1, 2, 3, 4]) + } + Change::Add | Change::Send => { + let text = format!("from {author}"); + sends.push((author, text.as_bytes().to_vec())); + cast.send(author, &text) + } + Change::Update => cast.update(author), + }; + made.push((author, envelope)); + } + + let audience: Vec = if joined { + vec![1, 2, 3, 4] + } else { + vec![1, 2, 3] + }; + let mut queues: Vec<(u8, VecDeque)> = audience + .iter() + .map(|&member| { + let theirs: Vec = made + .iter() + .filter(|(author, _)| *author != member) + .map(|(_, envelope)| envelope.clone()) + .collect(); + let seed = shuffles[usize::from(member - 1)]; + (member, shuffled(theirs, seed).into()) + }) + .collect(); + + let mut reads: BTreeMap>> = BTreeMap::new(); + while queues.iter().any(|(_, queue)| !queue.is_empty()) { + for (member, queue) in &mut queues { + let Some(message) = queue.pop_front() else { + continue; + }; + let outputs = cast + .session_mut(*member) + .process(&message) + .map_err(|err| TestCaseError::fail(format!("member {member}: {err}")))?; + for output in outputs { + if let Received::Plaintext(bytes) = output { + reads.entry(*member).or_default().push(bytes); + } + } + } + } + + let expected: BTreeSet = audience.iter().map(|seed| id(*seed)).collect(); + let mut every_send: Vec> = sends.iter().map(|(_, bytes)| bytes.clone()).collect(); + every_send.sort(); + for member in &audience { + prop_assert_eq!( + cast.members_of(*member), + expected.clone(), + "member {} roster", + member + ); + prop_assert_eq!( + cast.epoch_set(*member), + cast.epoch_set(audience[0]), + "member {} epoch set", + member + ); + let mut heard = reads.remove(member).unwrap_or_default(); + heard.extend( + sends + .iter() + .filter(|(author, _)| author == member) + .map(|(_, bytes)| bytes.clone()), + ); + heard.sort(); + prop_assert_eq!(heard, every_send.clone(), "member {} reads", member); + } + Ok(()) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(16))] + + /// Two or three admins make concurrent updates and sends (P4.7). + #[test] + fn test_concurrent_updates_and_sends_converge( + admins in 2usize..=3, + kinds in proptest::collection::vec(any::(), 3), + shuffles in proptest::collection::vec(any::(), 4), + ) { + let changes: Vec = kinds + .iter() + .map(|send| if *send { Change::Send } else { Change::Update }) + .take(admins) + .collect(); + check_concurrent_round(&changes, &shuffles)?; + } + + /// Two or three admins make concurrent sends, and one of them adds member 4 (P4.7). + #[test] + fn test_a_concurrent_add_and_sends_converge( + admins in 2usize..=3, + adder in 0usize..3, + shuffles in proptest::collection::vec(any::(), 4), + ) { + let changes: Vec = (0..admins) + .map(|index| if index == adder { Change::Add } else { Change::Send }) + .collect(); + check_concurrent_round(&changes, &shuffles)?; + } +} + +/// Open (P4.7). An update made without knowing a concurrent add never reaches the joiner: the +/// joiner's welcome carries the secrets of the adder's view, and the update's secret is not sent to +/// it. The joiner then holds one epoch fewer than the members, and messages under that epoch are +/// withheld from it. This pins the gap as it is. A refusal, or a fetch of the missing secret through +/// lazy history (P4.6), would change this test. +#[test] +fn test_open_a_joiner_misses_an_update_made_without_knowing_it() { + let mut cast = Cast::new(&[1, 2, 3, 4]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3, 4]); + + let add = concurrent_add(&mut cast, 2, 4, &[1, 2, 3, 4]); + let update = cast.update(1); + cast.deliver(&add, &[1, 3, 4]); + cast.deliver(&update, &[2, 3, 4]); + + assert!( + cast.epoch_set(4).is_subset(&cast.epoch_set(1)), + "the joiner holds only epochs the members hold" + ); + assert!( + cast.epoch_set(4).len() < cast.epoch_set(1).len(), + "the joiner misses the update's epoch" + ); + let message = cast.send(1, "under the update's epoch"); + assert_eq!( + cast.deliver(&message, &[4]), + vec![vec![Received::Withheld(message.id())]] + ); +} + // --- cost (P4.11) --------------------------------------------------------------------------------- /// The `index`th person of a benchmark group. [`person`] takes a one-byte seed, which runs out at From e1fee2ce82f0071d016cf1af722907bf0434533b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:56:14 -0500 Subject: [PATCH 19/21] feat(rust): heads rule with a cap of 32 parents [P4.7] A control message now names the heads it can see: the control messages that no delivered or published message names. It always names its author's own latest control message, even when a later message covers it. Application messages name the same parents. The orderer used to name the latest control message of each author. That list kept growing with the number of authors, and went past 32 parents in a group of 33, with no check. It also named messages that a later head already covered. A publish that would name more than 32 parents is refused with SchemeError::TooManyParents. The check runs before the crate call, so the refusal leaves the session as it was. Nothing is dropped from the parents. The merge in the plan (P4.7, N22) is not built, so a group with more than 32 heads cannot publish until a member sees fewer. Tests: the head names only the heads (red before), the author's own latest is named when a later message covers it, 32 parents are accepted, and 33 are refused for an update and a send with the state kept. --- pkgs/id/src/encryption/ordering.rs | 82 +++++++++++++++++++++---- pkgs/id/src/encryption/scheme.rs | 29 ++++++++- pkgs/id/src/encryption/tests.rs | 98 ++++++++++++++++++++++++++++++ 3 files changed, 196 insertions(+), 13 deletions(-) diff --git a/pkgs/id/src/encryption/ordering.rs b/pkgs/id/src/encryption/ordering.rs index c0f9f67e92..955ba1da35 100644 --- a/pkgs/id/src/encryption/ordering.rs +++ b/pkgs/id/src/encryption/ordering.rs @@ -1,9 +1,11 @@ //! The `DataScheme` orderer and the envelope it delivers. //! //! The crate's orderer (`MessageOrderer`) is test-only, so the adapter brings its own with the same -//! rules. A message names the last control message the sender had delivered from each author, and -//! it is delivered once every message it names is delivered. Nothing is delivered before the device -//! is welcomed: a create or a welcome opens delivery, and earlier messages wait in the queue. +//! rules. A message names the heads it can see: the latest control messages of the concurrent +//! branches. It always names its author's own latest control message, and it names at most +//! [`MAX_PARENTS`]. A publish that would name more is refused (P4.7). A message is delivered once +//! every message it names is delivered. Nothing is delivered before the device is welcomed: a create +//! or a welcome opens delivery, and earlier messages wait in the queue. //! //! Application messages are never named by other messages, so the adapter may leave one out //! without stalling anything. [`super::scheme`] does that for messages whose group secret the @@ -22,6 +24,10 @@ use thiserror::Error; use super::roster::Roster; +/// The most parents a message may name (P4.7, N22). A publish that would name more is refused, and +/// nothing is dropped from the list. +pub const MAX_PARENTS: usize = 32; + /// One published group message: a control message with its direct messages, or an application /// message. #[derive(Clone, Debug, Serialize, Deserialize)] @@ -31,7 +37,8 @@ pub struct Envelope { sender: VerifyingKey, /// The scheme version the message was encoded under: a copy of the group's signed policy (P4.4). scheme: u32, - /// The last control message seen from each author when this was published. + /// The heads when this was published, and the author's own latest control message. At most + /// [`MAX_PARENTS`] of them. previous: Vec, content: Content, } @@ -79,6 +86,11 @@ impl Envelope { self.scheme } + /// The control messages this one names, in the order it names them. + pub fn parents(&self) -> &[Hash] { + &self.previous + } + /// The scheme version copied into each direct message, in order. Empty for an application /// message. pub fn direct_schemes(&self) -> Vec { @@ -140,6 +152,15 @@ pub enum OrdererError { /// The message could not be encoded to compute its hash. #[error("cannot encode the message: {0}")] Encode(String), + /// The message would name more parents than [`MAX_PARENTS`]. The session checks this before the + /// crate call, so this is reached only if that check is skipped. + #[error("the message would name {count} parents, more than the cap of {cap}")] + TooManyParents { + /// The parents the message would name. + count: usize, + /// The most parents a message may name. + cap: usize, + }, } /// The orderer. Its state is [`OrdererState`]. @@ -153,7 +174,8 @@ impl Orderer { my_id, scheme, next_seq: 0, - previous: BTreeMap::new(), + heads: BTreeSet::new(), + own: None, messages: BTreeMap::new(), ready: BTreeSet::new(), waiting: BTreeMap::new(), @@ -172,8 +194,10 @@ pub struct OrdererState { /// The scheme version of every message this device publishes. scheme: u32, next_seq: u64, - /// The last control message delivered from each author, including our own. - previous: BTreeMap, + /// The control messages that no delivered or published control message names yet: the heads. + heads: BTreeSet, + /// Our own latest control message. Every message names it, even when a later message covers it. + own: Option, /// Every message received, by ID. messages: BTreeMap, /// Messages that are ready: every message they name is ready. Our own published messages are @@ -191,6 +215,32 @@ pub struct OrdererState { } impl OrdererState { + /// The parents a message published now names: our own latest control message, then the heads. + pub fn parent_list(&self) -> Vec { + let mut parents: Vec = self.own.into_iter().collect(); + parents.extend( + self.heads + .iter() + .copied() + .filter(|head| Some(*head) != self.own), + ); + parents + } + + /// How many parents a message published now would name. + pub fn parent_count(&self) -> usize { + self.parent_list().len() + } + + /// A control message is a head from the time it is delivered or published, until a control + /// message names it. The messages it names stop being heads. + fn observe(&mut self, envelope: &Envelope) { + for named in &envelope.previous { + self.heads.remove(named); + } + self.heads.insert(envelope.id); + } + /// The messages `id` names, directly or through the messages they name. fn past_of(&self, id: Hash) -> BTreeSet { let mut past = BTreeSet::new(); @@ -208,12 +258,19 @@ impl OrdererState { past } - /// Publishes our own message. It names the control messages we have seen, and it is ready. + /// Publishes our own message. It names the parents, and it is ready. A message whose parents + /// would be more than [`MAX_PARENTS`] is refused, and no sequence number is used. fn publish(&mut self, content: Content) -> Result { + let parents = self.parent_list(); + if parents.len() > MAX_PARENTS { + return Err(OrdererError::TooManyParents { + count: parents.len(), + cap: MAX_PARENTS, + }); + } let seq = self.next_seq; self.next_seq += 1; - let previous = self.previous.values().copied().collect(); - let envelope = Envelope::new(seq, self.my_id, self.scheme, previous, content)?; + let envelope = Envelope::new(seq, self.my_id, self.scheme, parents, content)?; self.ready.insert(envelope.id); Ok(envelope) } @@ -256,7 +313,8 @@ impl Ordering for Orderer { direct, }; let envelope = y.publish(content)?; - y.previous.insert(y.my_id, envelope.id); + y.observe(&envelope); + y.own = Some(envelope.id); Ok((y, envelope)) } @@ -336,7 +394,7 @@ impl Ordering for Orderer { return Ok((y, None)); }; if let Content::Control { .. } = envelope.content { - y.previous.insert(envelope.sender, id); + y.observe(&envelope); } Ok((y, Some(envelope))) } diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index 23cf732612..73f6967d46 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -44,7 +44,7 @@ use p2panda_encryption::traits::{ use thiserror::Error; use super::history::{HistoryAnswer, HistoryMode, HistoryRequest}; -use super::ordering::{Envelope, Orderer}; +use super::ordering::{Envelope, MAX_PARENTS, Orderer}; use super::roster::Roster; use crate::groups::{GroupView, Key, Policy}; @@ -143,6 +143,15 @@ pub enum SchemeError { /// The version the policy names. version: u32, }, + /// The message would name more parents than a message may carry, so it is refused before the + /// crate sees it. The session is not poisoned (P4.7). + #[error("the message would name {count} parents, more than the cap of {cap}, so it is refused")] + TooManyParents { + /// The parents the message would name: the heads and the author's own latest. + count: usize, + /// The most parents a message may name. + cap: usize, + }, /// A message's header or direct copy names a version other than the group's signed policy. #[error("the message names scheme v{found}, but the group's signed policy names v{expected}")] SchemeMismatch { @@ -309,6 +318,7 @@ impl Session { /// Rotates the epoch by giving every current member a new secret. pub fn update(&mut self, rng: &Rng) -> Result { self.ensure_welcomed()?; + self.ensure_parents_fit()?; self.step(|y| EncryptionGroup::update(y, rng)) } @@ -339,6 +349,7 @@ impl Session { /// Encrypts `plaintext` under the current epoch. pub fn send(&mut self, plaintext: &[u8], rng: &Rng) -> Result { self.ensure_welcomed()?; + self.ensure_parents_fit()?; self.step(|y| EncryptionGroup::send(y, plaintext, rng)) } @@ -489,6 +500,21 @@ impl Session { .collect()) } + /// Refuses a publish that would name more than [`MAX_PARENTS`] parents (P4.7). It runs before the + /// crate call, since a call that fails inside the orderer consumes the state and poisons the + /// session. Nothing is dropped from the parents: the change is refused. + fn ensure_parents_fit(&self) -> Result<(), SchemeError> { + let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; + let count = y.orderer.parent_count(); + if count <= MAX_PARENTS { + return Ok(()); + } + Err(SchemeError::TooManyParents { + count, + cap: MAX_PARENTS, + }) + } + const fn ensure_welcomed(&self) -> Result<(), SchemeError> { match &self.state { None => Err(SchemeError::Poisoned), @@ -552,6 +578,7 @@ impl Session { op: impl FnOnce(Group) -> Step, ) -> Result { self.check_policy(view)?; + self.ensure_parents_fit()?; let y = self.state.take().ok_or(SchemeError::Poisoned)?; let (y, value) = op(y).map_err(crate_error)?; let roster = roster_of(&y)?; diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index 59bbec75c3..88774da9c1 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -1691,6 +1691,104 @@ fn test_two_concurrent_adds_converge_for_a_third_member() { } } +// --- heads (P4.7) --------------------------------------------------------------------------------- + +#[test] +fn test_a_message_names_the_heads_and_not_every_authors_latest() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + // Member 2's update covers the create. Member 3 has heard it, so the only head it can see is + // member 2's update: it names that, and not the create. + let first = cast.update(2); + cast.deliver(&first, &[1, 3]); + let second = cast.update(3); + assert_eq!( + second.parents(), + [first.id()], + "the head, and not the create that the first update covers" + ); + assert!(!second.parents().contains(&create.id())); +} + +#[test] +fn test_an_author_names_its_own_latest_even_when_a_later_message_covers_it() { + let mut cast = Cast::new(&[1, 2, 3]); + let create = cast.create(1, &[1, 2, 3]); + cast.deliver(&create, &[2, 3]); + + // Member 2's update covers member 1's own create. Member 1 still names the create. + let first = cast.update(2); + cast.deliver(&first, &[1, 3]); + let third = cast.update(1); + let parents: BTreeSet = third.parents().iter().copied().collect(); + assert_eq!( + parents, + [create.id(), first.id()] + .into_iter() + .collect::>() + ); +} + +/// A group of 33 members. Members 2 to 33 each update from the create, so no update names another. +/// Member 1 has heard the first `heard` of them. Returns the group and the create. +fn concurrent_updates(heard: usize) -> (Cast, Envelope) { + let seeds: Vec = (1..=33).collect(); + let mut cast = Cast::new(&seeds); + let create = cast.create(1, &seeds); + let others: Vec = (2..=33).collect(); + cast.deliver(&create, &others); + let updates: Vec = others.iter().map(|who| cast.update(*who)).collect(); + for update in updates.iter().take(heard) { + cast.deliver(update, &[1]); + } + (cast, create) +} + +#[test] +fn test_a_message_may_name_32_parents() { + let (mut cast, create) = concurrent_updates(31); + // The 31 updates member 1 has heard are its heads, and its own create is named too. + let message = cast.update(1); + assert_eq!(message.parents().len(), 32, "the cap is 32, and it is met"); + assert!( + message.parents().contains(&create.id()), + "the own latest is named" + ); +} + +#[test] +fn test_a_message_naming_33_parents_is_refused_and_the_state_is_kept() { + let (mut cast, _) = concurrent_updates(32); + let epoch = cast.epoch(1); + let members = cast.members_of(1); + let rng = Rng::default(); + + let update = cast.session_mut(1).update(&rng); + assert!( + matches!( + update, + Err(SchemeError::TooManyParents { count: 33, cap: 32 }) + ), + "{update:?}" + ); + let send = cast.session_mut(1).send(b"refused", &rng); + assert!( + matches!( + send, + Err(SchemeError::TooManyParents { count: 33, cap: 32 }) + ), + "{send:?}" + ); + assert_eq!( + cast.epoch(1), + epoch, + "the refused change left the epoch as it was" + ); + assert_eq!(cast.members_of(1), members, "and the roster"); +} + /// A seeded shuffle, so a proptest case replays one delivery order. fn shuffled(items: Vec, seed: u64) -> Vec { let mut keyed: Vec<(u64, T)> = items From 77466306fb2134bc2062927713bcaa0755b392dc Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 10:58:33 -0500 Subject: [PATCH 20/21] docs(id): phase 4 heads and concurrency [phase 4] Record P4.7 as done (6001cfdd, e1fee2ce): the heads rule with a cap of 32 and refusal over it, the welcome-first delivery fix, the concurrency properties, and the open epoch gap for a concurrent update and add. --- ...-12T14-33-36Z_phase_4_groups_encryption.md | 66 ++++++++++++++----- 1 file changed, 51 insertions(+), 15 deletions(-) diff --git a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md index ea6e03d1bb..af6dbabd0e 100644 --- a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md +++ b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md @@ -7,21 +7,21 @@ ## Steps -| Step | Track | Status | Commits | Tests | Notes | -| ------------------------------------- | ------- | ------ | ------------------ | ------------------------------------- | ---------------------------------------- | -| P4.1 DataScheme adapter | adapter | done | a630a440 | | blocks the rest | -| P4.2 Our DGM and the from_join fork | adapter | done | e57c1223 | | | -| P4.3 from_join withholding rule | adapter | done | daa4f200 | | | -| P4.4 Scheme v1 | scheme | done | d22f6987, 3b671bb4 | | | -| P4.5 recent:N and full | history | done | 6b2a9005, 67207add | | | -| P4.6 Lazy full history | history | done | 25d7d814 | | | -| P4.7 Heads rule | heads | todo | | | | -| P4.8 Rotation policy and PCS recovery | warn | done | 205a5483 | 4 rotation and recovery tests | `Session::recover`; no CLI command yet | -| P4.9 Warnings | warn | done | 4b82eff2 | 11 warning tests (9 unit, 2 property) | pure evaluator; not yet wired into serve | -| P4.10 scheme none notice | warn | done | a95c52ae | 4 notice tests | function only; no UI yet | -| P4.11 DataScheme cost measurement | warn | done | 2a3de9a9 | 1 smoke test; benchmark ignored | numbers below | -| P4.12 Welcome chunking | history | done | c38e6a39 | | | -| P4.13 Roster follows the group fold | scheme | done | a39cc834 | 11 scheme tests (incl. fold property) | mismatch poisons the session | +| Step | Track | Status | Commits | Tests | Notes | +| ------------------------------------- | ------- | ------ | ------------------ | ------------------------------------- | ----------------------------------------- | +| P4.1 DataScheme adapter | adapter | done | a630a440 | | blocks the rest | +| P4.2 Our DGM and the from_join fork | adapter | done | e57c1223 | | | +| P4.3 from_join withholding rule | adapter | done | daa4f200 | | | +| P4.4 Scheme v1 | scheme | done | d22f6987, 3b671bb4 | | | +| P4.5 recent:N and full | history | done | 6b2a9005, 67207add | | | +| P4.6 Lazy full history | history | done | 25d7d814 | | | +| P4.7 Heads rule | heads | done | 6001cfdd, e1fee2ce | 8 new (4 heads, 4 concurrency) | cap 32, refusal not merge; open epoch gap | +| P4.8 Rotation policy and PCS recovery | warn | done | 205a5483 | 4 rotation and recovery tests | `Session::recover`; no CLI command yet | +| P4.9 Warnings | warn | done | 4b82eff2 | 11 warning tests (9 unit, 2 property) | pure evaluator; not yet wired into serve | +| P4.10 scheme none notice | warn | done | a95c52ae | 4 notice tests | function only; no UI yet | +| P4.11 DataScheme cost measurement | warn | done | 2a3de9a9 | 1 smoke test; benchmark ignored | numbers below | +| P4.12 Welcome chunking | history | done | c38e6a39 | | | +| P4.13 Roster follows the group fold | scheme | done | a39cc834 | 11 scheme tests (incl. fold property) | mismatch poisons the session | ## Decisions @@ -75,6 +75,42 @@ Reading: DataScheme's update cost is linear in the members, at about 309 bytes a - The recovery tests are `test_recovery_puts_the_device_back_and_its_compromised_copy_cannot_read` and `test_recovery_rejects_a_removal_that_leaves_the_device_in_the_model`. The compromised copy is the removed device's session, which holds the state from before the removal. It is withheld from every message under the new epoch. - The warning tests cover each threshold (95, 96, 127, 128, 999, 1000), flapping on size and churn, the non-client-made case, and two properties: the warning count follows the largest size, and it is monotone in size. +## P4.7: heads and concurrency + +Commits on `p4-heads` (not pushed): + +- `6001cfdd` test(rust): concurrent membership changes converge [P4.7]. The concurrency tests and the welcome-first fix. +- `e1fee2ce` feat(rust): heads rule with a cap of 32 parents [P4.7]. The heads rule, the cap, and the head tests. + +### The rule as built + +- A control message names the heads: the delivered or published control messages that no delivered or published control message names. It also names its author's own latest control message, even when a later message covers it. Application messages name the same list. +- At most 32 parents, own latest included. A publish that would name more is refused with `SchemeError::TooManyParents { count, cap }`. The check runs before the crate call, for update, send, add, remove and recovery. A refusal leaves the epoch and the roster as they were, and nothing is dropped from the parents. +- The merge in the plan (P4.7: merge when the heads would exceed the cap) is not built. A group with more than 32 heads cannot publish until a member sees fewer of them. This is open. +- The rule it replaces named the latest control message of each author. That list grew with the number of authors. At 33 authors it went past 32 with no check, and it named messages that a later head already covered. + +### Findings + +- The red test (`test_two_concurrent_adds_converge_for_a_third_member`) had two admins add members 4 and 5 from the same view, and member 1 ordered the two adds in either order. It failed before the fix. A joiner that received the other admin's add before its own welcome applied that add to an empty roster, and its roster lacked a member. The orderer now delivers the welcome after its own past and before any other pending message. A welcome that is not yet ready holds delivery. +- Open: an update made without knowing a concurrent add never reaches the joiner. The joiner then holds one epoch fewer than the members, and messages under that epoch are withheld from it. `test_open_a_joiner_misses_an_update_made_without_knowing_it` pins this. The heads rule does not fix it, since the update names nothing about the add. The options are a refusal, or a fetch of the missing secret through lazy history (P4.6). This needs a decision. +- In the two-add case, every member agrees on the latest epoch and on the epoch set. + +### Properties and tests + +- `test_concurrent_updates_and_sends_converge` and `test_a_concurrent_add_and_sends_converge`, 16 cases each. Two or three admins each make one change from the group as it was: an update, a send, or the add of member 4. Each member then hears the changes it did not make, one at a time, in its own shuffled order, with the members taking turns. At the end every member has the same roster and the same epoch set, and reads every send by another member. A local run at 128 cases passed. +- A property that mixed updates, sends and an add found the open gap above. The add and the updates are therefore in separate properties. +- Heads: `test_a_message_names_the_heads_and_not_every_authors_latest` (red before the change), `test_an_author_names_its_own_latest_even_when_a_later_message_covers_it`, `test_a_message_may_name_32_parents`, and `test_a_message_naming_33_parents_is_refused_and_the_state_is_kept` (red before the change). The last one checks that an update and a send are both refused at 33 parents, and that the epoch and the roster are unchanged. +- Results: the encryption module has 73 passed and 1 ignored (the P4.11 benchmark). The full `cargo test --lib` has 1172 passed, 0 failed and 4 ignored. Clippy reports nothing in `src/encryption`. + +### Open + +- The merge rule for more than 32 heads (above). +- The open epoch gap for a concurrent update and add (above). +- The S10 scenarios at 40 members are not reproduced. Concurrency is tested with 2 or 3 admins, and 33 members only for the cap. Storms and partitions at scale are open. +- Concurrent removals, and a removal concurrent with an update, are not in the properties. +- Message loss and long delays are not tested. Only reorderings are. + ## End - P4.8 to P4.11 done on `p4-warn`. Commits: 205a5483, 4b82eff2, a95c52ae, 2a3de9a9. Not pushed. +- P4.7 done on `p4-heads`. Commits: 6001cfdd, e1fee2ce. Not pushed. From b83174816040110bd50be1c46a081554f9d36968 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 11:18:07 -0500 Subject: [PATCH 21/21] docs(id): phase 4 full suite result [phase 4] --- .../2026-10-12T14-33-36Z_phase_4_groups_encryption.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md index af6dbabd0e..13962df8fd 100644 --- a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md +++ b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md @@ -114,3 +114,12 @@ Commits on `p4-heads` (not pushed): - P4.8 to P4.11 done on `p4-warn`. Commits: 205a5483, 4b82eff2, a95c52ae, 2a3de9a9. Not pushed. - P4.7 done on `p4-heads`. Commits: 6001cfdd, e1fee2ce. Not pushed. + +## 2026-10-12 Suite: phase 4 full run + +- Merged tracks: `p4-scheme` (6b9235ab), `p4-history` (8dc0ca61), `p4-warn` (b05d0d4f), `p4-heads` (cd7b8636). +- `cargo test --all-targets --no-fail-fast` on the merged tree: 1418 passed, 9 ignored, 1 failed. +- The failure is `serve_tests::test_world_module_shared_over_iroh_and_web_presentations`: the server stalls after `world: records document ready` and never prints `node:`. It fails the same way on the phase-3 tip (3a51589d), so phase 4 did not cause it. Issue #190. +- One earlier run failed `test_an_interrupted_session_restarts_without_duplicates` under load and passed alone three times. Issue #188. +- Not run in this pass: `just crash-gate` and the nix checks. +- Open from the tracks: the heads merge for groups above 32 heads (issue #189), the joiner that misses an update made without knowing a concurrent add (issue #189), the held-message cap (issue #186), and stalled delivery on missing pre-join controls (issue #187).