1
//! Computing microdescriptors
2

            
3
use super::*;
4

            
5
/// Error creating a microdescriptor
6
#[derive(Debug, Clone, thiserror::Error)]
7
#[non_exhaustive]
8
pub enum MicrodescError {
9
    /// Internal error
10
    #[error("internal error")]
11
    Internal(#[from] Bug),
12
}
13

            
14
/// Compute a microdescriptor from a routerdesc
15
///
16
/// <https://spec.torproject.org/dir-spec/computing-microdescriptors.html>
17
16
pub fn compute_microdesc(
18
16
    rd: &RouterDesc,
19
16
    meth: &TrackedConsensusMethod,
20
16
) -> Result<Microdesc, MicrodescError> {
21
16
    let family_ids: HappyFamilyIds = rd
22
16
        .family_cert
23
16
        .iter()
24
10
        .map(|cert| Ok::<_, Bug>(cert.get()?.family_ed25519.into()))
25
1
        .try_collect()?;
26

            
27
    let ipv4_policy =
28
15
        ip_summary::summarise_policy_v4_approximate(&rd.ipv4_policy, meth)?.into_intern();
29

            
30
    let m = Microdesc {
31
15
        family_ids,
32
15
        ipv4_policy,
33
15
        ipv6_policy: rd.ipv6_policy.clone(),
34
        ..MicrodescConstructor {
35
15
            ntor_onion_key: rd.ntor_onion_key.clone(),
36
15
            ed25519_id: rd.identity_ed25519.get()?.id_ed25519.into(),
37
        }
38
        .construct()
39
    };
40
15
    Ok(m)
41
16
}
42

            
43
/// Microdescriptors computed from one routerdesc, for various supported consensus methods
44
pub type MicrodescsForRouterDesc = BTreeMap<tor_netdoc::doc::netstatus::ConsensusMethods, String>;
45

            
46
/// Errors calculating one or more microdescriptors
47
pub type MicrodescsErrors = Vec<(SupportedConsensusMethod, MicrodescError)>;
48

            
49
/// Computes the microdescriptor for this descriptor, for each supported consensus method
50
///
51
/// If all goes well returns `MicrodescsForRouterDesc`, a map from methods to strings.
52
/// The map is guaranteed not to have the same *value* for different keys:
53
/// if different emthods yield the same microdesc, thy will be represented as
54
/// a single `ConsensusMethods` set mapping to a single `String`.
55
///
56
/// Hashing (calculating and collating document digests) is done by the caller of this function.
57
///
58
/// If any microdesc couldn't be computed (currently, only possible due to internal errors)
59
/// returns an `Err` containing both the failed consensus method(s) and the corresponding errors,
60
/// and the successful results (if any).
61
///
62
/// This unusual error handling is so that a handful of strange routerdescs,
63
/// that trigger bugs in our code, do not cause the whole algorithm to collapse.
64
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#microdescriptor-generation-error-handling>
65
11
pub fn compute_supported_microdescs(
66
11
    rd: &RouterDesc,
67
11
) -> Result<MicrodescsForRouterDesc, (MicrodescsErrors, MicrodescsForRouterDesc)> {
68
11
    compute_supported_generic(
69
        //
70
11
        SupportedConsensusMethod::iter_all(),
71
11
        |tracker| {
72
11
            let md = compute_microdesc(rd, tracker)?;
73
10
            let md = encode_netdoc_unsigned([&md])?;
74
10
            Ok(md)
75
11
        },
76
    )
77
11
}
78

            
79
/// "Good" output from [`compute_supported_generic`]
80
type Outputs<O> = BTreeMap<tor_netdoc::doc::netstatus::ConsensusMethods, O>;
81

            
82
/// Compute `O` for all supported consensus methods
83
///
84
/// This is the core of `compute_supported_microdescs`,
85
/// but made generic so that we can pass an interesting calculation function, for testing.
86
#[allow(clippy::type_complexity)] // return type is sadly rather complex
87
12
fn compute_supported_generic<O: Clone + Eq + Hash, E: From<Bug>>(
88
12
    all_methods: impl Iterator<Item = SupportedConsensusMethod>,
89
12
    computor: impl Fn(&TrackedConsensusMethod) -> Result<O, E>,
90
12
) -> Result<Outputs<O>, (Vec<(SupportedConsensusMethod, E)>, Outputs<O>)> {
91
12
    let mut results = HashMap::<O, tor_netdoc::doc::netstatus::ConsensusMethods>::new();
92
12
    let mut errors = vec![];
93

            
94
12
    let mut last = None::<(ConsensusMethodRange, O)>;
95
12
    for method in all_methods {
96
111
        (|| {
97
111
            let entry = if let Some((range, prev)) = &last
98
99
                && range.contains(&method)
99
            {
100
89
                results
101
89
                    .get_mut(prev)
102
                    .ok_or_else(|| internal!("prev not inserted!"))?
103
            } else {
104
22
                let tracker = TrackedConsensusMethod::new(method);
105
22
                let output = computor(&tracker)?;
106
20
                last = Some((tracker.finish_get_equivalent(), output.clone()));
107
20
                results.entry(output).or_default()
108
            };
109
109
            entry.methods.insert(method.into());
110
109
            Ok(())
111
        })()
112
2
        .unwrap_or_else(|e| {
113
2
            errors.push((method, e));
114
2
        });
115
    }
116

            
117
12
    let results = results
118
12
        .into_iter()
119
17
        .map(|(output, meths)| (meths, output))
120
        .collect();
121
12
    if errors.is_empty() {
122
10
        Ok(results)
123
    } else {
124
2
        Err((errors, results))
125
    }
126
12
}
127

            
128
impl tor_error::HasKind for MicrodescError {
129
    fn kind(&self) -> tor_error::ErrorKind {
130
        use MicrodescError as ME;
131
        use tor_error::ErrorKind as EK;
132
        match self {
133
            ME::Internal { .. } => EK::Internal,
134
        }
135
    }
136
}
137

            
138
#[cfg(test)]
139
mod test {
140
    // @@ begin test lint list maintained by maint/add_warning @@
141
    #![allow(clippy::bool_assert_comparison)]
142
    #![allow(clippy::clone_on_copy)]
143
    #![allow(clippy::dbg_macro)]
144
    #![allow(clippy::mixed_attributes_style)]
145
    #![allow(clippy::print_stderr)]
146
    #![allow(clippy::print_stdout)]
147
    #![allow(clippy::single_char_pattern)]
148
    #![allow(clippy::unwrap_used)]
149
    #![allow(clippy::unchecked_time_subtraction)]
150
    #![allow(clippy::useless_vec)]
151
    #![allow(clippy::needless_pass_by_value)]
152
    #![allow(clippy::string_slice)] // See arti#2571
153
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
154
    use super::*;
155
    use std::rc::Rc;
156
    use tor_checkable::TimeBound as _;
157
    use tor_error::ErrorReport as _;
158
    use tor_netdoc::{
159
        assert_eq_or_diff,
160
        doc::routerdesc::RouterDescUnverified,
161
        parse2::{NetdocParseableUnverified as _, ParseInput, parse_netdoc},
162
        test_support::regsub,
163
        testdata_live,
164
    };
165

            
166
    fn get_router_desc(relay: &testdata_live::PerRelay) -> anyhow::Result<RouterDesc> {
167
        let rd_txt = relay.data.plain;
168
        let rd: RouterDescUnverified = parse_netdoc(&ParseInput::new(rd_txt, relay.nick))?;
169
        let rd = rd.verify()?.dangerously_assume_timely();
170
        Ok(rd)
171
    }
172

            
173
    #[test]
174
    fn microdescs() -> anyhow::Result<()> {
175
        let method = TrackedConsensusMethod::new(
176
            // Test with method 100; will need to bump this occasionally,
177
            // and/or add more regsub fixups, if this test fails.
178
            ConsensusMethod(100).try_into()?,
179
        );
180

            
181
        for relay in testdata_live::RELAY_DESCRIPTORS {
182
            let rd = get_router_desc(relay)?;
183
            let md = compute_microdesc(&rd, &method)?;
184
            let md_txt = encode_netdoc_unsigned([&md])?;
185

            
186
            let mut exp_md = relay.data.md.to_owned();
187
            regsub(
188
                &mut exp_md,
189
                r#"(?x) ^ onion-key \n
190
                          -----BEGIN\ .*----- \n
191
                          [^-]+
192
                          -----END\ .*----- \n
193
                "#,
194
                "onion-key\n",
195
            );
196
            // test data may be from method 36 or earlier
197
            regsub(&mut exp_md, r#"(?x) ^ family \ .* \n"#, "");
198

            
199
            assert_eq_or_diff!(md_txt, exp_md, "for relay {}", relay.nick);
200
        }
201

            
202
        Ok(())
203
    }
204

            
205
    #[test]
206
    fn all_microdesc() -> anyhow::Result<()> {
207
        for relay in testdata_live::RELAY_DESCRIPTORS {
208
            let rd = get_router_desc(relay)?;
209
            let descs = compute_supported_microdescs(&rd).expect("no bugs");
210
            for md in descs.values() {
211
                let _md: Microdesc = parse_netdoc(&ParseInput::new(md, relay.nick))?;
212
            }
213
            itertools::assert_equal(
214
                descs
215
                    .keys()
216
                    .flat_map(|m| m.methods.iter())
217
                    .sorted()
218
                    .copied(),
219
                SupportedConsensusMethod::iter_all().map(|m| *m),
220
            );
221
        }
222
        Ok(())
223
    }
224

            
225
    #[test]
226
    #[allow(clippy::len_zero)] // assert!(!foo.is_empty()) is just terrible with all the subtle !
227
    fn buggy_microdesc() -> anyhow::Result<()> {
228
        // Test error handling of microdescriptor construction.
229
        // It turns out we can sabotage microdescriptor construction if we bypass
230
        // RouterDesc::verify, because that fails to populate family info that we need.
231
        let relay = &testdata_live::RELAY_DESCRIPTORS[0];
232
        let rd_txt = relay.data.plain;
233
        let rd: RouterDescUnverified = parse_netdoc(&ParseInput::new(rd_txt, relay.nick))?;
234
        let rd = rd.unwrap_unverified().0;
235
        let (errors, descs) = compute_supported_microdescs(&rd)
236
            .expect_err("should access unverified EmbeddedCert, throwing Bug");
237
        assert!(descs.len() == 0);
238
        assert!(errors.len() > 0);
239
        for (method, error) in errors {
240
            let _: SupportedConsensusMethod = method;
241
            let msg = error.report().to_string();
242
            let exp = "attempted to access verified data of unverified EmbeddedCert";
243
            assert!(msg.contains(exp), "{msg:?}");
244
        }
245
        Ok(())
246
    }
247

            
248
    #[test]
249
    fn all_supported_track_coalesce() {
250
        use crate::consensus::tracked_method::test::interesting_function;
251

            
252
        #[derive(Debug, thiserror::Error)]
253
        enum TestCaseError {
254
            #[error("expected")]
255
            Expected,
256
            #[error("{0:?}")]
257
            Internal(#[from] Bug),
258
        }
259

            
260
        let n_calls = Cell::new(0);
261

            
262
        let (errors, good) = compute_supported_generic(
263
            (1..=100)
264
                .map(ConsensusMethod)
265
                .map(SupportedConsensusMethod::new_unchecked),
266
            |tracker| {
267
                n_calls.update(|n_calls| n_calls + 1);
268
                eprintln!("called with {tracker:?}");
269

            
270
                if tracker == 80 {
271
                    Err(TestCaseError::Expected)
272
                } else {
273
                    let v = interesting_function(tracker);
274
                    Ok(Rc::new(v))
275
                }
276
            },
277
        )
278
        .expect_err("80 fails");
279

            
280
        // Check that we got the expected error
281
        match &*errors {
282
            [(m, TestCaseError::Expected)] if *m == 80 => {}
283
            other => panic!("{other:?}"),
284
        }
285

            
286
        // Check that results are consistent with calculating every value
287
        for (ms, o) in good {
288
            for &m in &ms.methods {
289
                let m = SupportedConsensusMethod::new_unchecked(m);
290
                let exp = interesting_function(&TrackedConsensusMethod::new(m));
291
                assert_eq!(*o, exp);
292
            }
293
        }
294

            
295
        // Check how many calculations were needed:
296
        assert_eq!(n_calls.get(), 11);
297
    }
298
}