tor_checkable/lib.rs
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// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53#![warn(unnameable_types)]
54
55use std::time::{self, Duration};
56use thiserror::Error;
57use web_time_compat::{SystemTime, SystemTimeExt};
58
59pub mod signed;
60pub mod timed;
61
62pub use timed::{TimeRange, TimeRangeBound, TimeRangeBoundBuilder};
63
64/// An error that can occur when checking whether a TimeBound object is
65/// currently valid.
66#[derive(Debug, Clone, Error, PartialEq, Eq)]
67#[non_exhaustive]
68pub enum TimeValidityError {
69 /// The object is not yet valid
70 #[error("Object will not be valid for {}", humantime::format_duration(*.0))]
71 NotYetValid(Duration),
72 /// The object is expired
73 #[error("Object has been expired for {}", humantime::format_duration(*.0))]
74 Expired(Duration),
75 /// The object isn't timely, and we don't know why, or won't say.
76 #[error("Object is not currently valid")]
77 Unspecified,
78}
79
80/// A `TimeBound` object is one that is only valid for a given range of time.
81///
82/// It's better to wrap things in a TimeBound than to give them an is_valid()
83/// valid method, so that you can make sure that nobody uses the object before
84/// checking it.
85///
86/// [`TimeBound`] implementations are required to be **inclusive** of the
87/// bounds when performing a verification. Mathematically speaking, this means
88/// that implementations must check whether `x ∊ [start; end]` but *not*
89/// `x ∊ (start; end)`.
90pub trait TimeBound: Sized {
91 /// The inner, wrapped type, which is being protected by this `TimeBound` implementation
92 type Inner;
93
94 /// Get the bounds, in the form of a `TimeRangeBound<()>`
95 ///
96 /// It is permissible for the start to be after the end.
97 /// In that case, it's simply never valid: either expired, or too soon, or both.
98 //
99 // We don't return an `impl RangeBounds` because an `impl RangeBounds` would seems to
100 // imply we support open (exclusive) ranges, which we don't.
101 // We don't actually need to be generic here; returning a concrete type which
102 // is just a pair of Option is fine.
103 fn bounds(&self) -> TimeRange;
104
105 /// Check whether this object is valid at a given time.
106 ///
107 /// Return Ok if the object is valid, and an error if the object is not.
108 ///
109 /// Generally, do not implement this method yourself:
110 /// the provided implementation (which uses `bounds`) will be correct.
111 //
112 // The actual implementation is the overridden impl on `TimeRangeBounds`.
113 fn check_valid_at(&self, t: &time::SystemTime) -> Result<(), TimeValidityError> {
114 // This calls the implemented for `TimeRangeBound`
115 self.bounds().check_valid_at(t)
116 }
117
118 /// Return the underlying object without checking whether it's valid.
119 fn dangerously_assume_timely(self) -> Self::Inner;
120
121 /// Unwrap this TimeBound object if it is valid at a given time.
122 fn if_valid_at(self, t: &time::SystemTime) -> Result<Self::Inner, TimeValidityError> {
123 self.check_valid_at(t)?;
124 Ok(self.dangerously_assume_timely())
125 }
126
127 /// Unwrap this TimeBound object if it is valid now.
128 fn if_valid_now(self) -> Result<Self::Inner, TimeValidityError> {
129 self.if_valid_at(&SystemTime::get())
130 }
131
132 /// Gain access to the `Inner`, handling the timeout with a `TimeRangeBoundBuilder`
133 ///
134 /// Unwraps `self`, giving access to `Self::Inner`.
135 /// Time time bounds are recorded in the `TimeRangeBoundBuilder`,
136 /// and will be applied to the `T` overall return value
137 /// from the `logic` closure supplied to [`TimeRangeBound::build_intersect`].
138 ///
139 /// Can only be called within the `logic` closure to `TimeRangeBound::build_intersect`.
140 ///
141 /// # CORRECTNESS
142 ///
143 /// Information from the `Inner` returned from `unwrap_with`
144 /// should only be used to help construct the return value from `logic`.
145 /// See [`TimeRangeBound::build_intersect`] for more details.
146 fn unwrap_with(self, builder: &mut TimeRangeBoundBuilder) -> Self::Inner {
147 builder.incorporate_unwrap(self)
148 }
149
150 /// Unwrap this object if it is valid at the provided time t.
151 /// If no time is provided, check the object at the current time.
152 ///
153 /// # Deprecated
154 ///
155 /// We do not believe runtime-selectable current time overrides,
156 /// via `Option<SystemTime>`, make sense.
157 /// We use `tor_rtcompat::Runtime` for mocking.
158 #[deprecated = "use check_valid_at"]
159 #[allow(clippy::disallowed_methods)]
160 fn check_valid_at_opt(
161 self,
162 t: Option<time::SystemTime>,
163 ) -> Result<Self::Inner, TimeValidityError> {
164 match t {
165 Some(when) => self.if_valid_at(&when),
166 None => self.if_valid_now(),
167 }
168 }
169}
170
171#[deprecated = "use the new name, TimeBound, instead"]
172pub use TimeBound as Timebound;
173
174/// A cryptographically signed object that can be validated without
175/// additional public keys.
176///
177/// It's better to wrap things in a SelfSigned than to give them an is_valid()
178/// method, so that you can make sure that nobody uses the object before
179/// checking it. It's better to wrap things in a SelfSigned than to check
180/// them immediately, since you might want to defer the signature checking
181/// operation to another thread.
182pub trait SelfSigned<T>: Sized {
183 /// An error type that's returned when the object is _not_ well-signed.
184 type Error;
185 /// Check the signature on this object
186 fn is_well_signed(&self) -> Result<(), Self::Error>;
187 /// Return the underlying object without checking its signature.
188 fn dangerously_assume_wellsigned(self) -> T;
189
190 /// Unwrap this object if the signature is valid
191 fn check_signature(self) -> Result<T, Self::Error> {
192 self.is_well_signed()?;
193 Ok(self.dangerously_assume_wellsigned())
194 }
195}
196
197/// A cryptographically signed object that needs an external public
198/// key to validate it.
199pub trait ExternallySigned<T>: Sized {
200 /// The type of the public key object.
201 ///
202 /// You can use a tuple or a vector here if the object is signed
203 /// with multiple keys.
204 type Key: ?Sized;
205
206 /// A type that describes what keys are missing for this object.
207 type KeyHint;
208
209 /// An error type that's returned when the object is _not_ well-signed.
210 type Error;
211
212 /// Check whether k is the right key for this object. If not, return
213 /// an error describing what key would be right.
214 ///
215 /// This function is allowed to return 'true' for a bad key, but never
216 /// 'false' for a good key.
217 fn key_is_correct(&self, k: &Self::Key) -> Result<(), Self::KeyHint>;
218
219 /// Check the signature on this object
220 fn is_well_signed(&self, k: &Self::Key) -> Result<(), Self::Error>;
221
222 /// Unwrap this object without checking any signatures on it.
223 fn dangerously_assume_wellsigned(self) -> T;
224
225 /// Unwrap this object if it's correctly signed by a provided key.
226 fn check_signature(self, k: &Self::Key) -> Result<T, Self::Error> {
227 self.is_well_signed(k)?;
228 Ok(self.dangerously_assume_wellsigned())
229 }
230}