Skip to main content

offline_protocol_sealed/
lib.rs

1//! The pieces both ends of a sealed conversation must agree on.
2//!
3//! A phone and a leaf node run different MLS implementations (ADR 0021: the
4//! phone runs OpenMLS, a Cortex-M leaf runs mls-rs), but they are not allowed
5//! to disagree about anything outside them. The envelope a ciphertext travels
6//! in, the derivation that turns an identity key into an address, the byte
7//! string a signature is taken over, and the ratchet numbers a session is
8//! configured with are all *shared* rather than *implemented twice*. This
9//! crate is where they live, and it exists because those pieces previously sat
10//! in crates a leaf node cannot link.
11//!
12//! Each piece is here for the same reason, stated as the failure a second copy
13//! causes:
14//!
15//! - [`envelope`]: two copies of the codec are two wire formats the moment one
16//!   is edited alone, and the symptom is a peer that cannot read a message.
17//! - [`mod@derive`]: two derivations are two identities for one key, and every
18//!   trust gate in the protocol is a derive-and-compare, so a drifted copy
19//!   rejects legitimate peers or, worse, accepts a mismatched one.
20//! - [`canonical`]: a verifier that rebuilds a signing payload differently
21//!   from the signer either rejects every signature or, if the difference is
22//!   an ambiguity rather than a mismatch, accepts a forged one.
23//! - [`constants`]: a number configured differently on the two ends produces
24//!   a session that silently stops decrypting under load.
25//! - [`freshness`]: two ends that disagree about how old a signed control
26//!   frame may be produce a pair that refuses its own traffic in one direction
27//!   and accepts a replayed frame in the other.
28//! - [`identity_assertion`]: a second copy of the byte layout a peer proves
29//!   its address with is a peer one platform can verify and another cannot,
30//!   and the symptom is a link that carries frames the receiving core then
31//!   refuses as unattributed.
32//!
33//! # Why this is not part of `offline-protocol-core`
34//!
35//! Core links no cryptography at all, deliberately, and address derivation is
36//! a SHA-256. Core also knows nothing about MLS, and these types name it.
37//! Putting them in core would push a hash implementation into every consumer
38//! of the protocol's base types, including a relay-only leaf image that never
39//! derives an address. See ADR 0022.
40//!
41//! # Building without `std`
42//!
43//! Like [`offline_protocol_core`], this crate compiles for bare-metal targets
44//! with `--no-default-features`, and `alloc` is required in both
45//! configurations. Nothing here reads a clock, draws entropy or takes a lock,
46//! so unlike core the no_std configuration loses no functionality: the `std`
47//! feature only forwards to dependencies.
48
49#![cfg_attr(not(feature = "std"), no_std)]
50#![deny(unsafe_code)]
51#![warn(missing_docs)]
52
53extern crate alloc;
54
55pub mod canonical;
56pub mod constants;
57pub mod derive;
58pub mod envelope;
59pub mod error;
60pub mod freshness;
61pub mod identity_assertion;
62pub mod keypackage;
63pub mod prefixes;
64
65pub use canonical::{
66    canonical_payload, control_signing_payload, control_signing_payload_v2,
67    gateway_address_proof_payload, CTRL_PK_META_KEY, CTRL_SIGN_DOMAIN, CTRL_SIGN_DOMAIN_V2,
68    CTRL_SIG_META_KEY, GATEWAY_ADDR_SIGN_DOMAIN,
69};
70pub use constants::{
71    ACK_FOR_KEY, LEAF_KEY_PACKAGE_LIFETIME, LEAF_KEY_PACKAGE_NOT_BEFORE_BACKDATE_SECONDS,
72    MAX_ACCEPTED_KEY_PACKAGE_LIFETIME, SENDER_RATCHET_MAXIMUM_FORWARD_DISTANCE,
73    SENDER_RATCHET_OUT_OF_ORDER_TOLERANCE,
74};
75pub use derive::{derive_address, ED25519_PUBLIC_KEY_LEN};
76pub use envelope::{EncryptedMessage, GroupId, MlsMessageType, WelcomeMessage};
77pub use error::{Result, SealedError};
78pub use freshness::{
79    control_frame_freshness, Freshness, CTRL_FRESHNESS_FUTURE_MS, CTRL_FRESHNESS_PAST_MS,
80    LEAF_CTRL_FRESHNESS_PAST_MS,
81};
82pub use identity_assertion::{
83    encode_identity_assertion, parse_identity_assertion, IdentityAssertion, ED25519_SIGNATURE_LEN,
84    IDENTITY_ASSERTION_MIN_LEN,
85};
86pub use keypackage::{
87    KeyPackagePayload, ACK_UNDECRYPTABLE_V1, CTRL_SIGN_V2, MLS_ENVELOPE_COMPACT_V1, SVC_SEALED_V1,
88};
89
90#[cfg(all(test, feature = "std"))]
91mod manifest_guard_tests {
92    /// Dependencies this crate declares locally instead of inheriting from the
93    /// workspace table, and which must therefore be kept in lockstep by hand.
94    /// See the comment above `[dependencies]` in this crate's `Cargo.toml` for
95    /// why inheritance is not an option here.
96    const LOCAL_DEPS: &[&str] = &[
97        "serde",
98        "serde_json",
99        "base64",
100        "thiserror",
101        "sha2",
102        "offline-protocol-core",
103    ];
104
105    /// Extracts the version requirement a manifest states for `name`.
106    ///
107    /// Handles both spellings cargo accepts: `name = "1.0"` and
108    /// `name = { version = "1.0", ... }`.
109    fn version_req(manifest: &str, name: &str) -> Option<String> {
110        let line = manifest
111            .lines()
112            .find(|l| l.starts_with(&format!("{name} = ")))?;
113        let rest = match line.find("version = \"") {
114            Some(i) => &line[i + "version = \"".len()..],
115            None => {
116                let i = line.find('"')?;
117                &line[i + 1..]
118            }
119        };
120        rest.find('"').map(|end| rest[..end].to_string())
121    }
122
123    /// The local dependency entries must not drift from the workspace table.
124    ///
125    /// Dropping inheritance is what makes `default-features = false` take
126    /// effect (cargo ignores it on an inherited dependency), but it also means
127    /// a workspace-wide version bump silently stops applying to this crate.
128    /// This test is what turns that silence into a failure.
129    #[test]
130    fn local_dep_versions_match_the_workspace_table() {
131        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
132        let root = dir.join("../../Cargo.toml");
133        // A published .crate archive contains no workspace root. Skip rather
134        // than panic: this guard protects the repo, and a packaged build that
135        // panics here fails the release for a condition it cannot observe.
136        let Ok(root_manifest) = std::fs::read_to_string(&root) else {
137            return;
138        };
139        let own_manifest =
140            std::fs::read_to_string(dir.join("Cargo.toml")).expect("own manifest is readable");
141
142        for dep in LOCAL_DEPS {
143            let workspace = version_req(&root_manifest, dep)
144                .unwrap_or_else(|| panic!("`{dep}` not found in the workspace dependency table"));
145            let own = version_req(&own_manifest, dep)
146                .unwrap_or_else(|| panic!("`{dep}` not found in this crate's manifest"));
147            assert_eq!(
148                workspace, own,
149                "`{dep}` version drifted: workspace says {workspace:?}, \
150                 offline-protocol-sealed says {own:?}. Update both together."
151            );
152        }
153    }
154}
155
156#[cfg(all(test, feature = "std"))]
157mod interop_harness_guard_tests {
158    /// `tools/mls-interop` is its own cargo workspace, so nothing in
159    /// `cargo test --workspace` compiles it and no type check connects it to
160    /// this crate. It is also the one harness whose whole purpose is to run
161    /// the SDK's configuration against a second MLS implementation, which it
162    /// stops doing the moment it declares its own copy of that configuration.
163    ///
164    /// It used to: a local `derive_address` and local ratchet constants, with
165    /// a manifest comment saying nothing pinned them. This test is what
166    /// replaced that comment, and it is the only thing in the workspace test
167    /// run that can notice them coming back.
168    #[test]
169    fn the_interop_harness_uses_this_crate_rather_than_its_own_copies() {
170        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
171        let harness = dir.join("../../tools/mls-interop");
172        // Absent in a published .crate archive; see the manifest guard above.
173        let (Ok(main_rs), Ok(manifest)) = (
174            std::fs::read_to_string(harness.join("src/main.rs")),
175            std::fs::read_to_string(harness.join("Cargo.toml")),
176        ) else {
177            eprintln!("tools/mls-interop not present, skipping harness copy check");
178            return;
179        };
180
181        assert!(
182            manifest.contains("offline-protocol-sealed"),
183            "the harness must depend on offline-protocol-sealed, not restate what it declares"
184        );
185
186        for symbol in [
187            "derive_address",
188            "SENDER_RATCHET_OUT_OF_ORDER_TOLERANCE",
189            "SENDER_RATCHET_MAXIMUM_FORWARD_DISTANCE",
190            "LEAF_KEY_PACKAGE_LIFETIME",
191            "LEAF_KEY_PACKAGE_NOT_BEFORE_BACKDATE_SECONDS",
192            "MAX_ACCEPTED_KEY_PACKAGE_LIFETIME",
193        ] {
194            assert!(
195                main_rs.contains(symbol),
196                "the harness no longer references `{symbol}`; if it stopped needing it, \
197                 drop it from this list, but if it declared its own copy instead, do not"
198            );
199        }
200
201        // The copies themselves. A `fn derive_address` or a bare numeric
202        // constant here is the harness testing itself instead of the SDK.
203        for copy in [
204            "fn derive_address",
205            "const OUT_OF_ORDER_TOLERANCE",
206            "const MAXIMUM_FORWARD_DISTANCE",
207            "const KEY_PACKAGE_LIFETIME",
208            "const NOT_BEFORE_BACKDATE",
209            "const MAX_ACCEPTED",
210        ] {
211            assert!(
212                !main_rs.contains(copy),
213                "`{copy}` is back in tools/mls-interop/src/main.rs: the harness has to use \
214                 offline-protocol-sealed's, or it stops testing the SDK's configuration"
215            );
216        }
217    }
218}
219
220#[cfg(all(test, feature = "std"))]
221mod second_codec_guard_tests {
222    /// Every `src/` tree in the workspace and the tools, except this crate's.
223    fn other_rust_sources() -> Vec<std::path::PathBuf> {
224        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
225        let mut out = Vec::new();
226        for group in ["crates", "tools"] {
227            let Ok(entries) = std::fs::read_dir(root.join(group)) else {
228                continue;
229            };
230            for entry in entries.flatten() {
231                let dir = entry.path();
232                if dir.file_name().and_then(|n| n.to_str()) == Some("offline-protocol-sealed") {
233                    continue;
234                }
235                collect_rs(&dir.join("src"), &mut out);
236            }
237        }
238        out
239    }
240
241    fn collect_rs(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
242        let Ok(entries) = std::fs::read_dir(dir) else {
243            return;
244        };
245        for entry in entries.flatten() {
246            let path = entry.path();
247            if path.is_dir() {
248                collect_rs(&path, out);
249            } else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
250                out.push(path);
251            }
252        }
253    }
254
255    /// The identity assertion was split three times before this crate held
256    /// it, once per bridge, and the Python copy was not even the same
257    /// format. The convenient route back is a harness, a transport or a
258    /// fixture writing `bytes[..32]`, `bytes[32..96]` and a second `fn
259    /// parse_identity_assertion` rather than taking the dependency. This is
260    /// the only thing in the workspace test run that can notice.
261    #[test]
262    fn no_other_crate_declares_an_identity_assertion_codec() {
263        let sources = other_rust_sources();
264        // A published .crate archive has no sibling crates; see the manifest
265        // guard above for why that is a skip and not a failure.
266        if sources.is_empty() {
267            eprintln!("no sibling crates present, skipping the second-codec check");
268            return;
269        }
270        for path in sources {
271            let text = std::fs::read_to_string(&path).expect("source is readable");
272            for copy in [
273                "fn parse_identity_assertion",
274                "fn encode_identity_assertion",
275            ] {
276                assert!(
277                    !text.contains(copy),
278                    "`{copy}` is declared in {}: the assertion layout has one home, \
279                     offline-protocol-sealed, and everything else calls it",
280                    path.display()
281                );
282            }
283        }
284    }
285}