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_basic_utils::intern::Intern;
26
use tor_error::internal;
27
use tor_llcrypto::d;
28
use tor_llcrypto::pk::{curve25519, ed25519, rsa};
29

            
30
use derive_deftly::Deftly;
31
use digest::Digest;
32
use std::str::FromStr as _;
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(Constructor, NetdocEncodable, NetdocParseable)]
63
#[allow(clippy::exhaustive_structs)]
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
    pub onion_key: MicrodescIntroItem,
68

            
69
    /// Public key used for the ntor circuit extension protocol.
70
    #[deftly(constructor)]
71
    #[deftly(netdoc(single_arg))]
72
    pub ntor_onion_key: Curve25519Public,
73

            
74
    /// Declared family for this relay.
75
    #[deftly(netdoc(default(skip)))]
76
    pub family: Intern<RelayFamily>,
77

            
78
    /// Family identities for this relay.
79
    #[deftly(netdoc(default(skip)))]
80
    pub family_ids: RelayFamilyIds,
81

            
82
    /// List of IPv4 ports to which this relay will exit
83
    #[deftly(netdoc(keyword = "p", default(skip)))]
84
    pub ipv4_policy: Intern<PortPolicy>,
85

            
86
    /// List of IPv6 ports to which this relay will exit
87
    #[deftly(netdoc(keyword = "p6", default(skip)))]
88
    pub ipv6_policy: Intern<PortPolicy>,
89

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

            
96
    // addr is obsolete and doesn't go here any more
97
    // pr is obsolete and doesn't go here any more.
98
    #[doc(hidden)]
99
    #[deftly(netdoc(skip))]
100
    pub __non_exhaustive: (),
