aboutsummaryrefslogtreecommitdiff
path: root/crates/arti-relay/src/keys.rs
blob: f7e58065735fcc6387cfd3f97afe4bc92e175119 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//! This module is where all relay related keys are declared along their key specifier for the
//! KeyMgr so some of them can be stored on disk.

use std::fmt;

use derive_deftly::Deftly;
use derive_more::Constructor;
use derive_more::derive::{From, Into};

use tor_error::Bug;
use tor_keymgr::{
    InvalidKeyPathComponentValue, KeySpecifier, KeySpecifierComponent,
    derive_deftly_template_CertSpecifier, derive_deftly_template_KeySpecifier,
};
use tor_persist::slug::{Slug, timestamp::Iso8601TimeSlug};
use web_time_compat::SystemTime;

/// The key specifier of the relay long-term identity key (RelayIdentityKeypair)
#[non_exhaustive]
#[derive(Deftly, PartialEq, Debug, Constructor, Copy, Clone)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KS_relayid_ed")]
#[deftly(summary = "Relay long-term identity keypair")]
pub(crate) struct RelayIdentityKeypairSpecifier;

/// The public part of the long-term identity key of the relay.
#[non_exhaustive]
#[derive(Deftly, PartialEq, Debug, Constructor, Copy, Clone)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KP_relayid_ed")]
#[deftly(summary = "Public part of the relay long-term identity keypair")]
pub(crate) struct RelayIdentityPublicKeySpecifier;

/// The key specifier of the legacy RSA relay long-term identity key (RelayIdentityRsaKeypair)
#[non_exhaustive]
#[derive(Deftly, PartialEq, Debug, Constructor, Copy, Clone)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KS_relayid_rsa")]
#[deftly(summary = "Legacy RSA long-term relay identity keypair")]
pub(crate) struct RelayIdentityRsaKeypairSpecifier;

/// The public part of the long-term identity key of the relay.
#[non_exhaustive]
#[derive(Deftly, PartialEq, Debug, Constructor, Copy, Clone)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KP_relayid_rsa")]
#[deftly(summary = "Public part of the relay long-term identity keypair")]
pub(crate) struct RelayIdentityRsaPublicKeySpecifier;

/// The key specifier of the relay medium-term signing key.
#[derive(Deftly, PartialEq, Debug, Constructor, Copy, Clone)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KS_relaysign_ed")]
#[deftly(summary = "Relay medium-term signing keypair")]
pub(crate) struct RelaySigningKeypairSpecifier {
    /// The expiration time of this key.
    ///
    /// This **must** be the same as the expiration timestamp from the
    /// `K_relaysign_ed` certificate of this key.
    ///
    /// This serves as a unique identifier for this key instance,
    /// and is used for deciding which `K_relaysign_ed` key to use
    /// (we use the newest key that is not yet expired according to
    /// the `valid_until` timestamp from its specifier).
    ///
    /// **Important**: this timestamp should not be used for anything other than
    /// distinguishing between different signing keypair instances.
    /// In particular, it should **not** be used for validating the keypair,
    /// or for checking its timeliness.
    #[deftly(denotator)]
    pub(crate) valid_until: Timestamp,
}

/// The key specifier of the public part of the relay medium-term signing key.
#[derive(Deftly, PartialEq, Debug, Constructor, Copy, Clone)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KP_relaysign_ed")]
#[deftly(summary = "Public part of the relay medium-term signing keypair")]
#[deftly(keypair_specifier = RelaySigningKeypairSpecifier)]
pub(crate) struct RelaySigningPublicKeySpecifier {
    /// The expiration time of this key.
    ///
    /// This **must** be the same as the expiration timestamp from the
    /// `K_relaysign_ed` certificate of this key.
    ///
    /// This serves as a unique identifier for this key instance,
    /// and is used for deciding which `K_relaysign_ed` key to use
    /// (we use the newest key that is not yet expired according to
    /// the `valid_until` timestamp from its specifier).
    ///
    /// **Important**: this timestamp should not be used for anything other than
    /// distinguishing between different signing keypair instances.
    /// In particular, it should **not** be used for validating the keypair,
    /// or for checking its timeliness.
    #[deftly(denotator)]
    pub(crate) valid_until: Timestamp,
}

impl From<&RelaySigningPublicKeySpecifier> for RelaySigningKeypairSpecifier {
    fn from(public_key_specifier: &RelaySigningPublicKeySpecifier) -> RelaySigningKeypairSpecifier {
        RelaySigningKeypairSpecifier::new(public_key_specifier.valid_until)
    }
}

/// The key specifier of the relay medium-term ntor circuit extension key.
#[derive(Deftly, PartialEq, Debug, Constructor, Copy, Clone)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KS_ntor")]
#[deftly(summary = "Relay medium-term ntor keypair")]
pub(crate) struct RelayNtorKeypairSpecifier {
    /// The expiration time of this key.
    #[deftly(denotator)]
    pub(crate) valid_until: Timestamp,
}

/// The key specifier of the public part of the relay medium-term ntor circuit extension key.
#[derive(Deftly, PartialEq, Debug, Constructor, Copy, Clone)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KP_ntor")]
#[deftly(summary = "Public part of the relay medium-term ntor keypair")]
#[deftly(keypair_specifier = RelayNtorKeypairSpecifier)]
pub(crate) struct RelayNtorPublicKeySpecifier {
    /// The expiration time of this key.
    #[deftly(denotator)]
    pub(crate) valid_until: Timestamp,
}

