Skip to main content

bitwarden_ipc/
ipc_client_ext.rs

1use bitwarden_threading::cancellation_token::CancellationToken;
2use serde::{Serialize, de::DeserializeOwned};
3
4use crate::{
5    RpcHandler,
6    broadcast::{BroadcastGroup, EndpointSendResult},
7    endpoint::Endpoint,
8    error::{BroadcastError, RequestError, SubscribeError},
9    ipc_client::IpcClientTypedSubscription,
10    ipc_client_trait::IpcClient,
11    message::{OutgoingMessage, PayloadTypeName, TypedOutgoingMessage},
12    rpc::{
13        error::RpcError,
14        request::RpcRequest,
15        request_message::{RPC_REQUEST_PAYLOAD_TYPE_NAME, RpcRequestMessage},
16        response_message::IncomingRpcResponseMessage,
17    },
18    serde_utils,
19    timeline::{self, Duration, Entry, Track},
20};
21
22/// Extension trait providing generic convenience methods on any [`IpcClient`].
23///
24/// This trait is automatically implemented for all types that implement [`IpcClient`],
25/// including `dyn IpcClient`. It provides typed subscriptions, handler registration,
26/// and RPC request functionality with full static type safety.
27pub trait IpcClientExt: IpcClient {
28    /// Register a new RPC handler for processing incoming RPC requests.
29    /// The handler will be executed by the IPC client when an RPC request is received and
30    /// the response will be sent back over IPC.
31    fn register_rpc_handler<H>(&self, handler: H) -> impl std::future::Future<Output = ()> + Send
32    where
33        H: RpcHandler + Send + Sync + 'static,
34    {
35        async move {
36            self.register_rpc_handler_erased(H::Request::NAME, Box::new(handler))
37                .await;
38        }
39    }
40
41    /// Send a message with a payload of any serializable type to the specified destination.
42    fn send_typed<Payload>(
43        &self,
44        payload: Payload,
45        destination: Endpoint,
46    ) -> impl std::future::Future<Output = Result<(), RequestError>> + Send
47    where
48        Payload: Serialize + PayloadTypeName + Send,
49    {
50        async move {
51            let message = TypedOutgoingMessage {
52                payload,
53                destination,
54            }
55            .try_into()
56            .map_err(|e: serde_utils::DeserializeError| {
57                RequestError::Rpc(RpcError::RequestSerialization(e.to_string()))
58            })?;
59
60            self.send(message).await.map_err(RequestError::from)
61        }
62    }
63
64    /// Send a message with a payload of any serializable type to every member of `group`. See
65    /// [`IpcClient::broadcast`] for how the group is resolved and how failures are reported.
66    fn broadcast_typed<Payload>(
67        &self,
68        payload: Payload,
69        group: BroadcastGroup,
70    ) -> impl std::future::Future<Output = Result<Vec<EndpointSendResult>, BroadcastError>> + Send
71    where
72        Payload: Serialize + PayloadTypeName + Send,
73    {
74        async move {
75            let payload =
76                serde_utils::to_vec(&payload).map_err(|e: serde_utils::SerializeError| {
77                    BroadcastError::Serialization(e.to_string())
78                })?;
79
80            self.broadcast(group, payload, Some(Payload::PAYLOAD_TYPE_NAME.to_owned()))
81                .await
82        }
83    }
84
85    /// Create a subscription to receive messages that can be deserialized into the provided
86    /// payload type.
87    fn subscribe_typed<Payload>(
88        &self,
89    ) -> impl std::future::Future<
90        Output = Result<IpcClientTypedSubscription<Payload>, SubscribeError>,
91    > + Send
92    where
93        Payload: DeserializeOwned + PayloadTypeName,
94    {
95        async move {
96            Ok(IpcClientTypedSubscription::new(
97                self.subscribe(Some(Payload::PAYLOAD_TYPE_NAME.to_owned()))
98                    .await?,
99            ))
100        }
101    }
102
103    /// Send a request to the specified destination and wait for a response.
104    /// The destination must have a registered RPC handler for the request type, otherwise
105    /// an error will be returned by the remote endpoint.
106    ///
107    /// The response is accepted only from `destination`, as identified by the source the
108    /// transport reports for each incoming message (the SDK trusts the transport, and any relay
109    /// in between, to label sources correctly). A response from any other source is ignored, so a
110    /// caller that needs a bound on the wait should pass a `cancellation_token`.
111    fn request<Request>(
112        &self,
113        request: Request,
114        destination: Endpoint,
115        cancellation_token: Option<CancellationToken>,
116    ) -> impl std::future::Future<Output = Result<Request::Response, RequestError>> + Send
117    where
118        Request: RpcRequest + Send,
119        Request::Response: Send,
120    {
121        async move {
122            let _span = timeline::span(Track::Requests, Duration::Actual, || Entry {
123                name: Request::NAME.to_owned(),
124                properties: vec![("Destination", format!("{destination:?}"))],
125            });
126
127            let request_payload = RpcRequestMessage::new(request);
128
129            // Each request gets its own response topic, subscribed to before sending, and the
130            // handler publishes its reply there. The subscription receives every message on that
131            // topic; the loop below accepts only the one from the destination. A deserialization
132            // failure of that message is therefore a malformed response to this request.
133            let mut response_subscription = self
134                .subscribe(Some(request_payload.response_topic.clone()))
135                .await?;
136
137            // Requests are dispatched by a single fixed topic that the receiver matches on to route
138            // them to the handler registry.
139            let payload = serde_utils::to_vec(&request_payload)
140                .map_err(|e| RequestError::Rpc(RpcError::RequestSerialization(e.to_string())))?;
141            let message = OutgoingMessage {
142                payload,
143                destination: destination.clone(),
144                topic: Some(RPC_REQUEST_PAYLOAD_TYPE_NAME.to_owned()),
145            };
146
147            self.send(message).await.map_err(RequestError::from)?;
148
149            // Only the endpoint the request was sent to may answer it. A message on the response
150            // topic from any other source is skipped without failing the request, so another peer
151            // cannot forge the response or end the wait by posting on the response topic.
152            let received = loop {
153                let received = response_subscription
154                    .receive(cancellation_token.clone())
155                    .await
156                    .map_err(|e| RequestError::Receive(e.into()))?;
157
158                if received.source.to_endpoint() == destination {
159                    break received;
160                }
161
162                tracing::warn!(
163                    source = ?received.source,
164                    ?destination,
165                    "Ignoring RPC response from a source other than the request destination"
166                );
167            };
168
169            let response: IncomingRpcResponseMessage<Request::Response> =
170                serde_utils::from_slice(&received.payload).map_err(|e| {
171                    RequestError::Rpc(RpcError::ResponseDeserialization(e.to_string()))
172                })?;
173
174            Ok(response.result?)
175        }
176    }
177}
178
179/// Blanket implementation: every [`IpcClient`] gets the extension methods for free.
180impl<T: IpcClient + ?Sized> IpcClientExt for T {}