1
//! Module exposing the relay circuit reactor subsystem.
2
//!
3
//! See [`reactor`](crate::circuit::reactor) for a description of the overall architecture.
4
//!
5
//! All cells moving in the forward direction (i.e. away from the client)
6
//! are handled by the decrypting reactor, which deals with
7
//!
8
//!  * unrecognized RELAY* cells, by moving them in the forward direction (towards the exit)
9
//!  * recognized RELAY* cells, by splitting each cell into messages, and handling
10
//!    each message individually as described in the table below
11
//!    (Note: since prop340 is not yet implemented, in practice there is only 1 message per cell).
12
//!  * DESTROY cells, by tearing down the circuit, and causing a DESTROY to be sent forward,
13
//!    to the next hop, if there is one
14
//!  * PADDING_NEGOTIATE cells (**not yet implemented**)
15
//!
16
//! ```text
17
//!
18
//! Legend: `D` = "decrypting reactor", `E` = "encrypting reactor", `S` = "stream reactor"
19
//! `DI` = `DecryptingReactorInner`
20
//!
21
//! | RELAY cmd  | Received in | Handled in            | Description                            |
22
//! |------------|-------------|-----------------------|----------------------------------------|
23
//! | DROP       | D           | DI::handle_meta_msg() | Passed to PaddingController for        |
24
//! |            |             |                       | validation                             |
25
//! |------------|-------------|-----------------------|----------------------------------------|
26
//! | EXTEND2    | D           | DI::handle_meta_msg() | Handled by the ExtendRequestHandler    |
27
//! |            |             |                       | See [forward::extend_handler].         |
28
//! |------------|-------------|-----------------------|----------------------------------------|
29
//! | TRUNCATE   | D           | DI::handle_meta_msg() | Not supported: TRUNCATE is considered  |
30
//! |            |             |                       | a protocol violation, because none of  |
31
//! |            |             |                       | of our implementations send it.        |
32
//! |------------|-------------|-----------------------|----------------------------------------|
33
//! | SENDME     | D           | E                     | Sent to EncryptingReactor for handling.|
34
//! | (sid = 0)  |             |                       | See the [crate::circuit::reactor] docs |
35
//! |------------|-------------|-----------------------|----------------------------------------|
36
//! | Other      | D           | DI::handle_meta_msg() | Rejected as unrecognized               |
37
//! | (sid = 0)  |             |                       |                                        |
38
//! |------------|-------------|-----------------------|----------------------------------------|
39
//! | Other      | D           | E                     | Handled in the `StreamReactor`         |
40
//! | (sid != 0) |             |                       |                                        |
41
//! ```
42

            
43
pub(crate) mod backward;
44
pub(crate) mod forward;
45

            
46
use std::sync::Arc;
47
use std::time::Duration;
48

            
49
use futures::StreamExt as _;
50
use futures::channel::mpsc;
51

            
52
use tor_cell::chancell::CircId;
53
use tor_cell::relaycell::RelayCmd;
54
use tor_linkspec::OwnedChanTarget;
55
use tor_memquota::mq_queue::{ChannelSpec, MpscSpec};
56
use tor_rtcompat::{DynTimeProvider, Runtime};
57

            
58
use crate::channel::Channel;
59
use crate::circuit::circhop::ReactorStreamComponents;
60
use crate::circuit::circhop::{CircHopOutbound, HopSettings};
61
use crate::circuit::metrics::CircuitMetrics;
62
use crate::circuit::reactor::Reactor as BaseReactor;
63
use crate::circuit::reactor::circ_state::CircuitState;
64
use crate::circuit::reactor::stream;
65
use crate::circuit::{CircuitRxReceiver, UniqId};
66
use crate::congestion::sendme::StreamRecvWindow;
67
use crate::crypto::cell::{InboundRelayLayer, OutboundRelayLayer};
68
use crate::memquota::{CircuitAccount, SpecificAccount};
69
use crate::relay::RelayCirc;
70
use crate::relay::channel_provider::ChannelProvider;
71
use crate::relay::reactor::backward::Backward;
72
use crate::relay::reactor::forward::Forward;
73
use crate::stream::flow_ctrl::state::WithSidechannelMitigations;
74
use crate::stream::flow_ctrl::xon_xoff::reader::XonXoffReaderCtrl;
75
use crate::stream::incoming::{
76
    IncomingCmdChecker, IncomingStream, IncomingStreamRequestFilter, IncomingStreamRequestHandler,
77
    StreamReqInfo,
78
};
79
use crate::stream::raw::StreamReceiver;
80
use crate::stream::{RECV_WINDOW_INIT, StreamComponents, StreamTarget, Tunnel};
81

            
82
// TODO(circpad): once padding is stabilized, the padding module will be moved out of client.
83
use crate::client::circuit::padding::{PaddingController, PaddingEventStream};
84

            
85
/// Type-alias for the relay base reactor type.
86
type RelayBaseReactor<R> = BaseReactor<R, Forward, Backward>;
87

            
88
/// The entry point of the circuit reactor subsystem.
89
#[must_use = "If you don't call run() on a reactor, the circuit won't work."]
90
pub(crate) struct Reactor<R: Runtime>(RelayBaseReactor<R>);
91

            
92
/// A handler customizing the relay stream reactor.
93
struct StreamHandler;
94

            
95
impl stream::StreamHandler for StreamHandler {
96
6
    fn halfstream_expiry(&self, hop: &CircHopOutbound) -> Duration {
97
6
        let ccontrol = hop.ccontrol();
98

            
99
        // Note: if we have no measurements for the RTT, this will be set to 0,
100
        // so the stream will be removed from the stream map immediately,
101
        // and any subsequent messages arriving on it will trigger
102
        // a proto violation causing the circuit to close.
103
        //
104
        // TODO(relay-tuning): we should make sure that this doesn't cause us to
105
        // wrongly close legitimate circuits that still have in-flight stream data
106
6
        ccontrol
107
6
            .lock()
108
6
            .expect("poisoned lock")
109
6
            .rtt()
110
6
            .max_rtt()
111
6
            // TODO(relay): we should fallback to a non-zero default here
112
6
            // if we don't have any RTT measurements yet
113
6
            .unwrap_or_default()
114
6
    }
115

            
116
8
    fn flowctrl_sidechannel_mitigations(&self) -> WithSidechannelMitigations {
117
        // We're a relay, so we don't want sidechannel mitigations for flow control.
118
8
        WithSidechannelMitigations::Disabled
119
8
    }
120
}
121

            
122
impl<R: Runtime> Reactor<R> {
123
    /// Create a new circuit reactor.
124
    ///
125
    /// Returns the [`Reactor`], a [`RelayCirc`] handle to it,
126
    /// and a [`Stream`](futures::Stream) of `IncomingStream`s.
127
    ///
128
    /// The reactor will send outbound messages on `channel`, receive incoming
129
    /// messages on `input`, and identify this circuit by the channel-local
130
    /// [`CircId`] provided.
131
    ///
132
    /// The internal unique identifier for this circuit will be `unique_id`.
133
    ///
134
    /// The returned `IncomingStream`s are exit, dns, or directory streams.
135
    /// An incoming stream is automatically rejected by the reactor
136
    /// if the provided `IncomingStreamRequestFilter` rejects it.
137
    /// You can also explicitly reject a stream by calling [`IncomingStream::reject`].
138
    /// If the `Stream` is dropped, the next incoming stream request
139
    /// (`BEGIN`, `BEGIN_DIR`, or RESOLVE`)
140
    /// on this circuit will cause the stream reactor to shut down,
141
    /// which will trigger a shutdown of all the circuit reactors (DEC, ENC),
142
    /// which causing the circuit to close.
143
    ///
144
    /// The streams not rejected by the `IncomingStreamRequestFilter` will
145
    /// get an entry in the circuit's stream map.
146
    /// Rejecting such a stream using [`IncomingStream::reject`] will remove the entry.
147
    ///
148
    /// The `IncomingStreamRequestFilter` should only perform inexpensive checks
149
    /// that won't block the reactor.
150
    /// More expensive, or blocking checks, should be handled outside of the circuit reactor,
151
    /// when processing new `IncomingStream`s from the returned Rust stream.
152
    ///
153
    /// Data and directory streams can be accepted by calling [`IncomingStream::accept_data`].
154
    /// The caller is responsible for proxying data between the resulting `DataStream`
155
    /// and the local application stream.
156
    ///
157
    // TODO(relay): say how RESOLVE streams should be handled
158
    //
159
    // TODO: declare a type-alias for the impl futures::Stream return type
160
    // when support for impl in type aliases gets stabilized.
161
    //
162
    // See issue #63063 <https://github.com/rust-lang/rust/issues/63063>
163
    //
164
    // TODO(DEDUP): the incoming stream handling is *very* similar
165
    // to the impll from ServiceOnionServiceDataTunnel::allow_stream_requests.
166
    // We should dedupe these someday, when we rewrite the client reactor
167
    // to use the new multi-reactor architecture
168
    #[allow(clippy::too_many_arguments)] // TODO
169
32
    pub(crate) fn new(
170
32
        runtime: R,
171
32
        channel: &Arc<Channel>,
172
32
        circ_id: CircId,
173
32
        unique_id: UniqId,
174
32
        input: CircuitRxReceiver,
175
32
        crypto_in: Box<dyn InboundRelayLayer + Send>,
176
32
        crypto_out: Box<dyn OutboundRelayLayer + Send>,
177
32
        settings: &HopSettings,
178
32
        chan_provider: Arc<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
179
32
        padding_ctrl: PaddingController,
180
32
        padding_event_stream: PaddingEventStream,
181
32
        incoming_filter: Box<dyn IncomingStreamRequestFilter>,
182
32
        allowed_stream_cmds: &[RelayCmd],
183
32
        memquota: &CircuitAccount,
184
32
        metrics: Arc<CircuitMetrics>,
185
32
    ) -> crate::Result<(
186
32
        Self,
187
32
        Arc<RelayCirc>,
188
32
        impl futures::Stream<Item = IncomingStream> + use<R>,
189
32
    )> {
190
        // NOTE: not registering this channel with the memquota subsystem is okay,
191
        // because it has no buffering (if ever decide to make the size of this buffer
192
        // non-zero for whatever reason, we must remember to register it with memquota
193
        // so that it counts towards the total memory usage for the circuit.
194
        #[allow(clippy::disallowed_methods)]
195
32
        let (stream_tx, stream_rx) = mpsc::channel(0);
196

            
197
        /// The size of the channel receiving IncomingStreamRequestContexts.
198
        ///
199
        // TODO(relay-tuning): buffer size
200
        //
201
        // This is currently set to 2x the initial receive window,
202
        // the same as the buffer size we use for onion services.
203
        // This value was picked arbitrarily,
204
        // and is not necessarily tuned for relay needs.
205
        const INCOMING_BUFFER: usize = crate::stream::STREAM_READER_BUFFER;
206

            
207
32
        let time_provider = DynTimeProvider::new(runtime.clone());
208
32
        let (incoming_sender, incoming_receiver) = MpscSpec::new(INCOMING_BUFFER)
209
32
            .new_mq(time_provider.clone(), memquota.as_raw_account())?;
210

            
211
        // Our IncomingCmdChecker does not reject BEGIN, BEGIN_DIR, RESOLVE cells,
212
        // but that doesn't necessarily mean the stream will be accepted.
213
        // An incoming stream can still be rejected at a later stage,
214
        // by the IncomingStreamRequestFilter, or directly by the consumer of the
215
        // futures::Stream<Item = IncomingStream> (by calling IncomingStream::reject()).
216
32
        let cmd_checker = IncomingCmdChecker::new_any(allowed_stream_cmds);
217
32
        let incoming_handler = IncomingStreamRequestHandler {
218
32
            incoming_sender,
219
32
            hop_num: None,
220
32
            cmd_checker,
221
32
            filter: incoming_filter,
222
32
        };
223
32
        let circ_state = CircuitState::new_relay(
224
32
            runtime.clone(),
225
32
            settings.clone(),
226
32
            unique_id,
227
32
            circ_id,
228
32
            StreamHandler,
229
32
            stream_tx,
230
32
            incoming_handler,
231
32
            memquota.clone(),
232
32
            Arc::clone(&metrics),
233
32
        );
234

            
235
        // TODO(relay): currently we don't need buffering on this channel,
236
        // but we might need it if we start using it for more than just EXTENDED2 events
237
        #[allow(clippy::disallowed_methods)]
238
32
        let (dec_ev_tx, dec_ev_rx) = mpsc::channel(0);
239
32
        let forward = Forward::new(
240
32
            channel,
241
32
            circ_id,
242
32
            unique_id,
243
32
            crypto_out,
244
32
            chan_provider,
245
32
            dec_ev_tx.clone(),
246
32
            memquota.clone(),
247
32
            Arc::clone(&metrics),
248
32
        );
249
32
        let backward = Backward::new(crypto_in);
250

            
251
32
        let (inner, handle) = BaseReactor::new(
252
32
            runtime,
253
32
            channel,
254
32
            circ_id,
255
32
            unique_id,
256
32
            input,
257
32
            forward,
258
32
            backward,
259
32
            circ_state,
260
32
            padding_ctrl,
261
32
            padding_event_stream,
262
32
            stream_rx,
263
32
            dec_ev_rx,
264
32
            dec_ev_tx,
265
32
            memquota,
266
32
            metrics,
267
32
        );
268

            
269
32
        let reactor = Self(inner);
270
32
        let handle = Arc::new(RelayCirc(handle));
271

            
272
        // Note: tunnel is a bit of a misnomer for relays
273
32
        let tunnel = Arc::clone(&handle);
274
        // TODO(relay): this is more or less copy-pasta from client code
275
32
        let stream = incoming_receiver.map(move |req_ctx| {
276
            let StreamReqInfo {
277
                req,
278
                stream_id,
279
                hop,
280
                stream_components:
281
                    ReactorStreamComponents {
282
                        stream_inbound_rx,
283
                        stream_outbound_tx,
284
                        rate_limit_rx,
285
                        drain_rate_request_rx,
286
                    },
287
                memquota,
288
                relay_cell_format,
289
8
            } = req_ctx;
290

            
291
            // There is no originating hop if we're a relay
292
8
            debug_assert!(hop.is_none());
293

            
294
8
            let target = StreamTarget {
295
8
                tunnel: Tunnel::Relay(Arc::clone(&tunnel)),
296
8
                tx: stream_outbound_tx,
297
8
                hop: None,
298
8
                stream_id,
299
8
                relay_cell_format,
300
8
                rate_limit_stream: rate_limit_rx,
301
8
            };
302

            
303
            // can be used to build a reader that supports XON/XOFF flow control
304
            let xon_xoff_reader_ctrl =
305
8
                XonXoffReaderCtrl::new(drain_rate_request_rx, target.clone());
306

            
307
8
            let reader = StreamReceiver {
308
8
                target: target.clone(),
309
8
                receiver: stream_inbound_rx,
310
8
                recv_window: StreamRecvWindow::new(RECV_WINDOW_INIT),
311
8
                ended: false,
312
8
            };
313

            
314
8
            let components = StreamComponents {
315
8
                stream_receiver: reader,
316
8
                target,
317
8
                memquota,
318
8
                xon_xoff_reader_ctrl,
319
8
            };
320

            
321
8
            IncomingStream::new(time_provider.clone(), req, components)
322
8
        });
323

            
324
32
        Ok((reactor, handle, stream))
325
32
    }
326

            
327
    /// Launch the reactor, and run until the circuit closes or we
328
    /// encounter an error.
329
    ///
330
    /// Once this method returns, the circuit is dead and cannot be
331
    /// used again.
332
32
    pub(crate) async fn run(self) -> crate::Result<()> {
333
32
        self.0.run().await
334
32
    }
335
}
336

            
337
#[cfg(test)]
338
pub(crate) mod test {
339
    // @@ begin test lint list maintained by maint/add_warning @@
340
    #![allow(clippy::bool_assert_comparison)]
341
    #![allow(clippy::clone_on_copy)]
342
    #![allow(clippy::dbg_macro)]
343
    #![allow(clippy::mixed_attributes_style)]
344
    #![allow(clippy::print_stderr)]
345
    #![allow(clippy::print_stdout)]
346
    #![allow(clippy::single_char_pattern)]
347
    #![allow(clippy::unwrap_used)]
348
    #![allow(clippy::unchecked_time_subtraction)]
349
    #![allow(clippy::useless_vec)]
350
    #![allow(clippy::needless_pass_by_value)]
351
    #![allow(clippy::string_slice)] // See arti#2571
352
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
353

            
354
    use super::*;
355
    use crate::channel::ChannelMode;
356
    use crate::channel::CtrlMsg;
357
    use crate::channel::circmap::CircIdRange;
358
    use crate::channel::test_utils::DummyChan;
359
    use crate::circuit::CircParameters;
360
    use crate::circuit::circ_sender;
361
    use crate::circuit::reactor::test::{AllowAllStreamsFilter, rmsg_to_ccmsg};
362
    use crate::circuit::test::new_circ_net_params;
363
    use crate::client::circuit::padding::new_padding;
364
    use crate::congestion::test_utils::params::build_cc_vegas_params;
365
    use crate::crypto::cell::RelayCellBody;
366
    use crate::crypto::cell::{InboundRelayLayer, OutboundRelayLayer};
367
    use crate::relay::CreateRequestHandler;
368
    use crate::relay::channel::test::DummyChanProvider;
369
    use crate::stream::flow_ctrl::params::FlowCtrlParameters;
370
    use crate::stream::incoming::{IncomingStream, IncomingStreamRequest, NoOpRequestFilter};
371

            
372
    use futures::AsyncReadExt as _;
373
    use futures::SinkExt as _;
374
    use oneshot_fused_workaround as oneshot;
375
    use tracing_test::traced_test;
376

            
377
    use tor_basic_utils::test_rng::{TestingRng, testing_rng};
378
    use tor_cell::chancell::{ChanCell, ChanCmd, msg as chanmsg};
379
    use tor_cell::relaycell::{AnyRelayMsgOuter, RelayCellFormat, StreamId, msg as relaymsg};
380
    use tor_key_forge::Keygen;
381
    use tor_linkspec::{EncodedLinkSpec, HasRelayIds, LinkSpec};
382
    use tor_llcrypto::pk::curve25519::StaticKeypair;
383
    use tor_llcrypto::pk::ed25519::Ed25519Identity;
384
    use tor_llcrypto::pk::rsa::RsaIdentity;
385
    use tor_llcrypto::rng::FakeEntropicRng;
386
    use tor_protover::{Protocols, named};
387
    use tor_relay_crypto::pk::RelayNtorKeys;
388
    use tor_rtcompat::SpawnExt;
389
    use tor_rtcompat::{DynTimeProvider, Runtime};
390
    use tor_rtmock::MockRuntime;
391

            
392
    use chanmsg::{AnyChanMsg, Destroy, DestroyReason, HandshakeType};
393
    use relaymsg::SendmeTag;
394

            
395
    use std::net::{IpAddr, Ipv4Addr};
396
    use std::num::NonZero;
397
    use std::sync::{Arc, Mutex, Weak, mpsc};
398
    use std::task::{Context, Poll, Waker};
399

            
400
    // An inbound encryption layer that doesn't do any crypto.
401
    struct DummyInboundCrypto {}
402

            
403
    // An outbound encryption layer that doesn't do any crypto.
404
    struct DummyOutboundCrypto {
405
        /// Channel for controlling whether the current cell is meant for us or not.
406
        ///
407
        /// Useful for tests that check if recognized/unrecognized
408
        /// cells are handled/forwarded correctly.
409
        recognized_rx: mpsc::Receiver<Recognized>,
410
    }
411

            
412
    const DUMMY_TAG: [u8; 20] = [1; 20];
413

            
414
    impl InboundRelayLayer for DummyInboundCrypto {
415
        fn originate(&mut self, _cmd: ChanCmd, _cell: &mut RelayCellBody) -> SendmeTag {
416
            DUMMY_TAG.into()
417
        }
418

            
419
        fn encrypt_inbound(&mut self, _cmd: ChanCmd, _cell: &mut RelayCellBody) {}
420
    }
421

            
422
    impl OutboundRelayLayer for DummyOutboundCrypto {
423
        fn decrypt_outbound(
424
            &mut self,
425
            _cmd: ChanCmd,
426
            _cell: &mut RelayCellBody,
427
        ) -> Option<SendmeTag> {
428
            // Note: this should never block.
429
            let recognized = self.recognized_rx.recv().unwrap();
430

            
431
            match recognized {
432
                Recognized::Yes => Some(DUMMY_TAG.into()),
433
                Recognized::No => None,
434
            }
435
        }
436
    }
437

            
438
    /// A circuit reactor handle, for building circuits of the form
439
    /// A -> B, and A -> B -> C, where the circuit reactor under test
440
    /// "thinks" it is B.
441
    ///
442
    /// [`ReactorTestCtrl::new`] builds and spawns:
443
    ///
444
    ///   * a channel reactor for the A - B "Tor Channel"
445
    ///   * a circuit reactor for B's view of the circuit
446
    ///
447
    /// Some of the tests in this module extend the circuit by another dummy hop,
448
    /// to obtain an A -> B -> C circuit. This involves sending an EXTEND2
449
    /// cell over the A -> B channel, and calling [`ReactorTestCtrl::do_create2_handshake`]
450
    /// to finalize the handshake.
451
    struct ReactorTestCtrl {
452
        /// The relay circuit handle.
453
        relay_circ: Arc<RelayCirc>,
454
        /// The circuit id on our `inbound_chan`.
455
        circid: CircId,
456
        /// The inbound channel ("towards the client").
457
        ///
458
        /// This is the "Tor channel" between A and B in
459
        /// a circuit of the form A -> B or A -> B -> C.
460
        inbound_chan: DummyChan,
461
        /// The outbound channel ("away from the client"), if any.
462
        ///
463
        /// Shared with the DummyChanProvider, which initializes this
464
        /// when the relay reactor launches a channel to the next hop
465
        /// via `get_or_launch()`.
466
        ///
467
        /// This is the "Tor channel" between B and C,
468
        /// if our test circuit is of the form A -> B -> C
469
        /// (i.e. if we have extended the "base" circuit by another mock hop, to C).
470
        outbound_chan: Arc<Mutex<Option<DummyChan>>>,
471
        /// MPSC channel for telling the DummyOutboundCrypto that the next
472
        /// cell we're about to send to the reactor should be "recognized".
473
        recognized_tx: mpsc::Sender<Recognized>,
474
    }
475

            
476
    /// Whether a forward cell to send should be "recognized"
477
    /// or "unrecognized" by the relay under test.
478
    enum Recognized {
479
        /// Recognized
480
        Yes,
481
        /// Unrecognized
482
        No,
483
    }
484

            
485
    /// The direction we expect the reactor to have sent a DESTROY in
486
    #[allow(dead_code)] // we don't use all of these yet
487
    enum DestroyDirection {
488
        /// Forward ("towards the exit")
489
        Forward,
490
        /// Backward ("towards the client")
491
        Backward,
492
        /// Both forward and backward
493
        Both,
494
    }
495

            
496
    /// Decode a cell, extracting the underlying message of type `expect_msg`
497
    macro_rules! decode_relay_cell {
498
        ($cell:expr, $expect_msg:tt) => {{
499
            let rmsg = match $cell.msg() {
500
                chanmsg::AnyChanMsg::Relay(r) => AnyRelayMsgOuter::decode_singleton(
501
                    RelayCellFormat::V0,
502
                    r.clone().into_relay_body(),
503
                )
504
                .unwrap(),
505
                msg => panic!("unexpected forwarded {msg:?}"),
506
            };
507

            
508
            let msg = match rmsg.msg() {
509
                relaymsg::AnyRelayMsg::$expect_msg(inner) => inner.clone(),
510
                _ => panic!("unexpected relay message {rmsg:?}"),
511
            };
512

            
513
            (rmsg.stream_id(), msg)
514
        }};
515
    }
516

            
517
    const DUMMY_ED25519_KEY: [u8; 32] = *b"32 bytes pretending to be a key!";
518
    const DUMMY_RSA_KEY: [u8; 20] = *b"not really an RSA ky";
519

            
520
    /// Helper for building a [`ChannelMode::Relay`] for our test reactor
521
    fn build_channel_mode<R: Runtime>(
522
        chan_provider: Arc<DummyChanProvider<R>>,
523
        allowed_stream_cmds: &[RelayCmd],
524
    ) -> ChannelMode {
525
        let our_ed25519_id = Ed25519Identity::from_bytes(&DUMMY_ED25519_KEY).unwrap();
526
        let our_rsa_id = RsaIdentity::from_bytes(&DUMMY_RSA_KEY).unwrap();
527

            
528
        let mut rng = FakeEntropicRng::<TestingRng>(testing_rng());
529
        let relay_ntor_keys = StaticKeypair::generate(&mut rng).unwrap();
530

            
531
        // A handler that will process CREATE* requests on channels
532
        //
533
        // Note: in practice, this won't actually be used at all,
534
        // because for the purposes of these tests, the circuit reactor is spawned manually,
535
        // by ReactorTestCtrl::new(), which also hackily initializes the channel's circuit map
536
        // with a circuit entry for it.
537
        //
538
        // This should be fine for now, but we might want to rethink it in the future
539
        // (i.e. we might want to let the channel reactor spawn the circuit reactor under test,
540
        // in response to CREATE*).
541
        let (create_request_handler, _circuit_stream_rx) = CreateRequestHandler::new(
542
            Arc::downgrade(&chan_provider) as Weak<_>,
543
            new_circ_net_params(),
544
            RelayNtorKeys::new(Arc::new(relay_ntor_keys.into())),
545
            // Don't filter any stream requests.
546
            Box::new(|| Box::new(NoOpRequestFilter) as Box<_>),
547
            allowed_stream_cmds,
548
        );
549
        let create_request_handler = Arc::new(create_request_handler);
550

            
551
        ChannelMode::Relay {
552
            create_request_handler,
553
            our_ed25519_id,
554
            our_rsa_id,
555
            // This doesn't actually matter for these tests
556
            circ_id_range: CircIdRange::Low,
557
        }
558
    }
559

            
560
    /// Prepare our "inbound" channel,
561
    ///
562
    /// > Note: the concept of an "inbound" channel only really makes sense
563
    /// > if you think about it from a circuit perspective:
564
    /// > these tests essentially simulate circuits of the form A -> B
565
    /// > and A -> B -> C. The relay circuit reactor under test "thinks" it's relay B,
566
    /// > and its "inbound" and "outbound" channels are the A -> B and B -> C channels,
567
    /// > respectively.
568
    ///
569
    /// This spawns a channel reactor and creates a fake circuit entry in it,
570
    /// which is wired up to the circuit Reactor under test by [`ReactorTestCtrl::new`].
571
    async fn prepare_inbound_chan<R: Runtime>(
572
        rt: &R,
573
        mode: ChannelMode,
574
    ) -> (CircId, CircuitRxReceiver, DummyChan) {
575
        let mut inbound_chan = DummyChan::run(rt, mode);
576

            
577
        let memquota = CircuitAccount::new_noop();
578
        let time_provider = DynTimeProvider::new(rt.clone());
579

            
580
        let (sender, receiver) = MpscSpec::new(128)
581
            .new_mq(time_provider, memquota.as_raw_account())
582
            .unwrap();
583
        let (sender, receiver) = circ_sender::channel(sender, receiver);
584
        let (created_sender, created_receiver) = oneshot::channel();
585

            
586
        let (tx, rx) = oneshot::channel();
587

            
588
        // Note: we need to make sure the circuit is in the channel reactor's
589
        // circuit map, because otherwise we can't test the DESTROY behavior,
590
        // (the channel reactor conditionally sends DESTROY based on whether
591
        // the circuit entry is still in the circmap or not;
592
        // the presence of a circuit in the circmap is a proxy for
593
        // whether we have sent a DESTROY ourselves or not).
594
        inbound_chan
595
            .channel
596
            .send_control(CtrlMsg::AllocateCircuit {
597
                created_sender,
598
                sender,
599
                tx,
600
            })
601
            .unwrap();
602
        let (circid, _circ_unique_id, _padding_ctrl, _padding_stream) = rx.await.unwrap().unwrap();
603

            
604
        // Hack: AllocateCircuit puts the circuit in the "Opening" state,
605
        // but in order to actually be able to send anything on this channel,
606
        // we need to advance it to "Open". We do that by sending a CREATED2 cell on the channel,
607
        // which is nonsensical from the perspective of the relay-specific test setup
608
        // (it would make sense if this was a client channel, however).
609
        // Alas, it is the only way we can advance the circuit's state to "Open"
610
        // in the channel's circmap without introducing a test-only CtrlMsg for this,
611
        // or without surrendering the circuit Reactor setup to the channel impl
612
        // (the latter might not be so bad actually, because it would be closer to what
613
        // happens in reality).
614
        let handshake = vec![];
615
        let created2 = chanmsg::Created2::new(handshake.clone());
616
        let cell = ChanCell::new(Some(circid), created2.into());
617
        inbound_chan.tx.try_send(Ok(cell)).unwrap();
618

            
619
        // We **have** to read the CREATED2 (otherwise the channel reactor shuts down with an error)
620
        let _ = created_receiver.await;
621

            
622
        (circid, receiver, inbound_chan)
623
    }
624

            
625
    impl ReactorTestCtrl {
626
        /// Spawn a relay circuit reactor, returning a `ReactorTestCtrl` for
627
        /// controlling it.
628
        async fn spawn_reactor<R: Runtime>(
629
            rt: &R,
630
            allowed_stream_cmds: &[RelayCmd],
631
        ) -> (Self, impl futures::Stream<Item = IncomingStream>) {
632
            let outbound_chan = Arc::new(Mutex::new(None));
633
            let chan_provider = Arc::new(DummyChanProvider::new(
634
                rt.clone(),
635
                Arc::clone(&outbound_chan),
636
            ));
637

            
638
            let mode = build_channel_mode(Arc::clone(&chan_provider), allowed_stream_cmds);
639
            let (circid, receiver, inbound_chan) = prepare_inbound_chan(rt, mode).await;
640

            
641
            let unique_id = UniqId::new(8, 17);
642
            let (padding_ctrl, padding_stream) = new_padding(DynTimeProvider::new(rt.clone()));
643
            let params = CircParameters::new(
644
                true,
645
                build_cc_vegas_params(),
646
                FlowCtrlParameters::defaults_for_tests(),
647
            );
648
            let settings = HopSettings::from_params_and_caps(
649
                crate::circuit::circhop::HopNegotiationType::Full,
650
                &params,
651
                &[named::FLOWCTRL_CC].into_iter().collect::<Protocols>(),
652
            )
653
            .unwrap();
654

            
655
            let (recognized_tx, recognized_rx) = mpsc::channel();
656
            let (reactor, relay_circ, incoming_streams) = Reactor::new(
657
                rt.clone(),
658
                &Arc::clone(&inbound_chan.channel),
659
                circid,
660
                unique_id,
661
                receiver,
662
                Box::new(DummyInboundCrypto {}),
663
                Box::new(DummyOutboundCrypto { recognized_rx }),
664
                &settings,
665
                chan_provider,
666
                padding_ctrl,
667
                padding_stream,
668
                Box::new(AllowAllStreamsFilter),
669
                allowed_stream_cmds,
670
                &CircuitAccount::new_noop(),
671
                Arc::new(CircuitMetrics::new()),
672
            )
673
            .unwrap();
674

            
675
            rt.spawn(async {
676
                let _ = reactor.run().await;
677
            })
678
            .unwrap();
679

            
680
            let ctrl = Self {
681
                relay_circ,
682
                circid,
683
                recognized_tx,
684
                inbound_chan,
685
                outbound_chan,
686
            };
687

            
688
            (ctrl, incoming_streams)
689
        }
690

            
691
        /// Simulate the sending of a forward relay message through our relay.
692
        async fn send_fwd(
693
            &mut self,
694
            id: Option<StreamId>,
695
            msg: relaymsg::AnyRelayMsg,
696
            recognized: Recognized,
697
            early: bool,
698
        ) {
699
            // This a bit janky, but for each forward cell we send to the reactor
700
            // we need to send a bit of metadata to the DummyOutboundLayer
701
            // specifying whether the cell should be treated as recognized
702
            // or unrecognized
703
            self.recognized_tx.send(recognized).unwrap();
704
            self.send_dec_cmsg(rmsg_to_ccmsg(id, msg, early)).await;
705
        }
706

            
707
        /// Simulate the sending of a forward channel message through our relay.
708
        async fn send_dec_cmsg(&mut self, msg: chanmsg::AnyChanMsg) {
709
            let cell = ChanCell::new(Some(self.circid), msg);
710
            self.inbound_chan.tx.send(Ok(cell)).await.unwrap();
711
        }
712

            
713
        /// Whether the reactor opened an outbound channel
714
        /// (i.e. a channel to the next relay in the circuit).
715
        fn outbound_chan_launched(&self) -> bool {
716
            self.outbound_chan.lock().unwrap().is_some()
717
        }
718

            
719
        /// Perform the CREATE2 handshake.
720
        async fn do_create2_handshake(
721
            &mut self,
722
            rt: &MockRuntime,
723
            expected_hs_type: HandshakeType,
724
        ) -> Option<CircId> {
725
            // First, check that the reactor actually sent a CREATE2 to the next hop...
726
            let (circid, msg) = self.read_outbound().into_circid_and_msg();
727
            let _create2 = match msg {
728
                chanmsg::AnyChanMsg::Create2(c) => {
729
                    assert_eq!(c.handshake_type(), expected_hs_type);
730
                    c
731
                }
732
                _ => panic!("unexpected forwarded {msg:?}"),
733
            };
734

            
735
            let handshake = vec![];
736
            let created2 = chanmsg::Created2::new(handshake.clone());
737
            // ...and then finalize the handshake by pretending to be
738
            // the responding relay
739
            self.write_outbound(circid, chanmsg::AnyChanMsg::Created2(created2));
740
            rt.advance_until_stalled().await;
741

            
742
            // Make sure we actually did send an EXTENDED2 towards the client
743
            let msg = self.read_inbound();
744

            
745
            let (_sid, e) = decode_relay_cell!(msg, Extended2);
746
            assert_eq!(e.clone().into_body(), handshake);
747

            
748
            circid
749
        }
750

            
751
        /// Whether the circuit is closing (e.g. due to a proto violation).
752
        fn is_closing(&self) -> bool {
753
            self.relay_circ.is_closing()
754
        }
755

            
756
        /// Read a cell from the inbound channel
757
        /// (moving towards the client).
758
        ///
759
        /// See [`try_read_inbound`](Self::try_read_inbound).
760
        ///
761
        /// Panics if there are no ready cells on the inbound MPSC channel.
762
        fn read_inbound(&mut self) -> ChanCell<AnyChanMsg> {
763
            self.try_read_inbound().unwrap()
764
        }
765

            
766
        /// Try to read a cell from the inbound channel
767
        /// (moving towards the client).
768
        ///
769
        /// For example, for a circuit of the form A -> B -> C,
770
        /// where B is the relay whose circuit reactor we're testing,
771
        /// this function reads a channel message on the A <-> B channel,
772
        /// from the perspective of A (i.e. it reads a channel message sent by B).
773
        ///
774
        /// Returns None if there are no ready cells on the inbound MPSC channel.
775
        fn try_read_inbound(&mut self) -> Option<ChanCell<AnyChanMsg>> {
776
            #[allow(deprecated)] // TODO(#2386)
777
            self.inbound_chan.rx.try_next().ok().flatten()
778
        }
779

            
780
        /// Read a cell from the outbound channel
781
        /// (moving towards the next hop).
782
        ///
783
        /// See [`try_read_outbound`](Self::try_read_outbound).
784
        ///
785
        /// Panics if there are no ready cells on the outbound MPSC channel,
786
        /// or if there is no outbound channel.
787
        fn read_outbound(&mut self) -> ChanCell<AnyChanMsg> {
788
            self.try_read_outbound().unwrap()
789
        }
790

            
791
        /// Read a cell from the outbound channel
792
        /// (moving towards the next hop).
793
        ///
794
        /// For example, for a circuit of the form A -> B -> C,
795
        /// where B is the relay whose circuit reactor we're testing,
796
        /// this function reads a channel message on the B <-> C channel,
797
        /// from the perspective of C (i.e. it reads a channel message sent by B).
798
        ///
799
        /// Returns None if there are no ready cells on the outbound MPSC channel,
800
        /// or if there is no outbound channel.
801
        fn try_read_outbound(&mut self) -> Option<ChanCell<AnyChanMsg>> {
802
            let mut lock = self.outbound_chan.lock().unwrap();
803
            let chan = lock.as_mut()?;
804
            #[allow(deprecated)] // TODO(#2386)
805
            chan.rx.try_next().ok().flatten()
806
        }
807

            
808
        /// Write to the sending end of the outbound Tor channel.
809
        ///
810
        /// Simulates the receipt of a cell from the next hop.
811
        ///
812
        /// Panics if the outbound chan sender is full.
813
        fn write_outbound(&mut self, circid: Option<CircId>, msg: chanmsg::AnyChanMsg) {
814
            let mut lock = self.outbound_chan.lock().unwrap();
815
            let chan = lock.as_mut().unwrap();
816
            let cell = ChanCell::new(circid, msg);
817

            
818
            chan.tx.try_send(Ok(cell)).unwrap();
819
        }
820
    }
821

            
822
    fn dummy_linkspecs() -> Vec<EncodedLinkSpec> {
823
        vec![
824
            LinkSpec::Ed25519Id([43; 32].into()).encode().unwrap(),
825
            LinkSpec::RsaId([45; 20].into()).encode().unwrap(),
826
            LinkSpec::OrPort("127.0.0.1".parse::<IpAddr>().unwrap(), 999)
827
                .encode()
828
                .unwrap(),
829
        ]
830
    }
831

            
832
    /// Helper for constructing `Begin` messages with less boilerplate.
833
    fn dummy_begin(addr: impl Into<relaymsg::BeginAddr>, port: u16) -> relaymsg::Begin {
834
        let addr = addr.into();
835
        let port = NonZero::new(port).unwrap();
836
        relaymsg::Begin::new(addr.encode(), port, 0)
837
    }
838

            
839
    macro_rules! assert_cell_is_destroy {
840
        ($cell:expr, $reason:expr) => {{
841
            match $cell.msg() {
842
                chanmsg::AnyChanMsg::Destroy(d) => {
843
                    assert_eq!(d.reason(), $reason);
844
                }
845
                _ => panic!("unexpected ending {:?}", $cell),
846
            }
847
        }};
848
    }
849

            
850
    /// Assert that we have sent a DESTROY cell with the specified `reason`
851
    /// towards the "client" and/or the "next hop".
852
    ///
853
    /// The test is expected to drain the inbound Tor "channel"
854
    /// of any non-ending cells it might be expecting before calling this function.
855
    fn assert_destroy_sent(
856
        ctrl: &mut ReactorTestCtrl,
857
        reason: DestroyReason,
858
        direction: DestroyDirection,
859
    ) {
860
        assert!(ctrl.is_closing());
861

            
862
        match direction {
863
            DestroyDirection::Backward => {
864
                assert_cell_is_destroy!(ctrl.read_inbound(), reason);
865
                assert!(ctrl.try_read_outbound().is_none());
866
            }
867
            DestroyDirection::Forward => {
868
                assert_cell_is_destroy!(ctrl.read_outbound(), reason);
869
                assert!(ctrl.try_read_inbound().is_none());
870
            }
871
            DestroyDirection::Both => {
872
                assert_cell_is_destroy!(ctrl.read_inbound(), reason);
873
                assert_cell_is_destroy!(ctrl.read_outbound(), reason);
874
            }
875
        }
876
    }
877

            
878
    macro_rules! expect_cell {
879
        ($cell:expr, $chanmsg:tt, $relaymsg:tt) => {{
880
            let msg = match $cell.msg() {
881
                chanmsg::AnyChanMsg::$chanmsg(m) => {
882
                    let body = m.clone().into_relay_body();
883
                    AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V0, body).unwrap()
884
                }
885
                _ => panic!("unexpected forwarded {:?}", $cell),
886
            };
887

            
888
            match msg.msg() {
889
                relaymsg::AnyRelayMsg::$relaymsg(m) => m.clone(),
890
                _ => panic!("unexpected cell {msg:?}"),
891
            }
892
        }};
893
    }
