aboutsummaryrefslogtreecommitdiff
path: root/crates/arti-rpcserver/src/session.rs
blob: dde88232290331100ab2e6937d8d9c6122db119f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//! High-level APIs for an RPC session
//!
//! A "session" is created when a user authenticates on an RPC connection.  It
//! is the root for all other RPC capabilities.

use arti_client::{
    TorClient,
    rpc::{ClientConnectionResult, ConnectWithPrefs, ResolvePtrWithPrefs, ResolveWithPrefs},
};
use derive_deftly::Deftly;
use std::{
    net::IpAddr,
    sync::{Arc, Mutex},
};
use tor_error::into_internal;
use tor_rtcompat::Runtime;

use tor_rpcbase::{self as rpc, static_rpc_invoke_fn, templates::*};

/// An authenticated RPC session: a capability through which most other RPC functionality is available
///
/// This relates to [`Connection`](crate::Connection) as follows:
///
///  * A `Connection` exists prior to authentication;
///    whereas an `RpcSession` comes into being as a result of authentication.
///
///  * The `RpcSession` is principally owned by the `Connection`'s object table.
///
///  * Typically, after authentication, there is one `RpcSession` for the `Connection`.
///    But a client may authenticate more than once; each time produces a new `RpcSession`.
///
/// ## In the arti rpc system
///
/// Base type for an authenticated RPC session.
///
/// Upon successful authentication via `auth:authenticate`,
/// a connection will return either a Session object of this type,
/// or a Session object that wraps this type.
/// All other useful objects are available via an RPC session.
///
/// This ObjectID for this object can be used as the target of a SOCKS stream.
#[derive(Deftly)]
#[derive_deftly(Object)]
#[deftly(rpc(expose_outside_of_session))]
pub struct RpcSession {
    /// An inner TorClient object that we use to implement remaining
    /// functionality.
    #[allow(unused)]
    client: Arc<dyn Client>,

    /// A superuser object representing administrative capability.
    ///
    /// If this object is absent, this session never had this capability,
    /// or dropped it.
    superuser: Mutex<Option<Arc<dyn rpc::Object>>>,
}

/// Type-erased `TorClient`, as used within an RpcSession.
trait Client: rpc::Object {
    /// Return a new isolated TorClient.
    fn isolated_client(&self) -> Arc<dyn rpc::Object>;

    /// Upcast `self` to an rpc::Object.
    fn upcast_arc(self: Arc<Self>) -> Arc<dyn rpc::Object>;
}

impl<R: Runtime> Client for TorClient<R> {
    fn isolated_client(&self) -> Arc<dyn rpc::Object> {
        TorClient::isolated_client(self)
    }

    fn upcast_arc(self: Arc<Self>) -> Arc<dyn rpc::Object> {
        self
    }
}

impl RpcSession {
    /// Create a new session object containing a single client object.
    pub fn new_with_client<R: Runtime>(client: Arc<arti_client::TorClient<R>>) -> Arc<Self> {
        Arc::new(Self {
            client,
            superuser: Mutex::new(None),
        })
    }

    /// Set the superuser object for this session to `superuser`.
    ///
    /// Calling this function indicates that this session has administrative privilege.
    pub fn provide_superuser_permission(&self, superuser: Arc<dyn rpc::Object>) {
        let mut su = self.superuser.lock().expect("Poisoned lock");
        *su = Some(superuser);
    }

    /// Return a view of the client associated with this session, as an `Arc<dyn
    /// rpc::Object>.`
    fn client_as_object(&self) -> Arc<dyn rpc::Object> {
        self.client.clone().upcast_arc()
    }
}

/// Return the default client for a session.
///
/// Allocates a new ObjectID,
/// but does not create a new underlying client object.
///
/// The returned ObjectID is a handle to a `TorClient`.
#[derive(Debug, serde::Deserialize, serde::Serialize, Deftly)]
#[derive_deftly(DynMethod)]
#[deftly(rpc(method_name = "arti:get_client"))]
struct GetClient {}

