1
//! Support for unit tests, in this crate and elsewhere.
2
//!
3
//! This module is only enabled when the `testing` feature is enabled.
4
//!
5
//! It is not covered by semver for the `tor-netdir` crate: see notes
6
//! on [`construct_network`].
7
//!
8
//! # Panics
9
//!
10
//! These functions can panic on numerous possible internal failures:
11
//! only use these functions for testing.
12

            
13
#![allow(clippy::unwrap_used)]
14

            
15
use crate::{MdReceiver, PartialNetDir};
16
use std::iter;
17
use std::net::SocketAddr;
18
use std::sync::Arc;
19
#[cfg(feature = "geoip")]
20
use tor_geoip::GeoipDb;
21
use tor_llcrypto::pk::ed25519::Ed25519Identity;
22
use tor_netdoc::doc::microdesc::{MicrodescAndHash, MicrodescBuilder};
23
use tor_netdoc::doc::netstatus::md::NetworkStatus as MdConsensus;
24
use tor_netdoc::doc::netstatus::{Lifetime, MdRouterStatusBuilder, RelayBandwidth};
25
use tor_netdoc::types::family::HappyFamilyId;
26
use tor_netdoc::types::relay_flags::RelayFlag;
27
pub use tor_netdoc::{BuildError, BuildResult};
28
use web_time_compat::{Duration, SystemTime, SystemTimeExt};
29

            
30
/// A set of builder objects for a single node.
31
#[derive(Debug, Clone)]
32
#[non_exhaustive]
33
pub struct NodeBuilders {
34
    /// Builds a routerstatus for a single node.
35
    ///
36
    /// Adjust fields in this builder to change the node's properties.
37
    pub rs: MdRouterStatusBuilder,
38

            
39
    /// Builds a microdescriptor for a single node.
40
    ///
41
    /// Adjust fields in this builder in order to change the node's
42
    /// properties.
43
    pub md: MicrodescBuilder,
44

            
45
    /// Set this value to `true` to omit the microdesc from the network.
46
    pub omit_md: bool,
47

            
48
    /// Set this value to `true` to omit the routerdesc from the network.
49
    pub omit_rs: bool,
50
}
51

            
52
/// Helper: a customization function that does nothing.
53
233440
pub fn simple_net_func(_idx: usize, _nb: &mut NodeBuilders, _bld: &mut MdConsensus) {}
54

            
55
/// As [`construct_network()`], but return a [`PartialNetDir`].
56
4092
pub fn construct_netdir() -> PartialNetDir {
57
4092
    construct_custom_netdir(simple_net_func).expect("failed to build default testing netdir")
58
4092
}
59

            
60
/// As [`construct_custom_network()`], but return a [`PartialNetDir`],
61
/// and allow network parameter customisation.
62
4235
pub fn construct_custom_netdir_with_params<F, P, PK>(
63
4235
    func: F,
64
4235
    params: P,
65
4235
    lifetime: Option<Lifetime>,
66
4235
) -> BuildResult<PartialNetDir>
67
4235
where
68
4235
    F: FnMut(usize, &mut NodeBuilders, &mut MdConsensus),
69
4235
    P: IntoIterator<Item = (PK, i32)>,
70
4235
    PK: Into<String>,
71
{
72
4235
    construct_custom_netdir_with_params_inner(
73
4235
        func,
74
4235
        params,
75
4235
        lifetime,
76
4235
        #[cfg(feature = "geoip")]
77
4235
        None,
78
4235
    )
79
4235
}
80

            
81
/// Implementation of `construct_custom_netdir_with_params`, written this way to avoid
82
/// the GeoIP argument crossing a crate API boundary.
83
4236
fn construct_custom_netdir_with_params_inner<F, P, PK>(
84
4236
    func: F,
85
4236
    params: P,
86
4236
    lifetime: Option<Lifetime>,
87
4236
    #[cfg(feature = "geoip")] geoip_db: Option<&GeoipDb>,
88
4236
) -> BuildResult<PartialNetDir>
89
4236
where
90
4236
    F: FnMut(usize, &mut NodeBuilders, &mut MdConsensus),