101
}
102

            
103
/// A single microdescriptor and also its SHA256 hash
104
///
105
/// API compatibility type.
106
///
107
/// This type is only generated when the microdescriptor is parsed
108
/// using the old parser ([`MicrodescAndHash::parse`])
109
/// rather than the new one
110
/// (`Microdesc as `[`NetdocParseable`](crate::parse2::NetdocParseable)).
111
#[derive(Clone, Debug, Deftly, PartialEq, Eq, derive_more::Deref, derive_more::DerefMut)]
112
#[non_exhaustive]
113
pub struct MicrodescAndHash {
114
    /// The microdescriptor
115
    #[deref]
116
    #[deref_mut]
117
    pub md: Microdesc,
118

            
119
    /// The SHA256 digest of the text of this microdescriptor.
120
    ///
121
    /// This value is used to identify the microdescriptor when
122
    /// downloading it, and when listing it in a consensus document.
123
    pub sha256: MdDigest,
124
}
125

            
126
impl Microdesc {
127
    /// Return the ntor onion key for this microdesc
128
1989516
    pub fn ntor_key(&self) -> &curve25519::PublicKey {
129
1989516
        &self.ntor_onion_key.0
130
1989516
    }
131
    /// Return the ipv4 exit policy for this microdesc
132
46037130
    pub fn ipv4_policy(&self) -> &Intern<PortPolicy> {
133
46037130
        &self.ipv4_policy
134
46037130
    }
135
    /// Return the ipv6 exit policy for this microdesc
136
6410090
    pub fn ipv6_policy(&self) -> &Intern<PortPolicy> {
137
6410090
        &self.ipv6_policy
138
6410090
    }
139
    /// Return the relay family for this microdesc
140
57532351
    pub fn family(&self) -> &RelayFamily {
141
57532351
        self.family.as_ref()
142
57532351
    }
143
    /// Return the ed25519 identity for this microdesc, if its
144
    /// Ed25519 identity is well-formed.
145
167533691
    pub fn ed25519_id(&self) -> &ed25519::Ed25519Identity {
146
167533691
        &self.ed25519_id.pk.0
147
167533691
    }
148
    /// Return a list of family ids for this microdesc.
149
110042843
    pub fn family_ids(&self) -> &[RelayFamilyId] {
150
110042843
        self.family_ids.as_ref()
151
110042843
    }
152
}
153

            
154
impl MicrodescAndHash {
155
    /// Create a new MicrodescBuilder that can be used to construct
156
    /// microdescriptors.
157
    ///
158
    /// This function is only available when the crate is built with the
159
    /// `build_docs` feature.
160
    ///
161
    /// # Limitations
162
    ///
163
    /// The generated microdescriptors cannot yet be encoded, and do
164
    /// not yet have correct sha256 digests. As such they are only
165
    /// useful for testing.
166
    #[cfg(feature = "build_docs")]
167
468523
    pub fn builder() -> MicrodescBuilder {
168
468523
        MicrodescBuilder::new()
169
468523
    }
170

            
171
    /// Return the sha256 digest of this microdesc.
172
71593143
    pub fn digest(&self) -> &MdDigest {
173
71593143
        &self.sha256
174
71593143
    }
175
}
176

            
177
/// Intro line for a [`Microdesc`].
178
///
179
/// The object (the onion key) is deprecated and optional, but the item itself
180
/// must be present, because it is used to mark the start of the netdoc.
181
///
182
/// The object is private to prevent interfacing applications
183
/// from generating microdesc's with an onion-key; they are not necessary
184
/// anymore and just waste space.
185
#[derive(Debug, Clone, Default, Deftly, PartialEq, Eq)]
186
#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
187
pub struct MicrodescIntroItem(#[deftly(netdoc(object))] Option<rsa::PublicKey>);
188

            
189
/// A microdescriptor annotated with additional data
190
///
191
/// TODO: rename this.
192
#[allow(dead_code)]
193
#[derive(Clone, Debug)]
194
pub struct AnnotatedMicrodesc {
195
    /// The microdescriptor
196
    md: MicrodescAndHash,
197
    /// The annotations for the microdescriptor
198
    ann: MicrodescAnnotation,
199
    /// Where did we find the microdescriptor with the originally parsed
200
    /// string?
201
    location: Option<Extent>,
202
}
203

            
204
impl AnnotatedMicrodesc {
205
    /// Consume this annotated microdesc and discard its annotations.
206
371
    pub fn into_microdesc(self) -> MicrodescAndHash {
207
371
        self.md
208
371
    }
209

            
210
    /// Return a reference to the microdescriptor within this annotated
211
    /// microdescriptor.
212
9
    pub fn md(&self) -> &MicrodescAndHash {
213
9
        &self.md
214
9
    }
215

            
216
    /// If this Microdesc was parsed from `s`, return its original text.
217
371
    pub fn within<'a>(&self, s: &'a str) -> Option<&'a str> {
218
371
        self.location.as_ref().and_then(|ext| ext.reconstruct(s))
219
371
    }
