Skip to main content

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