1
//! Code to handle the inner document of an onion service descriptor.
2

            
3
use std::time::SystemTime;
4

            
5
use super::{IntroAuthType, IntroPointDesc};
6
use crate::batching_split_before::IteratorExt as _;
7
use crate::doc::hsdesc::pow::PowParamSet;
8
use crate::parse::tokenize::{ItemResult, NetDocReader};
9
use crate::parse::{keyword::Keyword, parser::SectionRules};
10
use crate::types::misc::{UnvalidatedEdCert, B64};
11
use crate::{NetdocErrorKind as EK, Result};
12

            
13
use itertools::Itertools as _;
14
use once_cell::sync::Lazy;
15
use smallvec::SmallVec;
16
use tor_checkable::signed::SignatureGated;
17
use tor_checkable::timed::TimerangeBound;
18
use tor_checkable::Timebound;
19
use tor_hscrypto::pk::{HsIntroPtSessionIdKey, HsSvcNtorKey};
20
use tor_hscrypto::NUM_INTRO_POINT_MAX;
21
use tor_llcrypto::pk::ed25519::Ed25519Identity;
22
use tor_llcrypto::pk::{curve25519, ed25519, ValidatableSignature};
23

            
24
/// The contents of the inner document of an onion service descriptor.
25
#[derive(Debug, Clone)]
26
#[cfg_attr(feature = "hsdesc-inner-docs", visibility::make(pub))]
27
pub(crate) struct HsDescInner {
28
    /// The authentication types that this onion service accepts when
29
    /// connecting.
30
    //
31
    // TODO: This should probably be a bitfield or enum-set of something.
32
    // Once we know whether the "password" authentication type really exists,
33
    // let's change to a better representation here.
34
    pub(super) intro_auth_types: Option<SmallVec<[IntroAuthType; 2]>>,
35
    /// Is this onion service a "single onion service?"
36
    ///
37
    /// (A "single onion service" is one that is not attempting to anonymize
38
    /// itself.)
39
    pub(super) single_onion_service: bool,
40
    /// A list of advertised introduction points and their contact info.
41
    //
42
    // Always has >= 1 and <= NUM_INTRO_POINT_MAX entries
43
    pub(super) intro_points: Vec<IntroPointDesc>,
44
    /// A list of offered proof-of-work parameters, at most one per type.
45
    pub(super) pow_params: PowParamSet,
46
}
47

            
48
decl_keyword! {
49
    pub(crate) HsInnerKwd {
50
        "create2-formats" => CREATE2_FORMATS,
51
        "intro-auth-required" => INTRO_AUTH_REQUIRED,
52
        "single-onion-service" => SINGLE_ONION_SERVICE,
53
        "introduction-point" => INTRODUCTION_POINT,
54
        "onion-key" => ONION_KEY,
55
        "auth-key" => AUTH_KEY,
56
        "enc-key" => ENC_KEY,
57
        "enc-key-cert" => ENC_KEY_CERT,
58
        "legacy-key" => LEGACY_KEY,
59
        "legacy-key-cert" => LEGACY_KEY_CERT,
60
        "pow-params" => POW_PARAMS,
61
    }
62
}
63

            
64
/// Rules about how keywords appear in the header part of an onion service
65
/// descriptor.
66
96
static HS_INNER_HEADER_RULES: Lazy<SectionRules<HsInnerKwd>> = Lazy::new(|| {
67
    use HsInnerKwd::*;
68

            
69
96
    let mut rules = SectionRules::builder();
70
96
    rules.add(CREATE2_FORMATS.rule().required().args(1..));
71
96
    rules.add(INTRO_AUTH_REQUIRED.rule().args(1..));
72
96
    rules.add(SINGLE_ONION_SERVICE.rule());
73
96
    rules.add(POW_PARAMS.rule().args(1..).may_repeat().obj_optional());
74
96
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
75
96

            
76
96
    rules.build()
77
96
});
78

            
79
/// Rules about how keywords appear in each introduction-point section of an
80
/// onion service descriptor.
81
96
static HS_INNER_INTRO_RULES: Lazy<SectionRules<HsInnerKwd>> = Lazy::new(|| {
82
    use HsInnerKwd::*;
83

            
84
96
    let mut rules = SectionRules::builder();
85
96
    rules.add(INTRODUCTION_POINT.rule().required().args(1..));
86
96
    // Note: we're labeling ONION_KEY and ENC_KEY as "may_repeat", since even
87
96
    // though rend-spec labels them as "exactly once", they are allowed to
88
96
    // appear more than once so long as they appear only once _with an "ntor"_
89
96
    // key.  torspec!110 tries to document this issue.
90
96
    rules.add(ONION_KEY.rule().required().may_repeat().args(2..));
91
96
    rules.add(AUTH_KEY.rule().required().obj_required());
92
96
    rules.add(ENC_KEY.rule().required().may_repeat().args(2..));
93
96
    rules.add(ENC_KEY_CERT.rule().required().obj_required());
94
96
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
95
96

            
96
96
    // NOTE: We never look at the LEGACY_KEY* fields.  This does provide a
97
96
    // distinguisher for Arti implementations and C tor implementations, but
98
96
    // that's outside of Arti's threat model.
99
96
    //
100
96
    // (In fact, there's an easier distinguisher, since we enforce UTF-8 in
101
96
    // these documents, and C tor does not.)
102
96

            
103
96
    rules.build()
104
96
});
105

            
106
/// Helper type returned when we parse an HsDescInner.
107
pub(crate) type UncheckedHsDescInner = TimerangeBound<SignatureGated<HsDescInner>>;
108

            
109
/// Information about one of the certificates inside an HsDescInner.
110
///
111
/// This is a teporary structure that we use when parsing.
112
struct InnerCertData {
113
    /// The identity of the key that purportedly signs this certificate.
114
    signing_key: Ed25519Identity,
115
    /// The key that is being signed.
116
    subject_key: ed25519::PublicKey,
117
    /// A detached signature object that we must validate before we can conclude
118
    /// that the certificate is valid.
119
    signature: Box<dyn ValidatableSignature>,
120
    /// The time when the certificate expires.
121
    expiry: SystemTime,
122
}
123

            
124
/// Decode a certificate from `tok`, and check that its tag and type are
125
/// expected, that it contains a signing key,  and that both signing and subject
126
/// keys are Ed25519.
127
///
128
/// On success, return an InnerCertData.
129
2226
fn handle_inner_certificate(
130
2226
    tok: &crate::parse::tokenize::Item<HsInnerKwd>,
131
2226
    want_tag: &str,
132
2226
    want_type: tor_cert::CertType,
133
2226
) -> Result<InnerCertData> {
134
2226
    let make_err = |e, msg| {
135
        EK::BadObjectVal
136
            .with_msg(msg)
137
            .with_source(e)
138
            .at_pos(tok.pos())
139
    };
140

            
141
2226
    let cert = tok
142
2226
        .parse_obj::<UnvalidatedEdCert>(want_tag)?
143
2226
        .check_cert_type(want_type)?
144
2226
        .into_unchecked();
145

            
146
    // These certs have to include a signing key.
147
2226
    let cert = cert
148
2226
        .should_have_signing_key()
149
2226
        .map_err(|e| make_err(e, "Certificate was not self-signed"))?;
150

            
151
    // Peel off the signature.
152
2226
    let (cert, signature) = cert
153
2226
        .dangerously_split()
154
2226
        .map_err(|e| make_err(e, "Certificate was not Ed25519-signed"))?;
155
2226
    let signature = Box::new(signature);
156
2226

            
157
2226
    // Peel off the expiration
158
2226
    let cert = cert.dangerously_assume_timely();
159
2226
    let expiry = cert.expiry();
160
2226
    let subject_key = cert
161
2226
        .subject_key()
162
2226
        .as_ed25519()
163
2226
        .ok_or_else(|| {
164
            EK::BadObjectVal
165
                .with_msg("Certified key was not Ed25519")
166
                .at_pos(tok.pos())
167
2226
        })?
168
2226
        .try_into()
169
2226
        .map_err(|_| {
170
            EK::BadObjectVal
171
                .with_msg("Certified key was not valid Ed25519")
172
                .at_pos(tok.pos())
173
2226
        })?;
174

            
175
2226
    let signing_key = *cert.signing_key().ok_or_else(|| {
176
        EK::BadObjectVal
177
            .with_msg("Signing key was not Ed25519")
178
            .at_pos(tok.pos())
179
2226
    })?;
180

            
181
2226
    Ok(InnerCertData {
182
2226
        signing_key,
183
2226
        subject_key,
184
2226
        signature,
185
2226
        expiry,
186
2226
    })
187
2226
}
188

            
189
impl HsDescInner {
190
    /// Attempt to parse the inner document of an onion service descriptor from a
191
    /// provided string.
192
    ///
193
    /// On success, return the signing key that was used for every certificate in the
194
    /// inner document, and the inner document itself.
195
361
    #[cfg_attr(feature = "hsdesc-inner-docs", visibility::make(pub))]
196
361
    pub(super) fn parse(s: &str) -> Result<(Option<Ed25519Identity>, UncheckedHsDescInner)> {
197
361
        let mut reader = NetDocReader::new(s)?;
198
365
        let result = Self::take_from_reader(&mut reader).map_err(|e| e.within(s))?;
199
353
        Ok(result)
200
361
    }
201

            
202
    /// Attempt to parse the inner document of an onion service descriptor from a
203
    /// provided reader.
204
    ///
205
    /// On success, return the signing key that was used for every certificate in the
206
    /// inner document, and the inner document itself.
207
361
    fn take_from_reader(
208
361
        input: &mut NetDocReader<'_, HsInnerKwd>,
209
361
    ) -> Result<(Option<Ed25519Identity>, UncheckedHsDescInner)> {
210
        use HsInnerKwd::*;
211

            
212
        // Split up the input at INTRODUCTION_POINT items
213
361
        let mut sections =
214
7563
            input.batching_split_before_with_header(|item| item.is_ok_with_kwd(INTRODUCTION_POINT));
215
        // Parse the header.
216
361
        let header = HS_INNER_HEADER_RULES.parse(&mut sections)?;
217

            
218
        // Make sure that the "ntor" handshake is supported in the list of
219
        // `HTYPE`s (handshake types) in `create2-formats`.
220
        {
221
359
            let tok = header.required(CREATE2_FORMATS)?;
222
            // If we ever want to support a different HTYPE, we'll need to
223
            // store at least the intersection between "their" and "our" supported
224
            // HTYPEs.  For now we only support one, so either this set is empty
225
            // and failing now is fine, or `ntor` (2) is supported, so fine.
226
385
            if !tok.args().any(|s| s == "2") {
227
                return Err(EK::BadArgument
228
                    .at_pos(tok.pos())
229
                    .with_msg("Onion service descriptor does not support ntor handshake."));
230
359
            }
231
        }
232
        // Check whether any kind of introduction-point authentication is
233
        // specified in an `intro-auth-required` line.
234
359
        let auth_types = if let Some(tok) = header.get(INTRO_AUTH_REQUIRED) {
235
            let mut auth_types: SmallVec<[IntroAuthType; 2]> = SmallVec::new();
236
            let mut push = |at| {
237
                if !auth_types.contains(&at) {
238
                    auth_types.push(at);
239
                }
240
            };
241
            for arg in tok.args() {
242
                #[allow(clippy::single_match)]
243
                match arg {
244
                    "ed25519" => push(IntroAuthType::Ed25519),
245
                    _ => (), // Ignore unrecognized types.
246
                }
247
            }
248
            // .. but if no types are recognized, we can't connect.
249
            if auth_types.is_empty() {
250
                return Err(EK::BadArgument
251
                    .at_pos(tok.pos())
252
                    .with_msg("No recognized introduction authentication methods."));
253
            }
254

            
255
            Some(auth_types)
256
        } else {
257
359
            None
258
        };
259

            
260
        // Recognize `single-onion-service` if it's there.
261
359
        let is_single_onion_service = header.get(SINGLE_ONION_SERVICE).is_some();
262

            
263
        // Recognize `pow-params`, parsing each line and rejecting duplicate types
264
359
        let pow_params = PowParamSet::from_items(header.slice(POW_PARAMS))?;
265

            
266
355
        let mut signatures = Vec::new();
267
355
        let mut expirations = Vec::new();
268
355
        let mut cert_signing_key: Option<Ed25519Identity> = None;
269
355

            
270
355
        // Now we parse the introduction points.  Each of these will be a
271
355
        // section starting with `introduction-point`, ending right before the
272
355
        // next `introduction-point` (or before the end of the document.)
273
355
        let mut intro_points = Vec::new();
274
355
        let mut sections = sections.subsequent();
275
1468
        while let Some(mut ipt_section) = sections.next_batch() {
276
1113
            let ipt_section = HS_INNER_INTRO_RULES.parse(&mut ipt_section)?;
277

            
278
            // Parse link-specifiers
279
1113
            let link_specifiers = {
280
1113
                let tok = ipt_section.required(INTRODUCTION_POINT)?;
281
1113
                let ls = tok.parse_arg::<B64>(0)?;
282
1113
                let mut r = tor_bytes::Reader::from_slice(ls.as_bytes());
283
1113
                let n = r.take_u8()?;
284
1113
                let res = r.extract_n(n.into())?;
285
1113
                r.should_be_exhausted()?;
286
1113
                res
287
            };
288

            
289
            // Parse the ntor "onion-key" (`KP_ntor`) of the introduction point.
290
1113
            let ntor_onion_key = {
291
1113
                let tok = ipt_section
292
1113
                    .slice(ONION_KEY)
293
1113
                    .iter()
294
1197
                    .filter(|item| item.arg(0) == Some("ntor"))
295
1113
                    .exactly_one()
296
1113
                    .map_err(|_| EK::MissingToken.with_msg("No unique ntor onion key found."))?;
297
1113
                tok.parse_arg::<B64>(1)?.into_array()?.into()
298
            };
299

            
300
            // Extract the auth_key (`KP_hs_ipt_sid`) from the (unchecked)
301
            // "auth-key" certificate.
302
1113
            let auth_key: HsIntroPtSessionIdKey = {
303
                // Note that this certificate does not actually serve any
304
                // function _as_ a certificate; it was meant to cross-certify
305
                // the descriptor signing key (`KP_hs_desc_sign`) using the
306
                // authentication key (`KP_hs_ipt_sid`).  But the C tor
307
                // implementation got it backwards.
308
                //
309
                // We have to parse this certificate to extract
310
                // `KP_hs_ipt_sid`, but we don't actually need to validate it:
311
                // it appears inside the inner document, which is already signed
312
                // with `KP_hs_desc_sign`.  Nonetheless, we validate it anyway,
313
                // since that's what C tor does.
314
                //
315
                // See documentation for `CertType::HS_IP_V_SIGNING for more
316
                // info`.
317
1113
                let tok = ipt_section.required(AUTH_KEY)?;
318
                let InnerCertData {
319
1113
                    signing_key,
320
1113
                    subject_key,
321
1113
                    signature,
322
1113
                    expiry,
323
1113
                } = handle_inner_certificate(
324
1113
                    tok,
325
1113
                    "ED25519 CERT",
326
1113
                    tor_cert::CertType::HS_IP_V_SIGNING,
327
1113
                )?;
328
1113
                expirations.push(expiry);
329
1113
                signatures.push(signature);
330
1113
                if cert_signing_key.get_or_insert(signing_key) != &signing_key {
331
                    return Err(EK::BadObjectVal
332
                        .at_pos(tok.pos())
333
                        .with_msg("Mismatched signing key"));
334
1113
                }
335
1113

            
336
1113
                subject_key.into()
337
            };
338

            
339
            // Extract the key `KP_hss_ntor` that we'll use for our
340
            // handshake with the onion service itself.  This comes from the
341
            // "enc-key" item.
342
1113
            let svc_ntor_key: HsSvcNtorKey = {
343
1113
                let tok = ipt_section
344
1113
                    .slice(ENC_KEY)
345
1113
                    .iter()
346
1197
                    .filter(|item| item.arg(0) == Some("ntor"))
347
1113
                    .exactly_one()
348
1113
                    .map_err(|_| EK::MissingToken.with_msg("No unique ntor onion key found."))?;
349
1113
                let key = curve25519::PublicKey::from(tok.parse_arg::<B64>(1)?.into_array()?);
350
1113
                key.into()
351
            };
352

            
353
            // Check that the key in the "enc-key-cert" item matches the
354
            // `KP_hss_ntor` we just extracted.
355
            {
356
                // NOTE: As above, this certificate is backwards, and hence
357
                // useless.  Still, we validate it because that is what C tor does.
358
1113
                let tok = ipt_section.required(ENC_KEY_CERT)?;
359
                let InnerCertData {
360
1113
                    signing_key,
361
1113
                    subject_key,
362
1113
                    signature,
363
1113
                    expiry,
364
1113
                } = handle_inner_certificate(
365
1113
                    tok,
366
1113
                    "ED25519 CERT",
367
1113
                    tor_cert::CertType::HS_IP_CC_SIGNING,
368
1113
                )?;
369
1113
                expirations.push(expiry);
370
1113
                signatures.push(signature);
371
1113

            
372
1113
                // Yes, the sign bit is always zero here. This would have a 50%
373
1113
                // chance of making  the key unusable for verification. But since
374
1113
                // the certificate is backwards (see above) we don't actually have
375
1113
                // to check any signatures with it.
376
1113
                let sign_bit = 0;
377
1113
                let expected_ed_key =
378
1113
                    tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_public(
379
1113
                        &svc_ntor_key,
380
1113
                        sign_bit,
381
1113
                    );
382
1113
                if expected_ed_key != Some(subject_key) {
383
                    return Err(EK::BadObjectVal
384
                        .at_pos(tok.pos())
385
                        .with_msg("Mismatched subject key"));
386
1113
                }
387
1113

            
388
1113
                // Make sure signing key is as expected.
389
1113
                if cert_signing_key.get_or_insert(signing_key) != &signing_key {
390
                    return Err(EK::BadObjectVal
391
                        .at_pos(tok.pos())
392
                        .with_msg("Mismatched signing key"));
393
1113
                }
394
1113
            };
395
1113

            
396
1113
            // TODO SPEC: State who enforces NUM_INTRO_POINT_MAX and how (hsdirs, clients?)
397
1113
            //
398
1113
            // Simply discard extraneous IPTs.  The MAX value is hardcoded now, but a future
399
1113
            // protocol evolution might increase it and we should probably still work then.
400
1113
            //
401
1113
            // If the spec intended that hsdirs ought to validate this and reject descriptors
402
1113
            // with more than MAX (when they can), then this code is wrong because it would
403
1113
            // prevent any caller (eg future hsdir code in arti relay) from seeing the violation.
404
1113
            if intro_points.len() < NUM_INTRO_POINT_MAX {
405
1111
                intro_points.push(IntroPointDesc {
406
1111
                    link_specifiers,
407
1111
                    ipt_ntor_key: ntor_onion_key,
408
1111
                    ipt_sid_key: auth_key,
409
1111
                    svc_ntor_key,
410
1111
                });
411
1111
            }
412
        }
413

            
414
        // TODO SPEC: Might a HS publish descriptor with no IPTs to declare itself down?
415
        // If it might, then we should:
416
        //   - accept such descriptors here
417
        //   - check for this situation explicitly in tor-hsclient connect.rs intro_rend_connect
418
        //   - bail with a new `ConnError` (with ErrorKind OnionServiceNotRunning)
419
        // with the consequence that once we obtain such a descriptor,
420
        // we'll be satisfied with it and consider the HS down until the descriptor expires.
421
355
        if intro_points.is_empty() {
422
2
            return Err(EK::MissingEntry.with_msg("no introduction points"));
423
353
        }
424
353

            
425
353
        let inner = HsDescInner {
426
353
            intro_auth_types: auth_types,
427
353
            single_onion_service: is_single_onion_service,
428
353
            pow_params,
429
353
            intro_points,
430
353
        };
431
353
        let sig_gated = SignatureGated::new(inner, signatures);
432
353
        let time_bound = match expirations.iter().min() {
433
353
            Some(t) => TimerangeBound::new(sig_gated, ..t),
434
            None => TimerangeBound::new(sig_gated, ..),
435
        };
436

            
437
353
        Ok((cert_signing_key, time_bound))
438
361
    }
439
}
440

            
441
#[cfg(test)]
442
mod test {
443
    // @@ begin test lint list maintained by maint/add_warning @@
444
    #![allow(clippy::bool_assert_comparison)]
445
    #![allow(clippy::clone_on_copy)]
446
    #![allow(clippy::dbg_macro)]
447
    #![allow(clippy::mixed_attributes_style)]
448
    #![allow(clippy::print_stderr)]
449
    #![allow(clippy::print_stdout)]
450
    #![allow(clippy::single_char_pattern)]
451
    #![allow(clippy::unwrap_used)]
452
    #![allow(clippy::unchecked_duration_subtraction)]
453
    #![allow(clippy::useless_vec)]
454
    #![allow(clippy::needless_pass_by_value)]
455
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
456

            
457
    use std::{iter, time::Duration};
458

            
459
    use hex_literal::hex;
460
    use itertools::chain;
461
    use tor_checkable::{SelfSigned, Timebound};
462

            
463
    use super::*;
464
    use crate::doc::hsdesc::{
465
        middle::HsDescMiddle,
466
        outer::HsDescOuter,
467
        pow::PowParams,
468
        test_data::{TEST_DATA, TEST_SUBCREDENTIAL},
469
    };
470

            
471
    /// Test one particular canned 'inner' document, checking
472
    /// edge cases for zero intro points and too many intro points
473
    #[test]
474
    fn inner_text() {
475
        // This is the inner document from hsdesc1.txt aka TEST_DATA
476
        const TEST_DATA_INNER: &str = include_str!("../../../testdata/hsdesc-inner.txt");
477

            
478
        use crate::NetdocErrorKind as NEK;
479
        let _desc = HsDescInner::parse(TEST_DATA_INNER).unwrap();
480

            
481
        let none = format!(
482
            "{}\n",
483
            TEST_DATA_INNER
484
                .split_once("\nintroduction-point")
485
                .unwrap()
486
                .0,
487
        );
488
        let err = HsDescInner::parse(&none).map(|_| &none).unwrap_err();
489
        assert_eq!(err.kind, NEK::MissingEntry);
490

            
491
        let ipt = format!(
492
            "introduction-point{}",
493
            TEST_DATA_INNER
494
                .rsplit_once("\nintroduction-point")
495
                .unwrap()
496
                .1,
497
        );
498
        for n in NUM_INTRO_POINT_MAX..NUM_INTRO_POINT_MAX + 2 {
499
            let many =
500
                chain!(iter::once(&*none), std::iter::repeat_n(&*ipt, n),).collect::<String>();
501
            let desc = HsDescInner::parse(&many).unwrap();
502
            let desc = desc
503
                .1
504
                .dangerously_into_parts()
505
                .0
506
                .dangerously_assume_wellsigned();
507
            assert_eq!(desc.intro_points.len(), NUM_INTRO_POINT_MAX);
508
        }
509
    }
510

            
511
    /// Test parseability of an inner document generated by C tor with PoW v1
512
    #[test]
513
    #[cfg(feature = "hs-pow-full")]
514
    fn inner_c_pow_v1() {
515
        const TEST_DATA_INNER: &str = include_str!("../../../testdata/hsdesc-inner-pow-v1.txt");
516
        let desc = HsDescInner::parse(TEST_DATA_INNER).unwrap();
517
        let pow_params = desc
518
            .1
519
            .dangerously_into_parts()
520
            .0
521
            .dangerously_assume_wellsigned()
522
            .pow_params;
523
        assert_eq!(pow_params.slice().len(), 1);
524
        match &pow_params.slice()[0] {
525
            PowParams::V1(v1) => {
526
                let expected_effort: tor_hscrypto::pow::v1::Effort = 614.into();
527
                let expected_seed: tor_hscrypto::pow::v1::Seed =
528
                    hex!("144e901df0841833a6e8592190849b4412f307d1565f2f137b2a5bc21a31092a").into();
529
                let expected_expiry = Some(SystemTime::UNIX_EPOCH + Duration::new(1712812537, 0));
530
                assert_eq!(v1.suggested_effort(), expected_effort);
531
                assert_eq!(
532
                    v1.seed().to_owned().dangerously_assume_timely(),
533
                    expected_seed
534
                );
535
                assert_eq!(v1.seed().bounds().1, expected_expiry);
536
            }
537
            #[allow(unreachable_patterns)]
538
            _ => unreachable!(),
539
        }
540
    }
541

            
542
    /// Ensure the same valid v1 pow document parses with the addition of unknown schemes
543
    #[test]
544
    fn inner_c_pow_v1_with_unknown() {
545
        const TEMPLATE: &str = include_str!("../../../testdata/hsdesc-inner-pow-v1.txt");
546
        let parts = TEMPLATE.rsplit_once("\npow-params").unwrap();
547
        let test_data_inner = format!("{}\npow-params x-example\npow-params{}", parts.0, parts.1);
548
        let desc = HsDescInner::parse(&test_data_inner).unwrap();
549
        let pow_params = desc
550
            .1
551
            .dangerously_into_parts()
552
            .0
553
            .dangerously_assume_wellsigned()
554
            .pow_params;
555
        assert_eq!(pow_params.slice().len(), 1);
556
    }
557

            
558
    /// Incorrect reduced document with a pow-params line that has no scheme parameter
559
    #[test]
560
    fn inner_pow_empty() {
561
        const TEST_DATA_INNER: &str = include_str!("../../../testdata/hsdesc-inner-pow-empty.txt");
562
        let err = HsDescInner::parse(TEST_DATA_INNER).map(|_| ()).unwrap_err();
563
        assert_eq!(err.kind, crate::NetdocErrorKind::TooFewArguments);
564
    }
565

            
566
    /// Incorrect document with duplicated pow-params lines of the same known type
567
    #[test]
568
    fn inner_pow_duplicate() {
569
        // Modify the canned v1 pow example from c tor, by duplicating the entire pow-params line
570
        const TEMPLATE: &str = include_str!("../../../testdata/hsdesc-inner-pow-v1.txt");
571
        let first_split = TEMPLATE.rsplit_once("\npow-params").unwrap();
572
        let second_split = first_split.1.split_once("\n").unwrap();
573
        let test_data_inner = format!(
574
            "{}\npow-params{}\npow-params{}\n{}",
575
            first_split.0, second_split.0, second_split.0, second_split.1
576
        );
577
        let err = HsDescInner::parse(&test_data_inner)
578
            .map(|_| ())
579
            .unwrap_err();
580
        assert_eq!(err.kind, crate::NetdocErrorKind::DuplicateToken);
581
    }
582

            
583
    /// Incorrect document with an unexpected object encoded after the pow v1 scheme's pow-params
584
    #[test]
585
    #[cfg(feature = "hs-pow-full")]
586
    fn inner_pow_v1_object() {
587
        // Modify the canned v1 pow example
588
        const TEMPLATE: &str = include_str!("../../../testdata/hsdesc-inner-pow-v1.txt");
589
        let first_split = TEMPLATE.rsplit_once("\npow-params").unwrap();
590
        let second_split = first_split.1.split_once("\n").unwrap();
591
        let test_data_inner = format!(
592
            "{}\npow-params{}\n-----BEGIN THING-----\n-----END THING-----\n{}",
593
            first_split.0, second_split.0, second_split.1
594
        );
595
        let err = HsDescInner::parse(&test_data_inner)
596
            .map(|_| ())
597
            .unwrap_err();
598
        assert_eq!(err.kind, crate::NetdocErrorKind::UnexpectedObject);
599
    }
600

            
601
    /// Document including an unrecognized pow-params line, ignored without error and not
602
    /// represented in the output at all.
603
    ///
604
    /// Also tests that unrecognized schemes are not subject to a restriction against
605
    /// duplicate appearances. (The spec allows that implementations do not need to
606
    /// implement this prohibition for arbitrary scheme strings)
607
    ///
608
    /// TODO: We may want PowParamSet to provide a representation for arbitrary unknown PoW
609
    ///       schemes, to the extent that this information may be useful for error reporting
610
    ///       purposes after an onion service rendezvous fails.
611
    #[test]
612
    fn inner_pow_unrecognized() {
613
        // Use the reduced document from inner_pow_empty() as a template
614
        const TEMPLATE: &str = include_str!("../../../testdata/hsdesc-inner-pow-empty.txt");
615
        let parts = TEMPLATE.rsplit_once("\npow-params").unwrap();
616
        let test_data_inner = format!(
617
            "{}\npow-params x-example\npow-params x-example{}",
618
            parts.0, parts.1
619
        );
620
        let desc = HsDescInner::parse(&test_data_inner).unwrap();
621
        let pow_params = desc
622
            .1
623
            .dangerously_into_parts()
624
            .0
625
            .dangerously_assume_wellsigned()
626
            .pow_params;
627
        assert_eq!(pow_params.slice().len(), 0);
628
    }
629

            
630
    /// Document with an unrecognized pow-params line including an object
631
    #[test]
632
    fn inner_pow_unrecognized_object() {
633
        // Use the reduced document from inner_pow_empty() as a template
634
        const TEMPLATE: &str = include_str!("../../../testdata/hsdesc-inner-pow-empty.txt");
635
        let parts = TEMPLATE.rsplit_once("\npow-params").unwrap();
636
        let test_data_inner = format!(
637
            "{}\npow-params x-something-else with args\n-----BEGIN THING-----\n-----END THING-----{}",
638
            parts.0, parts.1
639
        );
640
        let desc = HsDescInner::parse(&test_data_inner).unwrap();
641
        let pow_params = desc
642
            .1
643
            .dangerously_into_parts()
644
            .0
645
            .dangerously_assume_wellsigned()
646
            .pow_params;
647
        assert_eq!(pow_params.slice().len(), 0);
648
    }
649

            
650
    #[test]
651
    fn parse_good() -> Result<()> {
652
        let desc = HsDescOuter::parse(TEST_DATA)?
653
            .dangerously_assume_wellsigned()
654
            .dangerously_assume_timely();
655
        let subcred = TEST_SUBCREDENTIAL.into();
656
        let body = desc.decrypt_body(&subcred).unwrap();
657
        let body = std::str::from_utf8(&body[..]).unwrap();
658

            
659
        let middle = HsDescMiddle::parse(body)?;
660
        let inner_body = middle
661
            .decrypt_inner(&desc.blinded_id(), desc.revision_counter(), &subcred, None)
662
            .unwrap();
663
        let inner_body = std::str::from_utf8(&inner_body).unwrap();
664
        let (ed_id, inner) = HsDescInner::parse(inner_body)?;
665
        let inner = inner
666
            .check_valid_at(&humantime::parse_rfc3339("2023-01-23T15:00:00Z").unwrap())
667
            .unwrap()
668
            .check_signature()
669
            .unwrap();
670

            
671
        assert_eq!(ed_id.as_ref(), Some(desc.desc_sign_key_id()));
672

            
673
        assert!(inner.intro_auth_types.is_none());
674
        assert_eq!(inner.single_onion_service, false);
675
        assert_eq!(inner.intro_points.len(), 3);
676

            
677
        let ipt0 = &inner.intro_points[0];
678
        assert_eq!(
679
            ipt0.ipt_ntor_key().as_bytes(),
680
            &hex!("553BF9F9E1979D6F5D5D7D20BB3FE7272E32E22B6E86E35C76A7CA8A377E402F")
681
        );
682

            
683
        assert_ne!(ipt0.link_specifiers, inner.intro_points[1].link_specifiers);
684

            
685
        Ok(())
686
    }
687
}