1
//! Tests for bridge descriptor downloading
2

            
3
// @@ begin test lint list maintained by maint/add_warning @@
4
#![allow(clippy::bool_assert_comparison)]
5
#![allow(clippy::clone_on_copy)]
6
#![allow(clippy::dbg_macro)]
7
#![allow(clippy::mixed_attributes_style)]
8
#![allow(clippy::print_stderr)]
9
#![allow(clippy::print_stdout)]
10
#![allow(clippy::single_char_pattern)]
11
#![allow(clippy::unwrap_used)]
12
#![allow(clippy::unchecked_time_subtraction)]
13
#![allow(clippy::useless_vec)]
14
#![allow(clippy::needless_pass_by_value)]
15
#![allow(clippy::string_slice)] // See arti#2571
16
//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
17

            
18
use std::future::Future;
19
use std::iter;
20
use std::time::UNIX_EPOCH;
21

            
22
use futures::Stream;
23
use futures::select_biased;
24
use futures::stream::FusedStream;
25
use itertools::{Itertools, chain};
26
use tempfile::TempDir;
27
use time::OffsetDateTime;
28
use tracing_test::traced_test;
29

            
30
use tor_linkspec::HasAddrs;
31
use tor_rtcompat::SleepProvider;
32
use tor_rtmock::MockRuntime;
33
use tor_rtmock::simple_time::SimpleMockTimeProvider;
34

            
35
use super::*;
36

            
37
const EXAMPLE_DESCRIPTOR: &str = include_str!("../../testdata/routerdesc1.txt");
38
const EXAMPLE_PORT: u16 = 9001;
39

            
40
12
fn example_validity() -> (SystemTime, SystemTime) {
41
    let bounds =
42
12
        parse2::parse_netdoc::<RouterDescUnverified>(&ParseInput::new(EXAMPLE_DESCRIPTOR, "test"))
43
12
            .unwrap()
44
12
            .verify()
45
12
            .unwrap()
46
12
            .bounds();
47
12
    let (t, u) = (bounds.start(), bounds.end());
48
24
    let ret = |tb| match tb {
49
24
        Some(t) => t,
50
        None => panic!("Time range does not have a starting bound"),
51
24
    };
52
12
    (ret(t), ret(u))
53
12
}
54
8
fn example_wallclock() -> SystemTime {
55
8
    example_validity().0 + Duration::from_secs(10)
56
8
}
57

            
58
type R = MockRuntime;
59
type M = Mock;
60
type Bdm = BridgeDescMgr<R, M>;
61
type RT = RetryTime;
62
use Error::TestError as TE;
63

            
64
#[derive(Debug, Clone)]
65
struct Mock {
66
    sleep: SimpleMockTimeProvider,
67

            
68
    // Using an async mutex lets us block a call to `download`
69
    // so we can see what the state is mid-download.
70
    mstate: Arc<futures::lock::Mutex<MockState>>,
71
}
72

            
73
const MOCK_NOT_MODIFIED: &str = "IF-MODIFIED-SINCE ";
74

            
75
struct MockState {
76
    /// Maps the port number for a download, to what we should return
77
    ///
78
    /// If the Ok string starts with `MOCK_NOT_MODIFIED` then the rest is the Debug
79
    /// output from a SystemTime.   In this case the manager is supposed to pass
80
    /// `if_modified_since` as `Some(that SystemTime)`, and we will actually return `None`.
81
    ///
82
    /// Otherwise the `if_modified_since` from the manager will be ignored
83
    /// and we always give it Some.
84
    docs: HashMap<u16, Result<String, Error>>,
85

            
86
    download_calls: usize,
87
}
88

            
89
impl Mockable<R> for Mock {}
90

            
91
#[async_trait]
92
impl mockable::MockableAPI<R> for Mock {
93
    type CircMgr = ();
94

            
95
    async fn download(
96
        self,
97
        _runtime: &R,
98
        _circmgr: &Self::CircMgr,
99
        bridge: &BridgeConfig,
100
        if_modified_since: Option<SystemTime>,
101
44
    ) -> Result<Option<String>, Error> {
102
        eprint!("download ...");
103
        let mut mstate = self.mstate.lock().await;
104
        mstate.download_calls += 1;
105
        eprintln!("#{} {:?}", mstate.download_calls, bridge);
106
        let addr = bridge
107
            .addrs()
108
            .next()
109
            .ok_or(TE("bridge has no error", RT::Never))?;
110
        let doc = mstate
111
            .docs
112
            .get(&addr.port())
113
            .ok_or(TE("no document", RT::AfterWaiting))?;
114
12
        doc.clone().map(|text| {
115
12
            if let Some(expect_ims) = text.strip_prefix(MOCK_NOT_MODIFIED) {
116
2
                eprintln!("#{} {:?}", mstate.download_calls, text);
117
2
                assert_eq!(format!("{:?}", if_modified_since.unwrap()), expect_ims,);
118
2
                None
119
            } else {
120
10
                Some(text)
121
            }
122
12
        })
123
44
    }
124
}
125

            
126
impl Mock {
127
20
    async fn expect_download_calls(&self, expected: usize) {
128
20
        let mut mstate = self.mstate.lock().await;
129
20
        assert_eq!(mstate.download_calls, expected);
130
20
        mstate.download_calls = 0;
131
20
    }
132
}
133

            
134
8
fn setup(runtime: MockRuntime) -> (TempDir, Bdm, R, M, BridgeKey, rusqlite::Connection) {
135
8
    let sleep = runtime.mock_sleep().clone();
136
8
    sleep.jump_wallclock(example_wallclock());
137

            
138
8
    let mut docs = HashMap::new();
139
8
    docs.insert(EXAMPLE_PORT, Ok(EXAMPLE_DESCRIPTOR.into()));
140

            
141
8
    let mstate = Arc::new(futures::lock::Mutex::new(MockState {
142
8
        docs,
143
8
        download_calls: 0,
144
8
    }));
145

            
146
8
    let mock = Mock { sleep, mstate };
147

            
148
8
    let (db_tmp_dir, store) = crate::storage::sqlite::test::new_empty().unwrap();
149
8
    let store = Arc::new(Mutex::new(Box::new(store) as _));
150

            
151
8
    let sql_path = db_tmp_dir.path().join("db.sql");
152
8
    let conn = rusqlite::Connection::open(sql_path).unwrap();
153

            
154
8
    let bdm = BridgeDescMgr::<R, M>::new_internal(
155
8
        runtime.clone(),
156
8
        (),
157
8
        store,
158
8
        &Default::default(),
159
8
        Dormancy::Active,
160
8
        mock.clone(),
161
8
    )
162
8
    .unwrap();
163

            
164
8
    let bridge = "51.68.172.83:9001 EB6EFB27F29AC9511A4246D7ABE1AFABFB416FF1"
165
8
        .parse()
166
8
        .unwrap();
167

            
168
8
    (db_tmp_dir, bdm, runtime, mock, bridge, conn)
169
8
}
170

            
171
10
async fn stream_drain_ready<S: Stream + Unpin + FusedStream>(s: &mut S) -> usize {
172
10
    let mut count = 0;
173
12
    while select_biased! {
174
12
        _ = s.next() => true,
175
12
        () = future::ready(()) => false,
176
    } {
177
2
        tor_rtcompat::task::yield_now().await;
178
2
        count += 1;
179
    }
180
10
    count
181
10
}
182

            
183
24
async fn stream_drain_until<S, F, FF, Y>(attempts: usize, s: &mut S, mut f: F) -> Y
184
24
where
185
24
    S: Stream + Unpin + FusedStream,
