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::{HappyFamilyId, HappyFamilyIds};
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
    /// Family identities for this relay.
75
    #[deftly(netdoc(default(skip)))]
76
    pub family_ids: HappyFamilyIds,
77

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

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

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

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

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

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

            
122
impl Microdesc {
123
    /// Return the ntor onion key for this microdesc
124
1989940
    pub fn ntor_key(&self) -> &curve25519::PublicKey {
125
1989940
        &self.ntor_onion_key.0
126
1989940
    }
127
    /// Return the ipv4 exit policy for this microdesc
128
46037130
    pub fn ipv4_policy(&self) -> &Intern<PortPolicy> {
129
46037130
        &self.ipv4_policy
130
46037130
    }
131
    /// Return the ipv6 exit policy for this microdesc
132
6410090
    pub fn ipv6_policy(&self) -> &Intern<PortPolicy> {
133
6410090
        &self.ipv6_policy
134
6410090
    }
135
    /// Return the ed25519 identity for this microdesc, if its
136
    /// Ed25519 identity is well-formed.
137
167487846
    pub fn ed25519_id(&self) -> &ed25519::Ed25519Identity {
138
167487846
        &self.ed25519_id.pk.0
139
167487846
    }
140
    /// Return a list of family ids for this microdesc.
141
112536652
    pub fn family_ids(&self) -> &[HappyFamilyId] {
142
112536652
        self.family_ids.as_ref()
143
112536652
    }
144
}
145

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

            
163
    /// Return the sha256 digest of this microdesc.
164
71575494
    pub fn digest(&self) -> &MdDigest {
165
71575494
        &self.sha256
166
71575494
    }
167
}
168

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

            
181
/// A microdescriptor annotated with additional data
182
///
183
/// TODO: rename this.
184
#[allow(dead_code)]
185
#[derive(Clone, Debug)]
186
pub struct AnnotatedMicrodesc {
187
    /// The microdescriptor
188
    md: MicrodescAndHash,
189
    /// The annotations for the microdescriptor
190
    ann: MicrodescAnnotation,
191
    /// Where did we find the microdescriptor with the originally parsed
192
    /// string?
193
    location: Option<Extent>,
194
}
195

            
196
impl AnnotatedMicrodesc {
197
    /// Consume this annotated microdesc and discard its annotations.
198
212
    pub fn into_microdesc(self) -> MicrodescAndHash {
199
212
        self.md
200
212
    }
201

            
202
    /// Return a reference to the microdescriptor within this annotated
203
    /// microdescriptor.
204
9
    pub fn md(&self) -> &MicrodescAndHash {
205
9
        &self.md
206
9
    }
207

            
208
    /// If this Microdesc was parsed from `s`, return its original text.
209
212
    pub fn within<'a>(&self, s: &'a str) -> Option<&'a str> {
210
212
        self.location.as_ref().and_then(|ext| ext.reconstruct(s))
211
212
    }
212
}
213

            
214
decl_keyword! {
215
    /// Keyword type for recognized objects in microdescriptors.
216
    MicrodescKwd {
217
        annotation "@last-listed" => ANN_LAST_LISTED,
218
        "onion-key" => ONION_KEY,
219
        "ntor-onion-key" => NTOR_ONION_KEY,
220
        "family" => FAMILY,
221
        "family-ids" => FAMILY_IDS,
222
        "p" => P,
223
        "p6" => P6,
224
        "id" => ID,
225
    }
226
}
227

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

            
244
54
    let mut rules = SectionRules::builder();
245
54
    rules.add(ONION_KEY.rule().required().no_args().obj_optional());
246
54
    rules.add(NTOR_ONION_KEY.rule().required().args(1..));
247
54
    rules.add(FAMILY.rule().args(1..));
248
54
    rules.add(FAMILY_IDS.rule().args(0..));
249
54
    rules.add(P.rule().args(2..));
250
54
    rules.add(P6.rule().args(2..));
251
54
    rules.add(ID.rule().may_repeat().args(2..));
252
54
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
253
54
    rules.build()