impl From<&RelayNtorPublicKeySpecifier> for RelayNtorKeypairSpecifier {
    fn from(public_key_specifier: &RelayNtorPublicKeySpecifier) -> RelayNtorKeypairSpecifier {
        RelayNtorKeypairSpecifier::new(public_key_specifier.valid_until)
    }
}

/// Certificate specifier for the [`RelaySigningPublicKeySpecifier`] certificate.
///
/// Represents `KP_relaysign_ed` signed by the `KS_relayid_ed` identity key.
#[derive(Deftly, Constructor)]
#[derive_deftly(CertSpecifier)]
pub(crate) struct RelaySigningKeyCertSpecifier {
    /// The subject key of this certificate.
    #[deftly(subject)]
    subject: RelaySigningPublicKeySpecifier,
}

/// The approximate time when a [`RelaySigningKeypairSpecifier`] was generated.
///
/// Used as a denotator to distinguish between the different signing keypair instances
/// that might be stored in the keystore.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] //
#[derive(Into, From)]
pub(crate) struct Timestamp(Iso8601TimeSlug);

impl From<SystemTime> for Timestamp {
    fn from(t: SystemTime) -> Self {
        Self(t.into())
    }
}

impl From<Timestamp> for SystemTime {
    fn from(t: Timestamp) -> Self {
        t.0.into()
    }
}

impl KeySpecifierComponent for Timestamp {
    fn to_slug(&self) -> Result<Slug, Bug> {
        self.0.try_into()
    }

    fn from_slug(s: &Slug) -> Result<Self, InvalidKeyPathComponentValue>
    where
        Self: Sized,
    {
        use std::str::FromStr as _;

        let timestamp = Iso8601TimeSlug::from_str(s.as_ref())
            .map_err(|e| InvalidKeyPathComponentValue::Slug(e.to_string()))?;

        Ok(Self(timestamp))
    }

    fn fmt_pretty(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// The key specifier of the relay link authentication key.
#[derive(Deftly, PartialEq, Debug, Constructor)]
#[derive_deftly(KeySpecifier)]
#[deftly(prefix = "relay")]
#[deftly(role = "KS_link_ed")]
#[deftly(summary = "Relay short-term link authentication keypair")]
pub(crate) struct RelayLinkSigningKeypairSpecifier {
    /// The expiration time of this key.
    ///
    /// This **must** be the same as the expiration timestamp from the
    /// `KP_link_ed` certificate of this key.
    ///
    /// This serves as a unique identifier for this key instance,
    /// and is used for deciding which `KP_link_ed` key to use
    /// (we use the newest key that is not yet expired according to
    /// the `valid_until` timestamp from its specifier).
    ///
    /// **Important**: this timestamp should not be used for anything other than
    /// distinguishing between different signing keypair instances.
    /// In particular, it should **not** be used for validating the keypair,
    /// or for checking its timeliness.
    #[deftly(denotator)]
    pub(crate) valid_until: Timestamp,
}

#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;

    use tor_keymgr::test_utils::check_key_specifier;
    use tor_keymgr::{CertSpecifierPattern, KeyCertificateSpecifier, KeyPathPattern};

    #[test]
    fn relay_signing_key_specifiers() {
        let ts = SystemTime::UNIX_EPOCH;
        let key_spec = RelaySigningKeypairSpecifier::new(ts.into());

        assert_eq!(
            key_spec.arti_path().unwrap().as_str(),
            "relay/ks_relaysign_ed+19700101000000"
        );

        check_key_specifier(&key_spec, "relay/ks_relaysign_ed+19700101000000");

        let pubkey_spec = RelaySigningPublicKeySpecifier::new(ts.into());

        assert_eq!(
            pubkey_spec.arti_path().unwrap().as_str(),
            "relay/kp_relaysign_ed+19700101000000"
        );

        check_key_specifier(&pubkey_spec, "relay/kp_relaysign_ed+19700101000000");
        let cert_spec = RelaySigningKeyCertSpecifier {
            subject: pubkey_spec,
        };

        assert_eq!(
            cert_spec.subject_key_specifier().arti_path().unwrap(),
            pubkey_spec.arti_path().unwrap()
        );

        assert_eq!(
            RelaySigningKeyCertSpecifierPattern::new_any()
                .arti_pattern()
                .unwrap(),
            KeyPathPattern::Arti("relay/kp_relaysign_ed+*".to_string())
        );
    }

    #[test]
    fn relay_identity_key_specifiers() {
        let key_spec = RelayIdentityKeypairSpecifier::new();

        assert_eq!(
            key_spec.arti_path().unwrap().as_str(),
            "relay/ks_relayid_ed"
        );

        check_key_specifier(&key_spec, "relay/ks_relayid_ed");

        let key_spec = RelayIdentityPublicKeySpecifier::new();

        assert_eq!(
            key_spec.arti_path().unwrap().as_str(),
            "relay/kp_relayid_ed"
        );

        check_key_specifier(&key_spec, "relay/kp_relayid_ed");
    }
}