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
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

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

            
56
pub mod signed;
57
pub mod timed;
58

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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