254
54
});
255

            
256
impl MicrodescAnnotation {
257
    /// Extract a (possibly empty) microdescriptor annotation from a
258
    /// reader.
259
    #[allow(dead_code)]
260
7
    fn parse_from_reader(
261
7
        reader: &mut NetDocReader<'_, MicrodescKwd>,
262
7
    ) -> Result<MicrodescAnnotation> {
263
        use MicrodescKwd::*;
264

            
265
11
        let mut items = reader.pause_at(|item| item.is_ok_with_non_annotation());
266
7
        let body = MICRODESC_ANNOTATIONS.parse(&mut items)?;
267

            
268
7
        let last_listed = match body.get(ANN_LAST_LISTED) {
269
3
            None => None,
270
4
            Some(item) => Some(item.args_as_str().parse::<Iso8601TimeSp>()?.into()),
271
        };
272

            
273
7
        Ok(MicrodescAnnotation { last_listed })
274
7
    }
275
}
276

            
277
impl MicrodescAndHash {
278
    /// Parse a string into a new microdescriptor.
279
6
    pub fn parse(s: &str) -> Result<MicrodescAndHash> {
280
6
        let mut items = crate::parse::tokenize::NetDocReader::new(s)?;
281
6
        let (result, _) = Self::parse_from_reader(&mut items).map_err(|e| e.within(s))?;
282
2
        items.should_be_exhausted()?;
283
2
        Ok(result)
284
6
    }
285

            
286
    /// Extract a single microdescriptor from a NetDocReader.
287
227
    fn parse_from_reader(
288
227
        reader: &mut NetDocReader<'_, MicrodescKwd>,
289
227
    ) -> Result<(MicrodescAndHash, Option<Extent>)> {
290
        use MicrodescKwd::*;
291
227
        let s = reader.str();
292

            
293
227
        let mut first_onion_key = true;
294
        // We'll pause at the next annotation, or at the _second_ onion key.
295
920
        let mut items = reader.pause_at(|item| match item {
296
            Err(_) => false,
297
            Ok(item) => {
298
920
                item.kwd().is_annotation()
299
917
                    || if item.kwd() == ONION_KEY {
300
389
                        let was_first = first_onion_key;
301
389
                        first_onion_key = false;
302
389
                        !was_first
303
                    } else {
304
528
                        false
305
                    }
306
            }
307
920
        });
308

            
309
227
        let body = MICRODESC_RULES.parse(&mut items)?;
310

            
311
        // We have to start with onion-key
312
        let start_pos = {
313
            // unwrap here is safe because parsing would have failed
314
            // had there not been at least one item.
315
            #[allow(clippy::unwrap_used)]
316
227
            let first = body.first_item().unwrap();
317
227
            if first.kwd() != ONION_KEY {
318
2
                return Err(EK::WrongStartingToken
319
2
                    .with_msg(first.kwd_str().to_string())
320
2
                    .at_pos(first.pos()));
321
225
            }
322
            // Unwrap is safe here because we are parsing these strings from s
323
            #[allow(clippy::unwrap_used)]
324
225
            util::str::str_offset(s, first.kwd_str()).unwrap()
325
        };
326

            
327
        // Legacy (tap) onion key.  We parse this to make sure it's well-formed,
328
        // but then we discard it immediately, since we never want to use it.
329
        //
330
        // In microdescriptors, the ONION_KEY field is mandatory, but its
331
        // associated object is optional.
332
        {
333
225
            let tok = body.required(ONION_KEY)?;
334
225
            if tok.has_obj() {
335
222
                let _: rsa::PublicKey = tok
336
222
                    .parse_obj::<RsaPublicParse1Helper>("RSA PUBLIC KEY")?
337
222
                    .check_len_eq(1024)?
338
222
                    .check_exponent(65537)?
339
                    .into();
340
3
            }
341
        }
342

            
343
        // Ntor onion key
344
225
        let ntor_onion_key = body
345
225
            .required(NTOR_ONION_KEY)?
346
225
            .parse_arg::<Curve25519Public>(0)?;
347

            
348
        // Family ids (happy families case).
349
225
        let family_ids = body
350
225
            .maybe(FAMILY_IDS)
351
225
            .args_as_str()
352
225
            .unwrap_or("")
353
225
            .split_ascii_whitespace()
354
225
            .map(HappyFamilyId::from_str)
355
225
            .collect::<Result<HappyFamilyIds>>()?;
356

            
357
        // exit policies.
358
225
        let ipv4_policy = body
359
225
            .maybe(P)
360
225
            .parse_args_as_str::<PortPolicy>()?
361
225
            .unwrap_or_else(PortPolicy::new_reject_all);
362
225
        let ipv6_policy = body
363
225
            .maybe(P6)
364
225
            .parse_args_as_str::<PortPolicy>()?
365
223
            .unwrap_or_else(PortPolicy::new_reject_all);
366

            
367
        // ed25519 identity
368
        let ed25519_id = {
369
223
            let id_tok = body
370
223
                .slice(ID)
371
223
                .iter()
372
223
                .find(|item| item.arg(0) == Some("ed25519"));
373
223
            match id_tok {
374
                None => {
375
2
                    return Err(EK::MissingToken.with_msg("id ed25519"));
376
                }
377
                Some(tok) => Ed25519IdentityLine {
378
221
                    alg: Ed25519AlgorithmString::Ed25519,
379
221
                    pk: tok.parse_arg::<Ed25519Public>(1)?,
380
                },
381
            }
382
        };
383

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

            
395
221
        let text = s
396
221
            .get(start_pos..end_pos)
397
            .ok_or_else(|| internal!("chopped utf8"))?;
398
221
        let sha256 = d::Sha256::digest(text.as_bytes()).into();
399

            
400
221
        let location = Extent::new(s, text);
401

            
402
221
        let md = Microdesc {
403
221
            onion_key: Default::default(),
404
221
            ntor_onion_key,
405
221
            ipv4_policy: ipv4_policy.intern(),
406
221
            ipv6_policy: ipv6_policy.intern(),
407
221
            ed25519_id,
408
221
            family_ids,
409
221
            __non_exhaustive: (),
410
221
        };
411
221
        let md = MicrodescAndHash { md, sha256 };
412
221
        Ok((md, location))
413
227
    }
414
}
415

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

            
445
/// An iterator that parses one or more (possibly annotated)
446
/// microdescriptors from a string.
447
#[derive(Debug)]
448
pub struct MicrodescReader<'a> {
449
    /// True if we accept annotations; false otherwise.
