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
#![warn(clippy::cognitive_complexity)]
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
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
49

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

            
54
pub mod signed;
55
pub mod timed;
56

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

            
73
/// A Timebound object is one that is only valid for a given range of time.
74
///
75
/// It's better to wrap things in a TimeBound than to give them an is_valid()
76
/// valid method, so that you can make sure that nobody uses the object before
77
/// checking it.
78
///
79
/// [`Timebound`] implementations are required to be **inclusive** of the
80
/// bounds when performing a verification.  Mathematically speaking, this means
81
/// that implementations must check whether `x ∊ [start; end]` but *not*
82
/// `x ∊ (start; end)`.
83
pub trait Timebound<T>: Sized {
84
    /// An error type that's returned when the object is _not_ timely.
85
    type Error;
86

            
87
    /// Check whether this object is valid at a given time.
88
    ///
89
    /// Return Ok if the object is valid, and an error if the object is not.
90
    fn is_valid_at(&self, t: &time::SystemTime) -> Result<(), Self::Error>;
91

            
92
    /// Return the underlying object without checking whether it's valid.
93
    fn dangerously_assume_timely(self) -> T;
94

            
95
    /// Unwrap this Timebound object if it is valid at a given time.
96
1916
    fn check_valid_at(self, t: &time::SystemTime) -> Result<T, Self::Error> {
97
1916
        self.is_valid_at(t)?;
98
1894
        Ok(self.dangerously_assume_timely())
99
1916
    }
100

            
101
    /// Unwrap this Timebound object if it is valid now.
102
8
    fn check_valid_now(self) -> Result<T, Self::Error> {
103
8
        self.check_valid_at(&SystemTime::get())
104
8
    }
105

            
106
    /// Unwrap this object if it is valid at the provided time t.
107
    /// If no time is provided, check the object at the current time.
108
6
    fn check_valid_at_opt(self, t: Option<time::SystemTime>) -> Result<T, Self::Error> {
109
6
        match t {
110
2
            Some(when) => self.check_valid_at(&when),
111
4
            None => self.check_valid_now(),
112
        }
113
6
    }
114
}
115

            
116
/// A cryptographically signed object that can be validated without
117
/// additional public keys.
118
///
119
/// It's better to wrap things in a SelfSigned than to give them an is_valid()
120
/// method, so that you can make sure that nobody uses the object before
121
/// checking it.  It's better to wrap things in a SelfSigned than to check
122
/// them immediately, since you might want to defer the signature checking
123
/// operation to another thread.
124
pub trait SelfSigned<T>: Sized {
125
    /// An error type that's returned when the object is _not_ well-signed.
126
    type Error;
127
    /// Check the signature on this object
128
    fn is_well_signed(&self) -> Result<(), Self::Error>;
129
    /// Return the underlying object without checking its signature.
130
    fn dangerously_assume_wellsigned(self) -> T;
131

            
132
    /// Unwrap this object if the signature is valid
133
1674
    fn check_signature(self) -> Result<T, Self::Error> {
134
1674
        self.is_well_signed()?;
135
1664
        Ok(self.dangerously_assume_wellsigned())
136
1674
    }
137
}
138

            
139
/// A cryptographically signed object that needs an external public
140
/// key to validate it.
141
pub trait ExternallySigned<T>: Sized {
142
    /// The type of the public key object.
143
    ///
144
    /// You can use a tuple or a vector here if the object is signed
145
    /// with multiple keys.
146
    type Key: ?Sized;
147

            
148
    /// A type that describes what keys are missing for this object.
149
    type KeyHint;
150

            
151
    /// An error type that's returned when the object is _not_ well-signed.
152
    type Error;
153

            
154
    /// Check whether k is the right key for this object.  If not, return
155
    /// an error describing what key would be right.
156
    ///
157
    /// This function is allowed to return 'true' for a bad key, but never
158
    /// 'false' for a good key.
159
    fn key_is_correct(&self, k: &Self::Key) -> Result<(), Self::KeyHint>;
160

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

            
164
    /// Unwrap this object without checking any signatures on it.
165
    fn dangerously_assume_wellsigned(self) -> T;
166

            
167
    /// Unwrap this object if it's correctly signed by a provided key.
168
26
    fn check_signature(self, k: &Self::Key) -> Result<T, Self::Error> {
169
26
        self.is_well_signed(k)?;
170
24
        Ok(self.dangerously_assume_wellsigned())
171
26
    }
172
}