1
//! Parsing implementation for Tor microdescriptors.
2
//!
3
//! A "microdescriptor" is an incomplete, infrequently-changing
4
//! summary of a relay's information that is generated by
5
//! the directory authorities.
6
//!
7
//! Microdescriptors are much smaller than router descriptors, and
8
//! change less frequently. For this reason, they're currently used
9
//! for building circuits by all relays and clients.
10
//!
11
//! Microdescriptors can't be used on their own: you need to know
12
//! which relay they are for, which requires a valid consensus
13
//! directory.
14

            
15
use crate::parse::keyword::Keyword;
16
use crate::parse::parser::SectionRules;
17
use crate::parse::tokenize::{ItemResult, NetDocReader};
18
use crate::types::family::{RelayFamily, RelayFamilyId, RelayFamilyIds};
19
use crate::types::misc::*;
20
use crate::types::policy::PortPolicy;
21
use crate::util;
22
use crate::util::PeekableIterator;
23
use crate::util::str::Extent;
24
use crate::{AllowAnnotations, Error, NetdocErrorKind as EK, Result};
25
use tor_error::internal;
26
use tor_llcrypto::d;
27
use tor_llcrypto::pk::{curve25519, ed25519, rsa};
28

            
29
use derive_deftly::Deftly;
30
use digest::Digest;
31
use std::str::FromStr as _;
32
use std::sync::Arc;
33
use std::sync::LazyLock;
34
use std::time;
35

            
36
#[cfg(feature = "build_docs")]
37
mod build;
38

            
39
#[cfg(feature = "build_docs")]
40
pub use build::MicrodescBuilder;
41

            
42
/// Length of a router microdescriptor digest
43
pub const DOC_DIGEST_LEN: usize = 32;
44

            
45
/// Annotations prepended to a microdescriptor that has been stored to
46
/// disk.
47
#[allow(dead_code)]
48
#[derive(Clone, Debug, Default)]
49
pub struct MicrodescAnnotation {
50
    /// A time at which this microdescriptor was last listed in some
51
    /// consensus document.
52
    last_listed: Option<time::SystemTime>,
53
}
54

            
55
/// The digest of a microdescriptor as used in microdesc consensuses
56
pub type MdDigest = [u8; DOC_DIGEST_LEN];
57

            
58
/// A single microdescriptor.
59
///
60
/// <https://spec.torproject.org/dir-spec/computing-microdescriptors.html>
61
#[derive(Clone, Debug, Deftly, PartialEq, Eq)]
62
#[derive_deftly(NetdocParseable)]
63
#[non_exhaustive]
64
pub struct Microdesc {
65
    /// The legacy onion key, whose object is optional but whose item serves
66
    /// as the intro line for these kind of descriptors.
67
    ///
68
    /// Let's keep this private for now to prevent interfacing applications
69
    /// from generating microdesc's with an onion-key; they are not necessary
70
    /// anymore and just waste space.
71
    onion_key: OnionKeyIntro,
72

            
73
    /// Public key used for the ntor circuit extension protocol.
74
    #[deftly(netdoc(single_arg))]
75
    pub ntor_onion_key: Curve25519Public,
76

            
77
    /// Declared family for this relay.
78
    #[deftly(netdoc(default))]
79
    pub family: Arc<RelayFamily>,
80

            
81
    /// Family identities for this relay.
82
    #[deftly(netdoc(default))]
83
    pub family_ids: RelayFamilyIds,
84

            
85
    /// List of IPv4 ports to which this relay will exit
86
    #[deftly(netdoc(keyword = "p", default))]
87
    pub ipv4_policy: Arc<PortPolicy>,
88

            
89
    /// List of IPv6 ports to which this relay will exit
90
    #[deftly(netdoc(keyword = "p6", default))]
91
    pub ipv6_policy: Arc<PortPolicy>,
92

            
93
    /// Ed25519 identity for this relay
94
    // TODO SPEC: Set this to "exactly once".
95
    #[deftly(netdoc(keyword = "id", with = "Ed25519IdentityLine"))]
96
    pub ed25519_id: Ed25519IdentityLine,
97

            
98
    // addr is obsolete and doesn't go here any more
99
    // pr is obsolete and doesn't go here any more.
100
    /// The SHA256 digest of the text of this microdescriptor.  This
101
    /// value is used to identify the microdescriptor when downloading
102
    /// it, and when listing it in a consensus document.
103
    // TODO: maybe this belongs somewhere else. Once it's used to store
104
    // correlate the microdesc to a consensus, it's never used again.
105
    #[deftly(netdoc(skip))]
106
    pub sha256: MdDigest,
107
}
108

            
109
impl Microdesc {
110
    /// Create a new MicrodescBuilder that can be used to construct
111
    /// microdescriptors.
112
    ///
113
    /// This function is only available when the crate is built with the
114
    /// `build_docs` feature.
115
    ///
116
    /// # Limitations
117
    ///
118
    /// The generated microdescriptors cannot yet be encoded, and do
119
    /// not yet have correct sha256 digests. As such they are only
120
    /// useful for testing.
121
    #[cfg(feature = "build_docs")]
122
477366
    pub fn builder() -> MicrodescBuilder {
123
477366
        MicrodescBuilder::new()
124
477366
    }
125

            
126
    /// Return the sha256 digest of this microdesc.
127
72943634
    pub fn digest(&self) -> &MdDigest {
128
72943634
        &self.sha256
129
72943634
    }
130
    /// Return the ntor onion key for this microdesc
131
2027056
    pub fn ntor_key(&self) -> &curve25519::PublicKey {
132
2027056
        &self.ntor_onion_key.0
133
2027056
    }
134
    /// Return the ipv4 exit policy for this microdesc
135
46905760
    pub fn ipv4_policy(&self) -> &Arc<PortPolicy> {
136
46905760
        &self.ipv4_policy
137
46905760
    }
138
    /// Return the ipv6 exit policy for this microdesc
139
6531040
    pub fn ipv6_policy(&self) -> &Arc<PortPolicy> {
140
6531040
        &self.ipv6_policy
141
6531040
    }
142
    /// Return the relay family for this microdesc
143
58577532
    pub fn family(&self) -> &RelayFamily {
144
58577532
        self.family.as_ref()
145
58577532
    }
146
    /// Return the ed25519 identity for this microdesc, if its
147
    /// Ed25519 identity is well-formed.
148
170694490
    pub fn ed25519_id(&self) -> &ed25519::Ed25519Identity {
149
170694490
        &self.ed25519_id.pk.0
150
170694490
    }
151
    /// Return a list of family ids for this microdesc.
152
111551154
    pub fn family_ids(&self) -> &[RelayFamilyId] {
153
111551154
        self.family_ids.as_ref()
154
111551154
    }
155
}
156

            
157
/// Intro line for a [`Microdesc`].
158
///
159
/// The object (the onion key) is deprecated and optional, but the item itself
160
/// must be present, because it is used to mark the start of the netdoc.
161
#[derive(Debug, Clone, Default, Deftly, PartialEq, Eq)]
162
#[derive_deftly(ItemValueParseable)]
163
struct OnionKeyIntro(#[deftly(netdoc(object))] Option<rsa::PublicKey>);
164

            
165
/// A microdescriptor annotated with additional data
166
///
167
/// TODO: rename this.
168
#[allow(dead_code)]
169
#[derive(Clone, Debug)]
170
pub struct AnnotatedMicrodesc {
171
    /// The microdescriptor
172
    md: Microdesc,
173
    /// The annotations for the microdescriptor
174
    ann: MicrodescAnnotation,
175
    /// Where did we find the microdescriptor with the originally parsed
176
    /// string?
177
    location: Option<Extent>,
178
}
179

            
180
impl AnnotatedMicrodesc {
181
    /// Consume this annotated microdesc and discard its annotations.
182
378
    pub fn into_microdesc(self) -> Microdesc {
183
378
        self.md
184
378
    }
185

            
186
    /// Return a reference to the microdescriptor within this annotated
187
    /// microdescriptor.
188
18
    pub fn md(&self) -> &Microdesc {
189
18
        &self.md
190
18
    }
191

            
192
    /// If this Microdesc was parsed from `s`, return its original text.
193
378
    pub fn within<'a>(&self, s: &'a str) -> Option<&'a str> {
194
385
        self.location.as_ref().and_then(|ext| ext.reconstruct(s))
195
378
    }
