1
//! Message types used in the Arti's RPC protocol.
2
//
3
// TODO: This could become a more zero-copy-friendly with some effort, but it's
4
// not really sure if it's needed.
5

            
6
mod invalid;
7
use serde::{Deserialize, Serialize};
8
use tor_rpcbase as rpc;
9

            
10
/// An identifier for a Request within the context of a Session.
11
///
12
/// Multiple inflight requests can share the same `RequestId`,
13
/// but doing so may make Arti's responses ambiguous.
14
#[derive(Debug, Eq, PartialEq, Hash, Clone, Serialize, Deserialize)]
15
#[serde(untagged)]
16
pub(crate) enum RequestId {
17
    /// A client-provided string.
18
    //
19
    // (We use Box<str> to save a word here, since these don't have to be
20
    // mutable ever.)
21
    Str(Box<str>),
22
    /// A client-provided integer.
23
    ///
24
    /// [I-JSON] says that we don't have to handle any integer that can't be
25
    /// represented as an `f64`, but we do anyway.  This won't confuse clients,
26
    /// since we won't send them any integer that they didn't send us first.
27
    ///
28
    /// [I-JSON]: https://www.rfc-editor.org/rfc/rfc7493
29
    Int(i64),
30
}
31

            
32
/// Metadata associated with a single Request.
33
//
34
// NOTE: When adding new fields to this type, make sure that `Default` gives
35
// the correct value for an absent metadata.
36
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
37
pub(crate) struct ReqMeta {
38
    /// If true, the client will accept intermediate Updates other than the
39
    /// final Request or Response.
40
    #[serde(default)]
41
    pub(crate) updates: bool,
42

            
43
    /// A list of features which must be implemented in order to understand the request.
44
    /// If any feature in this list is not available, the request must be rejected.
45
    #[serde(default)]
46
    pub(crate) require: Vec<String>,
47
}
48

            
49
/// A single Request received from an RPC client.
50
#[derive(Debug, Deserialize)]
51
pub(crate) struct Request {
52
    /// The client's identifier for this request.
53
    ///
54
    /// We'll use this to link all responses to this request.
55
    pub(crate) id: RequestId,
56
    /// The object to receive this request.
57
    pub(crate) obj: rpc::ObjectId,
58
    /// Any metadata to explain how this request is handled.
59
    #[serde(default)]
60
    pub(crate) meta: ReqMeta,
61
    /// The method to actually execute.
62
    ///
63
    /// Using "flatten" here will make it expand to "method" and "params".
64
    #[serde(flatten)]
65
    pub(crate) method: Box<dyn rpc::DeserMethod>,
66
}
67

            
68
/// A request that may or may not be valid.
69
///
70
/// If it invalid, it contains information that can be used to construct an error.
71
#[derive(Debug, serde::Deserialize)]
72
#[serde(untagged)]
73
pub(crate) enum FlexibleRequest {
74
    /// A valid request.
75
    Valid(Request),
76
    /// An invalid request.
77
    Invalid(invalid::InvalidRequest),
78
    // TODO RPC: Right now `InvalidRequest` should handle any Json Object,
79
    // but we might additionally want to parse any Json _Value_
80
    // (and reject it without killing the connection).
81
    // If we do, we ought to add a third variant here.
82
    //
83
    // Without this change, our implementation will be slightly more willing to close connections
84
    // than the spec requires:
85
    // The spec says we need to kill a connection on anything that can't be parsed as Json;
86
    // we kill a connection on anything that can't be parsed as a Json _Object_.
87
}
88

            
89
/// A Response to send to an RPC client.
90
#[derive(Debug, Serialize)]
91
pub(crate) struct BoxedResponse {
92
    /// An ID for the request that we're responding to.
93
    ///
94
    /// This is always present on a response to every valid request; it is also
95
    /// present on responses to invalid requests if we could discern what their
96
    /// `id` field was. We only omit it when the request id was indeterminate.
97
    /// If we do that, we close the connection immediately afterwards.
98
    #[serde(skip_serializing_if = "Option::is_none")]
99
    pub(crate) id: Option<RequestId>,
100
    /// The body  that we're sending.
101
    #[serde(flatten)]
102
    pub(crate) body: ResponseBody,
103
}
104

            
105
impl BoxedResponse {
106
    /// Construct a BoxedResponse from an error that can be converted into an
107
    /// RpcError.
108
    pub(crate) fn from_error<E>(id: Option<RequestId>, error: E) -> Self
109
    where
110
        E: Into<rpc::RpcError>,
111
    {
112
        let error: rpc::RpcError = error.into();
113
        let body = ResponseBody::Error(Box::new(error));
114
        Self { id, body }
115
    }
116
}
117

            
118
/// The body of a response for an RPC client.
119
#[derive(Serialize)]
120
pub(crate) enum ResponseBody {
121
    /// The request has failed; no more responses will be sent in reply to it.
122
    #[serde(rename = "error")]
123
    Error(Box<rpc::RpcError>),
124
    /// The request has succeeded; no more responses will be sent in reply to
125
    /// it.
126
    ///
127
    /// Note that in the spec, this is called a "result": we don't propagate
128
    /// that terminology into Rust, where `Result` has a different meaning.
129
    #[serde(rename = "result")]
130
    Success(Box<dyn erased_serde::Serialize + Send>),
131
    /// The request included the `updates` flag to increment that incremental
132
    /// progress information is acceptable.
133
    #[serde(rename = "update")]
134
    Update(Box<dyn erased_serde::Serialize + Send>),
135
}
136

            
137
impl ResponseBody {
138
    /// Return true if this body type indicates that no future responses will be
139
    /// sent for this request.
140
    pub(crate) fn is_final(&self) -> bool {
141
        match self {
142
            ResponseBody::Error(_) | ResponseBody::Success(_) => true,
143
            ResponseBody::Update(_) => false,
144
        }
145
    }
146
}
147

            
148
impl From<rpc::RpcError> for ResponseBody {
149
    fn from(inp: rpc::RpcError) -> ResponseBody {
150
        ResponseBody::Error(Box::new(inp))
151
    }
152
}
153

            
154
impl std::fmt::Debug for ResponseBody {
155
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156
        // We use serde_json to format the output for debugging, since that's all we care about at this point.
157
        let json = |x| match serde_json::to_string(x) {
158
            Ok(s) => s,
159
            Err(e) => format!("«could not serialize: {}»", e),
160
        };
161
        match self {
162
            Self::Error(arg0) => f.debug_tuple("Error").field(arg0).finish(),
163
            Self::Update(arg0) => f.debug_tuple("Update").field(&json(arg0)).finish(),
164
            Self::Success(arg0) => f.debug_tuple("Success").field(&json(arg0)).finish(),
165
        }
166
    }