894

            
895
    #[traced_test]
896
    #[test]
897
    fn reject_extend2_relay() {
898
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
899
            let (mut ctrl, _incoming_streams) =
900
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
901
            rt.advance_until_stalled().await;
902

            
903
            let linkspecs = dummy_linkspecs();
904
            let extend2 = relaymsg::Extend2::new(linkspecs, HandshakeType::NTOR_V3, vec![]).into();
905
            ctrl.send_fwd(None, extend2, Recognized::Yes, false).await;
906
            rt.advance_until_stalled().await;
907

            
908
            assert!(logs_contain("got EXTEND2 in a RELAY cell?!"));
909
            assert!(!ctrl.outbound_chan_launched());
910

            
911
            // There is no next hop because we haven't extended the circuit,
912
            // so only expect the DESTROY to be sent toward the client (Backward).
913
            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
914
        });
915
    }
916

            
917
    #[traced_test]
918
    #[test]
919
    fn reject_extend2_previous_hop() {
920
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
921
            let (mut ctrl, _incoming_streams) =
922
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
923
            rt.advance_until_stalled().await;
924

            
925
            // No outbound circuits yet
926
            assert!(!ctrl.outbound_chan_launched());
927

            
928
            // Build a linkspec with the identities of the dummy channel
929
            let mut linkspecs = ctrl
930
                .inbound_chan
931
                .channel
932
                .target()
933
                .identities()
934
                .map(|id| LinkSpec::from(id.to_owned()).encode())
935
                .collect::<Result<Vec<_>, _>>()
936
                .unwrap();
937

            
938
            // Make sure this channel actually has some identities
939
            // (i.e. that it's not a client channel or something)
940
            assert_eq!(linkspecs.len(), 2);
941

            
942
            // There must be at least one IPv4 OR port address
943
            linkspecs.push(
944
                LinkSpec::OrPort("127.0.0.1".parse::<IpAddr>().unwrap(), 999)
945
                    .encode()
946
                    .unwrap(),
947
            );
948
            let handshake_type = HandshakeType::NTOR_V3;
949
            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
950
            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
951
            rt.advance_until_stalled().await;
952

            
953
            // The reactor handled the EXTEND2 and launched an outbound channel
954
            assert!(logs_contain("Cannot extend circuit to previous hop"));
955
            assert!(!ctrl.outbound_chan_launched());
956
            assert!(ctrl.is_closing());
957
        });
