Skip to main content

bitwarden_ipc/
ipc_client.rs

1use std::sync::{Arc, Mutex};
2
3use bitwarden_threading::cancellation_token::CancellationToken;
4use serde::de::DeserializeOwned;
5use thiserror::Error;
6use tokio::select;
7
8use crate::{
9    broadcast::{BroadcastGroup, EndpointSendResult},
10    constants::CHANNEL_BUFFER_CAPACITY,
11    error::{
12        AlreadyRunningError, BroadcastError, ErrorKind, IpcErrorKind, ReceiveError, SendError,
13        SubscribeError, TypedReceiveError,
14    },
15    fragmentation::{
16        FragmentationError, Fragments, MAX_PAYLOAD_SIZE, REASSEMBLY_IDLE_TIMEOUT,
17        REASSEMBLY_TIMEOUT, Reassembler,
18    },
19    ipc_client_trait::IpcClient,
20    message::{IncomingMessage, OutgoingMessage, PayloadTypeName, TypedIncomingMessage},
21    rpc::{
22        error::RpcError,
23        exec::{
24            handler::{ErasedRpcHandler, RpcRequestInfo},
25            handler_registry::RpcHandlerRegistry,
26        },
27        request_message::{RPC_REQUEST_PAYLOAD_TYPE_NAME, RpcRequestPayload},
28        response_message::OutgoingRpcResponseMessage,
29    },
30    serde_utils,
31    timeline::{self, Duration, Entry, Track},
32    traits::{BroadcastResolution, CommunicationBackend, CryptoProvider, SessionRepository},
33};
34
35/// A subscription to receive messages over IPC.
36/// The subcription will start buffering messages after its creation and return them
37/// when receive() is called. Messages received before the subscription was created will not be
38/// returned.
39pub struct IpcClientSubscription {
40    pub(crate) receiver: tokio::sync::broadcast::Receiver<IncomingMessage>,
41    pub(crate) topic: Option<String>,
42}
43
44/// A subscription to receive messages over IPC.
45/// The subcription will start buffering messages after its creation and return them
46/// when receive() is called. Messages received before the subscription was created will not be
47/// returned.
48pub struct IpcClientTypedSubscription<Payload: DeserializeOwned + PayloadTypeName>(
49    IpcClientSubscription,
50    std::marker::PhantomData<Payload>,
51);
52
53/// Internal shared state for the IPC client.
54struct IpcClientInner<Crypto, Com, Ses>
55where
56    Crypto: CryptoProvider<Com, Ses>,
57    Com: CommunicationBackend,
58    Ses: SessionRepository<Crypto::Session>,
59{
60    crypto: Crypto,
61    communication: Com,
62    sessions: Ses,
63
64    handlers: RpcHandlerRegistry,
65    reassembler: Reassembler,
66    incoming: Mutex<Option<tokio::sync::broadcast::WeakSender<IncomingMessage>>>,
67    cancellation_token: Mutex<Option<CancellationToken>>,
68}
69
70/// An IPC client that handles communication between different components and clients.
71/// It uses a crypto provider to encrypt and decrypt messages, a communication backend to send and
72/// receive messages, and a session repository to persist sessions.
73///
74/// This is the concrete implementation of the [`IpcClient`] trait.
75pub struct IpcClientImpl<Crypto, Com, Ses>
76where
77    Crypto: CryptoProvider<Com, Ses>,
78    Com: CommunicationBackend,
79    Ses: SessionRepository<Crypto::Session>,
80{
81    inner: Arc<IpcClientInner<Crypto, Com, Ses>>,
82}
83
84impl<Crypto, Com, Ses> Clone for IpcClientImpl<Crypto, Com, Ses>
85where
86    Crypto: CryptoProvider<Com, Ses>,
87    Com: CommunicationBackend,
88    Ses: SessionRepository<Crypto::Session>,
89{
90    fn clone(&self) -> Self {
91        Self {
92            inner: self.inner.clone(),
93        }
94    }
95}
96
97impl<Crypto, Com, Ses> IpcClientImpl<Crypto, Com, Ses>
98where
99    Crypto: CryptoProvider<Com, Ses>,
100    Com: CommunicationBackend,
101    Ses: SessionRepository<Crypto::Session>,
102{
103    /// Create a new IPC client with the provided crypto provider, communication backend, and
104    /// session repository.
105    pub fn new(crypto: Crypto, communication: Com, sessions: Ses) -> Self {
106        Self {
107            inner: Arc::new(IpcClientInner {
108                crypto,
109                communication,
110                sessions,
111
112                handlers: RpcHandlerRegistry::new(),
113                reassembler: Reassembler::new(REASSEMBLY_TIMEOUT, REASSEMBLY_IDLE_TIMEOUT),
114                incoming: Mutex::new(None),
115                cancellation_token: Mutex::new(None),
116            }),
117        }
118    }
119}
120
121#[async_trait::async_trait]
122impl<Crypto, Com, Ses> crate::ipc_client_trait::IpcClient for IpcClientImpl<Crypto, Com, Ses>
123where
124    Crypto: CryptoProvider<Com, Ses>,
125    Com: CommunicationBackend,
126    Ses: SessionRepository<Crypto::Session>,
127{
128    async fn start(
129        &self,
130        cancellation_token: Option<CancellationToken>,
131    ) -> Result<(), AlreadyRunningError> {
132        if self.is_running() {
133            return Err(AlreadyRunningError);
134        }
135
136        let cancellation_token = cancellation_token.unwrap_or_default();
137        self.inner
138            .cancellation_token
139            .lock()
140            .expect("Failed to lock cancellation token mutex")
141            .replace(cancellation_token.clone());
142
143        let com_receiver = self.inner.communication.subscribe().await;
144        let (client_tx, _) = tokio::sync::broadcast::channel(CHANNEL_BUFFER_CAPACITY);
145
146        self.inner
147            .incoming
148            .lock()
149            .expect("Failed to lock incoming mutex")
150            .replace(client_tx.downgrade());
151
152        let inner = self.inner.clone();
153        let future = async move {
154            loop {
155                select! {
156                    _ = cancellation_token.cancelled() => {
157                        tracing::debug!("Cancellation signal received, stopping IPC client");
158                        break;
159                    }
160                    received = inner.crypto.receive(&com_receiver, &inner.communication, &inner.sessions) => {
161                        match received {
162                            Ok(message) => {
163                                let Some(message) = inner.reassembler.process(message) else {
164                                    continue;
165                                };
166                                let _span = timeline::span(
167                                    Track::Received,
168                                    Duration::AtLeastMessage,
169                                    || message_entry(&message.topic, &message.payload, "Source", &message.source),
170                                );
171                                if message.topic.as_deref() == Some(RPC_REQUEST_PAYLOAD_TYPE_NAME) {
172                                    handle_rpc_request(&inner, message);
173                                } else if client_tx.send(message).is_err() {
174                                    tracing::debug!("No subscriptions for incoming message, dropping it");
175                                }
176                            }
177                            Err(error) if matches!(error.kind(), ErrorKind::Fatal) => {
178                                tracing::error!(?error, "Fatal error receiving message, stopping IPC client");
179                                break;
180                            }
181                            Err(error) => {
182                                tracing::warn!(?error, "Recoverable error receiving message, continuing");
183                            }
184                        }
185                    }
186                }
187            }
188            tracing::debug!("IPC client shutting down");
189            stop_inner(&inner);
190        };
191
192        bitwarden_threading::spawn(future);
193
194        Ok(())
195    }
196
197    fn is_running(&self) -> bool {
198        let has_incoming = self
199            .inner
200            .incoming
201            .lock()
202            .expect("Failed to lock incoming mutex")
203            .as_ref()
204            .is_some_and(|sender| sender.strong_count() > 0);
205        let has_cancellation_token = self
206            .inner
207            .cancellation_token
208            .lock()
209            .expect("Failed to lock cancellation token mutex")
210            .is_some();
211        has_incoming && has_cancellation_token
212    }
213
214    async fn send(&self, message: OutgoingMessage) -> Result<(), SendError> {
215        send_message(&self.inner, message).await.result
216    }
217
218    async fn broadcast(
219        &self,
220        group: BroadcastGroup,
221        payload: Vec<u8>,
222        topic: Option<String>,
223    ) -> Result<Vec<EndpointSendResult>, BroadcastError> {
224        let endpoints = match self.inner.communication.resolve(&group).await {
225            BroadcastResolution::Endpoints(endpoints) => endpoints,
226            BroadcastResolution::Delegate(_) => return Err(BroadcastError::DelegationUnsupported),
227            BroadcastResolution::Unsupported => return Err(BroadcastError::Unsupported),
228        };
229
230        // Validate the whole resolution before sending anything, so a backend that names an
231        // endpoint outside the group cannot cause a partial delivery to it.
232        if let Some(endpoint) = endpoints.iter().find(|endpoint| !group.contains(endpoint)) {
233            return Err(BroadcastError::OutOfScope(endpoint.clone()));
234        }
235
236        // Endpoints are sent to one at a time. The crypto provider may serialize sends anyway (the
237        // Noise provider holds one lock per client for the whole send, handshake included), in
238        // which case concurrent sends would not deliver any sooner. A fatal error stops the client,
239        // so the remaining endpoints are not attempted and are absent from the results.
240        let mut results = Vec::with_capacity(endpoints.len());
241        for endpoint in endpoints {
242            let message = OutgoingMessage {
243                payload: payload.clone(),
244                destination: endpoint.clone(),
245                topic: topic.clone(),
246            };
247            let outcome = send_message(&self.inner, message).await;
248            results.push(EndpointSendResult {
249                endpoint,
250                result: outcome.result,
251            });
252            if outcome.fatal {
253                break;
254            }
255        }
256
257        Ok(results)
258    }
259
260    async fn subscribe(
261        &self,
262        topic: Option<String>,
263    ) -> Result<IpcClientSubscription, SubscribeError> {
264        Ok(IpcClientSubscription {
265            receiver: self
266                .inner
267                .incoming
268                .lock()
269                .expect("Failed to lock incoming mutex")
270                .as_ref()
271                .and_then(|sender| sender.upgrade())
272                .ok_or(SubscribeError::NotStarted)?
273                .subscribe(),
274            topic,
275        })
276    }
277
278    async fn register_rpc_handler_erased(&self, name: &str, handler: Box<dyn ErasedRpcHandler>) {
279        self.inner
280            .handlers
281            .register_erased(name.to_owned(), handler)
282            .await;
283    }
284}
285
286/// Timeline entry for a single message, named after its topic.
287fn message_entry(
288    topic: &Option<String>,
289    payload: &[u8],
290    peer_label: &'static str,
291    peer: &impl std::fmt::Debug,
292) -> Entry {
293    Entry {
294        name: topic.clone().unwrap_or_else(|| "message".to_owned()),
295        properties: vec![
296            (peer_label, format!("{peer:?}")),
297            ("Bytes", payload.len().to_string()),
298        ],
299    }
300}
301
302/// The outcome of [`send_message`].
303struct SendOutcome {
304    result: Result<(), SendError>,
305    /// Whether the send failed with a fatal error, which has stopped the client.
306    fatal: bool,
307}
308
309/// Send a message through the crypto provider, split into as many fragments as the provider's
310/// payload limit requires. Fragments are sent in order and sending stops at the first failed
311/// fragment. A fatal error stops the client.
312async fn send_message<Crypto, Com, Ses>(
313    inner: &IpcClientInner<Crypto, Com, Ses>,
314    message: OutgoingMessage,
315) -> SendOutcome
316where
317    Crypto: CryptoProvider<Com, Ses>,
318    Com: CommunicationBackend,
319    Ses: SessionRepository<Crypto::Session>,
320{
321    let _span = timeline::span(Track::Sent, Duration::AtLeastMessage, || {
322        message_entry(
323            &message.topic,
324            &message.payload,
325            "Destination",
326            &message.destination,
327        )
328    });
329
330    let fragments = match Fragments::split(message, inner.crypto.max_payload_len()) {
331        Ok(fragments) => fragments,
332        Err(e) => {
333            return SendOutcome {
334                result: Err(SendError::Other(e.to_string())),
335                fatal: false,
336            };
337        }
338    };
339
340    for fragment in fragments {
341        let outcome = send_fragment(inner, fragment).await;
342        if outcome.result.is_err() {
343            return outcome;
344        }
345    }
346
347    SendOutcome {
348        result: Ok(()),
349        fatal: false,
350    }
351}
352
353/// Send a single fragment through the crypto provider, stopping the client on a fatal error.
354async fn send_fragment<Crypto, Com, Ses>(
355    inner: &IpcClientInner<Crypto, Com, Ses>,
356    message: OutgoingMessage,
357) -> SendOutcome
358where
359    Crypto: CryptoProvider<Com, Ses>,
360    Com: CommunicationBackend,
361    Ses: SessionRepository<Crypto::Session>,
362{
363    let result = inner
364        .crypto
365        .send(&inner.communication, &inner.sessions, message)
366        .await;
367
368    if let Err(ref error) = result {
369        match error.kind() {
370            ErrorKind::Fatal => {
371                tracing::error!(?error, "Fatal error sending message, stopping IPC client");
372                stop_inner(inner);
373            }
374            // An unreachable destination is an expected condition and not logged
375            ErrorKind::Unreachable => {}
376            // Every other recoverable send failure is still surfaced.
377            ErrorKind::Other => {
378                tracing::debug!(
379                    ?error,
380                    "Recoverable error sending message, IPC client will continue running"
381                );
382            }
383        }
384    }
385
386    SendOutcome {
387        fatal: matches!(&result, Err(e) if e.kind() == ErrorKind::Fatal),
388        result: result.map_err(|e| match e.kind() {
389            ErrorKind::Unreachable => SendError::Unreachable,
390            _ => SendError::Other(format!("{e:?}")),
391        }),
392    }
393}
394
395fn stop_inner<Crypto, Com, Ses>(inner: &IpcClientInner<Crypto, Com, Ses>)
396where
397    Crypto: CryptoProvider<Com, Ses>,
398    Com: CommunicationBackend,
399    Ses: SessionRepository<Crypto::Session>,
400{
401    let mut cancellation_token = inner
402        .cancellation_token
403        .lock()
404        .expect("Failed to lock cancellation token mutex");
405
406    if let Some(cancellation_token) = cancellation_token.take() {
407        cancellation_token.cancel();
408    }
409}
410
411fn handle_rpc_request<Crypto, Com, Ses>(
412    inner: &Arc<IpcClientInner<Crypto, Com, Ses>>,
413    incoming_message: IncomingMessage,
414) where
415    Crypto: CryptoProvider<Com, Ses>,
416    Com: CommunicationBackend,
417    Ses: SessionRepository<Crypto::Session>,
418{
419    let inner = inner.clone();
420    let future = async move {
421        #[derive(Debug, Error)]
422        enum HandleError {
423            #[error("Failed to deserialize request message: {0}")]
424            Deserialize(String),
425
426            #[error("Failed to serialize response message: {0}")]
427            Serialize(String),
428        }
429
430        async fn handle(
431            incoming_message: IncomingMessage,
432            handlers: &RpcHandlerRegistry,
433        ) -> Result<OutgoingMessage, HandleError> {
434            let IncomingMessage {
435                payload, source, ..
436            } = incoming_message;
437            let request = RpcRequestPayload::from_slice(payload).map_err(
438                |e: serde_utils::DeserializeError| HandleError::Deserialize(e.to_string()),
439            )?;
440            let _span = timeline::span(Track::Handlers, Duration::Actual, || Entry {
441                name: request.request_type().to_owned(),
442                properties: vec![("Source", format!("{source:?}"))],
443            });
444
445            let info = RpcRequestInfo {
446                source: source.clone(),
447            };
448            let response = handlers.handle(&request, info).await;
449
450            let response_message = OutgoingRpcResponseMessage {
451                request_id: request.request_id(),
452                request_type: request.request_type(),
453                result: response,
454            };
455
456            // Publish the response on the dedicated topic the requester is subscribed to.
457            let mut payload = serde_utils::to_vec(&response_message)
458                .map_err(|e: serde_utils::SerializeError| HandleError::Serialize(e.to_string()))?;
459            if payload.len() > MAX_PAYLOAD_SIZE {
460                // Report the error, or the requester waits for a response that never arrives.
461                let error = FragmentationError::PayloadTooLarge(payload.len()).to_string();
462                let error_message = OutgoingRpcResponseMessage {
463                    result: Err(RpcError::ResponseSerialization(error)),
464                    ..response_message
465                };
466                payload = serde_utils::to_vec(&error_message).map_err(
467                    |e: serde_utils::SerializeError| HandleError::Serialize(e.to_string()),
468                )?;
469            }
470
471            Ok(OutgoingMessage {
472                payload,
473                destination: source.into(),
474                topic: Some(request.response_topic().to_owned()),
475            })
476        }
477
478        match handle(incoming_message, &inner.handlers).await {
479            Ok(outgoing_message) => {
480                // Send through the client, so the response is fragmented like any other message.
481                match (IpcClientImpl { inner }).send(outgoing_message).await {
482                    // A requester that went away is an expected condition and not logged.
483                    Ok(()) | Err(SendError::Unreachable) => {}
484                    Err(error) => tracing::error!(%error, "Failed to send response message"),
485                }
486            }
487            Err(error) => {
488                tracing::error!(%error, "Error handling RPC request");
489            }
490        }
491    };
492
493    bitwarden_threading::spawn(future);
494}
495
496impl IpcClientSubscription {
497    /// Receive a message, optionally filtering by topic.
498    /// Setting the cancellation_token to `None` will wait indefinitely.
499    pub async fn receive(
500        &mut self,
501        cancellation_token: Option<CancellationToken>,
502    ) -> Result<IncomingMessage, ReceiveError> {
503        let cancellation_token = cancellation_token.unwrap_or_default();
504
505        loop {
506            select! {
507                _ = cancellation_token.cancelled() => {
508                    return Err(ReceiveError::Cancelled)
509                }
510                result = self.receiver.recv() => {
511                    let received = result?;
512                    if self.topic.is_none() || received.topic == self.topic {
513                        return Ok::<IncomingMessage, ReceiveError>(received);
514                    }
515                }
516            }
517        }
518    }
519}
520
521impl<Payload> IpcClientTypedSubscription<Payload>
522where
523    Payload: DeserializeOwned + PayloadTypeName,
524{
525    pub(crate) fn new(subscription: IpcClientSubscription) -> Self {
526        Self(subscription, std::marker::PhantomData)
527    }
528
529    /// Receive a message.
530    /// Setting the cancellation_token to `None` will wait indefinitely.
531    pub async fn receive(
532        &mut self,
533        cancellation_token: Option<CancellationToken>,
534    ) -> Result<TypedIncomingMessage<Payload>, TypedReceiveError> {
535        let received = self.0.receive(cancellation_token).await?;
536        received
537            .try_into()
538            .map_err(|e: serde_utils::DeserializeError| TypedReceiveError::Typing(e.to_string()))
539    }
540}
541
542#[cfg(test)]
543mod tests {
544    use std::{collections::HashMap, time::Duration};
545
546    use bitwarden_threading::time::sleep;
547    use serde::{Deserialize, Serialize};
548
549    use super::*;
550    use crate::{
551        IpcClientExt,
552        endpoint::{Endpoint, HostId, Source},
553        ipc_client_trait::IpcClient,
554        message::PayloadTypeName,
555        rpc::{
556            request::RpcRequest,
557            request_message::{RPC_REQUEST_PAYLOAD_TYPE_NAME, RpcRequestMessage},
558            response_message::IncomingRpcResponseMessage,
559        },
560        traits::{InMemorySessionRepository, NoEncryptionCryptoProvider, TestCommunicationBackend},
561    };
562
563    /// Error type for [`TestCryptoProvider`] that carries an explicit fatal/recoverable
564    /// classification so tests can exercise both control-flow paths.
565    #[derive(Debug, Clone)]
566    struct TestCryptoError {
567        // Read only through the derived `Debug` impl (the outer `SendError` wraps it via
568        // `{e:?}`), which dead-code analysis does not count as a use.
569        #[allow(dead_code)]
570        message: String,
571        fatal: bool,
572    }
573
574    impl IpcErrorKind for TestCryptoError {
575        fn kind(&self) -> ErrorKind {
576            if self.fatal {
577                ErrorKind::Fatal
578            } else {
579                ErrorKind::Other
580            }
581        }
582    }
583
584    struct TestCryptoProvider {
585        /// Simulate a send result. Set to `None` wait indefinitely
586        send_result: Option<Result<(), TestCryptoError>>,
587        /// Simulate a receive result. Set to `None` wait indefinitely
588        receive_result: Option<Result<IncomingMessage, TestCryptoError>>,
589    }
590
591    type TestSessionRepository = InMemorySessionRepository<String>;
592    impl CryptoProvider<TestCommunicationBackend, TestSessionRepository> for TestCryptoProvider {
593        type Session = String;
594        type SendError = TestCryptoError;
595        type ReceiveError = TestCryptoError;
596
597        fn max_payload_len(&self) -> usize {
598            usize::MAX
599        }
600
601        async fn receive(
602            &self,
603            _receiver: &<TestCommunicationBackend as CommunicationBackend>::Receiver,
604            _communication: &TestCommunicationBackend,
605            _sessions: &TestSessionRepository,
606        ) -> Result<IncomingMessage, Self::ReceiveError> {
607            match &self.receive_result {
608                Some(result) => {
609                    // Yield (and throttle) so a recoverable error that makes the processing loop
610                    // `continue` doesn't busy-spin and starve the single-threaded test runtime.
611                    // Real backends await their underlying transport here, which has the same
612                    // effect.
613                    sleep(Duration::from_millis(5)).await;
614                    result.clone()
615                }
616                None => {
617                    // Simulate waiting for a message but never returning
618                    sleep(Duration::from_secs(600)).await;
619                    Err(TestCryptoError {
620                        message: "Simulated timeout".to_string(),
621                        fatal: true,
622                    })
623                }
624            }
625        }
626
627        async fn send(
628            &self,
629            _communication: &TestCommunicationBackend,
630            _sessions: &TestSessionRepository,
631            _message: OutgoingMessage,
632        ) -> Result<(), Self::SendError> {
633            match &self.send_result {
634                Some(result) => result.clone(),
635                None => {
636                    // Simulate waiting for a message to be send but never returning
637                    sleep(Duration::from_secs(600)).await;
638                    Err(TestCryptoError {
639                        message: "Simulated timeout".to_string(),
640                        fatal: true,
641                    })
642                }
643            }
644        }
645    }
646
647    #[tokio::test]
648    async fn returns_send_error_when_crypto_provider_returns_error() {
649        let message = OutgoingMessage {
650            payload: vec![],
651            destination: Endpoint::BrowserBackground { id: HostId::Own },
652            topic: None,
653        };
654        let crypto_provider = TestCryptoProvider {
655            send_result: Some(Err(TestCryptoError {
656                message: "Crypto error".to_string(),
657                fatal: false,
658            })),
659            receive_result: Some(Err(TestCryptoError {
660                message: "Should not have be called".to_string(),
661                fatal: false,
662            })),
663        };
664        let communication_provider = TestCommunicationBackend::new();
665        let session_map = TestSessionRepository::new(HashMap::new());
666        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
667        let _ = client.start(None).await;
668
669        let error = client.send(message).await.unwrap_err();
670
671        assert!(error.to_string().contains("Crypto error"));
672    }
673
674    #[tokio::test]
675    async fn communication_provider_has_outgoing_message_when_sending_through_ipc_client() {
676        let message = OutgoingMessage {
677            payload: vec![],
678            destination: Endpoint::BrowserBackground { id: HostId::Own },
679            topic: None,
680        };
681        let crypto_provider = NoEncryptionCryptoProvider;
682        let communication_provider = TestCommunicationBackend::new();
683        let session_map = InMemorySessionRepository::new(HashMap::new());
684        let client =
685            IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
686        let _ = client.start(None).await;
687
688        client.send(message.clone()).await.unwrap();
689
690        let outgoing_messages = communication_provider.outgoing().await;
691        assert_eq!(outgoing_messages, vec![message]);
692    }
693
694    #[tokio::test]
695    async fn returns_received_message_when_received_from_backend() {
696        let message = IncomingMessage {
697            payload: vec![],
698            source: Source::Web {
699                tab_id: 9001,
700                document_id: "doc-1".to_string(),
701                origin: "https://example.com".to_string(),
702            },
703            destination: Endpoint::BrowserBackground { id: HostId::Own },
704            topic: None,
705        };
706        let crypto_provider = NoEncryptionCryptoProvider;
707        let communication_provider = TestCommunicationBackend::new();
708        let session_map = InMemorySessionRepository::new(HashMap::new());
709        let client =
710            IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
711        let _ = client.start(None).await;
712
713        let mut subscription = client
714            .subscribe(None)
715            .await
716            .expect("Subscribing should not fail");
717        communication_provider.push_incoming(message.clone());
718        let received_message = subscription.receive(None).await.unwrap();
719
720        assert_eq!(received_message, message);
721    }
722
723    #[tokio::test]
724    async fn channel_keeps_no_message_every_subscription_has_received() {
725        let message = IncomingMessage {
726            payload: vec![1, 2, 3],
727            source: Source::DesktopMain,
728            destination: Endpoint::BrowserBackground { id: HostId::Own },
729            topic: Some("topic".to_owned()),
730        };
731        let communication_provider = TestCommunicationBackend::new();
732        let client = IpcClientImpl::new(
733            NoEncryptionCryptoProvider,
734            communication_provider.clone(),
735            InMemorySessionRepository::new(HashMap::new()),
736        );
737        let _ = client.start(None).await;
738        let queued = || {
739            client
740                .inner
741                .incoming
742                .lock()
743                .unwrap()
744                .as_ref()
745                .and_then(|sender| sender.upgrade())
746                .expect("Client should be running")
747                .len()
748        };
749
750        // Without subscriptions, the message is dropped and the client keeps running.
751        communication_provider.push_incoming(message.clone());
752        sleep(Duration::from_millis(50)).await;
753        assert_eq!(queued(), 0);
754        assert!(client.is_running());
755
756        let mut subscription = client.subscribe(None).await.unwrap();
757        communication_provider.push_incoming(message.clone());
758        assert_eq!(subscription.receive(None).await.unwrap(), message);
759        assert_eq!(queued(), 0);
760    }
761
762    #[tokio::test]
763    async fn skips_non_matching_topics_and_returns_first_matching_message() {
764        let non_matching_message = IncomingMessage {
765            payload: vec![],
766            source: Source::Web {
767                tab_id: 9001,
768                document_id: "doc-1".to_string(),
769                origin: "https://example.com".to_string(),
770            },
771            destination: Endpoint::BrowserBackground { id: HostId::Own },
772            topic: Some("non_matching_topic".to_owned()),
773        };
774        let matching_message = IncomingMessage {
775            payload: vec![109],
776            source: Source::Web {
777                tab_id: 9001,
778                document_id: "doc-1".to_string(),
779                origin: "https://example.com".to_string(),
780            },
781            destination: Endpoint::BrowserBackground { id: HostId::Own },
782            topic: Some("matching_topic".to_owned()),
783        };
784
785        let crypto_provider = NoEncryptionCryptoProvider;
786        let communication_provider = TestCommunicationBackend::new();
787        let session_map = InMemorySessionRepository::new(HashMap::new());
788        let client =
789            IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
790        let _ = client.start(None).await;
791        let mut subscription = client
792            .subscribe(Some("matching_topic".to_owned()))
793            .await
794            .expect("Subscribing should not fail");
795        communication_provider.push_incoming(non_matching_message.clone());
796        communication_provider.push_incoming(non_matching_message.clone());
797        communication_provider.push_incoming(matching_message.clone());
798
799        let received_message: IncomingMessage = subscription.receive(None).await.unwrap();
800
801        assert_eq!(received_message, matching_message);
802    }
803
804    #[tokio::test]
805    async fn skips_unrelated_messages_and_returns_typed_message() {
806        #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
807        struct TestPayload {
808            some_data: String,
809        }
810
811        impl PayloadTypeName for TestPayload {
812            const PAYLOAD_TYPE_NAME: &str = "TestPayload";
813        }
814
815        let unrelated = IncomingMessage {
816            payload: vec![],
817            source: Source::Web {
818                tab_id: 9001,
819                document_id: "doc-1".to_string(),
820                origin: "https://example.com".to_string(),
821            },
822            destination: Endpoint::BrowserBackground { id: HostId::Own },
823            topic: None,
824        };
825        let typed_message = crate::message::TypedIncomingMessage {
826            payload: TestPayload {
827                some_data: "Hello, world!".to_string(),
828            },
829            source: Source::Web {
830                tab_id: 9001,
831                document_id: "doc-1".to_string(),
832                origin: "https://example.com".to_string(),
833            },
834            destination: Endpoint::BrowserBackground { id: HostId::Own },
835        };
836
837        let crypto_provider = NoEncryptionCryptoProvider;
838        let communication_provider = TestCommunicationBackend::new();
839        let session_map = InMemorySessionRepository::new(HashMap::new());
840        let client =
841            IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
842        let _ = client.start(None).await;
843        let mut subscription = client
844            .subscribe_typed::<TestPayload>()
845            .await
846            .expect("Subscribing should not fail");
847        communication_provider.push_incoming(unrelated.clone());
848        communication_provider.push_incoming(unrelated.clone());
849        communication_provider.push_incoming(
850            typed_message
851                .clone()
852                .try_into()
853                .expect("Serialization should not fail"),
854        );
855
856        let received_message = subscription.receive(None).await.unwrap();
857
858        assert_eq!(received_message, typed_message);
859    }
860
861    #[tokio::test]
862    async fn returns_error_if_related_message_was_not_deserializable() {
863        #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
864        struct TestPayload {
865            some_data: String,
866        }
867
868        impl PayloadTypeName for TestPayload {
869            const PAYLOAD_TYPE_NAME: &str = "TestPayload";
870        }
871
872        let non_deserializable_message = IncomingMessage {
873            payload: vec![],
874            source: Source::Web {
875                tab_id: 9001,
876                document_id: "doc-1".to_string(),
877                origin: "https://example.com".to_string(),
878            },
879            destination: Endpoint::BrowserBackground { id: HostId::Own },
880            topic: Some("TestPayload".to_owned()),
881        };
882
883        let crypto_provider = NoEncryptionCryptoProvider;
884        let communication_provider = TestCommunicationBackend::new();
885        let session_map = InMemorySessionRepository::new(HashMap::new());
886        let client =
887            IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
888        let _ = client.start(None).await;
889        let mut subscription = client
890            .subscribe_typed::<TestPayload>()
891            .await
892            .expect("Subscribing should not fail");
893        communication_provider.push_incoming(non_deserializable_message.clone());
894
895        let result = subscription.receive(None).await;
896        assert!(matches!(result, Err(TypedReceiveError::Typing(_))));
897    }
898
899    #[tokio::test]
900    async fn ipc_client_stops_if_crypto_returns_fatal_send_error() {
901        let message = OutgoingMessage {
902            payload: vec![],
903            destination: Endpoint::BrowserBackground { id: HostId::Own },
904            topic: None,
905        };
906        let crypto_provider = TestCryptoProvider {
907            send_result: Some(Err(TestCryptoError {
908                message: "Crypto error".to_string(),
909                fatal: true,
910            })),
911            receive_result: None,
912        };
913        let communication_provider = TestCommunicationBackend::new();
914        let session_map = TestSessionRepository::new(HashMap::new());
915        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
916        let _ = client.start(None).await;
917
918        let error = client.send(message).await.unwrap_err();
919        let is_running = client.is_running();
920
921        assert!(error.to_string().contains("Crypto error"));
922        assert!(!is_running);
923    }
924
925    #[tokio::test]
926    async fn ipc_client_keeps_running_if_crypto_returns_recoverable_send_error() {
927        let message = OutgoingMessage {
928            payload: vec![],
929            destination: Endpoint::BrowserBackground { id: HostId::Own },
930            topic: None,
931        };
932        let crypto_provider = TestCryptoProvider {
933            // A recoverable send error (e.g. a handshake timeout because the peer is down) must
934            // not tear down the shared client.
935            send_result: Some(Err(TestCryptoError {
936                message: "Crypto error".to_string(),
937                fatal: false,
938            })),
939            // Block forever on receive so the loop stays alive while we inspect it.
940            receive_result: None,
941        };
942        let communication_provider = TestCommunicationBackend::new();
943        let session_map = TestSessionRepository::new(HashMap::new());
944        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
945        let _ = client.start(None).await;
946
947        let error = client.send(message).await.unwrap_err();
948        let is_running = client.is_running();
949
950        // The error is still surfaced to the caller...
951        assert!(error.to_string().contains("Crypto error"));
952        // ...but the client keeps running so future sends/requests can succeed.
953        assert!(is_running);
954    }
955
956    #[tokio::test]
957    async fn ipc_client_stops_if_crypto_returns_fatal_receive_error() {
958        let crypto_provider = TestCryptoProvider {
959            send_result: None,
960            receive_result: Some(Err(TestCryptoError {
961                message: "Crypto error".to_string(),
962                fatal: true,
963            })),
964        };
965        let communication_provider = TestCommunicationBackend::new();
966        let session_map = TestSessionRepository::new(HashMap::new());
967        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
968        let cancellation_token = CancellationToken::new();
969        let _ = client.start(Some(cancellation_token.clone())).await;
970
971        // Give the client some time to process the error
972        tokio::time::sleep(Duration::from_millis(100)).await;
973        let is_running = client.is_running();
974
975        assert!(!is_running);
976        assert!(cancellation_token.is_cancelled());
977    }
978
979    #[tokio::test]
980    async fn ipc_client_keeps_running_if_crypto_returns_recoverable_receive_error() {
981        let crypto_provider = TestCryptoProvider {
982            send_result: None,
983            // A recoverable receive error must not stop the processing loop.
984            receive_result: Some(Err(TestCryptoError {
985                message: "Crypto error".to_string(),
986                fatal: false,
987            })),
988        };
989        let communication_provider = TestCommunicationBackend::new();
990        let session_map = TestSessionRepository::new(HashMap::new());
991        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
992        let cancellation_token = CancellationToken::new();
993        let _ = client.start(Some(cancellation_token.clone())).await;
994
995        // Give the client time to hit the recoverable receive error (repeatedly).
996        tokio::time::sleep(Duration::from_millis(100)).await;
997        let is_running = client.is_running();
998
999        assert!(is_running);
1000        assert!(!cancellation_token.is_cancelled());
1001    }
1002
1003    #[tokio::test]
1004    async fn ipc_client_is_not_running_if_cancellation_token_is_cancelled() {
1005        let crypto_provider = TestCryptoProvider {
1006            send_result: None,
1007            receive_result: None,
1008        };
1009        let communication_provider = TestCommunicationBackend::new();
1010        let session_map = TestSessionRepository::new(HashMap::new());
1011        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
1012        let cancellation_token = CancellationToken::new();
1013        let _ = client.start(Some(cancellation_token.clone())).await;
1014
1015        // Give the client some time to process
1016        tokio::time::sleep(Duration::from_millis(100)).await;
1017
1018        // Cancel the token and give the client some time to process the cancellation
1019        cancellation_token.cancel();
1020        tokio::time::sleep(Duration::from_millis(100)).await;
1021        let is_running = client.is_running();
1022
1023        assert!(!is_running);
1024    }
1025
1026    #[tokio::test]
1027    async fn ipc_client_is_running_if_no_errors_are_encountered() {
1028        let crypto_provider = TestCryptoProvider {
1029            send_result: None,
1030            receive_result: None,
1031        };
1032        let communication_provider = TestCommunicationBackend::new();
1033        let session_map = TestSessionRepository::new(HashMap::new());
1034        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
1035        let cancellation_token = CancellationToken::new();
1036        let _ = client.start(Some(cancellation_token.clone())).await;
1037
1038        // Give the client some time to process
1039        tokio::time::sleep(Duration::from_millis(100)).await;
1040        let is_running = client.is_running();
1041
1042        assert!(is_running);
1043        assert!(!cancellation_token.is_cancelled());
1044    }
1045
1046    #[tokio::test]
1047    async fn ipc_client_is_not_running_if_not_started() {
1048        let crypto_provider = TestCryptoProvider {
1049            send_result: None,
1050            receive_result: None,
1051        };
1052        let communication_provider = TestCommunicationBackend::new();
1053        let session_map = TestSessionRepository::new(HashMap::new());
1054        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
1055
1056        // Give the client some time to process
1057        tokio::time::sleep(Duration::from_millis(100)).await;
1058        let is_running = client.is_running();
1059
1060        assert!(!is_running);
1061    }
1062
1063    #[tokio::test]
1064    async fn ipc_client_start_returns_error_if_already_running() {
1065        let crypto_provider = TestCryptoProvider {
1066            send_result: None,
1067            receive_result: None,
1068        };
1069        let communication_provider = TestCommunicationBackend::new();
1070        let session_map = TestSessionRepository::new(HashMap::new());
1071        let client = IpcClientImpl::new(crypto_provider, communication_provider, session_map);
1072        let cancellation_token = CancellationToken::new();
1073        let first_result = client.start(Some(cancellation_token.clone())).await;
1074        assert_eq!(first_result, Ok(()));
1075
1076        // Give the client some time to process
1077        tokio::time::sleep(Duration::from_millis(100)).await;
1078        assert!(client.is_running());
1079
1080        let second_result = client.start(Some(cancellation_token.clone())).await;
1081        assert_eq!(second_result, Err(AlreadyRunningError));
1082    }
1083
1084    mod request {
1085        use super::*;
1086        use crate::{RpcHandler, RpcRequestInfo};
1087
1088        #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
1089        struct TestRequest {
1090            a: i32,
1091            b: i32,
1092        }
1093
1094        #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
1095        struct TestResponse {
1096            result: i32,
1097        }
1098
1099        impl RpcRequest for TestRequest {
1100            type Response = TestResponse;
1101
1102            const NAME: &str = "TestRequest";
1103        }
1104
1105        struct TestHandler;
1106
1107        impl RpcHandler for TestHandler {
1108            type Request = TestRequest;
1109
1110            async fn handle(&self, request: Self::Request, _info: RpcRequestInfo) -> TestResponse {
1111                TestResponse {
1112                    result: request.a + request.b,
1113                }
1114            }
1115        }
1116
1117        /// A request whose handler responds with the source it was given, so tests can observe
1118        /// what the IPC client passes to handlers.
1119        #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
1120        struct EchoSourceRequest;
1121
1122        impl RpcRequest for EchoSourceRequest {
1123            type Response = Source;
1124
1125            const NAME: &str = "EchoSourceRequest";
1126        }
1127
1128        struct EchoSourceHandler;
1129
1130        impl RpcHandler for EchoSourceHandler {
1131            type Request = EchoSourceRequest;
1132
1133            async fn handle(&self, _request: Self::Request, info: RpcRequestInfo) -> Source {
1134                info.source
1135            }
1136        }
1137
1138        /// A second request type whose response is a unit enum, which serde serializes to a bare
1139        /// JSON string. Deserializing it as [`TestResponse`] fails, which is what makes it a
1140        /// faithful stand-in for the real `GetBiometricsStatus` / `UnlockBiometrics` pair.
1141        #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
1142        struct OtherRequest;
1143
1144        #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
1145        enum OtherResponse {
1146            Available,
1147        }
1148
1149        impl RpcRequest for OtherRequest {
1150            type Response = OtherResponse;
1151
1152            const NAME: &str = "OtherRequest";
1153        }
1154
1155        #[tokio::test]
1156        async fn request_sends_message_and_returns_response() {
1157            let crypto_provider = NoEncryptionCryptoProvider;
1158            let communication_provider = TestCommunicationBackend::new();
1159            let session_map = InMemorySessionRepository::default();
1160            let client =
1161                IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
1162            let _ = client.start(None).await;
1163            let request = TestRequest { a: 1, b: 2 };
1164            let response = TestResponse { result: 3 };
1165
1166            // Send the request
1167            let request_clone = request.clone();
1168            let client_clone = client.clone();
1169            let result_handle = tokio::spawn(async move {
1170                client_clone
1171                    .request::<TestRequest>(
1172                        request_clone,
1173                        Endpoint::BrowserBackground { id: HostId::Own },
1174                        None,
1175                    )
1176                    .await
1177            });
1178            tokio::time::sleep(Duration::from_millis(100)).await;
1179
1180            // Read and verify the outgoing message
1181            let outgoing_messages = communication_provider.outgoing().await;
1182            let outgoing_request: RpcRequestMessage<TestRequest> =
1183                serde_utils::from_slice(&outgoing_messages[0].payload)
1184                    .expect("Deserialization should not fail");
1185            assert_eq!(outgoing_request.request_type, "TestRequest");
1186            assert_eq!(outgoing_request.request, request);
1187
1188            // Simulate receiving a response
1189            let simulated_response = IncomingRpcResponseMessage {
1190                result: Ok(response),
1191                request_id: outgoing_request.request_id.clone(),
1192                request_type: outgoing_request.request_type.clone(),
1193            };
1194            let simulated_response = IncomingMessage {
1195                payload: serde_utils::to_vec(&simulated_response)
1196                    .expect("Serialization should not fail"),
1197                source: Source::BrowserBackground { id: HostId::Own },
1198                destination: Endpoint::Web {
1199                    tab_id: 9001,
1200                    document_id: "doc-1".to_string(),
1201                },
1202                // The requester subscribes to the dedicated topic it minted, so the response must
1203                // be published there.
1204                topic: Some(outgoing_request.response_topic.clone()),
1205            };
1206            communication_provider.push_incoming(simulated_response);
1207
1208            // Wait for the response
1209            let result = result_handle.await.unwrap();
1210            assert_eq!(result.unwrap().result, 3);
1211        }
1212
1213        /// Two requests in flight at once must each receive their own response. Each request mints
1214        /// its own response topic, so `TestRequest` and `OtherRequest` never see each other's
1215        /// responses even though their response types differ (`OtherResponse::Available` is a bare
1216        /// JSON string that would not deserialize into `TestResponse`).
1217        #[tokio::test]
1218        async fn concurrent_request_of_a_different_type_does_not_disturb_a_pending_request() {
1219            let crypto_provider = NoEncryptionCryptoProvider;
1220            let communication_provider = TestCommunicationBackend::new();
1221            let session_map = InMemorySessionRepository::default();
1222            let client =
1223                IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
1224            let _ = client.start(None).await;
1225
1226            // Put both requests in flight at the same time.
1227            let test_handle = {
1228                let client = client.clone();
1229                tokio::spawn(async move {
1230                    client
1231                        .request::<TestRequest>(
1232                            TestRequest { a: 1, b: 2 },
1233                            Endpoint::BrowserBackground { id: HostId::Own },
1234                            None,
1235                        )
1236                        .await
1237                })
1238            };
1239            let other_handle = {
1240                let client = client.clone();
1241                tokio::spawn(async move {
1242                    client
1243                        .request::<OtherRequest>(
1244                            OtherRequest,
1245                            Endpoint::BrowserBackground { id: HostId::Own },
1246                            None,
1247                        )
1248                        .await
1249                })
1250            };
1251            tokio::time::sleep(Duration::from_millis(100)).await;
1252
1253            // Recover both requests from the wire, keyed by type, so we can answer each on the
1254            // dedicated response topic it minted.
1255            let outgoing = communication_provider.outgoing().await;
1256            let requests: HashMap<String, RpcRequestMessage<serde_json::Value>> = outgoing
1257                .iter()
1258                .map(|message| {
1259                    let partial: RpcRequestMessage<serde_json::Value> =
1260                        serde_utils::from_slice(&message.payload)
1261                            .expect("Deserialization should not fail");
1262                    (partial.request_type.clone(), partial)
1263                })
1264                .collect();
1265
1266            let respond = |topic: String, payload: Vec<u8>| {
1267                communication_provider.push_incoming(IncomingMessage {
1268                    payload,
1269                    source: Source::BrowserBackground { id: HostId::Own },
1270                    destination: Endpoint::Web {
1271                        tab_id: 9001,
1272                        document_id: "doc-1".to_string(),
1273                    },
1274                    topic: Some(topic),
1275                });
1276            };
1277
1278            // Answer `OtherRequest` first, while `TestRequest` is still waiting. Each response goes
1279            // to its own dedicated topic, so the two can never be confused for one another.
1280            respond(
1281                requests["OtherRequest"].response_topic.clone(),
1282                serde_utils::to_vec(&IncomingRpcResponseMessage {
1283                    result: Ok(OtherResponse::Available),
1284                    request_id: requests["OtherRequest"].request_id.clone(),
1285                    request_type: "OtherRequest".to_string(),
1286                })
1287                .expect("Serialization should not fail"),
1288            );
1289
1290            respond(
1291                requests["TestRequest"].response_topic.clone(),
1292                serde_utils::to_vec(&IncomingRpcResponseMessage {
1293                    result: Ok(TestResponse { result: 3 }),
1294                    request_id: requests["TestRequest"].request_id.clone(),
1295                    request_type: "TestRequest".to_string(),
1296                })
1297                .expect("Serialization should not fail"),
1298            );
1299
1300            assert_eq!(
1301                other_handle
1302                    .await
1303                    .unwrap()
1304                    .expect("OtherRequest should succeed"),
1305                OtherResponse::Available
1306            );
1307            assert_eq!(
1308                test_handle
1309                    .await
1310                    .unwrap()
1311                    .expect("TestRequest should succeed"),
1312                TestResponse { result: 3 }
1313            );
1314        }
1315
1316        /// A response that reaches this request's dedicated topic but fails to deserialize into the
1317        /// expected response type is a genuine error for *this* request: because the topic is
1318        /// dedicated, there is no other request it could belong to, so the failure is surfaced
1319        /// immediately.
1320        #[tokio::test]
1321        async fn malformed_response_surfaces_error_instead_of_hanging() {
1322            let crypto_provider = NoEncryptionCryptoProvider;
1323            let communication_provider = TestCommunicationBackend::new();
1324            let session_map = InMemorySessionRepository::default();
1325            let client =
1326                IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
1327            let _ = client.start(None).await;
1328
1329            let result_handle = {
1330                let client = client.clone();
1331                tokio::spawn(async move {
1332                    client
1333                        .request::<TestRequest>(
1334                            TestRequest { a: 1, b: 2 },
1335                            Endpoint::BrowserBackground { id: HostId::Own },
1336                            None,
1337                        )
1338                        .await
1339                })
1340            };
1341            tokio::time::sleep(Duration::from_millis(100)).await;
1342
1343            // Recover the dedicated response topic and answer it with a body that cannot be
1344            // deserialized into `TestResponse` (`OtherResponse::Available` serializes to a bare
1345            // string).
1346            let outgoing = communication_provider.outgoing().await;
1347            let request: RpcRequestMessage<TestRequest> =
1348                serde_utils::from_slice(&outgoing[0].payload)
1349                    .expect("Deserialization should not fail");
1350            let malformed = IncomingRpcResponseMessage {
1351                result: Ok(OtherResponse::Available),
1352                request_id: request.request_id.clone(),
1353                request_type: request.request_type.clone(),
1354            };
1355            communication_provider.push_incoming(IncomingMessage {
1356                payload: serde_utils::to_vec(&malformed).expect("Serialization should not fail"),
1357                source: Source::BrowserBackground { id: HostId::Own },
1358                destination: Endpoint::Web {
1359                    tab_id: 9001,
1360                    document_id: "doc-1".to_string(),
1361                },
1362                topic: Some(request.response_topic.clone()),
1363            });
1364
1365            let result = tokio::time::timeout(Duration::from_secs(5), result_handle)
1366                .await
1367                .expect("request must not hang on a malformed response")
1368                .unwrap();
1369            assert!(matches!(
1370                result,
1371                Err(crate::error::RequestError::Rpc(
1372                    crate::rpc::error::RpcError::ResponseDeserialization(_)
1373                ))
1374            ));
1375        }
1376
1377        /// Builds a `TestRequest` response on the request's dedicated topic, as sent by `source`.
1378        fn test_response_from(
1379            request: &RpcRequestMessage<TestRequest>,
1380            result: i32,
1381            source: Source,
1382        ) -> IncomingMessage {
1383            let response = IncomingRpcResponseMessage {
1384                result: Ok(TestResponse { result }),
1385                request_id: request.request_id.clone(),
1386                request_type: request.request_type.clone(),
1387            };
1388            IncomingMessage {
1389                payload: serde_utils::to_vec(&response).expect("Serialization should not fail"),
1390                source,
1391                destination: Endpoint::DesktopRenderer,
1392                topic: Some(request.response_topic.clone()),
1393            }
1394        }
1395
1396        /// A message on the response topic from a peer other than the destination must not be
1397        /// accepted as the response, and must not stop the request from receiving the real one.
1398        #[tokio::test]
1399        async fn response_from_other_source_is_ignored_and_destination_response_is_returned() {
1400            let communication_provider = TestCommunicationBackend::new();
1401            let client = IpcClientImpl::new(
1402                NoEncryptionCryptoProvider,
1403                communication_provider.clone(),
1404                InMemorySessionRepository::default(),
1405            );
1406            let _ = client.start(None).await;
1407
1408            let result_handle = {
1409                let client = client.clone();
1410                tokio::spawn(async move {
1411                    client
1412                        .request::<TestRequest>(
1413                            TestRequest { a: 1, b: 2 },
1414                            Endpoint::DesktopMain,
1415                            None,
1416                        )
1417                        .await
1418                })
1419            };
1420            tokio::time::sleep(Duration::from_millis(100)).await;
1421
1422            let outgoing = communication_provider.outgoing().await;
1423            let request: RpcRequestMessage<TestRequest> =
1424                serde_utils::from_slice(&outgoing[0].payload)
1425                    .expect("Deserialization should not fail");
1426
1427            communication_provider.push_incoming(test_response_from(
1428                &request,
1429                999,
1430                Source::BrowserBackground { id: HostId::Id(42) },
1431            ));
1432            communication_provider.push_incoming(test_response_from(
1433                &request,
1434                3,
1435                Source::DesktopMain,
1436            ));
1437
1438            let result = tokio::time::timeout(Duration::from_secs(5), result_handle)
1439                .await
1440                .expect("request must complete once the destination responds")
1441                .unwrap();
1442            assert_eq!(result, Ok(TestResponse { result: 3 }));
1443        }
1444
1445        /// When only a peer other than the destination answers, the request keeps waiting and ends
1446        /// through its cancellation token, never returning the other peer's result.
1447        #[tokio::test]
1448        async fn response_only_from_other_source_waits_until_cancelled() {
1449            let communication_provider = TestCommunicationBackend::new();
1450            let client = IpcClientImpl::new(
1451                NoEncryptionCryptoProvider,
1452                communication_provider.clone(),
1453                InMemorySessionRepository::default(),
1454            );
1455            let _ = client.start(None).await;
1456
1457            let cancellation_token = CancellationToken::new();
1458            let result_handle = {
1459                let client = client.clone();
1460                let cancellation_token = cancellation_token.clone();
1461                tokio::spawn(async move {
1462                    client
1463                        .request::<TestRequest>(
1464                            TestRequest { a: 1, b: 2 },
1465                            Endpoint::DesktopMain,
1466                            Some(cancellation_token),
1467                        )
1468                        .await
1469                })
1470            };
1471            tokio::time::sleep(Duration::from_millis(100)).await;
1472
1473            let outgoing = communication_provider.outgoing().await;
1474            let request: RpcRequestMessage<TestRequest> =
1475                serde_utils::from_slice(&outgoing[0].payload)
1476                    .expect("Deserialization should not fail");
1477
1478            communication_provider.push_incoming(test_response_from(
1479                &request,
1480                999,
1481                Source::DesktopRenderer,
1482            ));
1483            tokio::time::sleep(Duration::from_millis(100)).await;
1484            assert!(
1485                !result_handle.is_finished(),
1486                "request must not complete on a response from another source"
1487            );
1488
1489            cancellation_token.cancel();
1490            let result = tokio::time::timeout(Duration::from_secs(5), result_handle)
1491                .await
1492                .expect("request must end once cancelled")
1493                .unwrap();
1494            assert!(matches!(
1495                result,
1496                Err(crate::error::RequestError::Receive(
1497                    TypedReceiveError::Cancelled
1498                ))
1499            ));
1500        }
1501
1502        /// A web source carries an `origin` that its endpoint does not, so the response is matched
1503        /// against the destination by endpoint identity (tab and document) alone.
1504        #[tokio::test]
1505        async fn response_from_web_destination_is_accepted_regardless_of_origin() {
1506            let communication_provider = TestCommunicationBackend::new();
1507            let client = IpcClientImpl::new(
1508                NoEncryptionCryptoProvider,
1509                communication_provider.clone(),
1510                InMemorySessionRepository::default(),
1511            );
1512            let _ = client.start(None).await;
1513
1514            let result_handle = {
1515                let client = client.clone();
1516                tokio::spawn(async move {
1517                    client
1518                        .request::<TestRequest>(
1519                            TestRequest { a: 1, b: 2 },
1520                            Endpoint::Web {
1521                                tab_id: 9001,
1522                                document_id: "doc-1".to_string(),
1523                            },
1524                            None,
1525                        )
1526                        .await
1527                })
1528            };
1529            tokio::time::sleep(Duration::from_millis(100)).await;
1530
1531            let outgoing = communication_provider.outgoing().await;
1532            let request: RpcRequestMessage<TestRequest> =
1533                serde_utils::from_slice(&outgoing[0].payload)
1534                    .expect("Deserialization should not fail");
1535
1536            // Same tab, different document: a page the request was not sent to.
1537            communication_provider.push_incoming(test_response_from(
1538                &request,
1539                999,
1540                Source::Web {
1541                    tab_id: 9001,
1542                    document_id: "doc-2".to_string(),
1543                    origin: "https://vault.bitwarden.com".to_string(),
1544                },
1545            ));
1546            communication_provider.push_incoming(test_response_from(
1547                &request,
1548                3,
1549                Source::Web {
1550                    tab_id: 9001,
1551                    document_id: "doc-1".to_string(),
1552                    origin: "https://vault.bitwarden.com".to_string(),
1553                },
1554            ));
1555
1556            let result = tokio::time::timeout(Duration::from_secs(5), result_handle)
1557                .await
1558                .expect("request must complete once the destination responds")
1559                .unwrap();
1560            assert_eq!(result, Ok(TestResponse { result: 3 }));
1561        }
1562
1563        #[tokio::test]
1564        async fn incoming_rpc_message_handles_request_and_returns_response() {
1565            let crypto_provider = NoEncryptionCryptoProvider;
1566            let communication_provider = TestCommunicationBackend::new();
1567            let session_map = InMemorySessionRepository::default();
1568            let client =
1569                IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
1570            let _ = client.start(None).await;
1571            let request_id = uuid::Uuid::new_v4().to_string();
1572            let request = TestRequest { a: 1, b: 2 };
1573            let response = TestResponse { result: 3 };
1574
1575            // Register the handler
1576            client.register_rpc_handler(TestHandler).await;
1577
1578            // Simulate receiving a request
1579            let response_topic = format!("RpcResponseMessage:{request_id}");
1580            let simulated_request = RpcRequestMessage {
1581                request,
1582                request_id: request_id.clone(),
1583                request_type: "TestRequest".to_string(),
1584                response_topic: response_topic.clone(),
1585            };
1586            let simulated_request_message = IncomingMessage {
1587                payload: serde_utils::to_vec(&simulated_request)
1588                    .expect("Serialization should not fail"),
1589                source: Source::Web {
1590                    tab_id: 9001,
1591                    document_id: "doc-1".to_string(),
1592                    origin: "https://example.com".to_string(),
1593                },
1594                destination: Endpoint::BrowserBackground { id: HostId::Own },
1595                topic: Some(RPC_REQUEST_PAYLOAD_TYPE_NAME.to_owned()),
1596            };
1597            communication_provider.push_incoming(simulated_request_message);
1598
1599            // Give the client some time to process the request
1600            tokio::time::sleep(Duration::from_millis(100)).await;
1601
1602            // Read and verify the outgoing message
1603            let outgoing_messages = communication_provider.outgoing().await;
1604            let outgoing_response: IncomingRpcResponseMessage<TestResponse> =
1605                serde_utils::from_slice(&outgoing_messages[0].payload)
1606                    .expect("Deserialization should not fail");
1607
1608            // The response must be published on the dedicated topic carried by the request.
1609            assert_eq!(outgoing_messages[0].topic, Some(response_topic));
1610            assert_eq!(outgoing_response.request_type, "TestRequest");
1611            assert_eq!(outgoing_response.result, Ok(response));
1612        }
1613
1614        #[tokio::test]
1615        async fn ipc_client_stops_if_rpc_response_send_returns_fatal_error() {
1616            let request = RpcRequestMessage {
1617                request: TestRequest { a: 1, b: 2 },
1618                request_id: "request".to_string(),
1619                request_type: "TestRequest".to_string(),
1620                response_topic: "RpcResponseMessage:request".to_string(),
1621            };
1622            let crypto_provider = TestCryptoProvider {
1623                send_result: Some(Err(TestCryptoError {
1624                    message: "Crypto error".to_string(),
1625                    fatal: true,
1626                })),
1627                receive_result: Some(Ok(IncomingMessage {
1628                    payload: serde_utils::to_vec(&request).expect("Serialization should not fail"),
1629                    source: Source::Web {
1630                        tab_id: 9001,
1631                        document_id: "doc-1".to_string(),
1632                        origin: "https://example.com".to_string(),
1633                    },
1634                    destination: Endpoint::BrowserBackground { id: HostId::Own },
1635                    topic: Some(RPC_REQUEST_PAYLOAD_TYPE_NAME.to_owned()),
1636                })),
1637            };
1638            let client = IpcClientImpl::new(
1639                crypto_provider,
1640                TestCommunicationBackend::new(),
1641                TestSessionRepository::new(HashMap::new()),
1642            );
1643            client.register_rpc_handler(TestHandler).await;
1644            let _ = client.start(None).await;
1645
1646            // Give the client some time to receive the request and fail to send the response
1647            tokio::time::sleep(Duration::from_millis(100)).await;
1648
1649            assert!(!client.is_running());
1650        }
1651
1652        #[tokio::test]
1653        async fn incoming_rpc_message_passes_message_source_to_handler() {
1654            let crypto_provider = NoEncryptionCryptoProvider;
1655            let communication_provider = TestCommunicationBackend::new();
1656            let session_map = InMemorySessionRepository::default();
1657            let client =
1658                IpcClientImpl::new(crypto_provider, communication_provider.clone(), session_map);
1659            let _ = client.start(None).await;
1660            client.register_rpc_handler(EchoSourceHandler).await;
1661
1662            let source = Source::Web {
1663                tab_id: 9001,
1664                document_id: "doc-1".to_string(),
1665                origin: "https://example.com".to_string(),
1666            };
1667            let request_id = uuid::Uuid::new_v4().to_string();
1668            let simulated_request = RpcRequestMessage {
1669                request: EchoSourceRequest,
1670                request_id: request_id.clone(),
1671                request_type: EchoSourceRequest::NAME.to_string(),
1672                response_topic: format!("RpcResponseMessage:{request_id}"),
1673            };
1674            communication_provider.push_incoming(IncomingMessage {
1675                payload: serde_utils::to_vec(&simulated_request)
1676                    .expect("Serialization should not fail"),
1677                source: source.clone(),
1678                destination: Endpoint::BrowserBackground { id: HostId::Own },
1679                topic: Some(RPC_REQUEST_PAYLOAD_TYPE_NAME.to_owned()),
1680            });
1681
1682            // Give the client some time to process the request
1683            tokio::time::sleep(Duration::from_millis(100)).await;
1684
1685            let outgoing_messages = communication_provider.outgoing().await;
1686            let outgoing_response: IncomingRpcResponseMessage<Source> =
1687                serde_utils::from_slice(&outgoing_messages[0].payload)
1688                    .expect("Deserialization should not fail");
1689
1690            assert_eq!(outgoing_response.result, Ok(source));
1691        }
1692    }
1693
1694    mod fragmentation {
1695        use super::*;
1696        use crate::{
1697            RequestError, RpcHandler, RpcRequestInfo,
1698            crypto_provider::noise::crypto_provider::NoiseCryptoProvider,
1699            fragmentation::{FRAGMENT_TOPIC, MAX_PAYLOAD_SIZE, test_support::*},
1700            traits::TestTwoWayCommunicationBackend,
1701        };
1702
1703        /// Larger than several Noise messages, and not a multiple of the fragment size.
1704        const LARGE_LEN: usize = 4 * 65535 + 123;
1705
1706        fn noise_client(
1707            backend: TestTwoWayCommunicationBackend,
1708        ) -> IpcClientImpl<
1709            NoiseCryptoProvider,
1710            TestTwoWayCommunicationBackend,
1711            InMemorySessionRepository<crate::NoiseCryptoProviderState>,
1712        > {
1713            IpcClientImpl::new(
1714                NoiseCryptoProvider::new(),
1715                backend,
1716                InMemorySessionRepository::new(HashMap::new()),
1717            )
1718        }
1719
1720        #[tokio::test]
1721        async fn large_payload_round_trips_through_noise_once_on_its_topic() {
1722            let (backend_1, backend_2) = TestTwoWayCommunicationBackend::new();
1723            let client_1 = noise_client(backend_1);
1724            let client_2 = noise_client(backend_2);
1725            client_1.start(None).await.unwrap();
1726            client_2.start(None).await.unwrap();
1727            let mut all_messages = client_2.subscribe(None).await.unwrap();
1728            let mut on_topic = client_2.subscribe(Some("bulk".to_owned())).await.unwrap();
1729            let mut on_fragment_topic = client_2
1730                .subscribe(Some(format!("{FRAGMENT_TOPIC}/bulk")))
1731                .await
1732                .unwrap();
1733
1734            let payload = large_payload(LARGE_LEN, 0);
1735            let message = OutgoingMessage {
1736                payload: payload.clone(),
1737                destination: Endpoint::DesktopMain,
1738                topic: Some("bulk".to_owned()),
1739            };
1740            client_1.send(message).await.unwrap();
1741
1742            let received = all_messages.receive(None).await.unwrap();
1743            assert_eq!(received.topic.as_deref(), Some("bulk"));
1744            assert_eq!(received.payload, payload);
1745
1746            // Neither the fragments nor a second copy reach subscribers.
1747            let next = bitwarden_threading::time::timeout(
1748                Duration::from_millis(200),
1749                all_messages.receive(None),
1750            )
1751            .await;
1752            assert!(next.is_err(), "unexpected extra message: {next:?}");
1753
1754            // Topic filters see the reassembled message, never its fragments.
1755            assert_eq!(on_topic.receive(None).await.unwrap().payload, payload);
1756            let fragment = bitwarden_threading::time::timeout(
1757                Duration::from_millis(10),
1758                on_fragment_topic.receive(None),
1759            )
1760            .await;
1761            assert!(
1762                fragment.is_err(),
1763                "fragment reached a subscriber: {fragment:?}"
1764            );
1765        }
1766
1767        #[derive(Debug, Clone, Serialize, Deserialize)]
1768        struct EchoRequest {
1769            data: String,
1770        }
1771
1772        impl RpcRequest for EchoRequest {
1773            type Response = String;
1774
1775            const NAME: &str = "EchoRequest";
1776        }
1777
1778        struct EchoHandler;
1779
1780        impl RpcHandler for EchoHandler {
1781            type Request = EchoRequest;
1782
1783            async fn handle(&self, request: EchoRequest, _info: RpcRequestInfo) -> String {
1784                request.data.repeat(2)
1785            }
1786        }
1787
1788        #[tokio::test]
1789        async fn rpc_with_response_larger_than_one_noise_message_succeeds() {
1790            let (backend_1, backend_2) = TestTwoWayCommunicationBackend::new();
1791            let client_1 = noise_client(backend_1);
1792            let client_2 = noise_client(backend_2);
1793            client_1.start(None).await.unwrap();
1794            client_2.start(None).await.unwrap();
1795            client_2.register_rpc_handler(EchoHandler).await;
1796
1797            // The request itself also exceeds one Noise message.
1798            let data = "a".repeat(LARGE_LEN / 2);
1799            let response = client_1
1800                .request(
1801                    EchoRequest { data: data.clone() },
1802                    Endpoint::DesktopMain,
1803                    None,
1804                )
1805                .await
1806                .unwrap();
1807
1808            assert_eq!(response, data.repeat(2));
1809        }
1810
1811        #[tokio::test]
1812        async fn rpc_response_over_the_maximum_returns_an_error_to_the_requester() {
1813            let (backend_1, backend_2) = TestTwoWayCommunicationBackend::new();
1814            let client_1 = noise_client(backend_1);
1815            let client_2 = noise_client(backend_2);
1816            client_1.start(None).await.unwrap();
1817            client_2.start(None).await.unwrap();
1818            client_2.register_rpc_handler(EchoHandler).await;
1819
1820            // The request fits, but the doubled response does not.
1821            let data = "a".repeat(MAX_PAYLOAD_SIZE / 2 + 1);
1822            let result = bitwarden_threading::time::timeout(
1823                Duration::from_secs(10),
1824                client_1.request(EchoRequest { data }, Endpoint::DesktopMain, None),
1825            )
1826            .await
1827            .expect("Requester should receive an error response");
1828
1829            assert!(
1830                matches!(
1831                    result,
1832                    Err(RequestError::Rpc(RpcError::ResponseSerialization(_)))
1833                ),
1834                "{result:?}"
1835            );
1836        }
1837
1838        #[tokio::test]
1839        async fn client_keeps_receiving_after_invalid_fragments() {
1840            let backend = TestCommunicationBackend::new();
1841            let client = IpcClientImpl::new(
1842                NoEncryptionCryptoProvider,
1843                backend.clone(),
1844                InMemorySessionRepository::default(),
1845            );
1846            client.start(None).await.unwrap();
1847            let mut subscription = client.subscribe(None).await.unwrap();
1848            let source = web_source(1);
1849
1850            backend.push_incoming(incoming(
1851                outgoing(vec![1, 2, 3], FRAGMENT_TOPIC),
1852                source.clone(),
1853            ));
1854            backend.push_incoming(crafted(source.clone(), 1, 5, 1024));
1855            backend.push_incoming(crafted(source.clone(), 2, 0, MAX_PAYLOAD_SIZE + 1));
1856            backend.push_incoming(crafted(source.clone(), 3, 0, 1024));
1857            backend.push_incoming(crafted(source.clone(), 3, 0, 1024));
1858
1859            let payload = large_payload(FRAGMENT_LEN * 2 + 1, 0);
1860            for fragment in split_all(outgoing(payload.clone(), "bulk"), MAX_LEN) {
1861                backend.push_incoming(incoming(fragment, source.clone()));
1862            }
1863
1864            let received = subscription.receive(None).await.unwrap();
1865            assert_eq!(received.topic.as_deref(), Some("bulk"));
1866            assert_eq!(received.payload, payload);
1867            assert!(client.is_running());
1868        }
1869
1870        #[tokio::test]
1871        async fn send_rejects_reserved_fragment_topic() {
1872            let client = IpcClientImpl::new(
1873                NoEncryptionCryptoProvider,
1874                TestCommunicationBackend::new(),
1875                InMemorySessionRepository::default(),
1876            );
1877            let result = client.send(outgoing(vec![0; 16], FRAGMENT_TOPIC)).await;
1878            assert!(matches!(result, Err(SendError::Other(_))));
1879        }
1880
1881        /// Records sent messages of up to [`MAX_LEN`] bytes and fails the send at index `fail_at`.
1882        struct FailingCryptoProvider {
1883            fail_at: usize,
1884            fatal: bool,
1885            sent: Arc<Mutex<Vec<OutgoingMessage>>>,
1886        }
1887
1888        impl CryptoProvider<TestCommunicationBackend, TestSessionRepository> for FailingCryptoProvider {
1889            type Session = String;
1890            type SendError = TestCryptoError;
1891            type ReceiveError = TestCryptoError;
1892
1893            fn max_payload_len(&self) -> usize {
1894                MAX_LEN
1895            }
1896
1897            async fn send(
1898                &self,
1899                _communication: &TestCommunicationBackend,
1900                _sessions: &TestSessionRepository,
1901                message: OutgoingMessage,
1902            ) -> Result<(), TestCryptoError> {
1903                let mut sent = self.sent.lock().unwrap();
1904                if sent.len() == self.fail_at {
1905                    return Err(TestCryptoError {
1906                        message: "Send failed".to_owned(),
1907                        fatal: self.fatal,
1908                    });
1909                }
1910                sent.push(message);
1911                Ok(())
1912            }
1913
1914            async fn receive(
1915                &self,
1916                _receiver: &<TestCommunicationBackend as CommunicationBackend>::Receiver,
1917                _communication: &TestCommunicationBackend,
1918                _sessions: &TestSessionRepository,
1919            ) -> Result<IncomingMessage, TestCryptoError> {
1920                std::future::pending().await
1921            }
1922        }
1923
1924        #[tokio::test]
1925        async fn failed_fragment_send_stops_the_message_and_fatal_errors_stop_the_client() {
1926            for fatal in [false, true] {
1927                let sent = Arc::new(Mutex::new(Vec::new()));
1928                let client = IpcClientImpl::new(
1929                    FailingCryptoProvider {
1930                        fail_at: 1,
1931                        fatal,
1932                        sent: sent.clone(),
1933                    },
1934                    TestCommunicationBackend::new(),
1935                    TestSessionRepository::default(),
1936                );
1937                client.start(None).await.unwrap();
1938
1939                let message = outgoing(large_payload(FRAGMENT_LEN * 3, 0), "bulk");
1940                assert!(client.send(message).await.is_err());
1941
1942                // Fragments after the failed one are not sent.
1943                assert_eq!(sent.lock().unwrap().len(), 1);
1944                assert_eq!(client.is_running(), !fatal);
1945            }
1946        }
1947    }
1948}