220
}
221

            
222
decl_keyword! {
223
    /// Keyword type for recognized objects in microdescriptors.
224
    MicrodescKwd {
225
        annotation "@last-listed" => ANN_LAST_LISTED,
226
        "onion-key" => ONION_KEY,
227
        "ntor-onion-key" => NTOR_ONION_KEY,
228
        "family" => FAMILY,
229
        "family-ids" => FAMILY_IDS,
230
        "p" => P,
231
        "p6" => P6,
232
        "id" => ID,
233
    }
234
}
235

            
236
/// Rules about annotations that can appear before a Microdescriptor
237
1
static MICRODESC_ANNOTATIONS: LazyLock<SectionRules<MicrodescKwd>> = LazyLock::new(|| {
238
    use MicrodescKwd::*;
239
1
    let mut rules = SectionRules::builder();
240
1
    rules.add(ANN_LAST_LISTED.rule().args(1..));
241
1
    rules.add(ANN_UNRECOGNIZED.rule().may_repeat().obj_optional());
242
    // unrecognized annotations are okay; anything else is a bug in this
243
    // context.
244
1
    rules.reject_unrecognized();
245
1
    rules.build()
246
1
});
247
/// Rules about entries that must appear in an Microdesc, and how they must
248
/// be formed.
249
54
static MICRODESC_RULES: LazyLock<SectionRules<MicrodescKwd>> = LazyLock::new(|| {
250
    use MicrodescKwd::*;
251

            
252
54
    let mut rules = SectionRules::builder();
253
54
    rules.add(ONION_KEY.rule().required().no_args().obj_optional());
254
54
    rules.add(NTOR_ONION_KEY.rule().required().args(1..));
255
54
    rules.add(FAMILY.rule().args(1..));
256
54
    rules.add(FAMILY_IDS.rule().args(0..));
257
54
    rules.add(P.rule().args(2..));
258
54
    rules.add(P6.rule().args(2..));
259
54
    rules.add(ID.rule().may_repeat().args(2..));
260
54
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
261
54
    rules.build()
262
54
});
263

            
264
impl MicrodescAnnotation {
265
    /// Extract a (possibly empty) microdescriptor annotation from a
266
    /// reader.
267
    #[allow(dead_code)]
268
7
    fn parse_from_reader(
269
7
        reader: &mut NetDocReader<'_, MicrodescKwd>,
270
7
    ) -> Result<MicrodescAnnotation> {
271
        use MicrodescKwd::*;
272

            
273
11
        let mut items = reader.pause_at(|item| item.is_ok_with_non_annotation());
274
7
        let body = MICRODESC_ANNOTATIONS.parse(&mut items)?;
275

            
276
7
        let last_listed = match body.get(ANN_LAST_LISTED) {
277
3
            None => None,
278
4
            Some(item) => Some(item.args_as_str().parse::<Iso8601TimeSp>()?.into()),
279
        };
280

            
281
7
        Ok(MicrodescAnnotation { last_listed })
282
7
    }
283
}
284

            
285
impl MicrodescAndHash {
286
    /// Parse a string into a new microdescriptor.
287
59
    pub fn parse(s: &str) -> Result<MicrodescAndHash> {
288
59
        let mut items = crate::parse::tokenize::NetDocReader::new(s)?;
289
59
        let (result, _) = Self::parse_from_reader(&mut items).map_err(|e| e.within(s))?;
290
55
        items.should_be_exhausted()?;
291
55
        Ok(result)
292
59
    }
293

            
294
    /// Extract a single microdescriptor from a NetDocReader.
295
439
    fn parse_from_reader(
296
439
        reader: &mut NetDocReader<'_, MicrodescKwd>,
297
439
    ) -> Result<(MicrodescAndHash, Option<Extent>)> {
298
        use MicrodescKwd::*;
299
439
        let s = reader.str();
300

            
301
439
        let mut first_onion_key = true;
302
        // We'll pause at the next annotation, or at the _second_ onion key.
303
1715
        let mut items = reader.pause_at(|item| match item {
304
            Err(_) => false,
305
1715
            Ok(item) => {
306
1715
                item.kwd().is_annotation()
307
1712
                    || if item.kwd() == ONION_KEY {
308
707
                        let was_first = first_onion_key;
309
707
                        first_onion_key = false;
310
707
                        !was_first
311
                    } else {
312
1005
                        false
313
                    }
314
            }
315
1715
        });
316

            
317
439
        let body = MICRODESC_RULES.parse(&mut items)?;
318

            
319
        // We have to start with onion-key
320
437
        let start_pos = {
321
            // unwrap here is safe because parsing would have failed
322
            // had there not been at least one item.
323
            #[allow(clippy::unwrap_used)]
324
439
            let first = body.first_item().unwrap();
325
439
            if first.kwd() != ONION_KEY {
326
2
                return Err(EK::WrongStartingToken
327
2
                    .with_msg(first.kwd_str().to_string())
328
2
                    .at_pos(first.pos()));
329
437
            }
330
            // Unwrap is safe here because we are parsing these strings from s
331
            #[allow(clippy::unwrap_used)]
332
437
            util::str::str_offset(s, first.kwd_str()).unwrap()
333
        };
334

            
335
        // Legacy (tap) onion key.  We parse this to make sure it's well-formed,
336
        // but then we discard it immediately, since we never want to use it.
337
        //
338
        // In microdescriptors, the ONION_KEY field is mandatory, but its
339
        // associated object is optional.
340
        {
341
437
            let tok = body.required(ONION_KEY)?;
342
437
            if tok.has_obj() {
343
434
                let _: rsa::PublicKey = tok
344
434
                    .parse_obj::<RsaPublicParse1Helper>("RSA PUBLIC KEY")?
345
434
                    .check_len_eq(1024)?
346
434
                    .check_exponent(65537)?
347
434
                    .into();
348
3
            }
349
        }
350

            
351
        // Ntor onion key
352
437
        let ntor_onion_key = body
353
437
            .required(NTOR_ONION_KEY)?
354
437
            .parse_arg::<Curve25519Public>(0)?;
355

            
356
        // family
357
        //
358
        // (We don't need to add the relay's own ID to this family, as we do in
359
        // RouterDescs: the authorities already took care of that for us.)
360
437
        let family = body
361
437
            .maybe(FAMILY)
362
437
            .parse_args_as_str::<RelayFamily>()?
363
437
            .unwrap_or_else(RelayFamily::new)
364
437
            .intern();
365

            
366
        // Family ids (happy families case).
367
437
        let family_ids = body
368
437
            .maybe(FAMILY_IDS)
369
437
            .args_as_str()
370
437
            .unwrap_or("")
371
437
            .split_ascii_whitespace()
372
437
            .map(RelayFamilyId::from_str)
373
437
            .collect::<Result<RelayFamilyIds>>()?;
374

            
375
        // exit policies.
376
437
        let ipv4_policy = body
377
437
            .maybe(P)
378
437
            .parse_args_as_str::<PortPolicy>()?
379
437
            .unwrap_or_else(PortPolicy::new_reject_all);
380
437
        let ipv6_policy = body
381
437
            .maybe(P6)
382
437
            .parse_args_as_str::<PortPolicy>()?
383
435
            .unwrap_or_else(PortPolicy::new_reject_all);
384

            
385
        // ed25519 identity
386
433
        let ed25519_id = {
387
435
            let id_tok = body
388
435
                .slice(ID)
389
435
                .iter()
390
435
                .find(|item| item.arg(0) == Some("ed25519"));
391
435
            match id_tok {
392
                None => {
393
2
                    return Err(EK::MissingToken.with_msg("id ed25519"));
394
                }
395
433
                Some(tok) => Ed25519IdentityLine {
396
433
                    alg: Ed25519AlgorithmString::Ed25519,
397
433
                    pk: tok.parse_arg::<Ed25519Public>(1)?,
398
                },
399
            }
400
        };
401

            
402
433
        let end_pos = {
403
            // unwrap here is safe because parsing would have failed
404
            // had there not been at least one item.
405
            #[allow(clippy::unwrap_used)]
406
433
            let last_item = body.last_item().unwrap();
407
433
            last_item.offset_after(s).ok_or_else(|| {
408
                Error::from(internal!("last item was not within source string"))
409
                    .at_pos(last_item.end_pos())
410
            })?
411
        };
412

            
413
433
        let text = s
414
433
            .get(start_pos..end_pos)
415
433
            .ok_or_else(|| internal!("chopped utf8"))?;
416
433
        let sha256 = d::Sha256::digest(text.as_bytes()).into();
417

            
418
433
        let location = Extent::new(s, text);
419

            
420
433
        let md = Microdesc {
421
433
            onion_key: Default::default(),
422
433
            ntor_onion_key,
423
433
            family,
424
433
            ipv4_policy: ipv4_policy.intern(),
425
433
            ipv6_policy: ipv6_policy.intern(),
426
433
            ed25519_id,
427
433
            family_ids,
428
433
            __non_exhaustive: (),
429
433
        };
430
433
        let md = MicrodescAndHash { md, sha256 };
431
433
        Ok((md, location))
432
439
    }
433
}
434

            
435
/// Consume tokens from 'reader' until the next token is the beginning
436
/// of a microdescriptor: an annotation or an ONION_KEY.  If no such
437
/// token exists, advance to the end of the reader.
438
2
fn advance_to_next_microdesc(reader: &mut NetDocReader<'_, MicrodescKwd>, annotated: bool) {
439
    use MicrodescKwd::*;
440
    loop {
441
2
        let item = reader.peek();
442
1
        match item {
443
1
            Some(Ok(t)) => {
444
1
                let kwd = t.kwd();
445
1
                if (annotated && kwd.is_annotation()) || kwd == ONION_KEY {
446
1
                    return;
447
                }
448
            }
449
            Some(Err(_)) => {
450
                // We skip over broken tokens here.
451
                //
452
                // (This case can't happen in practice, since if there had been
453
                // any error tokens, they would have been handled as part of
454
                // handling the previous microdesc.)
455
            }
456
            None => {
457
1
                return;
458
            }
459
        };
460
        let _ = reader.next();
461
    }
462
2
}
463

            
464
/// An iterator that parses one or more (possibly annotated)
465
/// microdescriptors from a string.
466
#[derive(Debug)]
467
pub struct MicrodescReader<'a> {
468
    /// True if we accept annotations; false otherwise.
