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