91
4236
    P: IntoIterator<Item = (PK, i32)>,
92
4236
    PK: Into<String>,
93
{
94
4236
    let (consensus, microdescs) = construct_custom_network(func, lifetime)?;
95
    #[cfg(feature = "geoip")]
96
4236
    let mut dir = if let Some(db) = geoip_db {
97
1
        PartialNetDir::new_with_geoip(consensus, Some(&params.into_iter().collect()), db)
98
    } else {
99
4235
        PartialNetDir::new(consensus, Some(&params.into_iter().collect()))
100
    };
101
    #[cfg(not(feature = "geoip"))]
102
    let mut dir = PartialNetDir::new(consensus, Some(&params.into_iter().collect()));
103
4236
    for md in microdescs {
104
169436
        dir.add_microdesc(md);
105
    }
106

            
107
4236
    Ok(dir)
108
4236
}
109

            
110
/// As [`construct_custom_network()`], but return a [`PartialNetDir`].
111
4148
pub fn construct_custom_netdir<F>(func: F) -> BuildResult<PartialNetDir>
112
4148
where
113
4148
    F: FnMut(usize, &mut NodeBuilders, &mut MdConsensus),
114
{
115
4148
    construct_custom_netdir_with_params(func, iter::empty::<(&str, _)>(), None)
116
4148
}
117

            
118
#[cfg(feature = "geoip")]
119
/// As [`construct_custom_netdir()`], but with a `GeoipDb`.
120
1
pub fn construct_custom_netdir_with_geoip<F>(func: F, db: &GeoipDb) -> BuildResult<PartialNetDir>
121
1
where
122
1
    F: FnMut(usize, &mut NodeBuilders, &mut MdConsensus),
123
{
124
1
    construct_custom_netdir_with_params_inner(func, iter::empty::<(&str, _)>(), None, Some(db))
125
1
}
126

            
127
/// As [`construct_custom_network`], but do not require a
128
/// customization function.
129
1227
pub fn construct_network() -> BuildResult<(MdConsensus, Vec<MicrodescAndHash>)> {
130
1227
    construct_custom_network(simple_net_func, None)
131
1227
}
132

            
133
/// Build a fake network with enough information to enable some basic
134
/// tests.
135
///
136
/// By default, the constructed network will contain 40 relays,
137
/// numbered 0 through 39. They will have with RSA and Ed25519
138
/// identity fingerprints set to 0x0000...00 through 0x2727...27.
139
/// Each pair of relays is in a family with one another: 0x00..00 with
140
/// 0x01..01, and so on.
141
///
142
/// All relays are marked as usable.  The first ten are marked with no
143
/// additional flags.  The next ten are marked with the exit flag.
144
/// The next ten are marked with the guard flag.  The last ten are
145
/// marked with the exit _and_ guard flags.
146
///
147
/// TAP and Ntor onion keys are present, but unusable.
148
///
149
/// Odd-numbered exit relays are set to allow ports 80 and 443 on
150
/// IPv4.  Even-numbered exit relays are set to allow ports 1-65535
151
/// on IPv4.  No exit relays are marked to support IPv6.
152
///
153
/// Even-numbered relays support the `DirCache=2` protocol.
154
///
155
/// Every relay is given a measured weight based on its position
156
/// within its group of ten.  The weights for the ten relays in each
157
/// group are: 1000, 2000, 3000, ... 10000.  There is no additional
158
/// flag-based bandwidth weighting.
159
///
160
/// The consensus is declared as using method 34, and as being valid for
161
/// one day (in realtime) after the current `SystemTime`.
162
///
163
/// # Customization
164
///
165
/// Before each relay is added to the consensus or the network, it is
166
/// passed through the provided filtering function.  This function
167
/// receives as its arguments the current index (in range 0..40), a
168
/// [`MdRouterStatusBuilder`], and a [`MicrodescBuilder`].  If it
169
/// returns a `RouterStatusBuilder`, the corresponding router status
170
/// is added to the consensus.  If it returns a `MicrodescBuilder`,
171
/// the corresponding microdescriptor is added to the vector of
172
/// microdescriptor.
173
///
174
/// # Notes for future expansion
175
///
176
/// _Resist the temptation to make unconditional changes to this
177
/// function._ If the network generated by this function gets more and
178
/// more complex, then it will become harder and harder over time to
179
/// make it support new test cases and new behavior, and eventually
180
/// we'll have to throw the whole thing away.  (We ran into this
181
/// problem with Tor's unit tests.)
182
///
183
/// Instead, refactor this function so that it takes a
184
/// description of what kind of network to build, and then builds it from
185
/// that description.
186
5924
pub fn construct_custom_network<F>(
187
5924
    mut func: F,
188
5924
    lifetime: Option<Lifetime>,
189
5924
) -> BuildResult<(MdConsensus, Vec<MicrodescAndHash>)>
190
5924
where
191
5924
    F: FnMut(usize, &mut NodeBuilders, &mut MdConsensus),