469
    annotated: bool,
470
    /// An underlying reader to give us Items for the microdescriptors
471
    reader: NetDocReader<'a, MicrodescKwd>,
472
}
473

            
474
impl<'a> MicrodescReader<'a> {
475
    /// Construct a MicrodescReader to take microdescriptors from a string
476
    /// 's'.
477
109
    pub fn new(s: &'a str, allow: &AllowAnnotations) -> Result<Self> {
478
109
        let reader = NetDocReader::new(s)?;
479
109
        let annotated = allow == &AllowAnnotations::AnnotationsAllowed;
480
109
        Ok(MicrodescReader { annotated, reader })
481
109
    }
482

            
483
    /// If we're annotated, parse an annotation from the reader. Otherwise
484
    /// return a default annotation.
485
380
    fn take_annotation(&mut self) -> Result<MicrodescAnnotation> {
486
380
        if self.annotated {
487
7
            MicrodescAnnotation::parse_from_reader(&mut self.reader)
488
        } else {
489
373
            Ok(MicrodescAnnotation::default())
490
        }
491
380
    }
492

            
493
    /// Parse a (possibly annotated) microdescriptor from the reader.
494
    ///
495
    /// On error, parsing stops after the first failure.
496
380
    fn take_annotated_microdesc_raw(&mut self) -> Result<AnnotatedMicrodesc> {
497
380
        let ann = self.take_annotation()?;
498
380
        let (md, location) = MicrodescAndHash::parse_from_reader(&mut self.reader)?;
499
378
        Ok(AnnotatedMicrodesc { md, ann, location })
500
380
    }
501

            
502
    /// Parse a (possibly annotated) microdescriptor from the reader.
503
    ///
504
    /// On error, advance the reader to the start of the next microdescriptor.
505
380
    fn take_annotated_microdesc(&mut self) -> Result<AnnotatedMicrodesc> {
506
380
        let pos_orig = self.reader.pos();
507
380
        let result = self.take_annotated_microdesc_raw();
508
380
        if result.is_err() {
509
2
            if self.reader.pos() == pos_orig {
510
                // No tokens were consumed from the reader.  We need to
511
                // drop at least one token to ensure we aren't looping.
512
                //
513
                // (This might not be able to happen, but it's easier to
514
                // explicitly catch this case than it is to prove that
515
                // it's impossible.)
516
                let _ = self.reader.next();
517
2
            }
518
2
            advance_to_next_microdesc(&mut self.reader, self.annotated);
519
378
        }
520
380
        result
521
380
    }
522
}
523

            
524
impl<'a> Iterator for MicrodescReader<'a> {
525
    type Item = Result<AnnotatedMicrodesc>;
526
489
    fn next(&mut self) -> Option<Self::Item> {
527
        // If there is no next token, we're at the end.
528
489
        self.reader.peek()?;
529

            
530
        Some(
531
380
            self.take_annotated_microdesc()
532
380
                .map_err(|e| e.within(self.reader.str())),
533
        )
534
489
    }
535
}
536

            
537
#[cfg(test)]
538
mod test {
539
    // @@ begin test lint list maintained by maint/add_warning @@
540
    #![allow(clippy::bool_assert_comparison)]
541
    #![allow(clippy::clone_on_copy)]
542
    #![allow(clippy::dbg_macro)]
543
    #![allow(clippy::mixed_attributes_style)]
544
    #![allow(clippy::print_stderr)]
545
    #![allow(clippy::print_stdout)]
546
    #![allow(clippy::single_char_pattern)]
547
    #![allow(clippy::unwrap_used)]
548
    #![allow(clippy::unchecked_time_subtraction)]
549
    #![allow(clippy::useless_vec)]
550
    #![allow(clippy::needless_pass_by_value)]
551
    #![allow(clippy::string_slice)] // See arti#2571
552
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
553
    use super::*;
554
    use crate::encode::encode_netdoc_unsigned;
555
    use hex_literal::hex;
556
    const TESTDATA: &str = include_str!("../../testdata/microdesc1.txt");
557
    const TESTDATA2: &str = include_str!("../../testdata/microdesc2.txt");
558
    const TESTDATA3: &str = include_str!("../../testdata/microdesc3.txt");
559
    const TESTDATA4: &str = include_str!("../../testdata/microdesc4.txt");
560

            
561
    fn read_bad(fname: &str) -> String {
562
        use std::fs;
563
        use std::path::PathBuf;
564
        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
565
        path.push("testdata");
566
        path.push("bad-mds");
567
        path.push(fname);
568

            
569
        fs::read_to_string(path).unwrap()
570
    }
571

            
572
    #[test]
573
    fn parse_single() -> Result<()> {
574
        let _md = MicrodescAndHash::parse(TESTDATA)?;
575
        Ok(())
576
    }
577

            
578
    #[test]
579
    fn parse_no_tap_key() -> Result<()> {
580
        let _md = MicrodescAndHash::parse(TESTDATA3)?;
581
        Ok(())
582
    }
583

            
584
    #[test]
585
    fn parse_multi() -> Result<()> {
586
        use humantime::parse_rfc3339;
587
        let mds: Result<Vec<_>> =
588
            MicrodescReader::new(TESTDATA2, &AllowAnnotations::AnnotationsAllowed)?.collect();
589
        let mds = mds?;
590
        assert_eq!(mds.len(), 4);
591

            
592
        assert_eq!(
593
            mds[0].ann.last_listed.unwrap(),
594
            parse_rfc3339("2020-01-27T18:52:09Z").unwrap()
595
        );
596
        assert_eq!(
597
            mds[0].md().digest(),
598
            &hex!("38c71329a87098cb341c46c9c62bd646622b4445f7eb985a0e6adb23a22ccf4f")
599
        );
600
        assert_eq!(
601
            mds[0].md().ntor_key().as_bytes(),
602
            &hex!("5e895d65304a3a1894616660143f7af5757fe08bc18045c7855ee8debb9e6c47")
603
        );
604
        assert!(mds[0].md().ipv4_policy().allows_port(993));
605
        assert!(mds[0].md().ipv6_policy().allows_port(993));
606
        assert!(!mds[0].md().ipv4_policy().allows_port(25));
607
        assert!(!mds[0].md().ipv6_policy().allows_port(25));
608
        assert_eq!(
609
            mds[0].md().ed25519_id().as_bytes(),
610
            &hex!("2d85fdc88e6c1bcfb46897fca1dba6d1354f93261d68a79e0b5bc170dd923084")
611
        );
612

            
613
        Ok(())
614
    }
615

            
616
    #[test]
617
    fn parse_family_ids() -> Result<()> {
618
        let mds: Vec<AnnotatedMicrodesc> =
619
            MicrodescReader::new(TESTDATA4, &AllowAnnotations::AnnotationsNotAllowed)?
620
                .collect::<Result<_>>()?;
621
        assert_eq!(mds.len(), 2);
622
        let md0 = mds[0].md();
623
        let md1 = mds[1].md();
624
        assert!(md0.family_ids().is_empty());
625
        assert_eq!(
626
            md1.family_ids(),
627
            &[
628
                "ed25519:dXMgdGhlIHRyaXVtcGguICAgIC1UaG9tYXMgUGFpbmU"
629
                    .parse()
630
                    .unwrap(),
631
                "other:Example".parse().unwrap()
632
            ]
633
        );
634
        assert!(matches!(md1.family_ids()[0], RelayFamilyId::Ed25519(_)));
635

            
636
        Ok(())
637
    }
638

            
639
    #[test]
640
    fn test_bad() {
641
        use crate::Pos;
642
        use crate::types::policy::PolicyError;
643
        fn check(fname: &str, e: &Error) {
644
            let content = read_bad(fname);
645
            let res = MicrodescAndHash::parse(&content);
646
            assert!(res.is_err());
647
            assert_eq!(&res.err().unwrap(), e);
648
        }
649

            
650
        check(
651
            "wrong-start",
652
            &EK::WrongStartingToken
653
                .with_msg("family")
654
                .at_pos(Pos::from_line(1, 1)),
655
        );
656
        check(
657
            "bogus-policy",
658
            &EK::BadPolicy
659
                .at_pos(Pos::from_line(9, 1))
660
                .with_source(PolicyError::InvalidPort),
661
        );
662
        check(
663
            "non-ascii-policy",
664
            &EK::BadPolicy
665
                .at_pos(Pos::from_line(9, 1))
666
                .with_source(PolicyError::InvalidPort),
667
        );
668
        check("wrong-id", &EK::MissingToken.with_msg("id ed25519"));
669
    }
670

            
671
    #[test]
672
    fn test_recover() -> Result<()> {
673
        let mut data = read_bad("wrong-start");
674
        data += TESTDATA;
675
        data += &read_bad("wrong-id");
676

            
677
        let res: Vec<Result<_>> =
678
            MicrodescReader::new(&data, &AllowAnnotations::AnnotationsAllowed)?.collect();
679

            
680
        assert_eq!(res.len(), 3);
681
        assert!(res[0].is_err());
682
        assert!(res[1].is_ok());
683
        assert!(res[2].is_err());
684
        Ok(())
685
    }
686

            
687
    /// Checks whether parse2 works on [`Microdesc`].
688
    ///
689
    /// Certain values such as public keys are hardcoded and can be simply
690
    /// replaced by a copy and paste in the case one replaces the testdata2
691
    /// vector's in the future.
692
    #[test]
693
    fn parse2() -> anyhow::Result<()> {
694
        use tor_llcrypto::pk::ed25519::Ed25519Identity;
695

            
696
        use crate::parse2;
697

            
698
        let md = include_str!("../../testdata2/cached-microdescs.new");
699
        let mds = parse2::parse_netdoc_multiple::<Microdesc>(&parse2::ParseInput::new(
700
            md,
701
            "../../testdata2/cached-microdescs.new",
702
        ))
703
        .unwrap();
704

            
705
        assert_eq!(mds.len(), 7);
706
        assert_eq!(
707
            mds[0],
708
            Microdesc {
709
                onion_key: MicrodescIntroItem(rsa::PublicKey::from_der(
710
                    pem::parse(
711
                        "
712
-----BEGIN RSA PUBLIC KEY-----
713
MIGJAoGBANF8Zgxp8amY1esYdPj2Ada1ORiVB/A4sgKLQ5ij/wsasO3yjjLcvHRB
714
UJ0mAQWql/nauvjnKUeZFcGm3t7q0v3F9uUsOGTAZ/IKh31UQAm5OS/TJyf8IHky
715
Yl0wCKpUZFHs5CHsajLSfXZKHkwfqRXFEJu9aMtmQdQFfqE9JOJHAgMBAAE=
716
-----END RSA PUBLIC KEY-----
717
                        "
718
                    )
719
                    .unwrap()
720
                    .contents()
721
                )),
722
                ntor_onion_key: curve25519::PublicKey::from(<[u8; 32]>::from(
723
                    FixedB64::<32>::from_str("I1S8JfcqPPHWVTxfjq/eGmGiu/OtR+fF0Z86Ge1mq3s")
724
                        .unwrap()
725
                ))
726
                .into(),
727
                family: Default::default(),
728
                ipv4_policy: Default::default(),
729
                ipv6_policy: Default::default(),
730
                ed25519_id: Ed25519Identity::from(<[u8; 32]>::from(
731
                    FixedB64::<32>::from_str("yhO6nETO5AUdvJbLgPnw4mFjozGXWMCqOp30nY6nM8E")
732
                        .unwrap()
733
                ))
734
                .into(),
735
                family_ids: Default::default(),
736
                __non_exhaustive: (),
737
            }
738
        );
739

            
740
        let enc = encode_netdoc_unsigned(&mds)?;
741
        let exp = md;
742
        assert_eq_or_diff!(&enc, &exp);
743

            
744
        Ok(())
745
    }
746

            
747
    /// Manual test for happy families.
748
    // TODO: This should be included in testdata2/ but that would require the
749
    // chutney/shadow integration test to actually do families at all.
750
    #[test]
751
    fn parse2_happy_family() {
752
        use tor_llcrypto::pk::ed25519::Ed25519Identity;
753

            
754
        use crate::parse2::{self, ParseInput};
755
        use std::iter;
756

            
757
        // A microdescriptor taken from the wild containing happy families.
758
        const MICRODESC: &str = "\
759
onion-key
760
-----BEGIN RSA PUBLIC KEY-----
761
MIGJAoGBAMk57F7qGHVadBJ6m4028w13I1Qk67Ee0JU88w7NObKBph3DQYjgYs4e
762
eUdiW4Gdsx8w/xOuK0foCo0O8Iqq5MXtVcpUP/N+5uB7SVvGdJFsKw21KdIc6v8g
763
ACZAijw5ZPOdhLbyLQyFHNV8zXUov1dlx/Fb9M3lPMVevnDbuKM5AgMBAAE=
764
-----END RSA PUBLIC KEY-----
765
ntor-onion-key fhhP23UKD4L2jehA5gopAo5b6NSoB+kZN5Q4ULv3Zww
766
family $4CFFD403DAB89A689F3FDB80B5366E46D879E736 $4D6C1486939A42D7FFE69BCD9F3FDAA86C743433 $73955E6A69BA5E0827F48206CAD78C045BBE8873 $8DBA9ADCA5B3A3AB6D2B4F88AC2F96614D33DAB3 $B29E3E30443F897F48B86765F1BC1DB917F5DF46 $CD642E7E722979580B6D631697772C0B72BCF25C $D9E7B6A73C8278274081B77D373ECCE4552E75FB $F2515315FE0DB7456194CABC503B526B49951415
767
family-ids ed25519:b54cKgML0ykRyhdIRcq1xtW19iEVsMYnGNbdY+vvcas
768
id ed25519 /MU/FVKRGcZAy8XFnzLS6Dgcg6s1VpYeFjkwb6+CVhw
769
";
770

            
771
        let md = parse2::parse_netdoc::<Microdesc>(&ParseInput::new(MICRODESC, "")).unwrap();
772
        assert_eq!(
773
            md.family_ids,
774
            RelayFamilyIds::from_iter(iter::once(RelayFamilyId::Ed25519(
775
                Ed25519Identity::from_base64("b54cKgML0ykRyhdIRcq1xtW19iEVsMYnGNbdY+vvcas")
776
                    .unwrap()
777
            )))
778
        );
779
    }
780
}