Skip to main content

tor_rpcbase/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![warn(clippy::cognitive_complexity)]
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![deny(clippy::print_stderr)]
28#![deny(clippy::print_stdout)]
29#![warn(clippy::rc_buffer)]
30#![deny(clippy::ref_option_ref)]
31#![warn(clippy::semicolon_if_nothing_returned)]
32#![warn(clippy::trait_duplication_in_bounds)]
33#![deny(clippy::unchecked_time_subtraction)]
34#![deny(clippy::unnecessary_wraps)]
35#![warn(clippy::unseparated_literal_suffix)]
36#![deny(clippy::unwrap_used)]
37#![deny(clippy::mod_module_files)]
38#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39#![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43#![allow(clippy::needless_lifetimes)] // See arti#1765
44#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45#![allow(clippy::collapsible_if)] // See arti#2342
46#![deny(clippy::unused_async)]
47#![deny(clippy::string_slice)] // See arti#2571
48//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
49
50pub mod dispatch;
51mod err;
52mod method;
53mod obj;
54
55use std::{collections::HashSet, convert::Infallible, sync::Arc};
56
57pub use dispatch::{DispatchTable, InvokeError, UpdateSink};
58pub use err::{RpcError, RpcErrorKind};
59pub use method::{
60    DeserMethod, DynMethod, Method, NoUpdates, RpcMethod, check_method_names, is_method_name,
61    iter_method_names,
62};
63pub use obj::{Object, ObjectArcExt, ObjectId};
64
65#[cfg(feature = "describe-methods")]
66pub use dispatch::description::RpcDispatchInformation;
67
68#[cfg(feature = "describe-methods")]
69#[doc(hidden)]
70pub use dispatch::description::DelegationNote;
71
72#[doc(hidden)]
73pub use obj::cast::CastTable;
74#[doc(hidden)]
75pub use {
76    derive_deftly, dispatch::RpcResult, downcast_rs, erased_serde, futures, inventory,
77    method::MethodInfo_, paste, tor_async_utils, tor_error::internal, typetag,
78};
79
80/// Templates for use with [`derive_deftly`]
81pub mod templates {
82    pub use crate::method::derive_deftly_template_DynMethod;
83    pub use crate::obj::derive_deftly_template_Object;
84}
85
86/// An error returned from [`ContextExt::lookup`].
87#[derive(Debug, Clone, thiserror::Error)]
88#[non_exhaustive]
89pub enum LookupError {
90    /// The specified object does not (currently) exist,
91    /// or the user does not have permission to access it.
92    #[error("No visible object with ID {0:?}")]
93    NoObject(ObjectId),
94
95    /// The specified object exists, but does not have the
96    /// expected type.
97    #[error("Unexpected type on object with ID {0:?}")]
98    WrongType(ObjectId),
99
100    /// The object once existed, but this is a weak reference,
101    /// and it has expired.
102    #[error("Weak reference {0:?} is no longer present")]
103    Expired(ObjectId),
104}
105
106impl LookupError {
107    /// Return the RpcErrorKind for this lookup error.
108    fn rpc_error_kind(&self) -> RpcErrorKind {
109        use LookupError as E;
110        use RpcErrorKind as EK;
111
112        match self {
113            E::NoObject(_) => EK::ObjectNotFound,
114            E::WrongType(_) => EK::InvalidRequest,
115            E::Expired(_) => EK::WeakReferenceExpired,
116        }
117    }
118}
119
120impl From<LookupError> for RpcError {
121    fn from(err: LookupError) -> Self {
122        RpcError::new(err.to_string(), err.rpc_error_kind())
123    }
124}
125
126/// A trait describing the context in which an RPC method is executed.
127pub trait Context: Send + Sync {
128    /// Look up an object by identity within this context.
129    fn lookup_object(&self, id: &ObjectId) -> Result<Arc<dyn Object>, LookupError>;
130
131    /// Create an owning reference to `object` within this context.
132    ///
133    /// Return an ObjectId for this object.
134    fn register_owned(&self, object: Arc<dyn Object>) -> ObjectId;
135
136    /// Create a non-owning weak referene to `object` within this context.
137    ///
138    /// Return an ObjectId for this object.
139    fn register_weak(&self, object: &Arc<dyn Object>) -> ObjectId;
140
141    /// Drop a reference to the object called `object` within this context.
142    ///
143    /// This will return an error if `object` does not exist.
144    fn release(&self, object: &ObjectId) -> Result<(), LookupError>;
145
146    /// Return a dispatch table that can be used to invoke other RPC methods.
147    fn dispatch_table(&self) -> &Arc<std::sync::RwLock<DispatchTable>>;
148}
149
150/// An error caused while trying to send an update to a method.
151///
152/// These errors should be impossible in our current implementation, since they
153/// can only happen if the `mpsc::Receiver` is closed—which can only happen
154/// when the session loop drops it, which only happens when the session loop has
155/// stopped polling its `FuturesUnordered` full of RPC request futures. Thus, any
156/// `send` that would encounter this error should be in a future that is never
157/// polled under circumstances when the error could happen.
158///
159/// Still, programming errors are real, so we are handling this rather than
160/// declaring it a panic or something.
161#[derive(Debug, Clone, thiserror::Error)]
162#[non_exhaustive]
163pub enum SendUpdateError {
164    /// The request was cancelled, or the connection was closed.
165    #[error("Unable to send on MPSC connection")]
166    ConnectionClosed,
167}
168
169impl tor_error::HasKind for SendUpdateError {
170    fn kind(&self) -> tor_error::ErrorKind {
171        tor_error::ErrorKind::Internal
172    }
173}
174
175impl From<Infallible> for SendUpdateError {
176    fn from(_: Infallible) -> Self {
177        unreachable!()
178    }
179}
180impl From<futures::channel::mpsc::SendError> for SendUpdateError {
181    fn from(_: futures::channel::mpsc::SendError) -> Self {
182        SendUpdateError::ConnectionClosed
183    }
184}
185
186/// Extension trait for [`Context`].
187///
188/// This is a separate trait so that `Context` can be object-safe.
189pub trait ContextExt: Context {
190    /// Look up an object of a given type, and downcast it.
191    ///
192    /// Return an error if the object can't be found, or has the wrong type.
193    fn lookup<T: Object>(&self, id: &ObjectId) -> Result<Arc<T>, LookupError> {
194        self.lookup_object(id)?
195            .downcast_arc()
196            .map_err(|_| LookupError::WrongType(id.clone()))
197    }
198}
199
200impl<T: Context> ContextExt for T {}
201
202/// Try to find an appropriate function for calling a given RPC method on a
203/// given ObjectId.
204///
205/// On success, return a Future.
206///
207/// Differs from using `DispatchTable::invoke()` in that it drops its lock
208/// on the dispatch table before invoking the method.
209pub fn invoke_rpc_method(
210    ctx: Arc<dyn Context>,
211    obj_id: &ObjectId,
212    method: Box<dyn DynMethod>,
213    sink: dispatch::BoxedUpdateSink,
214) -> Result<dispatch::RpcResultFuture, InvokeError> {
215    match method.invoke_without_dispatch(Arc::clone(&ctx), obj_id) {
216        Err(InvokeError::NoDispatchBypass) => {
217            // fall through
218        }
219        other => return other,
220    }
221
222    let obj = ctx.lookup_object(obj_id).map_err(InvokeError::NoObject)?;
223
224    let (obj, invocable) = ctx
225        .dispatch_table()
226        .read()
227        .expect("poisoned lock")
228        .resolve_rpc_invoker(obj, method.as_ref())?;
229
230    invocable.invoke(obj, method, ctx, sink)
231}
232
233/// Invoke the given `method` on `obj` within `ctx`, and return its
234/// actual result type.
235///
236/// Unlike `invoke_rpc_method`, this method does not return a type-erased result,
237/// and does not require that the result can be serialized as an RPC object.
238///
239/// Differs from using `DispatchTable::invoke_special()` in that it drops its lock
240/// on the dispatch table before invoking the method.
241pub async fn invoke_special_method<M: Method>(
242    ctx: Arc<dyn Context>,
243    obj: Arc<dyn Object>,
244    method: Box<M>,
245) -> Result<Box<M::Output>, InvokeError> {
246    let (obj, invocable) = ctx
247        .dispatch_table()
248        .read()
249        .expect("poisoned lock")
250        .resolve_special_invoker::<M>(obj)?;
251
252    invocable
253        .invoke_special(obj, method, ctx)?
254        .await
255        .downcast()
256        .map_err(|_| InvokeError::Bug(tor_error::internal!("Downcast to wrong type")))
257}
258
259/// A serializable empty object.
260///
261/// Used when we need to declare that a method returns nothing.
262#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
263#[non_exhaustive]
264pub struct Nil {}
265/// An instance of rpc::Nil.
266pub const NIL: Nil = Nil {};
267
268/// Common return type for RPC methods that return a single object ID
269/// and nothing else.
270#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, derive_more::From)]
271pub struct SingleIdResponse {
272    /// The ID of the object that we're returning.
273    id: ObjectId,
274}
275
276/// Error representing an "invalid" RPC identifier.
277#[derive(Clone, Debug, thiserror::Error)]
278#[non_exhaustive]
279#[cfg_attr(test, derive(Eq, PartialEq))]
280pub enum InvalidRpcIdentifier {
281    /// The method doesn't have a ':' to demarcate its namespace.
282    #[error("Identifier has no namespace separator")]
283    NoNamespace,
284
285    /// The method's namespace is not one we recognize.
286    #[error("Identifier has unrecognized namespace")]
287    UnrecognizedNamespace,
288
289    /// The method's name is not in snake_case.
290    #[error("Identifier name has unexpected format")]
291    BadIdName,
292}
293
294/// Check whether `method` is an expected and well-formed RPC identifier.
295///
296/// If `recognized_namespaces` is provided, only identifiers within those
297/// namespaces are accepted; otherwise, all namespaces are accepted.
298///
299/// (Examples of RPC identifiers are method names.)
300pub(crate) fn is_valid_rpc_identifier(
301    recognized_namespaces: Option<&HashSet<&str>>,
302    method: &str,
303) -> Result<(), InvalidRpcIdentifier> {
304    /// Return true if name is in acceptable format.
305    fn name_ok(n: &str) -> bool {
306        let mut chars = n.chars();
307        let Some(first) = chars.next() else {
308            return false;
309        };
310        first.is_ascii_lowercase()
311            && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
312    }
313    let (scope, name) = method
314        .split_once(':')
315        .ok_or(InvalidRpcIdentifier::NoNamespace)?;
316
317    if let Some(recognized_namespaces) = recognized_namespaces {
318        if !(scope.starts_with("x-") || recognized_namespaces.contains(scope)) {
319            return Err(InvalidRpcIdentifier::UnrecognizedNamespace);
320        }
321    }
322    if !name_ok(name) {
323        return Err(InvalidRpcIdentifier::BadIdName);
324    }
325
326    Ok(())
327}
328
329#[cfg(test)]
330mod test {
331    // @@ begin test lint list maintained by maint/add_warning @@
332    #![allow(clippy::bool_assert_comparison)]
333    #![allow(clippy::clone_on_copy)]
334    #![allow(clippy::dbg_macro)]
335    #![allow(clippy::mixed_attributes_style)]
336    #![allow(clippy::print_stderr)]
337    #![allow(clippy::print_stdout)]
338    #![allow(clippy::single_char_pattern)]
339    #![allow(clippy::unwrap_used)]
340    #![allow(clippy::unchecked_time_subtraction)]
341    #![allow(clippy::useless_vec)]
342    #![allow(clippy::needless_pass_by_value)]
343    #![allow(clippy::string_slice)] // See arti#2571
344    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
345
346    use futures::SinkExt as _;
347    use futures_await_test::async_test;
348
349    use super::*;
350    use crate::dispatch::test::{Ctx, GetKids, Swan};
351
352    #[async_test]
353    async fn invoke() {
354        let ctx = Arc::new(Ctx::from(DispatchTable::from_inventory()));
355        let discard = || Box::pin(futures::sink::drain().sink_err_into());
356        let id = ctx.register_owned(Arc::new(Swan));
357
358        let r = invoke_rpc_method(ctx.clone(), &id, Box::new(GetKids), discard())
359            .unwrap()
360            .await
361            .unwrap();
362        assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"v":"cygnets"}"#);
363
364        let r = invoke_special_method(ctx, Arc::new(Swan), Box::new(GetKids))
365            .await
366            .unwrap()
367            .unwrap();
368        assert_eq!(r.v, "cygnets");
369    }
370
371    #[test]
372    fn valid_method_names() {
373        let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
374
375        for name in [
376            "arti:clone",
377            "arti:clone7",
378            "arti:clone_now",
379            "wombat:knish",
380            "x-foo:bar",
381        ] {
382            assert!(is_valid_rpc_identifier(Some(&namespaces), name).is_ok());
383        }
384    }
385
386    #[test]
387    fn invalid_method_names() {
388        let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
389        use InvalidRpcIdentifier as E;
390
391        for (name, expect_err) in [
392            ("arti-foo:clone", E::UnrecognizedNamespace),
393            ("fred", E::NoNamespace),
394            ("arti:", E::BadIdName),
395            ("arti:7clone", E::BadIdName),
396            ("arti:CLONE", E::BadIdName),
397            ("arti:clone-now", E::BadIdName),
398        ] {
399            assert_eq!(
400                is_valid_rpc_identifier(Some(&namespaces), name),
401                Err(expect_err)
402            );
403        }
404    }
405}