958
    }
959

            
960
    #[traced_test]
961
    #[test]
962
    fn extend_and_forward() {
963
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
964
            let (mut ctrl, _incoming_streams) =
965
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
966
            rt.advance_until_stalled().await;
967

            
968
            // No outbound circuits yet
969
            assert!(!ctrl.outbound_chan_launched());
970

            
971
            let linkspecs = dummy_linkspecs();
972
            let handshake_type = HandshakeType::NTOR_V3;
973
            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
974
            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
975
            rt.advance_until_stalled().await;
976

            
977
            // The reactor handled the EXTEND2 and launched an outbound channel
978
            assert!(logs_contain(
979
                "Launched channel to the next hop circ_uniq_id=Circ 8.17"
980
            ));
981
            assert!(ctrl.outbound_chan_launched());
982
            assert!(!ctrl.is_closing());
983

            
984
            let _circid = ctrl.do_create2_handshake(&rt, handshake_type).await;
985
            assert!(logs_contain("Got CREATED2 response from next hop"));
986
            assert!(logs_contain("Extended circuit to the next hop"));
987

            
988
            // Time to forward a message to the next hop!
989
            let early = false;
990
            let begin = dummy_begin(Ipv4Addr::LOCALHOST, 1111);
991
            ctrl.send_fwd(None, begin.clone().into(), Recognized::No, early)
992
                .await;
993
            rt.advance_until_stalled().await;
994

            
995
            // Ensure the other end received the BEGIN cell
996
            let cell = ctrl.read_outbound();
997
            let recvd_begin = expect_cell!(cell, Relay, Begin);
998
            assert_eq!(begin, recvd_begin);
999

            
            // Now send the same message again, but this time in a RELAY_EARLY
            let early = true;
            let begin = dummy_begin(Ipv4Addr::LOCALHOST, 1111);
            ctrl.send_fwd(None, begin.clone().into(), Recognized::No, early)
                .await;
            rt.advance_until_stalled().await;
            let cell = ctrl.read_outbound();
            let recvd_begin = expect_cell!(cell, RelayEarly, Begin);
            assert_eq!(begin, recvd_begin);
        });
    }
    #[traced_test]
    #[test]
    fn forward_before_extend() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            let (mut ctrl, _incoming_streams) =
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
            rt.advance_until_stalled().await;
            // Send an arbitrary unrecognized cell. The reactor should flag this as
            // a protocol violation, because we don't have an outbound channel to forward it on.
            let end = relaymsg::End::new_misc().into();
            ctrl.send_fwd(None, end, Recognized::No, true).await;
            rt.advance_until_stalled().await;
            assert!(logs_contain(
                "Asked to forward cell before the circuit was extended?!"
            ));
            // There is no next hop because we haven't extended the circuit,
            // so only expect the DESTROY to be sent toward the client (Backward).
            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
        });
    }
    #[traced_test]
    #[test]
    fn reject_invalid_begin() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            let (mut ctrl, _incoming_streams) =
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
            rt.advance_until_stalled().await;
            let begin = dummy_begin(Ipv4Addr::LOCALHOST, 1111).into();
            // BEGIN cells *must* have a stream ID, so expect the reactor to reject this
            // and close the circuit
            ctrl.send_fwd(None, begin, Recognized::Yes, false).await;
            rt.advance_until_stalled().await;
            assert!(logs_contain(
                "Invalid stream ID [scrubbed] for relay command BEGIN"
            ));
            // There is no next hop because we haven't extended the circuit,
            // so only expect the DESTROY to be sent toward the client (Backward).
            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
        });
    }
    #[traced_test]
    #[test]
    fn destroy_from_client() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            let (mut ctrl, _incoming_streams) =
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
            rt.advance_until_stalled().await;
            // Extend the circuit by another hop
            let linkspecs = dummy_linkspecs();
            let handshake_type = HandshakeType::NTOR_V3;
            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
            rt.advance_until_stalled().await;
            let _circid = ctrl.do_create2_handshake(&rt, handshake_type).await;
            assert!(logs_contain("Extended circuit to the next hop"));
            assert!(ctrl.outbound_chan_launched());
            // Simulate the client sending us a DESTROY cell
            let destroy = Destroy::new(DestroyReason::PROTOCOL);
            ctrl.send_dec_cmsg(destroy.into()).await;
            rt.advance_until_stalled().await;
            assert!(logs_contain(
                "Received outbound DESTROY, circuit shutting down"
            ));
            // Since this is a circuit of the form A -> B -> C,
            // and A sent us a DESTROY, we expect our relay (B) to forward
            // the DESTROY to C.
            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Forward);
        });
    }
    #[traced_test]
    #[test]
    fn destroy_from_next_hop() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            let (mut ctrl, _incoming_streams) =
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
            rt.advance_until_stalled().await;
            // Extend the circuit by another hop
            let linkspecs = dummy_linkspecs();
            let handshake_type = HandshakeType::NTOR_V3;
            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
            rt.advance_until_stalled().await;
            let circid = ctrl.do_create2_handshake(&rt, handshake_type).await;
            assert!(logs_contain("Extended circuit to the next hop"));
            assert!(ctrl.outbound_chan_launched());
            // Simulate the next hop sending us a DESTROY cell
            let destroy = Destroy::new(DestroyReason::PROTOCOL);
            ctrl.write_outbound(circid, destroy.into());
            rt.advance_until_stalled().await;
            // We have *not* received an outbound destroy
            assert!(!logs_contain(
                "Received outbound DESTROY, circuit shutting down"
            ));
            // We received an inbound one (from the next hop)
            assert!(logs_contain(
                "Received inbound DESTROY, circuit shutting down"
            ));
            // There is no next hop because we haven't extended the circuit,
            // so only expect the DESTROY to be sent toward the client (Backward).
            // This also ensures the destroy reason (PROTOCOL) is not propagated.
            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
        });
    }
    #[traced_test]
    #[test]
    fn truncate() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            let (mut ctrl, _incoming_streams) =
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
            rt.advance_until_stalled().await;
            // Simulate the client sending us a TRUNCATE cell
            let truncate = relaymsg::Truncate::default().into();
            ctrl.send_fwd(None, truncate, Recognized::Yes, false).await;
            rt.advance_until_stalled().await;
            assert!(logs_contain(
                "Circuit protocol violation: TRUNCATE not allowed"
            ));
            // There is no next hop because we haven't extended the circuit,
            // so only expect the DESTROY to be sent toward the client (Backward).
            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
        });
    }
    #[traced_test]
    #[test]
    fn data_stream() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            const TO_SEND: &[u8] = b"The bells were musical in the silvery sun";
            let (mut ctrl, mut incoming_streams) =
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
            rt.advance_until_stalled().await;
            let begin = dummy_begin(Ipv4Addr::LOCALHOST, 1111).into();
            ctrl.send_fwd(StreamId::new(1), begin, Recognized::Yes, false)
                .await;
            rt.advance_until_stalled().await;
            let data = relaymsg::Data::new(TO_SEND).unwrap().into();
            ctrl.send_fwd(StreamId::new(1), data, Recognized::Yes, false)
                .await;
            // We should have a pending incoming stream
            let pending = incoming_streams.next().await.unwrap();
            // Accept it, and let's see what we have!
            let mut stream = pending
                .accept_data(relaymsg::Connected::new_empty())
                .await
                .unwrap();
            let mut recv_buf = [0_u8; TO_SEND.len()];
            stream.read_exact(&mut recv_buf).await.unwrap();
            assert_eq!(recv_buf, TO_SEND);
        });
    }
    #[traced_test]
    #[test]
    fn reject_stream() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            let (mut ctrl, mut incoming_streams) =
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
            rt.advance_until_stalled().await;
            let begin = dummy_begin(Ipv4Addr::LOCALHOST, 1111).into();
            ctrl.send_fwd(StreamId::new(1), begin, Recognized::Yes, false)
                .await;
            rt.advance_until_stalled().await;
            // We should have a pending incoming stream
            let pending = incoming_streams.next().await.unwrap();
            // Reject the stream, and wait for the reactor to finish sending the END
            let end = relaymsg::End::new_misc();
            pending.reject(end.clone()).await.unwrap();
            rt.advance_until_stalled().await;
            // The END cell written to the Tor channel should be the same as
            // the one we sent above, in reject().
            let cell = ctrl.read_inbound();
            let actual_end = expect_cell!(cell, Relay, End);
            assert_eq!(end.reason(), actual_end.reason());
            // Sending another message on this stream results is flagged
            // as a proto violation
            let data = relaymsg::Data::new(b"no dice").unwrap().into();
            ctrl.send_fwd(StreamId::new(1), data, Recognized::Yes, false)
                .await;
            rt.advance_until_stalled().await;
            assert!(logs_contain("Stream protocol violation"));
            assert!(logs_contain(
                "Unexpected RelayCmd(DATA) message on unknown stream 1"
            ));
        });
    }
    #[traced_test]
    #[test]
    fn only_allow_begin_dir() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            let (mut ctrl, mut incoming_streams) = ReactorTestCtrl::spawn_reactor(
                &rt,
                // The stream reactor will only accept BEGIN_DIR streams
                &[RelayCmd::BEGIN_DIR],
            )
            .await;
            rt.advance_until_stalled().await;
            // Directory streams should be allowed (because BEGIN_DIR is allowed)...
            let begin_dir = relaymsg::BeginDir::default().into();
            ctrl.send_fwd(StreamId::new(1), begin_dir, Recognized::Yes, false)
                .await;
            rt.advance_until_stalled().await;
            let pending_dir_stream = incoming_streams.next().await.unwrap();
            assert!(matches!(
                pending_dir_stream.request(),
                IncomingStreamRequest::BeginDir(_)
            ));
            let begin = dummy_begin(Ipv4Addr::LOCALHOST, 1111).into();
            ctrl.send_fwd(StreamId::new(2), begin, Recognized::Yes, false)
                .await;
            rt.advance_until_stalled().await;
            // ... but the exit stream is not
            assert!(logs_contain("stream reactor shut down"));
            assert!(logs_contain(
                "Stream protocol violation: Unexpected BEGIN on incoming stream circ_uniq_id=Circ 8.17"
            ));
            // The reactor won't create an IncomingStream,
            // because the stream request is rejected right away
            let mut noop_cx = Context::from_waker(Waker::noop());
            assert_eq!(
                incoming_streams.poll_next_unpin(&mut noop_cx).map(|_| ()),
                Poll::Pending
            );
        });
    }
    #[traced_test]
    #[test]
    fn resolve_stream() {
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
            let (mut ctrl, mut incoming_streams) =
                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::RESOLVE]).await;
            rt.advance_until_stalled().await;
            let resolve = relaymsg::Resolve::new("example.com");
            let resolve_sid = StreamId::new(1337);
            ctrl.send_fwd(resolve_sid, resolve.into(), Recognized::Yes, false)
                .await;
            rt.advance_until_stalled().await;
            // We should have a pending incoming stream
            let pending = incoming_streams.next().await.unwrap();
            let mut resolved = relaymsg::Resolved::new_empty();
            let resolved_val = relaymsg::ResolvedVal::Ip(IpAddr::from([1, 2, 3, 4]));
            resolved.add_answer(resolved_val.clone(), 1337);
            // We expect the client to receive this cell
            let expected_resolved = resolved.clone();
            // Respond with RESOLVED
            pending.resolve(resolved).await.unwrap();
            rt.advance_until_stalled().await;
            let (sid, resolved) = decode_relay_cell!(ctrl.read_inbound(), Resolved);
            // Make sure the RESOLVED cell sent towards the client
            // matches what we sent via the IncomingStream::resolve() call above
            assert_eq!(resolved.into_answers(), expected_resolved.into_answers());
            assert_eq!(sid, resolve_sid);
            assert!(logs_contain("Ending stream"));
        });
    }
}