1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
use std::time::{self, Duration};
52
use thiserror::Error;
53
use web_time_compat::{SystemTime, SystemTimeExt};
54

            
55
pub mod signed;
56
pub mod timed;
57

            
58
pub use timed::{TimeRange, TimeRangeBound, TimeRangeBoundBuilder};
59

            
60
/// An error that can occur when checking whether a TimeBound object is
61
/// currently valid.
62
#[derive(Debug, Clone, Error, PartialEq, Eq)]
63
#[non_exhaustive]
64
pub enum TimeValidityError {
65
    /// The object is not yet valid
66
    #[error("Object will not be valid for {}", humantime::format_duration(*.0))]
67
    NotYetValid(Duration),
68
    /// The object is expired
69
    #[error("Object has been expired for {}", humantime::format_duration(*.0))]
70
    Expired(Duration),
71
    /// The object isn't timely, and we don't know why, or won't say.
72
    #[error("Object is not currently valid")]
73
    Unspecified,
74
}
75

            
76
/// A `TimeBound` object is one that is only valid for a given range of time.
77
///
78
/// It's better to wrap things in a TimeBound than to give them an is_valid()
79
/// valid method, so that you can make sure that nobody uses the object before
80
/// checking it.
81
///
82
/// [`TimeBound`] implementations are required to be **inclusive** of the
83
/// bounds when performing a verification.  Mathematically speaking, this means
84
/// that implementations must check whether `x ∊ [start; end]` but *not*
85
/// `x ∊ (start; end)`.
86
pub trait TimeBound: Sized {
87
    /// The inner, wrapped type, which is being protected by this `TimeBound` implementation
88
    type Inner;
89

            
90
    /// Get the bounds, in the form of a `TimeRangeBound<()>`
91
    ///
92
    /// It is permissible for the start to be after the end.
93
    /// In that case, it's simply never valid: either expired, or too soon, or both.
94
    //
95
    // We don't return an `impl RangeBounds` because an `impl RangeBounds` would seems to
96
    // imply we support open (exclusive) ranges, which we don't.
97
    // We don't actually need to be generic here; returning a concrete type which
98
    // is just a pair of Option is fine.
99
    fn bounds(&self) -> TimeRange;
100

            
101
    /// Check whether this object is valid at a given time.
102
    ///
103
    /// Return Ok if the object is valid, and an error if the object is not.
104
    ///
105
    /// Generally, do not implement this method yourself:
106
    /// the provided implementation (which uses `bounds`) will be correct.
107
    //
108
    // The actual implementation is the overridden impl on `TimeRangeBounds`.
109
248
    fn check_valid_at(&self, t: &time::SystemTime) -> Result<(), TimeValidityError> {
110
        // This calls the implemented for `TimeRangeBound`
111
248
        self.bounds().check_valid_at(t)
112
248
    }
113

            
114
    /// Return the underlying object without checking whether it's valid.
115
    fn dangerously_assume_timely(self) -> Self::Inner;
116

            
117
    /// Unwrap this TimeBound object if it is valid at a given time.
118
5082
    fn if_valid_at(self, t: &time::SystemTime) -> Result<Self::Inner, TimeValidityError> {
119
5082
        self.check_valid_at(t)?;
120
5060
        Ok(self.dangerously_assume_timely())
121
5082
    }
122

            
123
    /// Unwrap this TimeBound object if it is valid now.
124
8
    fn if_valid_now(self) -> Result<Self::Inner, TimeValidityError> {
125
8
        self.if_valid_at(&SystemTime::get())
126
8
    }
127

            
128
    /// Gain access to the `Inner`, handling the timeout with a `TimeRangeBoundBuilder`
129
    ///
130
    /// Unwraps `self`, giving access to `Self::Inner`.
131
    /// Time time bounds are recorded in the `TimeRangeBoundBuilder`,
132
    /// and will be applied to the `T` overall return value
133
    /// from the `logic` closure supplied to [`TimeRangeBound::build_intersect`].
134
    ///
135
    /// Can only be called within the `logic` closure to `TimeRangeBound::build_intersect`.
136
    ///
137
    /// # CORRECTNESS
138
    ///
139
    /// Information from the `Inner` returned from `unwrap_with`
140
    /// should only be used to help construct the return value from `logic`.
141
    /// See [`TimeRangeBound::build_intersect`] for more details.
142
22616
    fn unwrap_with(self, builder: &mut TimeRangeBoundBuilder) -> Self::Inner {
143
22616
        builder.incorporate_unwrap(self)
144
22616
    }
145

            
146
    /// Unwrap this object if it is valid at the provided time t.
147
    /// If no time is provided, check the object at the current time.
148
    ///
149
    /// # Deprecated
150
    ///
151
    /// We do not believe runtime-selectable current time overrides,
152
    /// via `Option<SystemTime>`, make sense.
153
    /// We use `tor_rtcompat::Runtime` for mocking.
154
    #[deprecated = "use check_valid_at"]
155
    #[allow(clippy::disallowed_methods)]
156
6
    fn check_valid_at_opt(
157
6
        self,
158
6
        t: Option<time::SystemTime>,
159
6
    ) -> Result<Self::Inner, TimeValidityError> {
160
6
        match t {
161
2
            Some(when) => self.if_valid_at(&when),
162
4
            None => self.if_valid_now(),
163
        }
164
6
    }
165
}
166

            
167
#[deprecated = "use the new name, TimeBound, instead"]
168
pub use TimeBound as Timebound;
169

            
170
/// A cryptographically signed object that can be validated without
171
/// additional public keys.
172
///
173
/// It's better to wrap things in a SelfSigned than to give them an is_valid()
174
/// method, so that you can make sure that nobody uses the object before
175
/// checking it.  It's better to wrap things in a SelfSigned than to check
176
/// them immediately, since you might want to defer the signature checking
177
/// operation to another thread.
178
pub trait SelfSigned<T>: Sized {
179
    /// An error type that's returned when the object is _not_ well-signed.
180
    type Error;
181
    /// Check the signature on this object
182
    fn is_well_signed(&self) -> Result<(), Self::Error>;
183
    /// Return the underlying object without checking its signature.
184
    fn dangerously_assume_wellsigned(self) -> T;
185

            
186
    /// Unwrap this object if the signature is valid
187
23428
    fn check_signature(self) -> Result<T, Self::Error> {
188
23428
        self.is_well_signed()?;
189
23416
        Ok(self.dangerously_assume_wellsigned())
190
23428
    }
191
}
192

            
193
/// A cryptographically signed object that needs an external public
194
/// key to validate it.
195
pub trait ExternallySigned<T>: Sized {
196
    /// The type of the public key object.
197
    ///
198
    /// You can use a tuple or a vector here if the object is signed
199
    /// with multiple keys.
200
    type Key: ?Sized;
201

            
202
    /// A type that describes what keys are missing for this object.
203
    type KeyHint;
204

            
205
    /// An error type that's returned when the object is _not_ well-signed.
206
    type Error;
207

            
208
    /// Check whether k is the right key for this object.  If not, return
209
    /// an error describing what key would be right.
210
    ///
211
    /// This function is allowed to return 'true' for a bad key, but never
212
    /// 'false' for a good key.
213
    fn key_is_correct(&self, k: &Self::Key) -> Result<(), Self::KeyHint>;
214

            
215
    /// Check the signature on this object
216
    fn is_well_signed(&self, k: &Self::Key) -> Result<(), Self::Error>;
217

            
218
    /// Unwrap this object without checking any signatures on it.
219
    fn dangerously_assume_wellsigned(self) -> T;
220

            
221
    /// Unwrap this object if it's correctly signed by a provided key.
222
26
    fn check_signature(self, k: &Self::Key) -> Result<T, Self::Error> {
223
26
        self.is_well_signed(k)?;
224
24
        Ok(self.dangerously_assume_wellsigned())
225
26
    }
226
}