1
//! Facilities to construct microdescriptor objects.
2
//!
3
//! (These are only for testing right now, since we don't yet
4
//! support encoding.)
5

            
6
use super::{Microdesc, MicrodescAndHash};
7

            
8
use crate::types::family::{HappyFamilyId, HappyFamilyIds};
9
use crate::types::policy::PortPolicy;
10
use crate::{BuildError as Error, BuildResult as Result, Error as ParseError};
11
use tor_llcrypto::pk::{curve25519, ed25519};
12

            
13
use rand::RngExt;
14

            
15
/// A builder object used to construct a microdescriptor.
16
///
17
/// Create one of these with the [`MicrodescAndHash::builder`] method.
18
///
19
/// This facility is only enabled when the crate is built with
20
/// the `build_docs` feature.
21
#[cfg_attr(docsrs, doc(cfg(feature = "build_docs")))]
22
#[derive(Debug, Clone)]
23
pub struct MicrodescBuilder {
24
    /// The ntor onion key we'll be using.
25
    ///
26
    /// See [`Microdesc::ntor_onion_key`].
27
    ntor_onion_key: Option<curve25519::PublicKey>,
28
    /// See [`Microdesc::family_ids`]
29
    family_ids: HappyFamilyIds,
30
    /// See [`Microdesc::ipv4_policy`]
31
    ipv4_policy: PortPolicy,
32
    /// See [`Microdesc::ipv6_policy`]
33
    ipv6_policy: PortPolicy,
34
    /// See [`Microdesc::ed25519_id`]
35
    ed25519_id: Option<ed25519::Ed25519Identity>,
36
}
37

            
38
impl MicrodescBuilder {
39
    /// Create a new MicrodescBuilder.
40
466404
    pub(crate) fn new() -> Self {
41
466404
        MicrodescBuilder {
42
466404
            ntor_onion_key: None,
43
466404
            family_ids: HappyFamilyIds::new(),
44
466404
            ipv4_policy: PortPolicy::new_reject_all(),
45
466404
            ipv6_policy: PortPolicy::new_reject_all(),
46
466404
            ed25519_id: None,
47
466404
        }
48
466404
    }
49

            
50
    /// Set the ntor onion key.
51
    ///
52
    /// This key is required for a well-formed microdescriptor.
53
466403
    pub fn ntor_key(&mut self, key: curve25519::PublicKey) -> &mut Self {
54
466403
        self.ntor_onion_key = Some(key);
55
466403
        self
56
466403
    }
57

            
58
    /// Set the ed25519 identity key.
59
    ///
60
    /// This key is required for a well-formed microdescriptor.
61
466403
    pub fn ed25519_id(&mut self, key: ed25519::Ed25519Identity) -> &mut Self {
62
466403
        self.ed25519_id = Some(key);
63
466403
        self
64
466403
    }
65

            
66
    /// Add `id` as a family ID for this relay.
67
476788
    pub fn add_family_id(&mut self, id: HappyFamilyId) -> &mut Self {
68
476788
        self.family_ids.push(id);
69
476788
        self
70
476788
    }
71

            
72
    /// Set the ipv4 exit policy of this relay.
73
    ///
74
    /// By default, this policy is `reject 1-65535`.
75
491841
    pub fn ipv4_policy(&mut self, policy: PortPolicy) -> &mut Self {
76
491841
        self.ipv4_policy = policy;
77
491841
        self
78
491841
    }
79

            
80
    /// Set the ipv6 exit policy of this relay.
81
    ///
82
    /// By default, this policy is `reject 1-65535`.
83
2121
    pub fn ipv6_policy(&mut self, policy: PortPolicy) -> &mut Self {
84
2121
        self.ipv6_policy = policy;
85
2121
        self
86
2121
    }
87

            
88
    /// Set the ipv4 exit policy of this relay based on parsing
89
    /// a string.
90
    ///
91
    /// By default, this policy is `reject 1-65535`.
92
491841
    pub fn parse_ipv4_policy(&mut self, policy: &str) -> Result<&mut Self> {
93
491841
        Ok(self.ipv4_policy(policy.parse().map_err(ParseError::from)?))
94
491841
    }
95

            
96
    /// Set the ipv6 exit policy of this relay based on parsing
97
    /// a string.
98
    ///
99
    /// By default, this policy is `reject 1-65535`.
100
2121
    pub fn parse_ipv6_policy(&mut self, policy: &str) -> Result<&mut Self> {
101
2121
        Ok(self.ipv6_policy(policy.parse().map_err(ParseError::from)?))
102
2121
    }
103

            
104
    /// Try to build a microdescriptor from the settings on this builder.
105
    ///
106
    /// Give an error if any required fields are not set.
107
    ///
108
    /// # Limitations
109
    ///
110
    /// This is only for testing, since it does actually encode the
111
    /// information in a string, and since it sets the sha256 digest
112
    /// field at random.
113
    ///
114
    /// In the future, when we have authority support, we'll need an
115
    /// encoder function instead.
116
477004
    pub fn testing_md(&self) -> Result<MicrodescAndHash> {
117
477004
        let ntor_onion_key = self
118
477004
            .ntor_onion_key
119
477004
            .ok_or(Error::CannotBuild("Missing ntor_key"))?
120
            .into();
121
477003
        let ed25519_id = self
122
477003
            .ed25519_id
123
477003
            .ok_or(Error::CannotBuild("Missing ed25519_id"))?
124
            .into();
125

            
126
        // We generate a random sha256 value here, since this is only
127
        // for testing.
128
477002
        let sha256 = rand::rng().random();
129

            
130
477002
        let md = Microdesc {
131
477002
            // Including an empty onion_key is totally fine and valid.
132
477002
            onion_key: Default::default(),
133
477002
            ntor_onion_key,
134
477002
            family_ids: self.family_ids.clone(),
135
477002
            ipv4_policy: self.ipv4_policy.clone().intern(),
136
477002
            ipv6_policy: self.ipv6_policy.clone().intern(),
137
477002
            ed25519_id,
138
477002
            __non_exhaustive: (),
139
477002
        };
140
477002
        Ok(MicrodescAndHash { md, sha256 })
141
477004
    }
142
}
143

            
144
#[cfg(test)]
145
mod test {
146
    // @@ begin test lint list maintained by maint/add_warning @@
147
    #![allow(clippy::bool_assert_comparison)]
148
    #![allow(clippy::clone_on_copy)]
149
    #![allow(clippy::dbg_macro)]
150
    #![allow(clippy::mixed_attributes_style)]
151
    #![allow(clippy::print_stderr)]
152
    #![allow(clippy::print_stdout)]
153
    #![allow(clippy::single_char_pattern)]
154
    #![allow(clippy::unwrap_used)]
155
    #![allow(clippy::unchecked_time_subtraction)]
156
    #![allow(clippy::useless_vec)]
157
    #![allow(clippy::needless_pass_by_value)]
158
    #![allow(clippy::string_slice)] // See arti#2571
159
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
160
    use super::*;
161

            
162
    #[test]
163
    fn minimal() {
164
        let ed: ed25519::Ed25519Identity = (*b"this is not much of a public key").into();
165
        let ntor: curve25519::PublicKey = (*b"but fortunately nothing cares...").into();
166

            
167
        let md = MicrodescBuilder::new()
168
            .ed25519_id(ed)
169
            .ntor_key(ntor)
170
            .testing_md()
171
            .unwrap();
172

            
173
        assert_eq!(md.ed25519_id(), &ed);
174
        assert_eq!(md.ntor_key(), &ntor);
175
    }
176

            
177
    #[test]
178
    fn maximal() -> Result<()> {
179
        let ed: ed25519::Ed25519Identity = (*b"this is not much of a public key").into();
180
        let ntor: curve25519::PublicKey = (*b"but fortunately nothing cares...").into();
181

            
182
        let md = MicrodescAndHash::builder()
183
            .ed25519_id(ed)
184
            .ntor_key(ntor)
185
            .parse_ipv4_policy("accept 80,443")?
186
            .parse_ipv6_policy("accept 22-80")?
187
            .testing_md()
188
            .unwrap();
189

            
190
        assert!(md.ipv4_policy().allows_port(443));
191
        assert!(md.ipv4_policy().allows_port(80));
192
        assert!(!md.ipv4_policy().allows_port(55));
193

            
194
        assert!(!md.ipv6_policy().allows_port(443));
195
        assert!(md.ipv6_policy().allows_port(80));
196
        assert!(md.ipv6_policy().allows_port(55));
197

            
198
        Ok(())
199
    }
200

            
201
    #[test]
202
    fn failing() {
203
        let ed: ed25519::Ed25519Identity = (*b"this is not much of a public key").into();
204
        let ntor: curve25519::PublicKey = (*b"but fortunately nothing cares...").into();
205

            
206
        {
207
            let mut builder = MicrodescAndHash::builder();
208
            builder.ed25519_id(ed);
209
            assert!(builder.testing_md().is_err()); // no ntor
210
        }
211

            
212
        {
213
            let mut builder = MicrodescAndHash::builder();
214
            builder.ntor_key(ntor);
215
            assert!(builder.testing_md().is_err()); // no ed id.
216
        }
217
    }
218
}