offline_protocol/protocol/receive.rs
1//! Message receive loop and file chunk handling.
2
3use super::mesh_relay::RelayAdmission as MeshRelayAdmission;
4use super::{
5 internal_prefixes, lock_shared_state, ChunkOutcome, InternalMessageResult, OfflineProtocol,
6 PendingMediaMetadataEntry, ProtocolState, RichPayloadV1, CRITICAL_RELAY_BATTERY_LEVEL,
7};
8use crate::constants::ACK_FOR_KEY;
9use crate::events::{Event, SecurityWarningCode};
10use crate::file_transfer::FileChunk;
11use crate::media_envelope::{decode_media_envelope, is_media_envelope, MediaChunkPlaintext};
12use crate::mls_observability::{DecryptionFailureKind, MlsErrorCategory, MlsOperationContext};
13use crate::SessionStateError;
14use offline_protocol_core::{ContentType, MediaMetadata, Message};
15use offline_protocol_mls::{EncryptedMessage, GroupId};
16use offline_protocol_router::relay::RelayPriority;
17use offline_protocol_transport::TransportType;
18use std::time::Instant;
19use tracing::{debug, error, info, warn};
20
21impl OfflineProtocol {
22 /// Applies a successful MLS decryption to an inbound message: swaps the
23 /// ciphertext for the plaintext, marks the message encrypted, drops the
24 /// outer `reply_context`, and restores rich fields from a sealed
25 /// `__RICH_V1__` body when present.
26 ///
27 /// The outer `reply_context` field is hop-visible cleartext that any
28 /// relay can inject or rewrite in transit — it sits outside the MLS AEAD
29 /// boundary. The strip happens unconditionally *before* the sealed-body
30 /// restore below, so the encrypted envelope is the only trusted carrier
31 /// for reply context on encrypted messages. Without this strip, a
32 /// `MessageReceived { encrypted: true }` event could surface an
33 /// attacker-controlled quote preview as if it were part of the
34 /// authenticated conversation.
35 ///
36 /// Sealed-body parsing is never capability-gated (mirroring envelope
37 /// parsing): whatever a peer chose to seal, we try to read. On a rich
38 /// message the sealed body is authoritative for `reply_context`,
39 /// `media_metadata`, and `forwarded_from` — the relay-writable outer
40 /// copies are overwritten wholesale, `None`s included — and for
41 /// `content_type` when the body carries one (absent from bodies sealed
42 /// by senders predating the field, where the outer hint stands). The
43 /// sealed `content_type` restore runs before the receive loop's
44 /// `FileChunk` routing, so a relay restamping an encrypted rich
45 /// message's outer hint can no longer misroute it; `FileChunk` itself
46 /// is refused from the sealed body (mirroring the send boundary), or a
47 /// hostile sender could steer an ordinary message into the
48 /// file-transfer manager, which drops it. A body that fails to parse
49 /// (including a hostile `reply_context.sender` rejected by `UserId`
50 /// validation) surfaces as raw text with a warning rather than
51 /// dropping an authenticated message.
52 pub(super) fn apply_decrypted_content(message: &mut Message, plaintext: String) {
53 message.reply_context = None;
54 if plaintext.starts_with(internal_prefixes::RICH_V1) {
55 match RichPayloadV1::parse_sealed(&plaintext, message.sender.as_str()) {
56 Some(rich) => {
57 message.content = rich.text;
58 message.reply_context = rich.reply_context;
59 message.media_metadata = rich.media_metadata;
60 message.forwarded_from = rich.forward_info;
61 // `parse_sealed` already refused a FileChunk claim; a
62 // remaining None keeps the outer value (bodies sealed by
63 // senders predating the field).
64 if let Some(content_type) = rich.content_type {
65 message.content_type = content_type;
66 }
67 }
68 None => {
69 message.content = plaintext;
70 }
71 }
72 } else {
73 message.content = plaintext;
74 }
75 message
76 .metadata
77 .insert("encrypted".to_string(), "true".to_string());
78 }
79
80 /// Receives the next available message.
81 pub fn receive_message(&mut self) -> Option<Message> {
82 let Ok(mut state) = lock_shared_state(&self.shared_state) else {
83 error!("Failed to lock shared state in receive_message");
84 return None;
85 };
86 let protocol_running = state.state == ProtocolState::Running;
87
88 if !state.received_messages.is_empty() {
89 return state.received_messages.pop_front();
90 }
91
92 drop(state);
93
94 // Drive confirmation maintenance from receive polling as an additional
95 // liveness source when the app does not call process() on a timer.
96 // Uses the same throttle as process() to avoid redundant storage I/O.
97 if protocol_running {
98 self.run_throttled_reconciliation("receive_message_poll");
99 }
100
101 loop {
102 match self.transport_manager.receive() {
103 Ok(Some((transport_used, mut message))) => {
104 // The peer whose link this frame physically arrived on.
105 // Distinct from `message.sender`, which is who wrote it:
106 // the two agree only at the first hop. `None` when the
107 // carrier does not identify links (Nostr) or the platform
108 // did not supply an id.
109 let arrival_peer = message.transport_peer_id().map(str::to_string);
110
111 // Traffic for someone else is forwarded, not processed, and
112 // that decision comes first.
113 //
114 // Everything below this point treats the frame as part of
115 // our own exchange: it merges the sender's clock into ours,
116 // settles our outbox from acknowledgements, and consumes the
117 // frame. None of that is true of a frame merely passing
118 // through us — its acknowledgements belong to the pair it
119 // travels between, and once a node carries the whole
120 // neighborhood's traffic, absorbing every clock it sees
121 // would drag ours to the network's maximum.
122 //
123 // Never forward a frame claiming our own origin: a genuine
124 // self-originated frame is never received inbound with a
125 // foreign recipient (the send path does not loop back), so
126 // this is a routing loop or a forgery aimed at
127 // `internet_control_op`'s self-origination gate — re-issuing
128 // it from our outbox would let a mesh peer drive
129 // relay-native control ops on our authenticated relay
130 // connection. (A sender==self frame addressed *to* us is the
131 // legitimate relay echo and falls through unchanged.)
132 if message.recipient.as_str() != self.local_id {
133 if message.sender.as_str() == self.local_id {
134 debug!(
135 message_id = %message.id,
136 recipient = %message.recipient,
137 "Dropping inbound frame forging our own origin"
138 );
139 continue;
140 }
141 self.try_relay_message(&message, arrival_peer.as_deref());
142 continue;
143 }
144
145 // Block filter (early): check before any side-effects so
146 // that blocked users cannot advance our Lamport clock,
147 // leak our presence via re-ACK, or trigger any processing.
148 let sender_blocked = self.is_user_blocked(message.sender.as_str());
149
150 // Merge Lamport clock for every non-blocked received message
151 // — including duplicates, ACKs, and internal protocol
152 // messages — so the local clock always advances past any
153 // observed peer value.
154 if !sender_blocked && message.lamport_clock.value() > 0 {
155 self.lamport_clock.merge(message.lamport_clock);
156 self.persist_lamport_clock();
157 }
158
159 if message.metadata.contains_key(ACK_FOR_KEY) {
160 if !sender_blocked {
161 self.handle_ack_message(&message);
162 }
163 continue;
164 }
165
166 if self.deduplicator.is_duplicate_mut(&message.id) {
167 // Re-ACK duplicate packets so the sender can stop
168 // retrying — but NOT for blocked users, to avoid
169 // leaking presence information.
170 //
171 // Every copy is answered, including the several that
172 // one delivery produces when it travels through nearby
173 // devices. Answering only the first was tried and
174 // rejected: a copy arriving moments later and a
175 // retransmission arriving because the answer was lost
176 // are not distinguishable here, and staying quiet for
177 // the second turns a delivered message into a failed
178 // one. The redundant answers are bounded — a delivery
179 // arrives by at most as many paths as neighbors carried
180 // it, answers never provoke further answers, and every
181 // frame that leaves is rate-capped like any other.
182 if !sender_blocked && message.requires_ack {
183 if let Err(err) = self.send_delivery_ack(&message, transport_used) {
184 error!(
185 message_id = %message.id,
186 error = %err,
187 "Failed to send delivery ACK for duplicate message"
188 );
189 }
190 }
191 continue;
192 }
193
194 // Block filter: silently drop messages from blocked users
195 // addressed to us. No ACK, no event, no side-effects.
196 // Checked before mark_seen so that if the user is later
197 // unblocked, retransmissions can still be delivered.
198 if sender_blocked {
199 debug!(
200 sender = %message.sender,
201 message_id = %message.id,
202 "Dropping message from blocked user"
203 );
204 continue;
205 }
206
207 self.mark_seen_persisted(message.id.clone());
208
209 // Handle internal MLS messages
210 let mut was_decrypted = false;
211 if let Some(result) =
212 self.process_internal_message_via(&message, Some(transport_used))
213 {
214 match result {
215 InternalMessageResult::Consumed => {
216 // Internal control messages are still delivery-sensitive for
217 // the sender (invites/accept/welcome). ACK before consume.
218 if message.requires_ack {
219 if let Err(err) =
220 self.send_delivery_ack(&message, transport_used)
221 {
222 error!(
223 message_id = %message.id,
224 error = %err,
225 "Failed to send delivery ACK for internal message"
226 );
227 }
228 }
229 // Internal message handled, don't surface to app
230 continue;
231 }
232 InternalMessageResult::SecurityRejected => {
233 // Security gate rejected this message (spoofed sender,
234 // bad signature, unsigned control traffic, or a signing
235 // key that does not derive to the claimed sender
236 // address). Do NOT send a delivery
237 // ACK — acknowledging would confirm to the attacker that
238 // the target peer is online and processing messages.
239 // Forget the id too, or an exact replay would hit the
240 // duplicate re-ACK path above and leak that presence
241 // anyway; reprocessing a replay costs no more than a
242 // fresh forged message.
243 self.unmark_seen_persisted(&message.id);
244 continue;
245 }
246 InternalMessageResult::Deferred => {
247 // The message was not delivered, but the sender
248 // can still recover it by resending: it could not
249 // be decrypted *yet* (session not ready, so queued
250 // for delayed decryption), or it is undecryptable
251 // as it stands (epoch desync, or a hard crypto
252 // failure while `crypto_recovery_enabled`) and was
253 // dropped without queueing. See the three
254 // conditions on `InternalMessageResult::Deferred`.
255 //
256 // Do NOT send a delivery ACK and do NOT keep the id
257 // dedup-marked: the message is not delivered, so the
258 // sender must be free to retry and that retry must
259 // re-enter processing rather than hit the duplicate
260 // re-ACK path above. For a queued copy, the session
261 // confirming drains it: the message is surfaced and
262 // the id re-marked (see `process_pending_decryption`),
263 // so the sender's next resend is then deduped +
264 // re-ACKed. For the other two, recovery is that
265 // resend itself — re-sealed against a live
266 // generation by Tier 2.
267 self.unmark_seen_persisted(&message.id);
268 continue;
269 }
270 InternalMessageResult::Decrypted(plaintext) => {
271 was_decrypted = true;
272 Self::apply_decrypted_content(&mut message, plaintext);
273 }
274 }
275 }
276
277 // Policy gate for inbound plaintext (SEC: inbound text must
278 // honor require_encryption exactly like legacy media does).
279 // A message that reaches this point without decryption is
280 // unauthenticated cleartext with an attacker-controllable
281 // sender. FileChunk messages are exempt: encrypted media
282 // envelopes carry no content prefix (the ciphertext rides
283 // in binary_content), so they are indistinguishable from
284 // plaintext here — handle_incoming_file_chunk applies this
285 // same gate after telling the two apart. Rejection sends
286 // no delivery ACK, mirroring SecurityRejected: don't
287 // confirm to an injector that the target processes their
288 // messages. The id is forgotten so a replay re-enters
289 // this gate instead of the duplicate re-ACK path.
290 if !was_decrypted
291 && message.content_type != ContentType::FileChunk
292 && !self.accept_plaintext_content(message.sender.as_str())
293 {
294 warn!(
295 message_id = %message.id,
296 sender = %message.sender,
297 "Rejecting unencrypted inbound message (encryption policy)"
298 );
299 self.warn_plaintext_receive_rejected(
300 message.sender.as_str(),
301 "Inbound plaintext message rejected by encryption policy",
302 );
303 self.unmark_seen_persisted(&message.id);
304 continue;
305 }
306
307 // Route file-chunk messages to the transfer manager BEFORE
308 // the delivery ACK, and never surface them to the app as
309 // regular messages. An encrypted chunk that was not
310 // delivered but that the sender can still recover by
311 // resending — not decryptable yet (session not ready, so
312 // queued for delayed decryption), or undecryptable as it
313 // stands (epoch desync, crypto failure) — returns
314 // `Deferred`: it must NOT be ACKed and its id is unmarked,
315 // so the sender keeps retrying and the resend re-enters
316 // processing, matching the text `Deferred` path. Every other
317 // outcome (`Handled`: decrypted/assembled, or a terminal
318 // drop) is ACKed as before, since the sender cannot recover
319 // it by retrying.
320 if message.content_type == ContentType::FileChunk {
321 match self.handle_incoming_file_chunk_via(&message, Some(transport_used)) {
322 ChunkOutcome::Deferred => {
323 self.unmark_seen_persisted(&message.id);
324 }
325 // Plaintext chunk rejected by encryption policy:
326 // withhold the ACK and unmark the id, exactly like
327 // the plaintext-text rejection above and the text
328 // `SecurityRejected` path — don't confirm to an
329 // injector that we process their messages, and let a
330 // replay re-enter the gate rather than hit the
331 // duplicate re-ACK path.
332 ChunkOutcome::Rejected => {
333 self.unmark_seen_persisted(&message.id);
334 }
335 ChunkOutcome::Handled => {
336 if message.requires_ack {
337 if let Err(err) =
338 self.send_delivery_ack(&message, transport_used)
339 {
340 error!(
341 message_id = %message.id,
342 error = %err,
343 "Failed to send delivery ACK for media chunk"
344 );
345 }
346 }
347 }
348 }
349 continue;
350 }
351
352 if message.requires_ack {
353 if let Err(err) = self.send_delivery_ack(&message, transport_used) {
354 error!(
355 message_id = %message.id,
356 error = %err,
357 "Failed to send delivery ACK"
358 );
359 }
360 }
361
362 let forward_info = message
363 .forwarded_from
364 .as_ref()
365 .map(crate::events::ForwardInfoEvent::from);
366
367 let event = Event::MessageReceived {
368 message_id: message.id.as_str(),
369 sender: message.sender.as_str().to_string(),
370 recipient: message.recipient.as_str().to_string(),
371 content: message.content.clone(),
372 hop_count: message.hop_count.value(),
373 transport: transport_used.to_string(),
374 timestamp: message.timestamp.as_millis(),
375 lamport_clock: message.lamport_clock.value(),
376 reply_to_msg: message
377 .reply_to_msg
378 .as_ref()
379 .map(|id| id.as_str().to_string()),
380 reply_context: message
381 .reply_context
382 .as_ref()
383 .map(|rc| Box::new(crate::events::ReplyContextEvent::from(rc))),
384 content_type: message.content_type.to_string(),
385 media_metadata: message.media_metadata.clone(),
386 forward_info,
387 encrypted: was_decrypted,
388 app_id: message.app_id.as_str().to_string(),
389 };
390
391 let Ok(state) = lock_shared_state(&self.shared_state) else {
392 error!("Failed to lock shared state for message received event");
393 return None;
394 };
395 state.emit_event(event);
396 drop(state);
397
398 return Some(message);
399 }
400 Ok(None) => return None,
401 Err(err) => {
402 error!(error = %err, "Transport receive error");
403 return None;
404 }
405 }
406 }
407 }
408
409 /// Considers an inbound frame addressed to a third party for forwarding.
410 ///
411 /// Learns the route back toward the sender, then offers the frame to the
412 /// governor, which decides whether it travels any further. Nothing is
413 /// transmitted here: an accepted frame is queued and goes out from
414 /// [`Self::flush_mesh_relays`] once its delay elapses, which is what gives
415 /// a neighbor the chance to cover it first.
416 ///
417 /// `arrival_peer` is the neighbor that handed us this frame, when the
418 /// carrier identified the link.
419 fn try_relay_message(&mut self, message: &Message, arrival_peer: Option<&str>) {
420 // Cheapest answer first. This device sees the whole neighborhood's
421 // traffic, so in a crowded room most third-party arrivals are copies of
422 // a frame it has already dealt with — and everything below would be
423 // thrown away by the suppression check inside `admit`: a route-table
424 // write, a battery snapshot that locks and allocates across every
425 // transport, and an enumeration of every link. Answering a duplicate
426 // costs a hash lookup instead.
427 //
428 // Route learning is skipped along with the rest, which is deliberate:
429 // the copy teaches nothing the first one did not, and the table is not
430 // what forwarding decisions are made from. A duplicate we still hold a
431 // pending copy of is *not* absorbed here: it narrows that forward's
432 // fan-out, which `admit` records, so that case still takes the full
433 // path.
434 if self
435 .mesh_relay
436 .absorb_settled_duplicate(&message.id.as_str())
437 {
438 return;
439 }
440
441 // Carrying traffic for others costs this device's radio and battery,
442 // so it stays a local decision.
443 let relay_allowed = self.config.relay.allow_relay
444 && self.config.relay.relay_priority != RelayPriority::Never;
445
446 if !relay_allowed {
447 debug!(
448 message_id = %message.id,
449 "Not forwarding: relaying is disabled on this device"
450 );
451 return;
452 }
453
454 // Carrying other people's messages is the first thing to give up when
455 // the battery is going: a device that spends its last few percent
456 // relaying cannot send its own message when its owner needs to. The
457 // device keeps sending and receiving its own traffic either way.
458 //
459 // An unknown battery level is treated as willing — most platforms
460 // report one, and refusing to carry anything on a device that simply
461 // does not publish a level would quietly remove it from the network.
462 if !self.battery_allows_relaying() {
463 debug!(
464 message_id = %message.id,
465 "Not forwarding: battery is below the level for carrying traffic"
466 );
467 return;
468 }
469
470 let degree = self.transport_manager.mesh_neighbors().len();
471 match self.mesh_relay.admit(message, arrival_peer, degree) {
472 MeshRelayAdmission::Queued => {
473 debug!(
474 message_id = %message.id,
475 recipient = %message.recipient,
476 degree,
477 "Queued frame for forwarding"
478 );
479 }
480 MeshRelayAdmission::Rejected(reason) => {
481 debug!(
482 message_id = %message.id,
483 ?reason,
484 "Not forwarding"
485 );
486 }
487 }
488 }
489
490 /// Whether the battery is healthy enough to carry other people's traffic.
491 ///
492 /// Takes its own battery reading; the per-tick caller already holds one and
493 /// uses [`Self::battery_allows_relaying_with`] instead.
494 pub(super) fn battery_allows_relaying(&self) -> bool {
495 let (_statuses, available) = self.transport_manager.snapshot_status_and_available();
496 let (battery_level, is_charging) =
497 crate::telemetry::aggregator::device_battery_from_available(
498 self.transport_manager.current_transport(),
499 &available,
500 );
501 self.battery_allows_relaying_with(battery_level, is_charging)
502 }
503
504 /// [`Self::battery_allows_relaying`] against a reading the caller already
505 /// has.
506 ///
507 /// An unknown level means yes — see [`Self::try_relay_message`].
508 pub(super) fn battery_allows_relaying_with(
509 &self,
510 battery_level: Option<u8>,
511 is_charging: bool,
512 ) -> bool {
513 let Some(level) = battery_level else {
514 return true;
515 };
516 level >= self.relay_battery_floor(is_charging)
517 }
518
519 /// The battery level below which this device stops carrying other people's
520 /// traffic.
521 ///
522 /// [`RelayConfig::min_battery_for_relay`] is the floor in the ordinary
523 /// case, relaxed to the hard [`CRITICAL_RELAY_BATTERY_LEVEL`] for a device
524 /// that is either charging or configured [`RelayPriority::Always`] — the
525 /// two ways of saying "keep relaying anyway". The hard floor is never
526 /// crossed: it applies even to a configured minimum set below it, because
527 /// spending the last few percent on strangers' traffic leaves a device
528 /// unable to send its own.
529 pub(super) fn relay_battery_floor(&self, is_charging: bool) -> u8 {
530 let eager = matches!(self.config.relay.relay_priority, RelayPriority::Always);
531 if is_charging || eager {
532 CRITICAL_RELAY_BATTERY_LEVEL
533 } else {
534 self.config
535 .relay
536 .min_battery_for_relay
537 .max(CRITICAL_RELAY_BATTERY_LEVEL)
538 }
539 }
540
541 /// Transmits the forwards whose delay has elapsed.
542 ///
543 /// Called from the process tick. Each frame goes to a bounded set of
544 /// neighbors chosen by the governor, never back to the peer it came from or
545 /// to the peer that wrote it. A frame whose recipient is a neighbor of ours
546 /// is handed straight to them instead — the shortest path we can see.
547 pub(super) fn flush_mesh_relays(&mut self) {
548 self.flush_mesh_relays_at(Instant::now());
549 }
550
551 /// [`Self::flush_mesh_relays`] at a given instant, so a test can walk a
552 /// forward past the overdue cut-off without waiting it out.
553 pub(super) fn flush_mesh_relays_at(&mut self, now: Instant) {
554 let (due, abandoned) = self.mesh_relay.release_due(now);
555
556 // The drop point (`docs/spec/custody.md`): an ordinary forward here
557 // waited past the overdue cut-off without reaching a link, and its
558 // id is already released from the suppression cache; custody may
559 // take it on. A marked held forward goes back to the store, unjudged
560 // and uncounted.
561 for relay in abandoned {
562 self.judge_at_drop_point(relay);
563 }
564
565 if due.is_empty() {
566 return;
567 }
568
569 let neighbors = self.transport_manager.mesh_neighbors();
570
571 // `relay` is borrowed rather than destructured throughout: a frame that
572 // reaches no neighbor has to be handed back whole, and cloning the
573 // message to keep that option open would copy the payload — up to a
574 // whole media chunk — on every flush.
575 for relay in due {
576 let message = &relay.message;
577 let recipient = message.recipient.as_str().to_string();
578 let message_id = message.id.as_str();
579 let hop_count = message.hop_count.value();
580 let remaining_ttl = message.ttl.value();
581 let held = relay.custody_target.is_some();
582 let cause = if held {
583 "custody_redelivery"
584 } else {
585 "forward"
586 };
587
588 let targets = if let Some(target) = relay.custody_target.as_deref() {
589 // A held frame goes to the one neighbor it was queued toward,
590 // never through target selection: a fan-out here would defeat
591 // at most once per neighbor. Gone from range, it goes nowhere
592 // and back to the store below.
593 if neighbors.iter().any(|n| n.peer_id == target) {
594 vec![target.to_string()]
595 } else {
596 Vec::new()
597 }
598 } else {
599 let mut exclude: Vec<&str> = vec![message.sender.as_str()];
600 if let Some(peer) = relay.arrival_peer.as_deref() {
601 exclude.push(peer);
602 }
603 // Neighbors that handed us a copy while this waited hold the
604 // frame already (`MeshRelayGovernor::admit`).
605 exclude.extend(relay.heard_from.iter().map(String::as_str));
606 let onward = self.mesh_relay.select_targets(
607 neighbors
608 .iter()
609 .map(|n| (n.peer_id.as_str(), n.link_quality())),
610 &exclude,
611 &message_id,
612 );
613
614 // If the destination is one of our own neighbors, hand it over
615 // directly: no fan-out is worth more than arriving. Should that
616 // link fail between choosing it and writing to it, fall back to
617 // carrying it onward rather than dropping a frame we could still
618 // move.
619 if neighbors.iter().any(|n| n.peer_id == recipient) {
620 let mut ordered = vec![recipient.clone()];
621 ordered.extend(onward.into_iter().filter(|peer| peer != &recipient));
622 ordered
623 } else {
624 onward
625 }
626 };
627 let deliver_direct = targets.first() == Some(&recipient);
628
629 // Every neighbor we could hand it to has handed it to us. This is
630 // the one way a duplicate ends a forward: the frame is not lost,
631 // it is held all around us, and requeueing it would only spend
632 // the next ticks finding the same answer.
633 if targets.is_empty()
634 && !held
635 && !relay.heard_from.is_empty()
636 && neighbors
637 .iter()
638 .any(|n| relay.heard_from.iter().any(|peer| peer == &n.peer_id))
639 {
640 debug!(
641 message_id = %message.id,
642 "Every onward neighbor already holds this frame"
643 );
644 self.mesh_relay.drop_covered(relay);
645 continue;
646 }
647
648 if targets.is_empty() {
649 // Nowhere to hand it right now: we hold no link, or the only
650 // ones we hold are the peers this frame must not go back to.
651 // Falls through to the hand-back below rather than being
652 // dropped — a neighbor may well appear within the few seconds
653 // the frame is still worth carrying.
654 debug!(
655 message_id = %message.id,
656 cause,
657 "No onward neighbor for this frame"
658 );
659 }
660
661 let mut delivered_to = 0usize;
662 let mut reached_recipient = false;
663 for target in &targets {
664 // Each link this frame crosses is one transmission against the
665 // device's ceiling. Running out mid-fan-out stops the fan-out
666 // rather than the frame: the neighbors already reached carry it
667 // on, and the sender's retry covers the rest.
668 if !self.mesh_relay.take_send_token() {
669 debug!(
670 message_id = %message.id,
671 "At the forwarding limit; stopping this fan-out here"
672 );
673 break;
674 }
675
676 match self.transport_manager.send_to_neighbor(target, message) {
677 Ok(transport) => {
678 delivered_to += 1;
679 // Handing it to the recipient themselves ends the
680 // journey; the remaining neighbors are only a fallback
681 // for that link failing.
682 if deliver_direct && target == &recipient {
683 reached_recipient = true;
684 debug!(
685 message_id = %message.id,
686 next_hop = %target,
687 transport = ?transport,
688 cause,
689 "Delivered to its recipient directly"
690 );
691 break;
692 }
693 debug!(
694 message_id = %message.id,
695 next_hop = %target,
696 transport = ?transport,
697 hop_count,
698 remaining_ttl,
699 cause,
700 "Forwarded frame to neighbor"
701 );
702 }
703 Err(err) => {
704 // A link that went away between selection and send.
705 // The other targets still carry the frame.
706 debug!(
707 message_id = %message.id,
708 next_hop = %target,
709 error = %err,
710 "Could not forward to neighbor"
711 );
712 }
713 }
714 }
715
716 // Nothing reached a neighbor. Hand it back instead of dropping it:
717 // its id is already recorded as handled here, so a drop would lose
718 // this copy *and* refuse both the copies arriving behind it and the
719 // sender's retransmissions, for the whole retention window.
720 //
721 // Why it got nowhere does not change that. The budget ran out (the
722 // frames released alongside this one spent the allowance between
723 // them), every link chosen for it went away between being picked
724 // and being written to, or there was no usable link to pick. In all
725 // three the frame has travelled nowhere and this queue is the only
726 // thing that still remembers it. It keeps its due time, so one that
727 // stays stuck is abandoned by the overdue cut-off rather than
728 // retried forever.
729 //
730 // A held frame refused room on the way back goes to the custody
731 // store instead: the store still holds it, nothing is lost, and
732 // its id was never recorded here.
733 if delivered_to == 0 {
734 if let Some(returned) = self.mesh_relay.requeue(relay) {
735 self.return_held_to_store(returned);
736 }
737 continue;
738 }
739
740 if held {
741 self.record_custody_transmission(&relay, reached_recipient);
742 }
743 self.mesh_relay.record_forwarded();
744 self.emit_event(Event::message_relayed(
745 message.id.as_str(),
746 message.sender.as_str().to_string(),
747 recipient,
748 hop_count,
749 remaining_ttl,
750 ));
751 }
752 }
753
754 /// [`Self::handle_incoming_file_chunk_via`] with no known arrival transport
755 /// (a deferred chunk falls back to the resend-driven ACK). Used only by
756 /// tests; production always routes through the `_via` form with the inbound
757 /// transport.
758 #[cfg(test)]
759 pub(super) fn handle_incoming_file_chunk(&mut self, message: &Message) -> ChunkOutcome {
760 self.handle_incoming_file_chunk_via(message, None)
761 }
762
763 /// Routes an inbound file-chunk message through the transfer manager,
764 /// recording `arrival_transport` on the pending entry if the chunk must be
765 /// deferred, so the drain can ACK it directly once the session confirms.
766 pub(super) fn handle_incoming_file_chunk_via(
767 &mut self,
768 message: &Message,
769 arrival_transport: Option<TransportType>,
770 ) -> ChunkOutcome {
771 let sender = message.sender.as_str().to_string();
772
773 // SEC-H1: encrypted chunks carry the chunk bytes, media metadata, and
774 // original content type inside the MLS ciphertext; legacy plaintext
775 // chunks carry them on the wire Message and are accepted only where
776 // policy allows. Rich extras (caption, reply, forward) only ever come
777 // from the sealed plaintext — never from the wire Message.
778 let (chunk, media_metadata, original_content_type, rich_extras, data_purpose) =
779 if let Some(ref binary) = message.binary_content {
780 if is_media_envelope(binary) {
781 let encrypted = match decode_media_envelope(binary) {
782 Ok(e) => e,
783 // A frame whose magic byte still reads as a media envelope
784 // but whose encoding does not decode — in-transit
785 // corruption past the magic, or injected garbage. Under
786 // crypto recovery this is the pre-decrypt sibling of a hard
787 // decrypt failure: the frame as it stands is dead, but the
788 // sender's resend carries a fresh encoding that would
789 // decode, so withhold the ACK (`Deferred`) instead of
790 // telling the sender "delivered" for a chunk we dropped.
791 // Do NOT enqueue: an unparseable frame can never become
792 // parseable, so a queued copy could never drain — the same
793 // reasoning as the spent-generation arm below.
794 Err(e) => {
795 warn!(
796 message_id = %message.id,
797 error = %e,
798 "Failed to decode encrypted media envelope"
799 );
800 if !self.config.encryption.crypto_recovery_enabled {
801 return ChunkOutcome::Handled;
802 }
803 // Advisory, not terminal — the chunk was never ACKed, so
804 // the transfer is *stalled* pending a resend rather than
805 // failed. The terminal media signal stays
806 // `FileReceiveFailed`.
807 if let Ok(state) = lock_shared_state(&self.shared_state) {
808 state.emit_event(Event::message_decryption_failed(
809 message.id.clone(),
810 sender.clone(),
811 crate::events::DecryptionFailureCode::InvalidPayload,
812 "encrypted media envelope failed to decode; its file transfer is stalled until the sender resends".to_string(),
813 ));
814 }
815 return ChunkOutcome::Deferred;
816 }
817 };
818 let plaintext = match self.decrypt_media_chunk(
819 &sender,
820 &encrypted,
821 message,
822 arrival_transport,
823 ) {
824 MediaChunkDecrypt::Plaintext(p) => p,
825 // Not delivered and recoverable by a resend (queued for
826 // delayed decryption, or an undecryptable frame the
827 // sender can re-send): defer the ACK so the sender
828 // retries and the resend re-enters processing.
829 MediaChunkDecrypt::Deferred => return ChunkOutcome::Deferred,
830 // Illegitimate frame (foreign session slot, or an MLS
831 // credential naming a different sender): answer with
832 // silence, exactly like the text `SecurityRejected`
833 // path. ACKing here would tell an injector that the
834 // target is online and processing their frames — the
835 // one thing the text path withholds.
836 MediaChunkDecrypt::SecurityRejected => return ChunkOutcome::Rejected,
837 // Terminal drop (permanent refusal, empty plaintext, MLS
838 // unavailable): ACK as before — the sender cannot
839 // recover it by retrying.
840 MediaChunkDecrypt::Dropped => return ChunkOutcome::Handled,
841 };
842 let inner = match MediaChunkPlaintext::decode(&plaintext) {
843 Ok(i) => i,
844 Err(e) => {
845 warn!(
846 message_id = %message.id,
847 error = %e,
848 "Failed to parse decrypted media chunk plaintext, dropping"
849 );
850 return ChunkOutcome::Handled;
851 }
852 };
853 let chunk = match FileChunk::from_bytes(&inner.chunk_bytes) {
854 Ok(c) => c,
855 Err(e) => {
856 warn!(
857 message_id = %message.id,
858 error = %e,
859 "Failed to deserialize decrypted file chunk, dropping"
860 );
861 return ChunkOutcome::Handled;
862 }
863 };
864 (
865 chunk,
866 inner.media_metadata,
867 inner.original_content_type,
868 inner.rich_extras,
869 inner.data_purpose,
870 )
871 } else {
872 if !self.accept_plaintext_content(&sender) {
873 warn!(
874 message_id = %message.id,
875 sender = %sender,
876 "Rejecting unencrypted media chunk (encryption policy)"
877 );
878 self.warn_plaintext_receive_rejected(
879 &sender,
880 "Inbound plaintext media chunk rejected by encryption policy",
881 );
882 return ChunkOutcome::Rejected;
883 }
884 let chunk = match FileChunk::from_bytes(binary) {
885 Ok(c) => c,
886 Err(e) => {
887 warn!(
888 message_id = %message.id,
889 error = %e,
890 "Failed to deserialize binary file chunk, dropping"
891 );
892 return ChunkOutcome::Handled;
893 }
894 };
895 let (meta, oct) = Self::wire_media_metadata(message);
896 (chunk, meta, oct, None, None)
897 }
898 } else {
899 if !self.accept_plaintext_content(&sender) {
900 warn!(
901 message_id = %message.id,
902 sender = %sender,
903 "Rejecting unencrypted media chunk (encryption policy)"
904 );
905 self.warn_plaintext_receive_rejected(
906 &sender,
907 "Inbound plaintext media chunk rejected by encryption policy",
908 );
909 return ChunkOutcome::Rejected;
910 }
911 let chunk = match FileChunk::from_json(&message.content) {
912 Ok(c) => c,
913 Err(e) => {
914 warn!(
915 message_id = %message.id,
916 error = %e,
917 "Failed to deserialize file chunk, dropping"
918 );
919 return ChunkOutcome::Handled;
920 }
921 };
922 let (meta, oct) = Self::wire_media_metadata(message);
923 (chunk, meta, oct, None, None)
924 };
925
926 let file_id = chunk.file_id.clone();
927 let file_name = chunk.file_name.clone();
928 let file_size = chunk.file_size;
929 let is_first_chunk = chunk.chunk_index == 0;
930
931 // A duplicate chunk 0 must not reclassify a transfer already under
932 // way. Duplicates are accepted by replacement, and the manager's
933 // consistency check covers only the fields on the chunk itself: the
934 // purpose rides the sealed envelope, outside them. Without this an
935 // authenticated peer sends chunk 0 twice, once marked and once not,
936 // and chooses afterwards which side of the invisibility rule the
937 // transfer lands on. Either direction is a defect the marking
938 // exists to prevent: a document snapshot surfaced to a person as a
939 // downloaded file, or an app's own download turned invisible and
940 // left with no terminal event ever.
941 //
942 // Scoped to the sender the assembly belongs to. A chunk under
943 // another peer's file_id is refused by the manager's own sender
944 // check, and refusing it here instead would let any peer tombstone
945 // a transfer it merely named.
946 if is_first_chunk
947 && self
948 .pending_media_metadata
949 .get(&file_id)
950 .is_some_and(|entry| entry.sender == sender && entry.data_purpose != data_purpose)
951 {
952 warn!(
953 file_id = %file_id,
954 peer = %sender,
955 "Refusing a chunk 0 that reclassifies a transfer already under way"
956 );
957 self.file_transfer_manager.refuse_transfer(&file_id);
958 self.pending_media_metadata.remove(&file_id);
959 return ChunkOutcome::Handled;
960 }
961
962 // Refuse a blob nobody asked for at the door, not at the end.
963 //
964 // The check also runs on completion, which is where the hash is
965 // verified, but by then the whole transfer has been buffered,
966 // reassembled and checksummed. That is the storage and the battery
967 // this rule exists to protect: an authenticated peer could otherwise
968 // open as many transfers as the resource caps allow, hold them for
969 // the stale timeout, and pay one frame per transfer to do it.
970 //
971 // Chunk 0 carries the purpose, so this is where the question can
972 // first be asked. Answered with an ACK rather than silence: the
973 // sender is wrong rather than unlucky, and a retry would be refused
974 // exactly the same way.
975 if is_first_chunk
976 && !self.admits_data_media_transfer(&sender, data_purpose.as_ref(), file_size)
977 {
978 // Refused, not merely skipped. Chunks need not arrive in order,
979 // so any that landed before this one already opened an assembly,
980 // and any behind it would open another. The refusal has to
981 // outlive the chunk that prompted it, which is what the
982 // tombstone is for.
983 self.file_transfer_manager.refuse_transfer(&file_id);
984 self.pending_media_metadata.remove(&file_id);
985 return ChunkOutcome::Handled;
986 }
987
988 // Metadata is recorded only for chunks the manager accepts — a
989 // rejected chunk must leave no state behind (SEC-H2).
990 match self.file_transfer_manager.process_chunk(&sender, chunk) {
991 Ok(progress) => {
992 if is_first_chunk {
993 self.pending_media_metadata.insert(
994 file_id.clone(),
995 PendingMediaMetadataEntry {
996 content_type: original_content_type.unwrap_or(ContentType::File),
997 media_metadata,
998 last_updated_at: Instant::now(),
999 sender: sender.clone(),
1000 rich_extras,
1001 timestamp_ms: message.timestamp.as_millis(),
1002 app_id: message.app_id.as_str().to_string(),
1003 data_purpose,
1004 },
1005 );
1006 } else if let Some(entry) = self.pending_media_metadata.get_mut(&file_id) {
1007 entry.last_updated_at = Instant::now();
1008 }
1009 // What this transfer is, as far as this device can tell
1010 // right now. Read once and used twice below.
1011 let arriving = self
1012 .pending_media_metadata
1013 .get(&file_id)
1014 .and_then(|entry| entry.data_purpose.clone());
1015 // A chunk landing is the sign that an answer is coming, so
1016 // the question it answers is kept alive. The fetch record is
1017 // what admits the bytes at the end, and it expires on a
1018 // clock that a large blob over a slow radio outlives: without
1019 // this the record dies mid-carriage and the completed
1020 // transfer is then dropped as unsolicited, forever, because
1021 // every retry takes just as long.
1022 if let Some(purpose) = &arriving {
1023 self.note_data_media_progress(&sender, purpose);
1024 }
1025 // A data-purposed transfer is invisible to the application
1026 // for its whole life, not merely at the end. Reporting
1027 // progress on it would put a download nobody started in
1028 // front of a person, counting up to a file that never
1029 // appears.
1030 //
1031 // Positive knowledge, not absence of it: the purpose rides
1032 // chunk 0, so a chunk arriving before it leaves this device
1033 // unable to say what the transfer is. Reading "no entry yet"
1034 // as "not data-purposed" would emit exactly the phantom
1035 // progress this suppression exists to prevent, on any
1036 // transport that delivers chunk 1 first.
1037 //
1038 // The cost is that an ordinary transfer whose chunk 0 is
1039 // delayed loses the progress events until it lands. That is
1040 // cheap: progress is advisory and each event supersedes the
1041 // last, so the app sees the count resume rather than a gap.
1042 let reports_progress =
1043 arriving.is_none() && self.pending_media_metadata.contains_key(&file_id);
1044 if reports_progress {
1045 if let Ok(state) = lock_shared_state(&self.shared_state) {
1046 state.emit_event(Event::file_progress(
1047 file_id.clone(),
1048 progress.chunks_completed,
1049 progress.total_chunks,
1050 ));
1051 }
1052 }
1053 }
1054 Err(rejection) if rejection.is_resource_exhaustion() => {
1055 // A well-formed transfer was dropped by a receiver-side
1056 // resource limit. The chunk was already ACKed and will not
1057 // be retransmitted, so the transfer is unrecoverable —
1058 // surface that to the application instead of going silent.
1059 let dropped = self.pending_media_metadata.remove(&file_id);
1060 // Positive knowledge, the same rule the progress event
1061 // follows, reached by a different road. On chunk 0 the
1062 // purpose is in hand right here and the stored entry is not:
1063 // an entry is written only once the manager accepts a chunk,
1064 // which is exactly what did not happen. Off chunk 0 the
1065 // stored entry is the only knowledge there is.
1066 let identified = is_first_chunk || dropped.is_some();
1067 let purpose = if is_first_chunk { data_purpose } else { None }
1068 .or_else(|| dropped.and_then(|entry| entry.data_purpose));
1069 if let Some(purpose) = purpose {
1070 self.report_data_media_transfer_failure(&sender, &purpose, rejection.as_str());
1071 return ChunkOutcome::Handled;
1072 }
1073 if !identified {
1074 // A transfer whose chunk 0 has not landed cannot be named
1075 // as anything, so it must not be failed in front of a
1076 // person: it may be the document layer's. The app has
1077 // heard nothing about it either (progress is withheld by
1078 // the same rule), so there is no report to correct.
1079 debug!(
1080 file_id = %file_id,
1081 "Dropping a transfer whose purpose is not yet known; no failure reported"
1082 );
1083 return ChunkOutcome::Handled;
1084 }
1085 if let Ok(state) = lock_shared_state(&self.shared_state) {
1086 state.emit_event(Event::file_receive_failed(
1087 file_id,
1088 file_name,
1089 sender,
1090 rejection.as_str().to_string(),
1091 ));
1092 }
1093 return ChunkOutcome::Handled;
1094 }
1095 // Malformed or mismatched chunks are logged by the manager; the
1096 // assembly they targeted (if any) stays intact. Chunks of an
1097 // already-failed transfer land here too (`previously_failed`) —
1098 // its FileReceiveFailed event already fired exactly once.
1099 Err(_) => return ChunkOutcome::Handled,
1100 }
1101
1102 if self.file_transfer_manager.is_complete(&file_id) {
1103 let Some(file_data) = self.file_transfer_manager.finalize_file(&file_id) else {
1104 warn!(
1105 file_id = %file_id,
1106 "File transfer marked complete but reassembly or integrity checks failed"
1107 );
1108 let dropped = self.pending_media_metadata.remove(&file_id);
1109 // Completion implies chunk 0 was accepted, so this is
1110 // normally `true`. Checked anyway, and for the same reason as
1111 // the arm above: the alternative is naming a transfer this
1112 // device cannot identify as a file the app never saw begin.
1113 let identified = dropped.is_some();
1114 if let Some(purpose) = dropped.and_then(|entry| entry.data_purpose) {
1115 self.report_data_media_transfer_failure(
1116 &sender,
1117 &purpose,
1118 "integrity_check_failed",
1119 );
1120 return ChunkOutcome::Handled;
1121 }
1122 if !identified {
1123 debug!(
1124 file_id = %file_id,
1125 "Dropping a transfer whose purpose is not yet known; no failure reported"
1126 );
1127 return ChunkOutcome::Handled;
1128 }
1129 if let Ok(state) = lock_shared_state(&self.shared_state) {
1130 state.emit_event(Event::file_receive_failed(
1131 file_id,
1132 file_name,
1133 sender,
1134 "integrity_check_failed".to_string(),
1135 ));
1136 }
1137 return ChunkOutcome::Handled;
1138 };
1139 let metadata_entry = self.pending_media_metadata.remove(&file_id);
1140 // The one branch that makes a data-purposed transfer worth
1141 // having: the bytes go to the document layer and the person is
1142 // told nothing, because nothing happened that concerns them.
1143 if let Some(purpose) = metadata_entry
1144 .as_ref()
1145 .and_then(|entry| entry.data_purpose.clone())
1146 {
1147 self.route_data_media_payload(&sender, &purpose, file_data);
1148 return ChunkOutcome::Handled;
1149 }
1150 let (content_type, media_metadata, rich_extras, timestamp_ms, app_id) = metadata_entry
1151 .map(|entry| {
1152 (
1153 entry.content_type,
1154 entry.media_metadata,
1155 entry.rich_extras,
1156 Some(entry.timestamp_ms),
1157 Some(entry.app_id),
1158 )
1159 })
1160 .unwrap_or((ContentType::File, None, None, None, None));
1161 let rich_extras = rich_extras.unwrap_or_default();
1162
1163 if let Ok(state) = lock_shared_state(&self.shared_state) {
1164 state.emit_event(Event::file_received(
1165 file_id,
1166 file_name,
1167 file_size,
1168 sender,
1169 content_type,
1170 media_metadata,
1171 file_data,
1172 timestamp_ms,
1173 rich_extras.caption,
1174 rich_extras.reply_to_msg,
1175 rich_extras.reply_context.as_ref(),
1176 rich_extras.forward_info.as_ref(),
1177 app_id,
1178 ));
1179 }
1180 }
1181
1182 ChunkOutcome::Handled
1183 }
1184
1185 /// Whether a data-purposed transfer may be admitted at all.
1186 ///
1187 /// Only the attachment case is answerable by the fetch record: an
1188 /// attachment is bytes this device asked a named peer for, so the request
1189 /// either exists or it does not. A snapshot is unsolicited by design (it
1190 /// answers a version exchange rather than a fetch) and is bounded instead
1191 /// by the size check and the containment on the import path.
1192 ///
1193 /// The runtime kill switch is checked ahead of both, and what it saves is
1194 /// the buffering rather than the import. A device with the layer off was
1195 /// never going to write anything: `require_data_storage` fails closed
1196 /// with `DataDisabled` further down. But a transfer admitted at chunk 0
1197 /// is reassembled in full before it reaches that seam, so without this
1198 /// gate a device that opted out still holds a peer's whole blob in memory
1199 /// on its way to a refusal that was certain from the start.
1200 ///
1201 /// A conforming peer never sends one, because a build with the layer off
1202 /// never advertises the capability that permits it. This is the arm for
1203 /// the peer whose knowledge of us is stale or wrong.
1204 fn admits_data_media_transfer(
1205 &self,
1206 sender: &str,
1207 purpose: Option<&crate::media_envelope::DataPurpose>,
1208 declared_size: u64,
1209 ) -> bool {
1210 let Some(purpose) = purpose else {
1211 return true;
1212 };
1213 #[cfg(feature = "data")]
1214 {
1215 if !self.config.data.enabled {
1216 warn!(
1217 peer = %sender,
1218 "Refusing a document-layer transfer: the data layer is off"
1219 );
1220 return false;
1221 }
1222 match purpose {
1223 crate::media_envelope::DataPurpose::Attachment { hash } => {
1224 if !self.awaiting_attachment(sender, hash) {
1225 warn!(
1226 peer = %sender,
1227 "Refusing attachment bytes for a fetch this device never made"
1228 );
1229 return false;
1230 }
1231 }
1232 // A snapshot has no fetch record to judge it by, so the size
1233 // it declares is the only thing that can be judged here. It
1234 // is judged here rather than at the end because the ceiling
1235 // is certain: a document past it cannot be persisted by this
1236 // device even if every byte arrives, so admitting one spends
1237 // a whole reassembly to reach a refusal that was decided
1238 // before the first chunk. The completion check stays as the
1239 // backstop against a header that lied.
1240 crate::media_envelope::DataPurpose::Snapshot { doc } => {
1241 // The same refusal the import path makes, made before
1242 // the reassembly rather than after it, and for the same
1243 // reason the size check is here: the answer is already
1244 // certain. A document outside this space's interest is
1245 // refused whatever arrives, so admitting one spends a
1246 // whole transfer, up to the record ceiling, to reach a
1247 // decision that was made when the application narrowed
1248 // the space. Only a peer without entry 5 sends one,
1249 // which is exactly the peer whose traffic the declared
1250 // interest could not save.
1251 if !self.data_wants(sender, doc) {
1252 debug!(
1253 peer = %sender,
1254 doc,
1255 "Refusing a carried snapshot for a document outside this space's interest"
1256 );
1257 return false;
1258 }
1259 if declared_size > crate::protocol::data_sync::MAX_MEDIA_SNAPSHOT_BYTES as u64 {
1260 warn!(
1261 peer = %sender,
1262 declared = declared_size,
1263 "Refusing a carried snapshot larger than a record can hold"
1264 );
1265 return false;
1266 }
1267 }
1268 }
1269 true
1270 }
1271 #[cfg(not(feature = "data"))]
1272 {
1273 let _ = (sender, purpose, declared_size);
1274 // Nothing here can use these bytes, so nothing here should buffer
1275 // them either.
1276 false
1277 }
1278 }
1279
1280 /// Hand a completed data-purposed transfer to the document layer.
1281 ///
1282 /// Split behind a feature gate because the layer is optional and the
1283 /// bytes are not: a build compiled without it still has to recognise
1284 /// such a transfer, since recognising it is what keeps a document
1285 /// snapshot from being handed to a person as a downloaded file. It has
1286 /// nowhere to put the bytes, so it drops them. A conforming peer never
1287 /// sends one, because a build without the layer never advertises the
1288 /// capability that permits it.
1289 pub(super) fn route_data_media_payload(
1290 &mut self,
1291 sender: &str,
1292 purpose: &crate::media_envelope::DataPurpose,
1293 bytes: Vec<u8>,
1294 ) {
1295 #[cfg(feature = "data")]
1296 {
1297 self.accept_data_media_payload(sender, purpose, bytes);
1298 }
1299 #[cfg(not(feature = "data"))]
1300 {
1301 let _ = bytes;
1302 warn!(
1303 peer = %sender,
1304 ?purpose,
1305 "Dropping a document-layer transfer: this build has no data layer"
1306 );
1307 }
1308 }
1309
1310 /// Note that a data-purposed transfer is still arriving, so whatever
1311 /// this device is waiting on does not expire underneath it. See
1312 /// [`Self::route_data_media_payload`] for the gate.
1313 pub(super) fn note_data_media_progress(
1314 &mut self,
1315 sender: &str,
1316 purpose: &crate::media_envelope::DataPurpose,
1317 ) {
1318 #[cfg(feature = "data")]
1319 {
1320 self.refresh_attachment_fetch(sender, purpose);
1321 }
1322 #[cfg(not(feature = "data"))]
1323 {
1324 // A build with no data layer never admitted this transfer, so
1325 // there is nothing here that could be waiting on it.
1326 let _ = (sender, purpose);
1327 }
1328 }
1329
1330 /// Report a failed data-purposed transfer, where there is anything to
1331 /// report it to. See [`Self::route_data_media_payload`] for the gate.
1332 pub(super) fn report_data_media_transfer_failure(
1333 &mut self,
1334 sender: &str,
1335 purpose: &crate::media_envelope::DataPurpose,
1336 reason: &str,
1337 ) {
1338 #[cfg(feature = "data")]
1339 {
1340 self.report_data_media_failure(sender, purpose, reason);
1341 }
1342 #[cfg(not(feature = "data"))]
1343 {
1344 debug!(
1345 peer = %sender,
1346 ?purpose,
1347 reason,
1348 "A document-layer transfer failed; this build has no data layer"
1349 );
1350 }
1351 }
1352
1353 /// Extracts the chunk-0 metadata a legacy (unencrypted) chunk carries on
1354 /// the wire `Message`.
1355 fn wire_media_metadata(message: &Message) -> (Option<MediaMetadata>, Option<ContentType>) {
1356 use crate::constants::ORIGINAL_CONTENT_TYPE_KEY;
1357 let original_ct = message
1358 .metadata
1359 .get(ORIGINAL_CONTENT_TYPE_KEY)
1360 .map(|s| ContentType::parse(s));
1361 (message.media_metadata.clone(), original_ct)
1362 }
1363
1364 /// Policy gate for inbound plaintext content — text messages and legacy
1365 /// (unencrypted) media chunks alike: rejected when this node requires
1366 /// encryption, and rejected once the sender is known to run MLS — an
1367 /// encryption-capable peer sending plaintext is a downgrade/forgery attempt
1368 /// (plaintext carries no sender authentication, so anyone could inject it
1369 /// under a contact's name).
1370 ///
1371 /// # Capability, not confirmation
1372 ///
1373 /// This asks whether the peer *can* encrypt, not whether a session is
1374 /// confirmed. The distinction is the whole gate: a sender only ever emits
1375 /// plaintext when its own `should_auto_encrypt()` is false, which precludes
1376 /// it having established a session with us — while the session is merely
1377 /// pending it *queues* (`prepare_outbound_content`) rather than downgrading.
1378 /// So no honest peer sends cleartext while we know it speaks MLS, and
1379 /// asking only about *confirmed* sessions left a hole: an attacker with
1380 /// app-container write access deletes the `session_states` record, restore
1381 /// re-bootstraps it as `Pending` (which it must), the peer silently drops
1382 /// out of `confirmed_sessions`, and this gate re-opens. See
1383 /// [`OfflineProtocol::encryption_capable_peers`] for why that signal now
1384 /// comes from the credential store instead.
1385 ///
1386 /// The capability check is also *cheaper* than the confirmation one it
1387 /// precedes: it is an in-memory set lookup, where `is_session_confirmed`
1388 /// falls through to a protocol-state read plus a sealed-record open for any
1389 /// sender not already in `confirmed_sessions` — a path driven by the
1390 /// attacker-controlled `message.sender`. Ordering the cheap check first
1391 /// makes a flood of forged sender ids cost less than it used to.
1392 ///
1393 /// The group path has gated on existence rather than confirmation since it
1394 /// was written (`has_mls_group_state`); this brings the 1:1 path into line.
1395 fn accept_plaintext_content(&mut self, sender: &str) -> bool {
1396 if self.config.encryption.require_encryption {
1397 return false;
1398 }
1399 // `should_auto_encrypt()` guards both checks: a node with encryption
1400 // disabled or MLS uninitialized has no standing to call anything a
1401 // downgrade, and removing this guard would reject legitimate plaintext
1402 // on every plaintext-only deployment.
1403 if !self.should_auto_encrypt() {
1404 return true;
1405 }
1406 if self.is_encryption_capable(sender) {
1407 return false;
1408 }
1409 // Fail closed: if the confirmation lookup errors (storage failure),
1410 // treat the session as confirmed and reject — accepting plaintext on
1411 // error would let a storage fault disable the downgrade gate.
1412 if self.is_session_confirmed(sender).unwrap_or(true) {
1413 return false;
1414 }
1415 true
1416 }
1417
1418 /// Decrypts an encrypted media chunk envelope. Four failure dispositions,
1419 /// mirroring the text path in [`Self::handle_encrypted_message`]:
1420 ///
1421 /// - **Session not ready**: the whole message is queued for delayed
1422 /// decryption and [`MediaChunkDecrypt::Deferred`] is returned.
1423 /// - **Recoverable** (epoch desync, or a crypto/transport failure while
1424 /// `crypto_recovery_enabled`): [`MediaChunkDecrypt::Deferred`] *without*
1425 /// queueing — the ciphertext is dead either way, so recovery is the
1426 /// sender's resend, driven by the withheld ACK.
1427 /// - **Security rejection** (the envelope names another pair's session
1428 /// slot, or the MLS credential authenticates a different sender than the
1429 /// wire envelope claims): [`MediaChunkDecrypt::SecurityRejected`], which
1430 /// the caller answers with silence. Deliberately *not* gated on
1431 /// `crypto_recovery_enabled` — this is about what the receiver reveals,
1432 /// not about recovery, and the text path's equivalent is unconditional.
1433 /// - **Terminal** (a permanent refusal, an empty plaintext, or any crypto
1434 /// failure with recovery switched off): decryption telemetry plus
1435 /// [`MediaChunkDecrypt::Dropped`], which the caller still ACKs.
1436 ///
1437 /// On `Deferred` or `SecurityRejected` the caller must skip the ACK and
1438 /// unmark the id — for the former so the sender keeps retrying, for the
1439 /// latter so a replay re-enters this gate rather than hitting the duplicate
1440 /// re-ACK path. A successful decrypt doubles as a session confirmation
1441 /// signal, exactly like text decrypts.
1442 fn decrypt_media_chunk(
1443 &mut self,
1444 sender: &str,
1445 encrypted: &EncryptedMessage,
1446 message: &Message,
1447 arrival_transport: Option<TransportType>,
1448 ) -> MediaChunkDecrypt {
1449 let group_id = encrypted.group_id.as_str().to_string();
1450
1451 // Media envelopes are only ever produced for the sender's 1:1 session,
1452 // whose MLS group id is deterministic. Enforce that binding before
1453 // decrypting: MLS authenticates group membership, not the wire sender
1454 // claim, so without this check any peer holding a valid session with
1455 // us could deliver its own ciphertext under an arbitrary
1456 // `message.sender` and have the file attributed to that identity.
1457 let Ok(expected_group) = GroupId::for_session(&self.local_id, sender) else {
1458 warn!(
1459 sender = %sender,
1460 "Cannot derive 1:1 session id for media chunk sender, dropping"
1461 );
1462 return MediaChunkDecrypt::Dropped;
1463 };
1464 if encrypted.group_id != expected_group {
1465 error!(
1466 sender = %sender,
1467 group_id = %group_id,
1468 expected = %expected_group,
1469 "SECURITY: encrypted media chunk MLS group does not match the claimed sender's session, rejecting"
1470 );
1471 self.emit_security_warning(
1472 sender,
1473 SecurityWarningCode::MediaSenderGroupMismatch,
1474 "Encrypted media chunk MLS group does not match the claimed sender",
1475 );
1476 // Not ACKed: the text path answers the identical condition
1477 // (`MlsError::SessionIdentityMismatch` →
1478 // `InternalMessageResult::SecurityRejected`) with silence, and an
1479 // ACK here would leak exactly what that silence protects — an
1480 // injector who gets an ACK for a media chunk but nothing for the
1481 // same text frame learns the target is live either way.
1482 return MediaChunkDecrypt::SecurityRejected;
1483 }
1484
1485 let Some(mls) = self.mls_manager.clone() else {
1486 warn!(
1487 sender = %sender,
1488 "Encrypted media chunk received but MLS is not initialized, dropping"
1489 );
1490 self.emit_mls_decryption_failed(
1491 sender,
1492 Some(&group_id),
1493 DecryptionFailureKind::NotInitialized,
1494 MlsOperationContext::Receive,
1495 );
1496 return MediaChunkDecrypt::Dropped;
1497 };
1498
1499 let decrypt_result = {
1500 let manager = match mls.read() {
1501 Ok(m) => m,
1502 Err(_) => {
1503 error!("MLS lock poisoned while decrypting media chunk");
1504 return MediaChunkDecrypt::Dropped;
1505 }
1506 };
1507 manager.decrypt(encrypted, sender)
1508 };
1509
1510 match decrypt_result {
1511 Ok(Some(plaintext)) => {
1512 // A group-aware decrypt is the same confirmation signal the
1513 // text path uses; skip when already cache-confirmed to avoid
1514 // per-chunk storage I/O.
1515 if !self.confirmed_sessions.contains(sender) {
1516 self.confirm_session_from_successful_decrypt(sender, &group_id);
1517 }
1518 MediaChunkDecrypt::Plaintext(plaintext)
1519 }
1520 Ok(None) => {
1521 warn!(sender = %sender, "Media chunk decryption returned empty, dropping");
1522 MediaChunkDecrypt::Dropped
1523 }
1524 // Intercepted BEFORE classification, mirroring the text path in
1525 // `handle_encrypted_message`. Both variants classify as
1526 // `SessionStateError::Unknown`, whose disposition must stay
1527 // terminal-drop-and-ACK for the refusals that genuinely belong
1528 // there (`CommitNotAuthorized`), so the split has to happen here
1529 // rather than in the classifier.
1530 Err(ref e) if is_media_security_rejection(e) => {
1531 error!(
1532 sender = %sender,
1533 error = %e,
1534 "SECURITY: encrypted media chunk failed its sender/session identity check, rejecting"
1535 );
1536 MediaChunkDecrypt::SecurityRejected
1537 }
1538 Err(e) => {
1539 let classification = SessionStateError::from(&e);
1540 match classification {
1541 SessionStateError::SessionNotReady | SessionStateError::GroupNotFound => {
1542 info!(
1543 sender = %sender,
1544 error_code = classification.code(),
1545 "Encrypted media chunk received before session ready, queuing"
1546 );
1547 self.emit_mls_session_missing(
1548 Some(sender),
1549 Some(&group_id),
1550 MlsOperationContext::SessionLookup,
1551 MlsErrorCategory::SessionStateMissing,
1552 );
1553 self.enqueue_pending_decryption_via(sender, message, arrival_transport);
1554 MediaChunkDecrypt::Deferred
1555 }
1556 SessionStateError::SessionDesync
1557 if self.config.encryption.crypto_recovery_enabled =>
1558 {
1559 // Epoch desync (see the text path in `handle_encrypted_message`):
1560 // heal the channel with a rate-limited re-key and return
1561 // Deferred so the chunk is not ACKed and its id is
1562 // unmarked. We do NOT enqueue — the chunk is sealed to the
1563 // dead epoch and can never decrypt after the re-key.
1564 //
1565 // Unlike a DM, an in-flight media chunk cannot be
1566 // re-sealed for recovery: Tier 2 reseal is a deliberate
1567 // no-op for media (the media outbox is not persisted and
1568 // chunks are re-encoded, not replayed). Withholding the
1569 // ACK here is what drives recovery: the sender's media
1570 // outbox keeps retrying and, once its retry/ACK-timeout
1571 // budget lapses, surfaces `MediaResendRequired`, and the
1572 // app re-supplies the bytes via `send_media_with` — which
1573 // re-encodes fresh chunks against the now-healed session.
1574 // So media recovers via descriptor-based resend, not reseal.
1575 info!(
1576 sender = %sender,
1577 error_code = classification.code(),
1578 "Encrypted media chunk failed to decrypt due to epoch desync, re-keying"
1579 );
1580 self.schedule_session_rekey(sender);
1581 MediaChunkDecrypt::Deferred
1582 }
1583 SessionStateError::TransportFailure | SessionStateError::CryptoFailure
1584 if self.config.encryption.crypto_recovery_enabled =>
1585 {
1586 // A genuine crypto/transport failure on a chunk (AEAD
1587 // failure, spent ratchet generation, malformed frame).
1588 // Mirrors the text path in `handle_encrypted_message`:
1589 // withhold the ACK and unmark the id rather than lying
1590 // "delivered" for a chunk we dropped. Do NOT enqueue —
1591 // the generation is spent, so a queued copy could never
1592 // drain — and do NOT re-key, which stays desync-only.
1593 //
1594 // Recovery differs from a DM: chunks have no Tier 2
1595 // re-seal (they are re-encoded, not replayed), so the
1596 // un-ACKed chunk drives the media outbox's retry/ACK
1597 // budget to lapse and surface `MediaResendRequired`,
1598 // and the app re-supplies the bytes via `send_media_with`
1599 // — re-encoded against a live generation. Same
1600 // descriptor-based recovery as the media desync arm.
1601 warn!(
1602 sender = %sender,
1603 error = %e,
1604 error_code = classification.code(),
1605 "Failed to decrypt media chunk; withholding ACK so the transfer can be resent"
1606 );
1607 let kind = DecryptionFailureKind::from_mls_error(&e);
1608 self.emit_mls_decryption_failed(
1609 sender,
1610 Some(&group_id),
1611 kind,
1612 MlsOperationContext::Receive,
1613 );
1614 // Advisory, not terminal — matching a pending-queue
1615 // eviction: the chunk was never ACKed, so the transfer
1616 // is *stalled* pending a resend, not failed. The
1617 // terminal media signal is still `FileReceiveFailed`.
1618 if let Ok(state) = lock_shared_state(&self.shared_state) {
1619 state.emit_event(Event::message_decryption_failed(
1620 message.id.clone(),
1621 sender.to_string(),
1622 Self::decryption_failure_code_from_kind(kind),
1623 format!(
1624 "encrypted media chunk failed to decrypt ({}); its file transfer is stalled until the sender resends",
1625 classification.code()
1626 ),
1627 ));
1628 }
1629 MediaChunkDecrypt::Deferred
1630 }
1631 _ => {
1632 warn!(
1633 sender = %sender,
1634 error = %e,
1635 error_code = classification.code(),
1636 "Failed to decrypt media chunk, dropping"
1637 );
1638 let kind = DecryptionFailureKind::from_mls_error(&e);
1639 self.emit_mls_decryption_failed(
1640 sender,
1641 Some(&group_id),
1642 kind,
1643 MlsOperationContext::Receive,
1644 );
1645 // Permanently undecryptable (or crypto recovery is
1646 // switched off): the chunk is ACKed and stays
1647 // dedup-marked, so this loss is terminal for the
1648 // transfer — surface it to the app, not just as MLS
1649 // telemetry.
1650 if let Ok(state) = lock_shared_state(&self.shared_state) {
1651 state.emit_event(Event::message_decryption_failed(
1652 message.id.clone(),
1653 sender.to_string(),
1654 Self::decryption_failure_code_from_kind(kind),
1655 format!(
1656 "encrypted media chunk failed to decrypt ({}); its file transfer cannot complete",
1657 classification.code()
1658 ),
1659 ));
1660 }
1661 MediaChunkDecrypt::Dropped
1662 }
1663 }
1664 }
1665 }
1666 }
1667}
1668
1669/// Four-way outcome of [`OfflineProtocol::decrypt_media_chunk`]: the plaintext,
1670/// a deferral (not delivered, but recoverable by the sender's resend — either
1671/// queued because the session is not ready, or dropped as undecryptable with
1672/// the ACK withheld), a security rejection (an illegitimate frame the caller
1673/// must answer with silence), or a terminal drop the caller ACKs.
1674enum MediaChunkDecrypt {
1675 Plaintext(Vec<u8>),
1676 Deferred,
1677 /// The frame is not a legitimate message from the claimed sender: its
1678 /// envelope named another pair's session slot, or the MLS credential
1679 /// authenticated a different member than the wire envelope claims. Mirrors
1680 /// the text path's [`InternalMessageResult::SecurityRejected`] — the caller
1681 /// must NOT ACK (an ACK confirms to an injector that the target is online
1682 /// and processing their frames, which is exactly what the text path refuses
1683 /// to reveal) and must unmark the id.
1684 ///
1685 /// [`InternalMessageResult::SecurityRejected`]: super::InternalMessageResult::SecurityRejected
1686 SecurityRejected,
1687 Dropped,
1688}
1689
1690/// Whether an MLS decrypt error is a *security* rejection rather than a session
1691/// state problem — the two classes for which the receiver must stay silent
1692/// instead of ACKing.
1693///
1694/// Used as the match guard that intercepts these variants *before*
1695/// [`SessionStateError`] classification, exactly as the text path does inline in
1696/// `handle_encrypted_message`. The intercept cannot be replaced by a
1697/// classification arm: both variants map to [`SessionStateError::Unknown`], and
1698/// `Unknown` must keep its terminal drop-and-ACK disposition for the classes
1699/// that genuinely belong there (notably `CommitNotAuthorized`, a permanent
1700/// refusal whose sender gains nothing from retrying).
1701///
1702/// Kept as a named predicate rather than an inline pattern so the classification
1703/// itself is testable: `SenderIdentityMismatch` is not reachable through any
1704/// SDK-built ciphertext (see
1705/// `test_media_security_rejection_classifies_both_identity_mismatches`).
1706pub(super) fn is_media_security_rejection(error: &offline_protocol_mls::MlsError) -> bool {
1707 matches!(
1708 error,
1709 offline_protocol_mls::MlsError::SenderIdentityMismatch { .. }
1710 | offline_protocol_mls::MlsError::SessionIdentityMismatch { .. }
1711 // The leaf-binding refusals join them for the same reason: an
1712 // `__MLS_ENC__` envelope naming a `group:` id reaches group decrypt
1713 // through this path, both classify as `Unknown`, and `Unknown` must
1714 // keep drop-and-ACK for `CommitNotAuthorized`.
1715 | offline_protocol_mls::MlsError::LeafAddressMismatch { .. }
1716 | offline_protocol_mls::MlsError::UnsupportedSender { .. }
1717 )
1718}