impl rpc::RpcMethod for GetClient {
    type Output = rpc::SingleIdResponse;
    type Update = rpc::NoUpdates;
}

/// Implement GetClient on an RpcSession.
async fn get_client_on_session(
    session: Arc<RpcSession>,
    _method: Box<GetClient>,
    ctx: Arc<dyn rpc::Context>,
) -> Result<rpc::SingleIdResponse, rpc::RpcError> {
    Ok(rpc::SingleIdResponse::from(
        ctx.register_owned(session.client.clone().upcast_arc()),
    ))
}

/// Implement IsolatedClient on an RpcSession.
async fn isolated_client_on_session(
    session: Arc<RpcSession>,
    _method: Box<arti_client::rpc::IsolatedClient>,
    ctx: Arc<dyn rpc::Context>,
) -> Result<rpc::SingleIdResponse, rpc::RpcError> {
    let new_client = session.client.isolated_client();
    Ok(rpc::SingleIdResponse::from(ctx.register_owned(new_client)))
}

/// Implement ConnectWithPrefs on an RpcSession
///
/// (Delegates to TorClient.)
async fn session_connect_with_prefs(
    session: Arc<RpcSession>,
    method: Box<ConnectWithPrefs>,
    ctx: Arc<dyn rpc::Context>,
) -> ClientConnectionResult<arti_client::DataStream> {
    *rpc::invoke_special_method(ctx, session.client_as_object(), method)
        .await
        .map_err(|e| Box::new(into_internal!("unable to delegate to TorClient")(e)) as _)?
}

/// Implement ResolveWithPrefs on an RpcSession
///
/// (Delegates to TorClient.)
async fn session_resolve_with_prefs(
    session: Arc<RpcSession>,
    method: Box<ResolveWithPrefs>,
    ctx: Arc<dyn rpc::Context>,
) -> ClientConnectionResult<Vec<IpAddr>> {
    *rpc::invoke_special_method(ctx, session.client_as_object(), method)
        .await
        .map_err(|e| Box::new(into_internal!("unable to delegate to TorClient")(e)) as _)?
}

/// Implement ResolvePtrWithPrefs on an RpcSession
///
/// (Delegates to TorClient.)
async fn session_resolve_ptr_with_prefs(
    session: Arc<RpcSession>,
    method: Box<ResolvePtrWithPrefs>,
    ctx: Arc<dyn rpc::Context>,
) -> ClientConnectionResult<Vec<String>> {
    *rpc::invoke_special_method(ctx, session.client_as_object(), method)
        .await
        .map_err(|e| Box::new(into_internal!("unable to delegate to TorClient")(e)) as _)?
}

/// Return the superuser capability for a session.
///
/// Just as a session is the root object proving that
/// your program has authenticated
///
/// Returns an error if this session is not authorized for superuser access,
/// or if you have dropped superuser access via `arti:remove_superuser_permission`.
#[derive(Debug, serde::Deserialize, serde::Serialize, Deftly)]
#[derive_deftly(DynMethod)]
#[deftly(rpc(method_name = "arti:get_superuser_capability"))]
struct GetSuperuserCapability {}

impl rpc::RpcMethod for GetSuperuserCapability {
    type Output = rpc::SingleIdResponse;
    type Update = rpc::NoUpdates;
}

/// Implement `arti::get_superuser_capability` on RpcSession.
async fn get_superuser_capability_on_session(
    session: Arc<RpcSession>,
    _method: Box<GetSuperuserCapability>,
    ctx: Arc<dyn rpc::Context>,
) -> Result<rpc::SingleIdResponse, rpc::RpcError> {
    let opt_su = session.superuser.lock().expect("Lock poisoned");
    match opt_su.as_ref() {
        Some(su) => {
            let su = Arc::clone(su);
            drop(opt_su);
            let id = ctx.register_owned(su);
            Ok(id.into())
        }
        None => Err(rpc::RpcError::new(
            "Superuser access not permitted on this session".into(),
            rpc::RpcErrorKind::RequestError,
        )),
    }
}