167
}
168

            
169
#[cfg(test)]
170
mod test {
171
    // @@ begin test lint list maintained by maint/add_warning @@
172
    #![allow(clippy::bool_assert_comparison)]
173
    #![allow(clippy::clone_on_copy)]
174
    #![allow(clippy::dbg_macro)]
175
    #![allow(clippy::mixed_attributes_style)]
176
    #![allow(clippy::print_stderr)]
177
    #![allow(clippy::print_stdout)]
178
    #![allow(clippy::single_char_pattern)]
179
    #![allow(clippy::unwrap_used)]
180
    #![allow(clippy::unchecked_duration_subtraction)]
181
    #![allow(clippy::useless_vec)]
182
    #![allow(clippy::needless_pass_by_value)]
183
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
184
    use super::*;
185
    use derive_deftly::Deftly;
186
    use tor_rpcbase::templates::*;
187

            
188
    /// Assert that two arguments have the same output from `std::fmt::Debug`.
189
    ///
190
    /// This can be handy for testing for some notion of equality on objects
191
    /// that implement `Debug` but not `PartialEq`.
192
    macro_rules! assert_dbg_eq {
193
        ($a:expr, $b:expr) => {
194
            assert_eq!(format!("{:?}", $a), format!("{:?}", $b));
195
        };
196
    }
197

            
198
    // TODO RPC: note that the existence of this method type can potentially
199
    // leak into our real RPC engine when we're compiled with `test` enabled!
200
    // We should consider how bad this is, and maybe use a real method instead.
201
    #[derive(Debug, serde::Deserialize, Deftly)]
202
    #[derive_deftly(DynMethod)]
203
    #[deftly(rpc(method_name = "x-test:dummy"))]
204
    struct DummyMethod {
205
        #[serde(default)]
206
        #[allow(dead_code)]
207
        stuff: u64,
208
    }
209

            
210
    impl rpc::RpcMethod for DummyMethod {
211
        type Output = DummyResponse;
212
        type Update = rpc::NoUpdates;
213
    }
214

            
215
    #[derive(Serialize)]
216
    struct DummyResponse {
217
        hello: i64,
218
        world: String,
219
    }
220

            
221
    #[test]
222
    fn valid_requests() {
223
        let parse_request = |s| match serde_json::from_str::<FlexibleRequest>(s) {
224
            Ok(FlexibleRequest::Valid(req)) => req,
225
            other => panic!("{:?}", other),
226
        };
227

            
228
        let r =
229
            parse_request(r#"{"id": 7, "obj": "hello", "method": "x-test:dummy", "params": {} }"#);
230
        assert_dbg_eq!(
231
            r,
232
            Request {
233
                id: RequestId::Int(7),
234
                obj: rpc::ObjectId::from("hello"),
235
                meta: ReqMeta::default(),
236
                method: Box::new(DummyMethod { stuff: 0 })
237
            }
238
        );
239
    }
240

            
241
    #[test]
242
    fn invalid_requests() {
243
        use crate::err::RequestParseError as RPE;
244
        fn parsing_error(s: &str) -> RPE {
245
            match serde_json::from_str::<FlexibleRequest>(s) {
246
                Ok(FlexibleRequest::Invalid(req)) => req.error(),
247
                x => panic!("Didn't expect {:?}", x),
248
            }
249
        }
250

            
251
        macro_rules! expect_err {
252
            ($p:pat, $e:expr) => {
253
                let err = parsing_error($e);
254
                assert!(matches!(err, $p), "Unexpected error type {:?}", err);
255
            };
256
        }
257

            
258
        expect_err!(
259
            RPE::IdMissing,
260
            r#"{ "obj": "hello", "method": "x-test:dummy", "params": {} }"#
261
        );
262
        expect_err!(
263
            RPE::IdType,
264
            r#"{ "id": {}, "obj": "hello", "method": "x-test:dummy", "params": {} }"#
265
        );
266
        expect_err!(
267
            RPE::ObjMissing,
268
            r#"{ "id": 3, "method": "x-test:dummy", "params": {} }"#
269
        );
270
        expect_err!(
271
            RPE::ObjType,
272
            r#"{ "id": 3, "obj": 9, "method": "x-test:dummy", "params": {} }"#
273
        );
274
        expect_err!(
275
            RPE::MethodMissing,
276
            r#"{ "id": 3, "obj": "hello",  "params": {} }"#
277
        );
278
        expect_err!(
279
            RPE::MethodType,
280
            r#"{ "id": 3, "obj": "hello", "method": [], "params": {} }"#
281
        );
282
        expect_err!(
283
            RPE::MetaType,
284
            r#"{ "id": 3, "obj": "hello", "meta": 7, "method": "x-test:dummy", "params": {} }"#
285
        );
286
        expect_err!(
287
            RPE::MetaType,
288
            r#"{ "id": 3, "obj": "hello", "meta": { "updates": 3}, "method": "x-test:dummy", "params": {} }"#
289
        );
290
        expect_err!(
291
            RPE::NoSuchMethod,
292
            r#"{ "id": 3, "obj": "hello", "method": "arti:this-is-not-a-method", "params": {} }"#
293
        );
294
        expect_err!(
295
            RPE::MissingParams,
296
            r#"{ "id": 3, "obj": "hello", "method": "x-test:dummy" }"#
297
        );
298
        expect_err!(
299
            RPE::ParamType,
300
            r#"{ "id": 3, "obj": "hello", "method": "x-test:dummy", "params": 7 }"#
301
        );
302
    }
303

            
304
    #[test]
305
    fn fmt_replies() {
306
        let resp = BoxedResponse {
307
            id: Some(RequestId::Int(7)),
308
            body: ResponseBody::Success(Box::new(DummyResponse {
309
                hello: 99,
310
                world: "foo".into(),
311
            })),
312
        };
313
        let s = serde_json::to_string(&resp).unwrap();
314
        // NOTE: This is a bit fragile for a test, since nothing in serde or
315
        // serde_json guarantees that the fields will be serialized in this
316
        // exact order.
317
        assert_eq!(s, r#"{"id":7,"result":{"hello":99,"world":"foo"}}"#);
318

            
319
        let resp = BoxedResponse {
320
            id: None,
321
            body: ResponseBody::Error(Box::new(rpc::RpcError::from(
322
                crate::err::RequestParseError::IdMissing,
323
            ))),
324
        };
325
        let s = serde_json::to_string(&resp).unwrap();
326
        // NOTE: as above.
327
        assert_eq!(
328
            s,
329
            r#"{"error":{"message":"Request did not have any `id` field.","code":-32600,"kinds":["rpc:InvalidRequest"]}}"#
330
        );
331
    }
332
}