Skip to main content

bitwarden_ipc/discover/
mod.rs

1#![doc = include_str!("README.md")]
2
3use std::time::Duration;
4
5use bitwarden_threading::{
6    cancellation_token::CancellationToken,
7    time::{sleep, timeout},
8};
9use serde::{Deserialize, Serialize};
10use tokio::select;
11
12use crate::{
13    IpcClient, IpcClientExt, RequestError, RpcHandler, RpcRequestInfo, TypedReceiveError,
14    endpoint::Endpoint, rpc::request::RpcRequest,
15};
16
17/// Upper bound for a single discover attempt in [`wait_for_peer`], so a lost message cannot stall
18/// the wait. Must stay longer than the Noise handshake timeout (2s), so a handshake finishes or
19/// fails on its own first.
20const ATTEMPT_TIMEOUT: Duration = Duration::from_secs(5);
21/// Pause between failed discover attempts in [`wait_for_peer`].
22const RETRY_DELAY: Duration = Duration::from_millis(250);
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25/// A request to discover/ping a client.
26pub struct DiscoverRequest;
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29#[bitwarden_ffi::wasm_record]
30/// The response to a discover/ping request.
31pub struct DiscoverResponse {
32    /// The version of the client that responded to the discover request.
33    pub version: String,
34}
35
36impl RpcRequest for DiscoverRequest {
37    type Response = DiscoverResponse;
38
39    const NAME: &str = "DiscoverRequest";
40}
41
42/// A simple handler for the `DiscoverRequest` that always returns the same response.
43/// Used to enable discovery/ping functionality and provide version information.
44pub struct DiscoverHandler {
45    response: DiscoverResponse,
46}
47
48impl DiscoverHandler {
49    /// Creates a new `DiscoverHandler` with the given response.
50    pub fn new(response: DiscoverResponse) -> Self {
51        Self { response }
52    }
53}
54
55impl RpcHandler for DiscoverHandler {
56    type Request = DiscoverRequest;
57
58    async fn handle(&self, _request: Self::Request, _info: RpcRequestInfo) -> DiscoverResponse {
59        self.response.clone()
60    }
61}
62
63/// Waits until `destination` answers a [`DiscoverRequest`], retrying until it does or
64/// `cancellation_token` is cancelled.
65///
66/// Use this before sending to a peer that may not have started yet. An error answer from the peer,
67/// such as having no discover handler, is returned without retrying, since the peer is up. A
68/// subscribe error, such as the local client not running, is also returned without retrying.
69pub async fn wait_for_peer<C: IpcClient + ?Sized>(
70    client: &C,
71    destination: Endpoint,
72    cancellation_token: Option<CancellationToken>,
73) -> Result<DiscoverResponse, RequestError> {
74    let attempts = async {
75        loop {
76            let attempt = timeout(
77                ATTEMPT_TIMEOUT,
78                client.request(DiscoverRequest, destination.clone(), None),
79            )
80            .await;
81
82            match attempt {
83                Ok(Ok(response)) => return Ok(response),
84                Ok(Err(e @ (RequestError::Rpc(_) | RequestError::Subscribe(_)))) => return Err(e),
85                _ => sleep(RETRY_DELAY).await,
86            }
87        }
88    };
89
90    let Some(cancellation_token) = cancellation_token else {
91        return attempts.await;
92    };
93    select! {
94        result = attempts => result,
95        _ = cancellation_token.cancelled() => {
96            Err(RequestError::Receive(TypedReceiveError::Cancelled))
97        }
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use std::{collections::HashMap, sync::Arc};
104
105    use super::*;
106    use crate::{
107        HostId, IncomingMessage, IpcClientImpl, NoEncryptionCryptoProvider, Source, SubscribeError,
108        rpc::error::RpcError,
109        traits::{InMemorySessionRepository, TestCommunicationBackend},
110    };
111
112    async fn start_client(backend: &TestCommunicationBackend) -> Arc<dyn IpcClient> {
113        let client: Arc<dyn IpcClient> = Arc::new(IpcClientImpl::new(
114            NoEncryptionCryptoProvider,
115            backend.clone(),
116            InMemorySessionRepository::new(HashMap::new()),
117        ));
118        client.start(None).await.expect("client starts");
119        client
120    }
121
122    fn peer() -> Endpoint {
123        Endpoint::BrowserBackground { id: HostId::Own }
124    }
125
126    /// Deliver the messages sent through `from` to `to`, as if they came from `source`.
127    async fn relay(from: &TestCommunicationBackend, to: &TestCommunicationBackend, source: Source) {
128        for message in from.drain_outgoing().await {
129            to.push_incoming(IncomingMessage {
130                payload: message.payload,
131                destination: message.destination,
132                source: source.clone(),
133                topic: message.topic,
134            });
135        }
136    }
137
138    /// Relay one discover round trip between the waiting client and the peer.
139    async fn round_trip(client: &TestCommunicationBackend, peer: &TestCommunicationBackend) {
140        tokio::time::sleep(Duration::from_millis(20)).await;
141        relay(client, peer, Source::BrowserForeground { id: 1 }).await;
142        tokio::time::sleep(Duration::from_millis(20)).await;
143        relay(peer, client, Source::BrowserBackground { id: HostId::Own }).await;
144    }
145
146    async fn start_peer(with_handler: bool) -> TestCommunicationBackend {
147        let backend = TestCommunicationBackend::new();
148        let client = start_client(&backend).await;
149        if with_handler {
150            client
151                .register_rpc_handler(DiscoverHandler::new(DiscoverResponse {
152                    version: "1.0.0".to_string(),
153                }))
154                .await;
155        }
156        backend
157    }
158
159    #[tokio::test(start_paused = true)]
160    async fn test_wait_for_peer_retries_until_the_peer_answers() {
161        let peer_backend = start_peer(true).await;
162        let backend = TestCommunicationBackend::new();
163        let client = start_client(&backend).await;
164
165        let wait = tokio::spawn(async move { wait_for_peer(client.as_ref(), peer(), None).await });
166
167        // The first attempt is lost, as if the peer had not started.
168        tokio::time::sleep(Duration::from_millis(20)).await;
169        backend.drain_outgoing().await;
170        tokio::time::sleep(ATTEMPT_TIMEOUT + RETRY_DELAY).await;
171        round_trip(&backend, &peer_backend).await;
172
173        let response = wait.await.expect("task joins").expect("peer answers");
174        assert_eq!(response.version, "1.0.0");
175    }
176
177    #[tokio::test(start_paused = true)]
178    async fn test_wait_for_peer_returns_peer_errors_without_retrying() {
179        let peer_backend = start_peer(false).await;
180        let backend = TestCommunicationBackend::new();
181        let client = start_client(&backend).await;
182
183        let wait = tokio::spawn(async move { wait_for_peer(client.as_ref(), peer(), None).await });
184        round_trip(&backend, &peer_backend).await;
185
186        let result = wait.await.expect("task joins");
187        assert!(matches!(
188            result,
189            Err(RequestError::Rpc(RpcError::NoHandlerFound))
190        ));
191        assert!(backend.drain_outgoing().await.is_empty());
192    }
193
194    #[tokio::test(start_paused = true)]
195    async fn test_wait_for_peer_returns_subscribe_errors_without_retrying() {
196        let backend = TestCommunicationBackend::new();
197        let client = IpcClientImpl::new(
198            NoEncryptionCryptoProvider,
199            backend.clone(),
200            InMemorySessionRepository::new(HashMap::new()),
201        );
202
203        let result = wait_for_peer(&client, peer(), None).await;
204
205        assert!(matches!(
206            result,
207            Err(RequestError::Subscribe(SubscribeError::NotStarted))
208        ));
209        assert!(backend.drain_outgoing().await.is_empty());
210    }
211
212    #[tokio::test(start_paused = true)]
213    async fn test_wait_for_peer_stops_when_cancelled() {
214        let backend = TestCommunicationBackend::new();
215        let client = start_client(&backend).await;
216        let cancellation_token = CancellationToken::new();
217
218        let wait = tokio::spawn({
219            let cancellation_token = cancellation_token.clone();
220            async move { wait_for_peer(client.as_ref(), peer(), Some(cancellation_token)).await }
221        });
222        tokio::time::sleep(ATTEMPT_TIMEOUT * 2).await;
223        cancellation_token.cancel();
224
225        let result = wait.await.expect("task joins");
226        assert!(matches!(
227            result,
228            Err(RequestError::Receive(TypedReceiveError::Cancelled))
229        ));
230    }
231}