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