186
24
    S::Item: Debug,
187
24
    F: FnMut() -> FF,
188
24
    FF: Future<Output = Option<Y>>,
189
24
{
190
24
    for _ in 0..attempts {
191
36
        let event = s.next().await;
192
36
        eprintln!("stream_drain_until, got {:?}", event);
193

            
194
36
        if let Some(y) = f().await {
195
24
            return y;
196
12
        }
197
    }
198
    panic!("untilness didn't occur");
199
24
}
200

            
201
6
fn queues_are_empty(bdm: &Bdm) -> Option<()> {
202
6
    let state = bdm.mgr.lock_only();
203
6
    (state.running.is_empty() && state.queued.is_empty()).then_some(())
204
6
}
205

            
206
12
fn in_results(bdm: &Bdm, bridge: &BridgeKey, wanted: Option<Result<(), ()>>) -> Option<()> {
207
12
    let bridges = bdm.bridges();
208
12
    let got = bridges.get(bridge);
209
12
    let got = got.map(|got| got.as_ref().map(|_| ()).map_err(|_| ()));
210
12
    (got == wanted).then_some(())
211
12
}
212

            
213
4
async fn clear_and_re_request<S>(bdm: &Bdm, events: &mut S, bridge: &BridgeKey)
214
4
where
215
4
    S: Stream + Unpin + FusedStream,