196
}
197

            
198
decl_keyword! {
199
    /// Keyword type for recognized objects in microdescriptors.
200
    MicrodescKwd {
201
        annotation "@last-listed" => ANN_LAST_LISTED,
202
        "onion-key" => ONION_KEY,
203
        "ntor-onion-key" => NTOR_ONION_KEY,
204
        "family" => FAMILY,
205
        "family-ids" => FAMILY_IDS,
206
        "p" => P,
207
        "p6" => P6,
208
        "id" => ID,
209
    }
210
}
211

            
212
/// Rules about annotations that can appear before a Microdescriptor
213
2
static MICRODESC_ANNOTATIONS: LazyLock<SectionRules<MicrodescKwd>> = LazyLock::new(|| {
214
    use MicrodescKwd::*;
215
2
    let mut rules = SectionRules::builder();
216
2
    rules.add(ANN_LAST_LISTED.rule().args(1..));
217
2
    rules.add(ANN_UNRECOGNIZED.rule().may_repeat().obj_optional());
218
    // unrecognized annotations are okay; anything else is a bug in this
219
    // context.
220
2
    rules.reject_unrecognized();
221
2
    rules.build()
222
2
});
223
/// Rules about entries that must appear in an Microdesc, and how they must
224
/// be formed.
225
56
static MICRODESC_RULES: LazyLock<SectionRules<MicrodescKwd>> = LazyLock::new(|| {
226
    use MicrodescKwd::*;
227

            
228
56
    let mut rules = SectionRules::builder();
229
56
    rules.add(ONION_KEY.rule().required().no_args().obj_optional());
230
56
    rules.add(NTOR_ONION_KEY.rule().required().args(1..));
231
56
    rules.add(FAMILY.rule().args(1..));
232
56
    rules.add(FAMILY_IDS.rule().args(0..));
233
56
    rules.add(P.rule().args(2..));
234
56
    rules.add(P6.rule().args(2..));
235
56
    rules.add(ID.rule().may_repeat().args(2..));
236
56
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
237
56
    rules.build()
238
56
});
239

            
240
impl MicrodescAnnotation {
241
    /// Extract a (possibly empty) microdescriptor annotation from a
242
    /// reader.
243
    #[allow(dead_code)]
244
14
    fn parse_from_reader(
245
14
        reader: &mut NetDocReader<'_, MicrodescKwd>,
246
14
    ) -> Result<MicrodescAnnotation> {
247
        use MicrodescKwd::*;
248

            
249
29
        let mut items = reader.pause_at(|item| item.is_ok_with_non_annotation());
250
14
        let body = MICRODESC_ANNOTATIONS.parse(&mut items)?;
251

            
252
14
        let last_listed = match body.get(ANN_LAST_LISTED) {
253
6
            None => None,
254
8
            Some(item) => Some(item.args_as_str().parse::<Iso8601TimeSp>()?.into()),
255
        };
256

            
257
14
        Ok(MicrodescAnnotation { last_listed })
258
14
    }
259
}
260

            
261
impl Microdesc {
262
    /// Parse a string into a new microdescriptor.
263
66
    pub fn parse(s: &str) -> Result<Microdesc> {
264
66
        let mut items = crate::parse::tokenize::NetDocReader::new(s)?;
265
70
        let (result, _) = Self::parse_from_reader(&mut items).map_err(|e| e.within(s))?;
266
58
        items.should_be_exhausted()?;
267
58
        Ok(result)
268
66
    }
269

            
270
    /// Extract a single microdescriptor from a NetDocReader.
271
    #[allow(clippy::string_slice)] // TODO
272
462
    fn parse_from_reader(
273
462
        reader: &mut NetDocReader<'_, MicrodescKwd>,
274
462
    ) -> Result<(Microdesc, Option<Extent>)> {
275
        use MicrodescKwd::*;
276
462
        let s = reader.str();
277

            
278
462
        let mut first_onion_key = true;
279
        // We'll pause at the next annotation, or at the _second_ onion key.
280
1841
        let mut items = reader.pause_at(|item| match item {
281
            Err(_) => false,
282
1818
            Ok(item) => {
283
1818
                item.kwd().is_annotation()
284
1812
                    || if item.kwd() == ONION_KEY {
285
738
                        let was_first = first_onion_key;
286
738
                        first_onion_key = false;
287
738
                        !was_first
288
                    } else {
289
1074
                        false
290
                    }
291
            }
292
1818
        });
293

            
294
462
        let body = MICRODESC_RULES.parse(&mut items)?;
295

            
296
        // We have to start with onion-key
297
458
        let start_pos = {
298
            // unwrap here is safe because parsing would have failed
299
            // had there not been at least one item.
300
            #[allow(clippy::unwrap_used)]
301
462
            let first = body.first_item().unwrap();
302
462
            if first.kwd() != ONION_KEY {
303
4
                return Err(EK::WrongStartingToken
304
4
                    .with_msg(first.kwd_str().to_string())
305
4
                    .at_pos(first.pos()));
306
458
            }
307
            // Unwrap is safe here because we are parsing these strings from s
308
            #[allow(clippy::unwrap_used)]
309
458
            util::str::str_offset(s, first.kwd_str()).unwrap()
310
        };
311

            
312
        // Legacy (tap) onion key.  We parse this to make sure it's well-formed,
313
        // but then we discard it immediately, since we never want to use it.
314
        //
315
        // In microdescriptors, the ONION_KEY field is mandatory, but its
316
        // associated object is optional.
317
        {
318
458
            let tok = body.required(ONION_KEY)?;
319
458
            if tok.has_obj() {
320
452
                let _: rsa::PublicKey = tok
321
452
                    .parse_obj::<RsaPublicParse1Helper>("RSA PUBLIC KEY")?
322
452
                    .check_len_eq(1024)?
323
452
                    .check_exponent(65537)?
324
452
                    .into();
325
6
            }
326
        }
327

            
328
        // Ntor onion key
329
458
        let ntor_onion_key = body
330
458
            .required(NTOR_ONION_KEY)?
331
458
            .parse_arg::<Curve25519Public>(0)?;
332

            
333
        // family
334
        //
335
        // (We don't need to add the relay's own ID to this family, as we do in
336
        // RouterDescs: the authorities already took care of that for us.)
337
458
        let family = body
338
458
            .maybe(FAMILY)
339
458
            .parse_args_as_str::<RelayFamily>()?
340
458
            .unwrap_or_else(RelayFamily::new)
341
458
            .intern();
342

            
343
        // Family ids (happy families case).
344
458
        let family_ids = body
345
458
            .maybe(FAMILY_IDS)
346
458
            .args_as_str()
347
458
            .unwrap_or("")
348
458
            .split_ascii_whitespace()
349
458
            .map(RelayFamilyId::from_str)
350
458
            .collect::<Result<RelayFamilyIds>>()?;
351

            
352
        // exit policies.
353
458
        let ipv4_policy = body
354
458
            .maybe(P)
355
458
            .parse_args_as_str::<PortPolicy>()?
356
458
            .unwrap_or_else(PortPolicy::new_reject_all);
357
458
        let ipv6_policy = body
358
458
            .maybe(P6)
359
458
            .parse_args_as_str::<PortPolicy>()?
360
454
            .unwrap_or_else(PortPolicy::new_reject_all);
361

            
362
        // ed25519 identity
363
450
        let ed25519_id = {
364
454
            let id_tok = body
365
454
                .slice(ID)
366
454
                .iter()
367
473
                .find(|item| item.arg(0) == Some("ed25519"));
368
454
            match id_tok {
369
                None => {
370
4
                    return Err(EK::MissingToken.with_msg("id ed25519"));
371
                }
372
450
                Some(tok) => Ed25519IdentityLine {
373
450
                    alg: Ed25519AlgorithmString::Ed25519,
374
450
                    pk: tok.parse_arg::<Ed25519Public>(1)?,
375
                },
376
            }
377
        };
378

            
379
450
        let end_pos = {
380
            // unwrap here is safe because parsing would have failed
381
            // had there not been at least one item.
382
            #[allow(clippy::unwrap_used)]
383
450
            let last_item = body.last_item().unwrap();
384
450
            last_item.offset_after(s).ok_or_else(|| {
385
                Error::from(internal!("last item was not within source string"))
386
                    .at_pos(last_item.end_pos())
387
            })?
388
        };
389

            
390
450
        let text = &s[start_pos..end_pos];
391
450
        let sha256 = d::Sha256::digest(text.as_bytes()).into();
392

            
393
450
        let location = Extent::new(s, text);
394

            
395
450
        let md = Microdesc {
396
450
            onion_key: Default::default(),
397
450
            sha256,
398
450
            ntor_onion_key,
399
450
            family,
400
450
            ipv4_policy: ipv4_policy.intern(),
401
450
            ipv6_policy: ipv6_policy.intern(),
402
450
            ed25519_id,
403
450
            family_ids,
404
450
        };
405
450
        Ok((md, location))
406
462
    }
407
}
408

            
409
/// Consume tokens from 'reader' until the next token is the beginning
410
/// of a microdescriptor: an annotation or an ONION_KEY.  If no such
411
/// token exists, advance to the end of the reader.
412
4
fn advance_to_next_microdesc(reader: &mut NetDocReader<'_, MicrodescKwd>, annotated: bool) {
413
    use MicrodescKwd::*;
414
    loop {
415
4
        let item = reader.peek();
416
2
        match item {
417
2
            Some(Ok(t)) => {
418
2
                let kwd = t.kwd();
419
2
                if (annotated && kwd.is_annotation()) || kwd == ONION_KEY {
420
2
                    return;
421
                }
422
            }
423
            Some(Err(_)) => {
424
                // We skip over broken tokens here.
425
                //
426
                // (This case can't happen in practice, since if there had been
427
                // any error tokens, they would have been handled as part of
428
                // handling the previous microdesc.)
429
            }
430
            None => {
431
2
                return;
432
            }
433
        };
434
        let _ = reader.next();
435
    }
436
4
}
437

            
438
/// An iterator that parses one or more (possibly annotated)
439
/// microdescriptors from a string.
440
#[derive(Debug)]
441
pub struct MicrodescReader<'a> {
442
    /// True if we accept annotations; false otherwise.