192
{
193
5924
    let f = RelayFlag::Running
194
5924
        | RelayFlag::Valid
195
5924
        | RelayFlag::V2Dir
196
5924
        | RelayFlag::Fast
197
5924
        | RelayFlag::Stable;
198
    // define 4 groups of flags
199
5924
    let flags = [
200
5924
        f | RelayFlag::HSDir,
201
5924
        f | RelayFlag::Exit,
202
5924
        f | RelayFlag::Guard,
203
5924
        f | RelayFlag::Exit | RelayFlag::Guard,
204
5924
    ];
205
5924
    let mut consensus = simple_empty_consensus(lifetime)?;
206

            
207
5924
    let mut microdescs = Vec::new();
208
5924
    for idx in 0..40_u8 {
209
        // Each relay gets a couple of no-good onion keys.
210
        // Its identity fingerprints are set to `idx`, repeating.
211
        // They all get the same address.
212
236960
        let flags = flags[(idx / 10) as usize];
213
236960
        let policy = if flags.contains(RelayFlag::Exit) {
214
118480
            if idx % 2 == 1 {
215
59240
                "accept 80,443"
216
            } else {
217
59240
                "accept 1-65535"
218
            }
219
        } else {
220
118480
            "reject 1-65535"
221
        };
222
        // everybody is family with the adjacent relay.
223
236960
        let fam_id = HappyFamilyId::Ed25519(Ed25519Identity::from([idx & !1; 32]));
224

            
225
236960
        let mut md_builder = MicrodescAndHash::builder();
226
236960
        md_builder
227
236960
            .ntor_key((*b"----nothing in dirmgr uses this-").into())
228
236960
            .ed25519_id([idx; 32].into())
229
236960
            .add_family_id(fam_id)
230
236960
            .parse_ipv4_policy(policy)
231
236960
            .unwrap();
232
236960
        let protocols = if idx % 2 == 0 {
233
            // even-numbered relays are dircaches.
234
118480
            "DirCache=2".parse().unwrap()
235
        } else {
236
118480
            "".parse().unwrap()
237
        };
238
236960
        let weight = RelayBandwidth::Measured(1000 * u32::from(idx % 10 + 1));
239
236960
        let mut rs_builder = MdRouterStatusBuilder::new();
240
236960
        rs_builder
241
236960
            .identity([idx; 20].into())
242
236960
            .add_or_port(SocketAddr::from(([idx % 5, 0, 0, 3], 9001)))
243
236960
            .protos(protocols)
244
236960
            .set_flags(flags)
245
236960
            .weight(weight);
246

            
247
236960
        let mut node_builders = NodeBuilders {
248
236960
            rs: rs_builder,
249
236960
            md: md_builder,
250
236960
            omit_rs: false,
251
236960
            omit_md: false,
252
236960
        };
253

            
254
236960
        func(idx as usize, &mut node_builders, &mut consensus);
255

            
256
236960
        let md = node_builders.md.testing_md()?;
257
236960
        let md_digest = *md.digest();
258
236960
        if !node_builders.omit_md {
259
236956
            microdescs.push(md);
260
4
        }
261

            
262
236960
        if !node_builders.omit_rs {
263
236611
            consensus
264
236611
                .routers
265
236611
                .push(node_builders.rs.doc_digest(md_digest).build()?);
266
349
        }
267
    }
268

            
269
461374
    consensus.routers.sort_by_key(|r| *r.rsa_identity());
270

            
271
5924
    Ok((consensus, microdescs))
272
5924
}
273

            
274
/// Return a simple MD-flavored consensus, as empty as we can make it.
275
9615
pub(crate) fn simple_empty_consensus(lifetime: Option<Lifetime>) -> BuildResult<MdConsensus> {
276
    use tor_netdoc::doc::netstatus::{
277
        ConsensusAuthoritySectionConstructor, ConsensusFooterFieldsConstructor,
278
        ProtoStatusesConstructor, VotingDelayConstructor,
279
        md::{FooterConstructor, NetworkStatusConstructor, PreambleConstructor},
280
    };
281
    use tor_netdoc::types::{NotPresent, relay_flags::DocRelayFlags};
282

            
283
9615
    let lifetime = lifetime.map(Ok).unwrap_or_else(|| {
284
9557
        let now = SystemTime::get();
285
9557
        let one_day = Duration::new(86400, 0);
286

            
287
9557
        Lifetime::new(now, now + one_day / 2, now + one_day)
288
9557
    })?;
289
9615
    let proto_statuses = Arc::new(ProtoStatusesConstructor {}.construct());
290
9615
    Ok(NetworkStatusConstructor {
291
9615
        preamble: PreambleConstructor {
292
9615
            consensus_methods: NotPresent,
293
9615
            published: NotPresent,
294
9615
            consensus_method: (34,),
295
9615
            lifetime,
296
9615
            params: "bwweightscale=1"
297
9615
                .parse()
298
9615
                .expect("unparsable internal param set"),
299
9615
            known_flags: DocRelayFlags::new_empty_unknown_discarded(),
300
9615
            proto_statuses,
301
9615
            voting_delay: VotingDelayConstructor {
302
9615
                dist_seconds: 600,
303
9615
                vote_seconds: 600,
304
9615
            }
305
9615
            .construct(),
306
9615
        }
307
9615
        .construct(),
308
9615
        authority: ConsensusAuthoritySectionConstructor {
309
9615
            authorities: vec![],
310
9615
        }
311
9615
        .construct(),
312
9615
        footer: FooterConstructor {
313
9615
            consensus: ConsensusFooterFieldsConstructor {}.into(),
314
9615
        }
315
9615
        .construct(),
316
9615
    }
317
9615
    .construct())
318
9615
}
319

            
320
#[cfg(test)]
321
mod test {
322
    // @@ begin test lint list maintained by maint/add_warning @@
323
    #![allow(clippy::bool_assert_comparison)]
324
    #![allow(clippy::clone_on_copy)]
325
    #![allow(clippy::dbg_macro)]
326
    #![allow(clippy::mixed_attributes_style)]
327
    #![allow(clippy::print_stderr)]
328
    #![allow(clippy::print_stdout)]
329
    #![allow(clippy::single_char_pattern)]
330
    #![allow(clippy::unwrap_used)]
331
    #![allow(clippy::unchecked_time_subtraction)]
332
    #![allow(clippy::useless_vec)]
333
    #![allow(clippy::needless_pass_by_value)]
334
    #![allow(clippy::string_slice)] // See arti#2571
335
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
336
    use super::*;
337
    #[test]
338
    fn try_with_function() {
339
        let mut val = 0_u32;
340
        let _net = construct_custom_netdir(|_idx, _nb, _bld| {
341
            val += 1;
342
        });
343
        assert_eq!(val, 40);
344
    }
345
}