/// Remove the superuser permission from a session.
///
/// Calling this method on a session ensures that future calls to
/// `arti:get_superuser_capability` will return an error.`
///
/// This method does nothing if the session did not have superuser access.
///
/// This method does not drop existing superuser capability objects
/// previously returned from `arti:get_superuser_capability`,
/// or other privileged objects derived from them.
///
/// Additionally, it does not prevent you from from using `auth`
/// methods to create a new session from the same connection object.
///
/// Therefore, to ensure that you cannot acquire new superuser functionality
/// on a given connection, you must:
/// - Drop any existing superuser capabilities.
/// - Invoke this method on the session.
///
/// To ensure that an _application_ cannot reacquire superuser permission,
/// you also must prevent it from opening a new RPC connection to any
/// Arti RPC connect point that allows superuser access.
#[derive(Debug, serde::Deserialize, serde::Serialize, Deftly)]
#[derive_deftly(DynMethod)]
#[deftly(rpc(method_name = "arti:remove_superuser_permission"))]
struct RemoveSuperuserPermission {}

impl rpc::RpcMethod for RemoveSuperuserPermission {
    type Output = rpc::Nil;
    type Update = rpc::NoUpdates;
}

/// Implement `arti::remove_superuser_permission` on RpcSession.
async fn remove_superuser_permission_on_session(
    session: Arc<RpcSession>,
    _method: Box<RemoveSuperuserPermission>,
    _ctx: Arc<dyn rpc::Context>,
) -> Result<rpc::Nil, rpc::RpcError> {
    let mut opt_su = session.superuser.lock().expect("Lock poisoned");
    *opt_su = None;
    Ok(rpc::Nil::default())
}

static_rpc_invoke_fn! {
    get_client_on_session;
    isolated_client_on_session;
    get_superuser_capability_on_session;
    remove_superuser_permission_on_session;
    @special session_connect_with_prefs;
    @special session_resolve_with_prefs;
    @special session_resolve_ptr_with_prefs;
}

#[cfg(feature = "describe-methods")]
#[allow(clippy::missing_docs_in_private_items)] // TODO
mod list_all_methods {
    use std::{convert::Infallible, sync::Arc};

    use derive_deftly::Deftly;
    use tor_rpcbase::{self as rpc, RpcDispatchInformation, static_rpc_invoke_fn, templates::*};

    /// Return a description of all recognized RPC methods.
    ///
    /// Note that not every recognized method is necessarily invocable in practice.
    /// Depending on the session's access level, you might not be able to
    /// access any objects that the method might be invocable upon.
    ///
    /// **This is an experimental method.**
    /// Methods starting with "x_" are extra-unstable.
    /// See [`RpcDispatchInformation`] for caveats about type names.
    #[derive(Debug, serde::Deserialize, Deftly)]
    #[derive_deftly(DynMethod)]
    #[deftly(rpc(method_name = "arti:x_list_all_rpc_methods"))]
    struct ListAllRpcMethods {}

    impl rpc::RpcMethod for ListAllRpcMethods {
        type Output = RpcDispatchInformation;
        type Update = rpc::NoUpdates;
    }

    /// Implement ListAllRpcMethods on an RpcSession.
    async fn session_list_all_rpc_methods(
        _session: Arc<super::RpcSession>,
        _method: Box<ListAllRpcMethods>,
        ctx: Arc<dyn rpc::Context>,
    ) -> Result<RpcDispatchInformation, Infallible> {
        Ok(ctx
            .dispatch_table()
            .read()
            .expect("poisoned lock")
            .dispatch_information())
    }

    static_rpc_invoke_fn! { session_list_all_rpc_methods; }
}