443
    annotated: bool,
444
    /// An underlying reader to give us Items for the microdescriptors
445
    reader: NetDocReader<'a, MicrodescKwd>,
446
}
447

            
448
impl<'a> MicrodescReader<'a> {
449
    /// Construct a MicrodescReader to take microdescriptors from a string
450
    /// 's'.
451
114
    pub fn new(s: &'a str, allow: &AllowAnnotations) -> Result<Self> {
452
114
        let reader = NetDocReader::new(s)?;
453
114
        let annotated = allow == &AllowAnnotations::AnnotationsAllowed;
454
114
        Ok(MicrodescReader { annotated, reader })
455
114
    }
456

            
457
    /// If we're annotated, parse an annotation from the reader. Otherwise
458
    /// return a default annotation.
459
396
    fn take_annotation(&mut self) -> Result<MicrodescAnnotation> {
460
396
        if self.annotated {
461
14
            MicrodescAnnotation::parse_from_reader(&mut self.reader)
462
        } else {
463
382
            Ok(MicrodescAnnotation::default())
464
        }
465
396
    }
466

            
467
    /// Parse a (possibly annotated) microdescriptor from the reader.
468
    ///
469
    /// On error, parsing stops after the first failure.
470
396
    fn take_annotated_microdesc_raw(&mut self) -> Result<AnnotatedMicrodesc> {
471
396
        let ann = self.take_annotation()?;
472
396
        let (md, location) = Microdesc::parse_from_reader(&mut self.reader)?;
473
392
        Ok(AnnotatedMicrodesc { md, ann, location })
474
396
    }
475

            
476
    /// Parse a (possibly annotated) microdescriptor from the reader.
477
    ///
478
    /// On error, advance the reader to the start of the next microdescriptor.
479
396
    fn take_annotated_microdesc(&mut self) -> Result<AnnotatedMicrodesc> {
480
396
        let pos_orig = self.reader.pos();
481
396
        let result = self.take_annotated_microdesc_raw();
482
396
        if result.is_err() {
483
4
            if self.reader.pos() == pos_orig {
484
                // No tokens were consumed from the reader.  We need to
485
                // drop at least one token to ensure we aren't looping.
486
                //
487
                // (This might not be able to happen, but it's easier to
488
                // explicitly catch this case than it is to prove that
489
                // it's impossible.)
490
                let _ = self.reader.next();
491
4
            }
492
4
            advance_to_next_microdesc(&mut self.reader, self.annotated);
493
392
        }
494
396
        result
495
396
    }
496
}
497

            
498
impl<'a> Iterator for MicrodescReader<'a> {
499
    type Item = Result<AnnotatedMicrodesc>;
500
510
    fn next(&mut self) -> Option<Self::Item> {
501
        // If there is no next token, we're at the end.
502
510
        self.reader.peek()?;
503

            
504
        Some(
505
396
            self.take_annotated_microdesc()
506
398
                .map_err(|e| e.within(self.reader.str())),
507
        )
508
510
    }
509
}
510

            
511
#[cfg(test)]
512
mod test {
513
    // @@ begin test lint list maintained by maint/add_warning @@
514
    #![allow(clippy::bool_assert_comparison)]
515
    #![allow(clippy::clone_on_copy)]
516
    #![allow(clippy::dbg_macro)]
517
    #![allow(clippy::mixed_attributes_style)]
518
    #![allow(clippy::print_stderr)]
519
    #![allow(clippy::print_stdout)]
520
    #![allow(clippy::single_char_pattern)]
521
    #![allow(clippy::unwrap_used)]
522
    #![allow(clippy::unchecked_time_subtraction)]
523
    #![allow(clippy::useless_vec)]
524
    #![allow(clippy::needless_pass_by_value)]
525
    #![allow(clippy::string_slice)] // See arti#2571
526
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
527
    use super::*;
528
    use hex_literal::hex;
529
    const TESTDATA: &str = include_str!("../../testdata/microdesc1.txt");
530
    const TESTDATA2: &str = include_str!("../../testdata/microdesc2.txt");
531
    const TESTDATA3: &str = include_str!("../../testdata/microdesc3.txt");
532
    const TESTDATA4: &str = include_str!("../../testdata/microdesc4.txt");
533

            
534
    fn read_bad(fname: &str) -> String {
535
        use std::fs;
536
        use std::path::PathBuf;
537
        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
538
        path.push("testdata");
539
        path.push("bad-mds");
540
        path.push(fname);
541

            
542
        fs::read_to_string(path).unwrap()
543
    }
544

            
545
    #[test]
546
    fn parse_single() -> Result<()> {
547
        let _md = Microdesc::parse(TESTDATA)?;
548
        Ok(())
549
    }
550

            
551
    #[test]
552
    fn parse_no_tap_key() -> Result<()> {
553
        let _md = Microdesc::parse(TESTDATA3)?;
554
        Ok(())
555
    }
556

            
557
    #[test]
558
    fn parse_multi() -> Result<()> {
559
        use humantime::parse_rfc3339;
560
        let mds: Result<Vec<_>> =
561
            MicrodescReader::new(TESTDATA2, &AllowAnnotations::AnnotationsAllowed)?.collect();
562
        let mds = mds?;
563
        assert_eq!(mds.len(), 4);
564

            
565
        assert_eq!(
566
            mds[0].ann.last_listed.unwrap(),
567
            parse_rfc3339("2020-01-27T18:52:09Z").unwrap()
568
        );
569
        assert_eq!(
570
            mds[0].md().digest(),
571
            &hex!("38c71329a87098cb341c46c9c62bd646622b4445f7eb985a0e6adb23a22ccf4f")
572
        );
573
        assert_eq!(
574
            mds[0].md().ntor_key().as_bytes(),
575
            &hex!("5e895d65304a3a1894616660143f7af5757fe08bc18045c7855ee8debb9e6c47")
576
        );
577
        assert!(mds[0].md().ipv4_policy().allows_port(993));
578
        assert!(mds[0].md().ipv6_policy().allows_port(993));
579
        assert!(!mds[0].md().ipv4_policy().allows_port(25));
580
        assert!(!mds[0].md().ipv6_policy().allows_port(25));
581
        assert_eq!(
582
            mds[0].md().ed25519_id().as_bytes(),
583
            &hex!("2d85fdc88e6c1bcfb46897fca1dba6d1354f93261d68a79e0b5bc170dd923084")
584
        );
585

            
586
        Ok(())
587
    }
588

            
589
    #[test]
590
    fn parse_family_ids() -> Result<()> {
591
        let mds: Vec<AnnotatedMicrodesc> =
592
            MicrodescReader::new(TESTDATA4, &AllowAnnotations::AnnotationsNotAllowed)?
593
                .collect::<Result<_>>()?;
594
        assert_eq!(mds.len(), 2);
595
        let md0 = mds[0].md();
596
        let md1 = mds[1].md();
597
        assert!(md0.family_ids().is_empty());
598
        assert_eq!(
599
            md1.family_ids(),
600
            &[
601
                "ed25519:dXMgdGhlIHRyaXVtcGguICAgIC1UaG9tYXMgUGFpbmU"
602
                    .parse()
603
                    .unwrap(),
604
                "other:Example".parse().unwrap()
605
            ]
606
        );
607
        assert!(matches!(md1.family_ids()[0], RelayFamilyId::Ed25519(_)));
608

            
609
        Ok(())
610
    }
611

            
612
    #[test]
613
    fn test_bad() {
614
        use crate::Pos;
615
        use crate::types::policy::PolicyError;
616
        fn check(fname: &str, e: &Error) {
617
            let content = read_bad(fname);
618
            let res = Microdesc::parse(&content);
619
            assert!(res.is_err());
620
            assert_eq!(&res.err().unwrap(), e);
621
        }
622

            
623
        check(
624
            "wrong-start",
625
            &EK::WrongStartingToken
626
                .with_msg("family")
627
                .at_pos(Pos::from_line(1, 1)),
628
        );
629
        check(
630
            "bogus-policy",
631
            &EK::BadPolicy
632
                .at_pos(Pos::from_line(9, 1))
633
                .with_source(PolicyError::InvalidPort),
634
        );
635
        check(
636
            "non-ascii-policy",
637
            &EK::BadPolicy
638
                .at_pos(Pos::from_line(9, 1))
639
                .with_source(PolicyError::InvalidPort),
640
        );
641
        check("wrong-id", &EK::MissingToken.with_msg("id ed25519"));
642
    }
643

            
644
    #[test]
645
    fn test_recover() -> Result<()> {
646
        let mut data = read_bad("wrong-start");
647
        data += TESTDATA;
648
        data += &read_bad("wrong-id");
649

            
650
        let res: Vec<Result<_>> =
651
            MicrodescReader::new(&data, &AllowAnnotations::AnnotationsAllowed)?.collect();
652

            
653
        assert_eq!(res.len(), 3);
654
        assert!(res[0].is_err());
655
        assert!(res[1].is_ok());
656
        assert!(res[2].is_err());
657
        Ok(())
658
    }
659

            
660
    /// Checks whether parse2 works on [`Microdesc`].
661
    ///
662
    /// Certain values such as public keys are hardcoded and can be simply
663
    /// replaced by a copy and paste in the case one replaces the testdata2
664
    /// vector's in the future.
665
    #[test]
666
    fn parse2() {
667
        use tor_llcrypto::pk::ed25519::Ed25519Identity;
668

            
669
        use crate::parse2;
670

            
671
        let md = include_str!("../../testdata2/cached-microdescs.new");
672
        let mds = parse2::parse_netdoc_multiple::<Microdesc>(&parse2::ParseInput::new(
673
            md,
674
            "../../testdata2/cached-microdescs.new",
675
        ))
676
        .unwrap();
677

            
678
        assert_eq!(mds.len(), 7);
679
        assert_eq!(
680
            mds[0],
681
            Microdesc {
682
                onion_key: OnionKeyIntro(rsa::PublicKey::from_der(
683
                    pem::parse(
684
                        "
685
-----BEGIN RSA PUBLIC KEY-----
686
MIGJAoGBANF8Zgxp8amY1esYdPj2Ada1ORiVB/A4sgKLQ5ij/wsasO3yjjLcvHRB
687
UJ0mAQWql/nauvjnKUeZFcGm3t7q0v3F9uUsOGTAZ/IKh31UQAm5OS/TJyf8IHky
688
Yl0wCKpUZFHs5CHsajLSfXZKHkwfqRXFEJu9aMtmQdQFfqE9JOJHAgMBAAE=
689
-----END RSA PUBLIC KEY-----
690
                        "
691
                    )
692
                    .unwrap()
693
                    .contents()
694
                )),
695
                sha256: [0; 32],
696
                ntor_onion_key: curve25519::PublicKey::from(<[u8; 32]>::from(
697
                    FixedB64::<32>::from_str("I1S8JfcqPPHWVTxfjq/eGmGiu/OtR+fF0Z86Ge1mq3s")
698
                        .unwrap()
699
                ))
700
                .into(),
701
                family: Default::default(),
702
                ipv4_policy: Default::default(),
703
                ipv6_policy: Default::default(),
704
                ed25519_id: Ed25519Identity::from(<[u8; 32]>::from(
705
                    FixedB64::<32>::from_str("yhO6nETO5AUdvJbLgPnw4mFjozGXWMCqOp30nY6nM8E")
706
                        .unwrap()
707
                ))
708
                .into(),
709
                family_ids: Default::default(),
710
            }
711
        );
712
    }
713

            
714
    /// Manual test for happy families.
715
    // TODO: This should be included in testdata2/ but that would require the
716
    // chutney/shadow integration test to actually do families at all.
717
    #[test]
718
    fn parse2_happy_family() {
719
        use tor_llcrypto::pk::ed25519::Ed25519Identity;
720

            
721
        use crate::parse2::{self, ParseInput};
722
        use std::iter;
723

            
724
        // A microdescriptor taken from the wild containing happy families.
725
        const MICRODESC: &str = "\
726
onion-key
727
-----BEGIN RSA PUBLIC KEY-----
728
MIGJAoGBAMk57F7qGHVadBJ6m4028w13I1Qk67Ee0JU88w7NObKBph3DQYjgYs4e
729
eUdiW4Gdsx8w/xOuK0foCo0O8Iqq5MXtVcpUP/N+5uB7SVvGdJFsKw21KdIc6v8g
730
ACZAijw5ZPOdhLbyLQyFHNV8zXUov1dlx/Fb9M3lPMVevnDbuKM5AgMBAAE=
731
-----END RSA PUBLIC KEY-----
732
ntor-onion-key fhhP23UKD4L2jehA5gopAo5b6NSoB+kZN5Q4ULv3Zww
733
family $4CFFD403DAB89A689F3FDB80B5366E46D879E736 $4D6C1486939A42D7FFE69BCD9F3FDAA86C743433 $73955E6A69BA5E0827F48206CAD78C045BBE8873 $8DBA9ADCA5B3A3AB6D2B4F88AC2F96614D33DAB3 $B29E3E30443F897F48B86765F1BC1DB917F5DF46 $CD642E7E722979580B6D631697772C0B72BCF25C $D9E7B6A73C8278274081B77D373ECCE4552E75FB $F2515315FE0DB7456194CABC503B526B49951415
734
family-ids ed25519:b54cKgML0ykRyhdIRcq1xtW19iEVsMYnGNbdY+vvcas
735
id ed25519 /MU/FVKRGcZAy8XFnzLS6Dgcg6s1VpYeFjkwb6+CVhw
736
";
737

            
738
        let md = parse2::parse_netdoc::<Microdesc>(&ParseInput::new(MICRODESC, "")).unwrap();
739
        assert_eq!(
740
            md.family_ids,
741
            RelayFamilyIds::from_iter(iter::once(RelayFamilyId::Ed25519(
742
                Ed25519Identity::from_base64("b54cKgML0ykRyhdIRcq1xtW19iEVsMYnGNbdY+vvcas")
743
                    .unwrap()
744
            )))
745
        );
746
    }
747
}