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