216
4
    S::Item: Debug,
217
4
{
218
4
    bdm.set_bridges(&[]);
219
4
    stream_drain_until(3, events, || async {
220
4
        in_results(bdm, bridge, None)
221
4
            .and_then(|()| bdm.mgr.lock_only().running.is_empty().then_some(()))
222
8
    })
223
4
    .await;
224
4
    bdm.set_bridges(std::slice::from_ref(bridge));
225
4
}
226

            
227
12
fn bad_bridge(i: usize) -> BridgeKey {
228
12
    let bad = format!("192.126.0.1:{} EB6EFB27F29AC9511A4246D7ABE1AFABFB416FF1", i);
229
12
    let bad: BridgeConfig = bad.parse().unwrap();
230
12
    bad
231
12
}
232

            
233
#[traced_test]
234
#[test]
235
1
fn success() -> Result<(), anyhow::Error> {
236
2
    MockRuntime::try_test_with_various(|runtime| async {
237
2
        let (_db_tmp_dir, bdm, runtime, mock, bridge, ..) = setup(runtime);
238

            
239
2
        bdm.check_consistency(Some([]));
240

            
241
2
        let mut events = bdm.events().fuse();
242

            
243
2
        eprintln!("----- test downloading one descriptor -----");
244

            
245
2
        stream_drain_ready(&mut events).await;
246

            
247
2
        let hold = mock.mstate.lock().await;
248

            
249
2
        bdm.set_bridges(std::slice::from_ref(&bridge));
250
2
        bdm.check_consistency(Some([&bridge]));
251

            
252
2
        drop(hold);
253

            
254
2
        let got = stream_drain_until(3, &mut events, || async {
255
2
            bdm.bridges().get(&bridge).cloned()
256
4
        })
257
2
        .await;
258

            
259
2
        dbg!(runtime.wallclock(), example_validity(),);
260

            
261
2
        eprintln!("got: {:?}", got.unwrap());
262

            
263
2
        bdm.check_consistency(Some([&bridge]));
264
2
        mock.expect_download_calls(1).await;
265

            
266
2
        eprintln!("----- add a number of failing descriptors -----");
267

            
268
        const NFAIL: usize = 6;
269

            
270
2
        let bad = (1..=NFAIL).map(bad_bridge).collect_vec();
271

            
272
2
        let mut bridges = chain!(iter::once(bridge.clone()), bad.iter().cloned(),).collect_vec();
273

            
274
2
        let hold = mock.mstate.lock().await;
275

            
276
2
        bdm.set_bridges(&bridges);
277
2
        bdm.check_consistency(Some(&bridges));
278

            
279
2
        drop(hold);
280

            
281
6
        let () = stream_drain_until(13, &mut events, || async {
282
6
            bdm.check_consistency(Some(&bridges));
283
6
            bridges
284
6
                .iter()
285
28
                .all(|b| bdm.bridges().contains_key(b))
286
6
                .then_some(())
287
12
        })
288
2
        .await;
289

            
290
2
        for b in &bad {
291
12
            bdm.bridges().get(b).unwrap().as_ref().unwrap_err();
292
        }
293

            
294
2
        bdm.check_consistency(Some(&bridges));
295
2
        mock.expect_download_calls(NFAIL).await;
296

            
297
2
        eprintln!("----- move the clock forward to do some retries ----------");
298

            
299
2
        mock.sleep.advance(Duration::from_secs(5000));
300

            
301
2
        bdm.check_consistency(Some(&bridges));
302

            
303
6
        let () = stream_drain_until(13, &mut events, || async {
304
6
            bdm.check_consistency(Some(&bridges));
305
6
            (mock.mstate.lock().await.download_calls == NFAIL).then_some(())
306
12
        })
307
2
        .await;
308

            
309
2
        stream_drain_ready(&mut events).await;
310

            
311
2
        bdm.check_consistency(Some(&bridges));
312
2
        mock.expect_download_calls(NFAIL).await;
313

            
314
2
        eprintln!("----- set the bridges to the ones we have already ----------");
315

            
316
2
        let hold = mock.mstate.lock().await;
317

            
318
2
        bdm.set_bridges(&bridges);
319
2
        bdm.check_consistency(Some(&bridges));
320

            
321
2
        drop(hold);
322

            
323
2
        let events_counted = stream_drain_ready(&mut events).await;
324
2
        assert_eq!(events_counted, 0);
325
2
        bdm.check_consistency(Some(&bridges));
326
2
        mock.expect_download_calls(0).await;
327

            
328
2
        eprintln!("----- set the bridges to one fewer than we have already ----------");
329

            
330
2
        let _ = bridges.pop().unwrap();
331

            
332
2
        let hold = mock.mstate.lock().await;
333

            
334
2
        bdm.set_bridges(&bridges);
335
2
        bdm.check_consistency(Some(&bridges));
336

            
337
2
        drop(hold);
338

            
339
2
        let events_counted = stream_drain_ready(&mut events).await;
340
2
        assert_eq!(events_counted, 1);
341
2
        bdm.check_consistency(Some(&bridges));
342
2
        mock.expect_download_calls(0).await;
343

            
344
2
        eprintln!("----- remove a bridge while we have some requeued ----------");
345

            
346
2
        let hold = mock.mstate.lock().await;
347

            
348
2
        mock.sleep.advance(Duration::from_secs(8000));
349
2
        bdm.check_consistency(Some(&bridges));
350

            
351
        // should yield, but not produce any events yet
352
2
        let count = stream_drain_ready(&mut events).await;
353
2
        assert_eq!(count, 0);
354
2
        bdm.check_consistency(Some(&bridges));
355

            
356
2
        let removed = bridges.pop().unwrap();
357
2
        bdm.set_bridges(&bridges);
358

            
359
        // should produce a removed bridge event
360
2
        let () = stream_drain_until(1, &mut events, || async {
361
2
            bdm.check_consistency(Some(&bridges));
362
2
            (!bdm.bridges().contains_key(&removed)).then_some(())
363
4
        })
364
2
        .await;
365

            
366
2
        drop(hold);
367

            
368
        // Check that queues become empty.
369
        // Depending on scheduling, there may be tasks still live from the work above.
370
        // For example, one of the requeues might be still running after we did the remove.
371
        // So we may get a number of change events.  Certainly not more than 10.
372
6
        let () = stream_drain_until(10, &mut events, || async {
373
6
            bdm.check_consistency(Some(&bridges));
374
6
            queues_are_empty(&bdm)
375
12
        })
376
2
        .await;
377

            
378
        {
379
            // When we cancel the download, we race with the manager.
380
            // Maybe the download for the one we removed was started, or maybe not.
381
2
            let mut mstate = mock.mstate.lock().await;
382
2
            assert!(
383
2
                ((NFAIL - 1)..=NFAIL).contains(&mstate.download_calls),
384
                "{:?}",
385
                mstate.download_calls
386
            );
387
2
            mstate.download_calls = 0;
388
        }
389

            
390
2
        Ok(())
391
4
    })
392
1
}
393

            
394
#[traced_test]
395
#[test]
396
1
fn cache() -> Result<(), anyhow::Error> {
397
2
    MockRuntime::try_test_with_various(|runtime| async {
398
2
        let (_db_tmp_path, bdm, runtime, mock, bridge, sql_conn, ..) = setup(runtime);
399
2
        let mut events = bdm.events().fuse();
400

            
401
6
        let in_results = |wanted| in_results(&bdm, &bridge, wanted);
402

            
403
2
        eprintln!("----- test that a downloaded descriptor goes into the cache -----");
404

            
405
2
        bdm.set_bridges(std::slice::from_ref(&bridge));
406
4
        stream_drain_until(3, &mut events, || async { in_results(Some(Ok(()))) }).await;
407

            
408
2
        mock.expect_download_calls(1).await;
409

            
410
2
        sql_conn
411
2
            .query_row("SELECT * FROM BridgeDescs", [], |row| {
412
                let get_time =
413
4
                    |f| -> SystemTime { row.get_unwrap::<&str, OffsetDateTime>(f).into() };
414
2
                let bline: String = row.get_unwrap("bridge_line");
415
2
                let fetched: SystemTime = get_time("fetched");
416
2
                let until: SystemTime = get_time("until");
417
2
                let contents: String = row.get_unwrap("contents");
418
2
                let now = runtime.wallclock();
419
2
                assert_eq!(bline, bridge.to_string());
420
2
                assert!(fetched <= now);
421
2
                assert!(now < until);
422
2
                assert_eq!(contents, EXAMPLE_DESCRIPTOR);
423
2
                Ok(())
424
2
            })
425
            .unwrap();
426

            
427
2
        eprintln!("----- forget the descriptor and try to reload it from the cache -----");
428

            
429
2
        clear_and_re_request(&bdm, &mut events, &bridge).await;
430
4
        stream_drain_until(3, &mut events, || async { in_results(Some(Ok(()))) }).await;
431

            
432
        // Should not have been re-downloaded, since the fetch time is great.
433
2
        mock.expect_download_calls(0).await;
434

            
435
2
        eprintln!("----- corrupt the cache and check we re-download -----");
436

            
437
2
        sql_conn
438
2
            .execute_batch("UPDATE BridgeDescs SET contents = 'garbage'")
439
2
            .unwrap();
440

            
441
2
        clear_and_re_request(&bdm, &mut events, &bridge).await;
442
4
        stream_drain_until(3, &mut events, || async { in_results(Some(Ok(()))) }).await;
443

            
444
2
        mock.expect_download_calls(1).await;
445

            
446
2
        eprintln!("----- advance the lock and check that we do an if-modified-since -----");
447

            
448
2
        let published = bdm
449
2
            .bridges()
450
2
            .get(&bridge)
451
2
            .unwrap()
452
2
            .as_ref()
453
2
            .unwrap()
454
2
            .as_ref()
455
2
            .published();
456

            
457
2
        mock.mstate.lock().await.docs.insert(
458
2
            EXAMPLE_PORT,
459
2
            Ok(format!("{}{:?}", MOCK_NOT_MODIFIED, published)),
460
        );
461

            
462
        // Exceeds default max_refetch
463
2
        mock.sleep.advance(Duration::from_secs(20000));
464

            
465
2
        stream_drain_until(3, &mut events, || async {
466
2
            (mock.mstate.lock().await.download_calls > 0).then_some(())
467
4
        })
468
2
        .await;
469

            
470
2
        mock.expect_download_calls(1).await;
471

            
472
2
        Ok(())
473
4
    })
474
1
}
475

            
476
#[traced_test]
477
#[test]
478
1
fn dormant() -> Result<(), anyhow::Error> {
479
2
    MockRuntime::try_test_with_various(|runtime| async {
480
        #[allow(unused_variables)] // avoids churn and makes all of these identical
481
2
        let (db_tmp_path, bdm, runtime, mock, bridge, sql_conn, ..) = setup(runtime);
482
2
        let mut events = bdm.events().fuse();
483

            
484
        use Dormancy::*;
485

            
486
2
        eprintln!("----- become dormant, but request a bridge -----");
487
2
        bdm.set_dormancy(Dormant);
488
2
        bdm.set_bridges(std::slice::from_ref(&bridge));
489

            
490
        // Drive all tasks until we are idle
491
2
        runtime.progress_until_stalled().await;
492

            
493
2
        eprintln!("----- become active -----");
494
2
        bdm.set_dormancy(Active);
495
        // This should immediately trigger the download:
496

            
497
2
        stream_drain_until(3, &mut events, || async {
498
2
            in_results(&bdm, &bridge, Some(Ok(())))
499
4
        })
500
2
        .await;
501
2
        mock.expect_download_calls(1).await;
502

            
503
2
        Ok(())
504
4
    })
505
1
}
506

            
507
#[traced_test]
508
#[test]
509
1
fn process_doc() -> Result<(), anyhow::Error> {
510
2
    MockRuntime::try_test_with_various(|runtime| async {
511
        #[allow(unused_variables)] // avoids churn and makes all of these identical
512
2
        let (db_tmp_path, bdm, runtime, mock, bridge, sql_conn, ..) = setup(runtime);
513

            
514
2
        let text = EXAMPLE_DESCRIPTOR;
515
2
        let config = BridgeDescDownloadConfig::default();
516
2
        let valid = example_validity();
517

            
518
44
        let pr_t = |s: &str, t: SystemTime| {
519
44
            let now = runtime.wallclock();
520
44
            eprintln!(
521
                "                  {:10} {:?} {:10}",
522
44
                s,
523
44
                t,
524
44
                t.duration_since(UNIX_EPOCH).unwrap().as_secs_f64()
525
44
                    - now.duration_since(UNIX_EPOCH).unwrap().as_secs_f64(),
526
            );
527
44
        };
528

            
529
14
        let expecting_of = |text: &str, exp: Result<SystemTime, &str>| {
530
14
            let got = process_document(&runtime, &config, text);
531
14
            match exp {
532
                Ok(exp_refetch) => {
533
8
                    let refetch = got.unwrap().refetch;
534
8
                    pr_t("refetch", refetch);
535
8
                    assert_eq!(refetch, exp_refetch);
536
                }
537
                Err(exp_msg) => {
538
6
                    let msg = got.as_ref().expect_err(exp_msg).to_string();
539
6
                    assert!(
540
6
                        msg.contains(exp_msg),
541
                        "{:?} {:?} exp={:?}",
542
                        msg,
543
                        got,
544
                        exp_msg
545
                    );
546
                }
547
            }
548
14
        };
549

            
550
10
        let expecting_at = |now: SystemTime, exp| {
551
10
            mock.sleep.jump_wallclock(now);
552
10
            pr_t("now", now);
553
10
            pr_t("valid.0", valid.0);
554
10
            pr_t("valid.1", valid.1);
555
10
            if let Ok(exp) = exp {
556
6
                pr_t("expect", exp);
557
4
            }
558
10
            expecting_of(text, exp);
559
10
        };
560

            
561
2
        let secs = Duration::from_secs;
562

            
563
2
        eprintln!("----- good -----");
564
2
        expecting_of(text, Ok(runtime.wallclock() + config.max_refetch));
565

            
566
2
        eprintln!("----- modified under signature -----");
567
2
        expecting_of(
568
2
            &text.replace("\nbandwidth 10485760", "\nbandwidth 10485761"),
569
2
            Err("Signature check failed"),
570
2
        );
571

            
572
2
        eprintln!("----- doc not yet valid -----");
573
2
        expecting_at(
574
2
            valid.0 - secs(10),
575
2
            Err("Descriptor is outside its validity time"),
576
2
        );
577

            
578
2
        eprintln!("----- need to refetch due to doc validity expiring soon -----");
579
2
        expecting_at(valid.1 - secs(5000), Ok(valid.1 - secs(1000)));
580

            
581
2
        eprintln!("----- will refetch later than usual, due to min refetch interval -----");
582
        {
583
2
            let now = valid.1 - secs(4000); // would want to refetch at valid.1-1000 ie 30000
584
2
            expecting_at(now, Ok(now + config.min_refetch));
585
        }
586

            
587
2
        eprintln!("----- will refetch after doc validity ends, due to min refetch interval -----");
588
        {
589
2
            let now = valid.1 - secs(10);
590
2
            let exp = now + config.min_refetch;
591
2
            assert!(exp > valid.1);
592
2
            expecting_at(now, Ok(exp));
593
        }
594

            
595
2
        eprintln!("----- expired -----");
596
2
        expecting_at(
597
2
            valid.1 + secs(10),
598
2
            Err("Descriptor is outside its validity time"),
599
2
        );
600

            
601
        // TODO ideally we would test the unbounded case in process_download's
602
        // expiry time handling, but that would require making a document with unbounded
603
        // validity time.  Even if that is possible, I don't think we have code in-tree to
604
        // make signed test documents.
605

            
606
2
        Ok(())
607
4
    })
608
1
}