450
    annotated: bool,
451
    /// An underlying reader to give us Items for the microdescriptors
452
    reader: NetDocReader<'a, MicrodescKwd>,
453
}
454

            
455
impl<'a> MicrodescReader<'a> {
456
    /// Construct a MicrodescReader to take microdescriptors from a string
457
    /// 's'.
458
56
    pub fn new(s: &'a str, allow: &AllowAnnotations) -> Result<Self> {
459
56
        let reader = NetDocReader::new(s)?;
460
56
        let annotated = allow == &AllowAnnotations::AnnotationsAllowed;
461
56
        Ok(MicrodescReader { annotated, reader })
462
56
    }
463

            
464
    /// If we're annotated, parse an annotation from the reader. Otherwise
465
    /// return a default annotation.
466
221
    fn take_annotation(&mut self) -> Result<MicrodescAnnotation> {
467
221
        if self.annotated {
468
7
            MicrodescAnnotation::parse_from_reader(&mut self.reader)
469
        } else {
470
214
            Ok(MicrodescAnnotation::default())
471
        }
472
221
    }
473

            
474
    /// Parse a (possibly annotated) microdescriptor from the reader.
475
    ///
476
    /// On error, parsing stops after the first failure.
477
221
    fn take_annotated_microdesc_raw(&mut self) -> Result<AnnotatedMicrodesc> {
478
221
        let ann = self.take_annotation()?;
479
221
        let (md, location) = MicrodescAndHash::parse_from_reader(&mut self.reader)?;
480
219
        Ok(AnnotatedMicrodesc { md, ann, location })
481
221
    }
482

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

            
505
impl<'a> Iterator for MicrodescReader<'a> {
506
    type Item = Result<AnnotatedMicrodesc>;
507
277
    fn next(&mut self) -> Option<Self::Item> {
508
        // If there is no next token, we're at the end.
509
277
        self.reader.peek()?;
510

            
511
        Some(
512
221
            self.take_annotated_microdesc()
513
2
                .map_err(|e| e.within(self.reader.str())),
514
        )
515
277
    }
516
}
517

            
518
#[cfg(test)]
519
mod test {
520
    // @@ begin test lint list maintained by maint/add_warning @@
521
    #![allow(clippy::bool_assert_comparison)]
522
    #![allow(clippy::clone_on_copy)]
523
    #![allow(clippy::dbg_macro)]
524
    #![allow(clippy::mixed_attributes_style)]
525
    #![allow(clippy::print_stderr)]
526
    #![allow(clippy::print_stdout)]
527
    #![allow(clippy::single_char_pattern)]
528
    #![allow(clippy::unwrap_used)]
529
    #![allow(clippy::unchecked_time_subtraction)]
530
    #![allow(clippy::useless_vec)]
531
    #![allow(clippy::needless_pass_by_value)]
532
    #![allow(clippy::string_slice)] // See arti#2571
533
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
534
    use super::*;
535
    use crate::encode::encode_netdoc_unsigned;
536
    use crate::test_support::{raw_find_item_rhs, raw_find_object, raw_item_count};
537
    use hex_literal::hex;
538
    const TESTDATA: &str = include_str!("../../testdata/microdesc1.txt");
539
    const TESTDATA2: &str = include_str!("../../testdata/microdesc2.txt");
540
    const TESTDATA3: &str = include_str!("../../testdata/microdesc3.txt");
541
    const TESTDATA4: &str = include_str!("../../testdata/microdesc4.txt");
542

            
543
    fn read_bad(fname: &str) -> String {
544
        use std::fs;
545
        use std::path::PathBuf;
546
        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
547
        path.push("testdata");
548
        path.push("bad-mds");
549
        path.push(fname);
550

            
551
        fs::read_to_string(path).unwrap()
552
    }
553

            
554
    #[test]
555
    fn parse_single() -> Result<()> {
556
        let _md = MicrodescAndHash::parse(TESTDATA)?;
557
        Ok(())
558
    }
559

            
560
    #[test]
561
    fn parse_no_tap_key() -> Result<()> {
562
        let _md = MicrodescAndHash::parse(TESTDATA3)?;
563
        Ok(())
564
    }
565

            
566
    #[test]
567
    fn parse_multi() -> Result<()> {
568
        use humantime::parse_rfc3339;
569
        let mds: Result<Vec<_>> =
570
            MicrodescReader::new(TESTDATA2, &AllowAnnotations::AnnotationsAllowed)?.collect();
571
        let mds = mds?;
572
        assert_eq!(mds.len(), 4);
573

            
574
        assert_eq!(
575
            mds[0].ann.last_listed.unwrap(),
576
            parse_rfc3339("2020-01-27T18:52:09Z").unwrap()
577
        );
578
        assert_eq!(
579
            mds[0].md().digest(),
580
            &hex!("38c71329a87098cb341c46c9c62bd646622b4445f7eb985a0e6adb23a22ccf4f")
581
        );
582
        assert_eq!(
583
            mds[0].md().ntor_key().as_bytes(),
584
            &hex!("5e895d65304a3a1894616660143f7af5757fe08bc18045c7855ee8debb9e6c47")
585
        );
586
        assert!(mds[0].md().ipv4_policy().allows_port(993));
587
        assert!(mds[0].md().ipv6_policy().allows_port(993));
588
        assert!(!mds[0].md().ipv4_policy().allows_port(25));
589
        assert!(!mds[0].md().ipv6_policy().allows_port(25));
590
        assert_eq!(
591
            mds[0].md().ed25519_id().as_bytes(),
592
            &hex!("2d85fdc88e6c1bcfb46897fca1dba6d1354f93261d68a79e0b5bc170dd923084")
593
        );
594

            
595
        Ok(())
596
    }
597

            
598
    #[test]
599
    fn parse_family_ids() -> Result<()> {
600
        let mds: Vec<AnnotatedMicrodesc> =
601
            MicrodescReader::new(TESTDATA4, &AllowAnnotations::AnnotationsNotAllowed)?
602
                .collect::<Result<_>>()?;
603
        assert_eq!(mds.len(), 2);
604
        let md0 = mds[0].md();
605
        let md1 = mds[1].md();
606
        assert!(md0.family_ids().is_empty());
607
        assert_eq!(
608
            md1.family_ids(),
609
            &[
610
                "ed25519:dXMgdGhlIHRyaXVtcGguICAgIC1UaG9tYXMgUGFpbmU"
611
                    .parse()
612
                    .unwrap(),
613
                "other:Example".parse().unwrap()
614
            ]
615
        );
616
        assert!(matches!(md1.family_ids()[0], HappyFamilyId::Ed25519(_)));
617

            
618
        Ok(())
619
    }
620

            
621
    #[test]
622
    fn test_bad() {
623
        use crate::Pos;
624
        use crate::types::policy::PolicyError;
625
        fn check(fname: &str, e: &Error) {
626
            let content = read_bad(fname);
627
            let res = MicrodescAndHash::parse(&content);
628
            assert!(res.is_err());
629
            assert_eq!(&res.err().unwrap(), e);
630
        }
631

            
632
        check(
633
            "wrong-start",
634
            &EK::WrongStartingToken
635
                .with_msg("family")
636
                .at_pos(Pos::from_line(1, 1)),
637
        );
638
        check(
639
            "bogus-policy",
640
            &EK::BadPolicy
641
                .at_pos(Pos::from_line(9, 1))
642
                .with_source(PolicyError::InvalidPort),
643
        );
644
        check(
645
            "non-ascii-policy",
646
            &EK::BadPolicy
647
                .at_pos(Pos::from_line(9, 1))
648
                .with_source(PolicyError::InvalidPort),
649
        );
650
        check("wrong-id", &EK::MissingToken.with_msg("id ed25519"));
651
    }
652

            
653
    #[test]
654
    fn test_recover() -> Result<()> {
655
        let mut data = read_bad("wrong-start");
656
        data += TESTDATA;
657
        data += &read_bad("wrong-id");
658

            
659
        let res: Vec<Result<_>> =
660
            MicrodescReader::new(&data, &AllowAnnotations::AnnotationsAllowed)?.collect();
661

            
662
        assert_eq!(res.len(), 3);
663
        assert!(res[0].is_err());
664
        assert!(res[1].is_ok());
665
        assert!(res[2].is_err());
666
        Ok(())
667
    }
668

            
669
    /// Checks whether parse2 works on [`Microdesc`].
670
    ///
671
    /// If this test fails when updating testdata2, it probably means that the assert_eq
672
    /// is insufficiently sophisticated.  If there has been a one-off change in the way
673
    /// the test data is generated, simply update the hardcoded values.
674
    ///
675
    /// If the testdata2 data is varying more interestingly, add code to extract the
676
    /// values ad-hoc with a minimum of use of the existing parsing code,
677
    /// eg with `raw_...` from `test_support`.
678
    #[test]
679
    fn parse2() -> anyhow::Result<()> {
680
        use tor_llcrypto::pk::ed25519::Ed25519Identity;
681

            
682
        use crate::parse2;
683

            
684
        let md = include_str!("../../testdata2/cached-microdescs.new");
685
        let mds = parse2::parse_netdoc_multiple::<Microdesc>(&parse2::ParseInput::new(
686
            md,
687
            "../../testdata2/cached-microdescs.new",
688
        ))
689
        .unwrap();
690

            
691
        assert_eq!(mds.len(), raw_item_count(md, "onion-key"));
692
        assert_eq!(
693
            mds[0],
694
            Microdesc {
695
                onion_key: MicrodescIntroItem(rsa::PublicKey::from_der(
696
                    pem::parse(dbg!(raw_find_object(md, "onion-key")))
697
                        .unwrap()
698
                        .contents()
699
                )),
700
                ntor_onion_key: curve25519::PublicKey::from(<[u8; 32]>::from(
701
                    FixedB64::<32>::from_str(raw_find_item_rhs(md, "ntor-onion-key")).unwrap()
702
                ))
703
                .into(),
704
                ipv4_policy: Default::default(),
705
                ipv6_policy: Default::default(),
706
                ed25519_id: Ed25519Identity::from(<[u8; 32]>::from(
707
                    FixedB64::<32>::from_str(raw_find_item_rhs(md, "id ed25519")).unwrap()
708
                ))
709
                .into(),
710
                family_ids: Default::default(),
711
                __non_exhaustive: (),
712
            }
713
        );
714

            
715
        let enc = encode_netdoc_unsigned(&mds)?;
716
        let exp = md;
717
        assert_eq_or_diff!(&enc, &exp);
718

            
719
        Ok(())
720
    }
721

            
722
    /// Manual test for happy families.
723
    // TODO: This should be included in testdata2/ but that would require the
724
    // chutney/shadow integration test to actually do families at all.
725
    #[test]
726
    fn parse2_happy_family() {
727
        use tor_llcrypto::pk::ed25519::Ed25519Identity;
728

            
729
        use crate::parse2::{self, ParseInput};
730
        use std::iter;
731

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

            
746
        let md = parse2::parse_netdoc::<Microdesc>(&ParseInput::new(MICRODESC, "")).unwrap();
747
        assert_eq!(
748
            md.family_ids,
749
            HappyFamilyIds::from_iter(iter::once(HappyFamilyId::Ed25519(
750
                Ed25519Identity::from_base64("b54cKgML0ykRyhdIRcq1xtW19iEVsMYnGNbdY+vvcas")
751
                    .unwrap()
752
            )))
753
        );
754
    }
755
}