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 corroboration;
58pub mod derive;
59pub mod envelope;
60pub mod error;
61pub mod freshness;
62pub mod identity_assertion;
63pub mod keypackage;
64pub mod prefixes;
65
66pub use canonical::{
67    canonical_payload, control_signing_payload, control_signing_payload_v2,
68    gateway_address_proof_payload, CTRL_PK_META_KEY, CTRL_SIGN_DOMAIN, CTRL_SIGN_DOMAIN_V2,
69    CTRL_SIG_META_KEY, GATEWAY_ADDR_SIGN_DOMAIN,
70};
71pub use constants::{
72    ACK_FOR_KEY, LEAF_KEY_PACKAGE_LIFETIME, LEAF_KEY_PACKAGE_NOT_BEFORE_BACKDATE_SECONDS,
73    LEAF_SENDER_RATCHET_MAXIMUM_FORWARD_DISTANCE, MAX_ACCEPTED_KEY_PACKAGE_LIFETIME,
74    SENDER_RATCHET_MAXIMUM_FORWARD_DISTANCE, SENDER_RATCHET_OUT_OF_ORDER_TOLERANCE,
75};
76pub use corroboration::{
77    SessionCorroboration, SESSION_CORROBORATION_LABEL, SESSION_CORROBORATION_NONCE_LEN,
78    SESSION_CORROBORATION_TAG_LEN,
79};
80pub use derive::{derive_address, ED25519_PUBLIC_KEY_LEN};
81pub use envelope::{EncryptedMessage, GroupId, MlsMessageType, WelcomeMessage};
82pub use error::{Result, SealedError};
83pub use freshness::{
84    control_frame_freshness, Freshness, CTRL_FRESHNESS_FUTURE_MS, CTRL_FRESHNESS_PAST_MS,
85    LEAF_CTRL_FRESHNESS_PAST_MS,
86};
87pub use identity_assertion::{
88    encode_identity_assertion, parse_identity_assertion, IdentityAssertion, ED25519_SIGNATURE_LEN,
89    IDENTITY_ASSERTION_MIN_LEN,
90};
91pub use keypackage::{
92    KeyPackagePayload, ACK_COALESCED_V1, ACK_UNDECRYPTABLE_V1, CTRL_SIGN_V2,
93    MLS_ENVELOPE_COMPACT_V1, SVC_SEALED_V1,
94};
95
96#[cfg(all(test, feature = "std"))]
97mod manifest_guard_tests {
98    /// Dependencies this crate declares locally instead of inheriting from the
99    /// workspace table, and which must therefore be kept in lockstep by hand.
100    /// See the comment above `[dependencies]` in this crate's `Cargo.toml` for
101    /// why inheritance is not an option here.
102    const LOCAL_DEPS: &[&str] = &[
103        "serde",
104        "serde_json",
105        "base64",
106        "thiserror",
107        "sha2",
108        "offline-protocol-core",
109    ];
110
111    /// Extracts the version requirement a manifest states for `name`.
112    ///
113    /// Handles both spellings cargo accepts: `name = "1.0"` and
114    /// `name = { version = "1.0", ... }`.
115    fn version_req(manifest: &str, name: &str) -> Option<String> {
116        let line = manifest
117            .lines()
118            .find(|l| l.starts_with(&format!("{name} = ")))?;
119        let rest = match line.find("version = \"") {
120            Some(i) => &line[i + "version = \"".len()..],
121            None => {
122                let i = line.find('"')?;
123                &line[i + 1..]
124            }
125        };
126        rest.find('"').map(|end| rest[..end].to_string())
127    }
128
129    /// The local dependency entries must not drift from the workspace table.
130    ///
131    /// Dropping inheritance is what makes `default-features = false` take
132    /// effect (cargo ignores it on an inherited dependency), but it also means
133    /// a workspace-wide version bump silently stops applying to this crate.
134    /// This test is what turns that silence into a failure.
135    #[test]
136    fn local_dep_versions_match_the_workspace_table() {
137        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
138        let root = dir.join("../../Cargo.toml");
139        // A published .crate archive contains no workspace root. Skip rather
140        // than panic: this guard protects the repo, and a packaged build that
141        // panics here fails the release for a condition it cannot observe.
142        let Ok(root_manifest) = std::fs::read_to_string(&root) else {
143            return;
144        };
145        let own_manifest =
146            std::fs::read_to_string(dir.join("Cargo.toml")).expect("own manifest is readable");
147
148        for dep in LOCAL_DEPS {
149            let workspace = version_req(&root_manifest, dep)
150                .unwrap_or_else(|| panic!("`{dep}` not found in the workspace dependency table"));
151            let own = version_req(&own_manifest, dep)
152                .unwrap_or_else(|| panic!("`{dep}` not found in this crate's manifest"));
153            assert_eq!(
154                workspace, own,
155                "`{dep}` version drifted: workspace says {workspace:?}, \
156                 offline-protocol-sealed says {own:?}. Update both together."
157            );
158        }
159    }
160}
161
162#[cfg(all(test, feature = "std"))]
163mod interop_harness_guard_tests {
164    /// `tools/mls-interop` is its own cargo workspace, so nothing in
165    /// `cargo test --workspace` compiles it and no type check connects it to
166    /// this crate. It is also the one harness whose whole purpose is to run
167    /// the SDK's configuration against a second MLS implementation, which it
168    /// stops doing the moment it declares its own copy of that configuration.
169    ///
170    /// It used to: a local `derive_address` and local ratchet constants, with
171    /// a manifest comment saying nothing pinned them. This test is what
172    /// replaced that comment, and it is the only thing in the workspace test
173    /// run that can notice them coming back.
174    #[test]
175    fn the_interop_harness_uses_this_crate_rather_than_its_own_copies() {
176        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
177        let harness = dir.join("../../tools/mls-interop");
178        // Absent in a published .crate archive; see the manifest guard above.
179        let (Ok(main_rs), Ok(manifest)) = (
180            std::fs::read_to_string(harness.join("src/main.rs")),
181            std::fs::read_to_string(harness.join("Cargo.toml")),
182        ) else {
183            eprintln!("tools/mls-interop not present, skipping harness copy check");
184            return;
185        };
186
187        assert!(
188            manifest.contains("offline-protocol-sealed"),
189            "the harness must depend on offline-protocol-sealed, not restate what it declares"
190        );
191
192        for symbol in [
193            "derive_address",
194            "SENDER_RATCHET_OUT_OF_ORDER_TOLERANCE",
195            "SENDER_RATCHET_MAXIMUM_FORWARD_DISTANCE",
196            "LEAF_SENDER_RATCHET_MAXIMUM_FORWARD_DISTANCE",
197            "LEAF_KEY_PACKAGE_LIFETIME",
198            "LEAF_KEY_PACKAGE_NOT_BEFORE_BACKDATE_SECONDS",
199            "MAX_ACCEPTED_KEY_PACKAGE_LIFETIME",
200        ] {
201            assert!(
202                main_rs.contains(symbol),
203                "the harness no longer references `{symbol}`; if it stopped needing it, \
204                 drop it from this list, but if it declared its own copy instead, do not"
205            );
206        }
207
208        // The copies themselves. A `fn derive_address` or a bare numeric
209        // constant here is the harness testing itself instead of the SDK.
210        for copy in [
211            "fn derive_address",
212            "const OUT_OF_ORDER_TOLERANCE",
213            "const MAXIMUM_FORWARD_DISTANCE",
214            "const LEAF_FORWARD_DISTANCE",
215            "const KEY_PACKAGE_LIFETIME",
216            "const NOT_BEFORE_BACKDATE",
217            "const MAX_ACCEPTED",
218        ] {
219            assert!(
220                !main_rs.contains(copy),
221                "`{copy}` is back in tools/mls-interop/src/main.rs: the harness has to use \
222                 offline-protocol-sealed's, or it stops testing the SDK's configuration"
223            );
224        }
225    }
226}
227
228#[cfg(all(test, feature = "std"))]
229mod second_codec_guard_tests {
230    /// Every `src/` tree in the workspace and the tools, except this crate's.
231    fn other_rust_sources() -> Vec<std::path::PathBuf> {
232        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
233        let mut out = Vec::new();
234        for group in ["crates", "tools"] {
235            let Ok(entries) = std::fs::read_dir(root.join(group)) else {
236                continue;
237            };
238            for entry in entries.flatten() {
239                let dir = entry.path();
240                if dir.file_name().and_then(|n| n.to_str()) == Some("offline-protocol-sealed") {
241                    continue;
242                }
243                collect_rs(&dir.join("src"), &mut out);
244            }
245        }
246        out
247    }
248
249    fn collect_rs(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
250        let Ok(entries) = std::fs::read_dir(dir) else {
251            return;
252        };
253        for entry in entries.flatten() {
254            let path = entry.path();
255            if path.is_dir() {
256                collect_rs(&path, out);
257            } else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
258                out.push(path);
259            }
260        }
261    }
262
263    /// The identity assertion was split three times before this crate held
264    /// it, once per bridge, and the Python copy was not even the same
265    /// format. The convenient route back is a harness, a transport or a
266    /// fixture writing `bytes[..32]`, `bytes[32..96]` and a second `fn
267    /// parse_identity_assertion` rather than taking the dependency. This is
268    /// the only thing in the workspace test run that can notice.
269    #[test]
270    fn no_other_crate_declares_an_identity_assertion_codec() {
271        let sources = other_rust_sources();
272        // A published .crate archive has no sibling crates; see the manifest
273        // guard above for why that is a skip and not a failure.
274        if sources.is_empty() {
275            eprintln!("no sibling crates present, skipping the second-codec check");
276            return;
277        }
278        for path in sources {
279            let text = std::fs::read_to_string(&path).expect("source is readable");
280            for copy in [
281                "fn parse_identity_assertion",
282                "fn encode_identity_assertion",
283            ] {
284                assert!(
285                    !text.contains(copy),
286                    "`{copy}` is declared in {}: the assertion layout has one home, \
287                     offline-protocol-sealed, and everything else calls it",
288                    path.display()
289                );
290            }
291        }
292    }
293}