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