Debian Codegraph @

src/cli/types/expiration.rs

raw
1 use std::fmt::Display;
2 use std::fmt::Formatter;
3 use std::ops::Deref;
4 use std::str::FromStr;
5 use std::time::Duration;
6 use std::time::SystemTime;
7
8 use chrono::DateTime;
9 use chrono::Utc;
10
11 use clap::builder::IntoResettable;
12 use clap::builder::OsStr;
13 use clap::builder::Resettable;
14
15 use typenum::Unsigned;
16
17 use crate::Result;
18 use crate::cli::KEY_ROTATE_RETIRE_IN_DURATION;
19 use crate::cli::THIRD_PARTY_CERTIFICATION_VALIDITY_DURATION;
20 use crate::cli::config;
21 use crate::cli::pki::vouch::CERTIFICATION_EXPIRATION;
22 use crate::cli::types::Time;
23
24 // Argument parser options.
25
26 /// Expiration argument kind specialization.
27 pub enum ExpirationKind {
28 Default,
29 Certification,
30 RetireIn,
31 }
32
33 impl From<usize> for ExpirationKind {
34 fn from(v: usize) -> ExpirationKind {
35 match v {
36 0 => {
37 debug_assert_eq!(0, DefaultKind::to_usize());
38 ExpirationKind::Default
39 },
40
41 1 => {
42 debug_assert_eq!(1, CertificationKind::to_usize());
43 ExpirationKind::Certification
44 },
45
46 2 => {
47 debug_assert_eq!(2, RetireInKind::to_usize());
48 ExpirationKind::RetireIn
49 },
50
51 _ => unreachable!(),
52 }
53 }
54 }
55
56 impl ExpirationKind {
57 fn name(&self) -> &'static str {
58 match self {
59 ExpirationKind::Default => "expiration",
60 ExpirationKind::Certification => "expiration",
61 ExpirationKind::RetireIn => "retire-in",
62 }
63 }
64 }
65
66 /// Default expiration parameter.
67 pub type DefaultKind = typenum::U0;
68
69 /// Specialization for third-party certifications.
70 pub type CertificationKind = typenum::U1;
71
72 /// Specialization for `sq key rotate --retire-in`.
73 pub type RetireInKind = typenum::U2;
74
75 #[derive(Debug)]
76 pub struct ExpirationArg<Kind = DefaultKind> {
77 expiration: Expiration,
78
79 /// Argument parser specializations.
80 arguments: std::marker::PhantomData<Kind>,
81 }
82
83 impl<Kind> Deref for ExpirationArg<Kind> {
84 type Target = Expiration;
85
86 fn deref(&self) -> &Self::Target {
87 &self.expiration
88 }
89 }
90
91 impl<Kind> ExpirationArg<Kind> {
92 /// Returns the expiration time.
93 pub fn value(&self) -> Expiration {
94 self.expiration.clone()
95 }
96 }
97
98 impl<Kind> clap::Args for ExpirationArg<Kind>
99 where
100 Kind: typenum::Unsigned,
101 {
102 fn augment_args(cmd: clap::Command) -> clap::Command {
103 let kind: ExpirationKind = Kind::to_usize().into();
104
105 const EXPIRATION_LONG_HELP: &str = "\
106 Sets the expiration time
107
108 EXPIRATION is either an ISO 8601 formatted date with an optional time \
109 or a custom duration. A duration takes the form `N[ymwds]`, where the \
110 letters stand for years, months, weeks, days, and seconds, respectively. \
111 Alternatively, the keyword `never` does not set an expiration time.";
112
113 const RETIRE_IN_LONG_HELP: &str = "\
114 Sets the time at which the certificate should be retired
115
116 TIME is either an ISO 8601 formatted date with an optional time \
117 or a custom duration. A duration takes the form `N[ymwds]`, where the \
118 letters stand for years, months, weeks, days, and seconds, respectively. \
119 Alternatively, the keyword `never` skips the certification of a \
120 revocation certificate.";
121
122 let name = kind.name();
123
124 cmd.arg(
125 clap::Arg::new(name)
126 .long(name)
127 .allow_hyphen_values(true)
128 .value_name(match kind {
129 ExpirationKind::Default => "EXPIRATION",
130 ExpirationKind::Certification => "EXPIRATION",
131 ExpirationKind::RetireIn => "TIME",
132 })
133 .value_parser(Expiration::new)
134 .default_value(match kind {
135 ExpirationKind::Default => Expiration::Never,
136 ExpirationKind::Certification =>
137 Expiration::from_duration(
138 THIRD_PARTY_CERTIFICATION_VALIDITY_DURATION),
139 ExpirationKind::RetireIn =>
140 Expiration::from_duration(
141 KEY_ROTATE_RETIRE_IN_DURATION),
142 })
143 .help(match kind {
144 ExpirationKind::Default | ExpirationKind::Certification =>
145 "Sets the expiration time",
146 ExpirationKind::RetireIn =>
147 "Sets the time at which the certificate should be retired",
148 })
149 .long_help(match kind {
150 ExpirationKind::Default => EXPIRATION_LONG_HELP.into(),
151 ExpirationKind::Certification =>
152 config::augment_help(CERTIFICATION_EXPIRATION,
153 EXPIRATION_LONG_HELP),
154 ExpirationKind::RetireIn => RETIRE_IN_LONG_HELP.into(),
155 })
156 )
157 }
158
159 fn augment_args_for_update(cmd: clap::Command) -> clap::Command {
160 Self::augment_args(cmd)
161 }
162 }
163
164 impl<Kind> clap::FromArgMatches for ExpirationArg<Kind>
165 where
166 Kind: typenum::Unsigned
167 {
168 fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches)
169 -> clap::error::Result<()>
170 {
171 let kind: ExpirationKind = Kind::to_usize().into();
172
173 if let Some(v) = matches.get_one::<Expiration>(kind.name()) {
174 self.expiration = v.clone();
175 }
176
177 Ok(())
178 }
179
180 fn from_arg_matches(matches: &clap::ArgMatches)
181 -> clap::error::Result<Self>
182 {
183 let mut expiration = ExpirationArg {
184 expiration: Expiration::Never,
185 arguments: Default::default(),
186 };
187
188 expiration.update_from_arg_matches(matches)?;
189 Ok(expiration)
190 }
191 }
192
193 /// Expiration information
194 ///
195 /// This enum tracks expiry information either in the form of a timestamp or
196 /// a duration.
197 #[derive(Debug, Clone, Eq, PartialEq)]
198 #[non_exhaustive]
199 pub enum Expiration {
200 /// An expiry timestamp
201 Timestamp(Time),
202 /// There is no expiry
203 Never,
204 }
205
206 impl Expiration {
207 /// Create a new Expiration in a Result
208 ///
209 /// If `expiry` ends with `"y"`, `"m"`, `"w"`, `"w"`, `"d"` or `"s"` it
210 /// is treated as a duration, which is parsed using `parse_duration()` and
211 /// returned in an `Expiration::Duration`.
212 /// If the special keyword `"never"` is provided as `expiry`,
213 /// `Expiration::Never` is returned.
214 /// If `expiry` is an ISO 8601 compatible string it is returned as
215 /// `cli::types::Time` in an `Expiration::Timestamp`.
216 pub fn new(expiry: &str) -> Result<Self> {
217 match expiry {
218 "never" => Ok(Expiration::Never),
219 _ => Ok(Expiration::Timestamp(Time::from_str(expiry)?)),
220 }
221 }
222
223 /// Create a new Expiration from a `Duration`.
224 pub fn from_duration(duration: Duration) -> Self {
225 Expiration::Timestamp(Time::from_duration(duration))
226 }
227
228 /// Return the expiry as an optional Duration in a Result
229 ///
230 /// This method returns an Error if the reference time is later than the
231 /// time provided in an `Expiration::Timestamp(Time)`.
232 ///
233 /// If self is `Expiration::Timestamp(Time)`, `reference` is used as the start
234 /// of a period, `Some(Time - reference)` is returned.
235 /// If self is `Expiration::Duration(duration)`, `Some(duration)` is returned.
236 /// If self is `Expiration::Never`, `None` is returned.
237 pub fn as_duration(
238 &self,
239 reference: DateTime<Utc>,
240 ) -> Result<Option<Duration>> {
241 match self {
242 Expiration::Timestamp(time) => {
243 Ok(Some(time.duration_since(reference.into())?))
244 }
245 Expiration::Never => Ok(None),
246 }
247 }
248
249 /// Return the expiry as absolute time.
250 pub fn to_system_time(&self, now: SystemTime) -> Result<Option<SystemTime>> {
251 match self {
252 Expiration::Timestamp(t) => Ok(Some(t.to_system_time(now)?)),
253 Expiration::Never => Ok(None),
254 }
255 }
256 }
257
258 impl FromStr for Expiration {
259 type Err = anyhow::Error;
260
261 fn from_str(s: &str) -> Result<Expiration> {
262 Expiration::new(s)
263 }
264 }
265
266 impl Display for Expiration {
267 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
268 match self {
269 Expiration::Timestamp(time) => write!(f, "{}", time),
270 Expiration::Never => write!(f, "never"),
271 }
272 }
273 }
274
275 impl IntoResettable<OsStr> for Expiration {
276 fn into_resettable(self) -> Resettable<OsStr> {
277 Resettable::Value(format!("{}", self).into()).into()
278 }
279 }
280
281 #[cfg(test)]
282 mod test {
283 use super::*;
284
285 use crate::SECONDS_IN_YEAR;
286
287 #[test]
288 fn test_expiry() {
289 assert_eq!(
290 Expiration::new("1y").unwrap(),
291 Expiration::from_duration(Duration::new(SECONDS_IN_YEAR, 0)),
292 );
293 assert_eq!(
294 Expiration::new("2023-05-15T20:00:00Z").unwrap(),
295 Expiration::Timestamp(Time::from_str("2023-05-15T20:00:00Z").unwrap()),
296 );
297 assert_eq!(
298 Expiration::new("never").unwrap(),
299 Expiration::Never,
300 );
301 }
302
303 #[test]
304 fn test_expiry_as_duration() {
305 let reference = DateTime::from_timestamp(1, 0).unwrap();
306
307 let expiry = Expiration::Timestamp(
308 Time::try_from(DateTime::from_timestamp(2, 0).unwrap())
309 .expect("valid"));
310 assert_eq!(
311 expiry.as_duration(reference).unwrap(),
312 Some(Duration::new(1, 0)),
313 );
314
315 let expiry = Expiration::from_duration(Duration::new(2, 0));
316 assert_eq!(
317 expiry.as_duration(reference).unwrap(),
318 Some(Duration::new(2, 0)),
319 );
320
321 let expiry = Expiration::Never;
322 assert_eq!(expiry.as_duration(reference).unwrap(), None);
323 }
324
325 #[test]
326 fn test_expiry_as_duration_errors() {
327 let reference = DateTime::from_timestamp(2, 0).unwrap();
328 let expiry = Expiration::Timestamp(
329 Time::try_from(DateTime::from_timestamp(1, 0).unwrap())
330 .expect("valid"));
331 assert!(expiry.as_duration(reference).is_err());
332 }
333 }