tor_rpcbase/
lib.rs

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