Skip to main content

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