Skip to main content

vcon_server/tenants/
key_life.rs

1//! How long an access key lives, and when it was last used.
2//!
3//! A new key expires 90 days after it is made unless its maker asks for
4//! another number of days, from 1 to 365, or for no expiry. The
5//! configuration can refuse a key with no expiry (`keys.no_expiry`). A key
6//! made before keys had an expiry has none.
7//!
8//! A key's last-used time is the start of the minute of an accepted
9//! request. It is written when a request is accepted in a later minute
10//! than the one stored, so one key causes at most one write to the registry
11//! in a minute, however many requests it makes.
12
13use std::sync::atomic::Ordering;
14
15use super::{TenantError, Tenants, commit};
16use crate::clock::nanos;
17use crate::ids::KeyId;
18
19/// The days a new key lives when its maker names none.
20pub const DEFAULT_DAYS: u32 = 90;
21
22/// The most days a new key with an expiry may live.
23pub const MAX_DAYS: u32 = 365;
24
25/// The nanoseconds in a second: the resolution of an expiry.
26const SECOND: i64 = 1_000_000_000;
27
28/// The nanoseconds in a day.
29const DAY: i64 = 86_400 * SECOND;
30
31/// The nanoseconds in a minute: the resolution of a last-used time.
32const MINUTE: i64 = 60 * 1_000_000_000;
33
34/// What the maker of a key asked for its expiry.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum KeyLife {
37    /// 90 days.
38    #[default]
39    Default,
40    /// This many days, from 1 to 365.
41    Days(u32),
42    /// No expiry.
43    Never,
44    /// An expiry no key can have, as a request asked it: days outside 1
45    /// to 365, or days and no expiry together. It is refused where
46    /// the key would be made, so the refusal is recorded as the others are
47    /// and comes after that of the key's scopes.
48    Invalid,
49}
50
51impl KeyLife {
52    /// The life a request's two fields ask for: `days` (`expires_in_days`)
53    /// and `never` (`no_expiry`), each absent or given.
54    /// [`KeyLife::Invalid`] when the days are not from 1 to 365, or
55    /// when days are given and no expiry is asked as well.
56    #[must_use]
57    pub fn asked(days: Option<i64>, never: Option<bool>) -> KeyLife {
58        match (days, never.unwrap_or(false)) {
59            (None, false) => KeyLife::Default,
60            (None, true) => KeyLife::Never,
61            (Some(_), true) => KeyLife::Invalid,
62            (Some(days), false) => u32::try_from(days)
63                .ok()
64                .filter(|days| (1..=MAX_DAYS).contains(days))
65                .map_or(KeyLife::Invalid, KeyLife::Days),
66        }
67    }
68
69    /// When a key made at `now` (nanoseconds) with this life expires, cut
70    /// down to the whole second; `Ok(None)` for no expiry.
71    ///
72    /// # Errors
73    ///
74    /// [`TenantError::BadExpiry`] for days outside 1 to [`MAX_DAYS`], for
75    /// no expiry when `never_allowed` is false, and for a time past the
76    /// range of the clock.
77    pub(crate) fn expires_at(
78        self,
79        now: i64,
80        never_allowed: bool,
81    ) -> Result<Option<i64>, TenantError> {
82        let days = match self {
83            KeyLife::Never if never_allowed => return Ok(None),
84            KeyLife::Never => return Err(TenantError::BadExpiry),
85            KeyLife::Default => DEFAULT_DAYS,
86            KeyLife::Days(days) if (1..=MAX_DAYS).contains(&days) => days,
87            KeyLife::Days(_) | KeyLife::Invalid => return Err(TenantError::BadExpiry),
88        };
89        // Cut down to the whole second: the time is then written with no
90        // fraction, so the answer that carries it has one length whenever
91        // the key is made, and the key never lives longer than asked.
92        i64::from(days)
93            .checked_mul(DAY)
94            .and_then(|life| now.checked_add(life))
95            .and_then(|at| at.checked_sub(at.rem_euclid(SECOND)))
96            .map(Some)
97            .ok_or(TenantError::BadExpiry)
98    }
99}
100
101/// Whether a key with this expiry is refused at `now`: from the instant of
102/// its expiry on. A key with no expiry never is.
103#[must_use]
104pub(crate) fn expired(expires_at: Option<i64>, now: i64) -> bool {
105    expires_at.is_some_and(|at| now >= at)
106}
107
108/// The start of the minute `at` (nanoseconds) is in.
109#[must_use]
110pub(crate) fn minute(at: i64) -> i64 {
111    at - at.rem_euclid(MINUTE)
112}
113
114/// The last-used time to write for a request accepted at `now`, given the
115/// one `stored`: the start of the minute of `now` when that is later than
116/// the stored time, and None when there is nothing to write.
117#[must_use]
118pub(crate) fn last_used_due(stored: Option<i64>, now: i64) -> Option<i64> {
119    let due = minute(now);
120    stored.is_none_or(|stored| stored < due).then_some(due)
121}
122
123impl Tenants {
124    /// Whether a key may be made with no expiry (`keys.no_expiry`): true
125    /// until [`Tenants::allow_no_expiry`] says otherwise.
126    pub(crate) fn no_expiry_allowed(&self) -> bool {
127        self.no_expiry.load(Ordering::Relaxed)
128    }
129
130    /// Sets whether a key may be made with no expiry, as the
131    /// configuration says (`keys.no_expiry`). Keys made earlier are not
132    /// changed.
133    pub fn allow_no_expiry(&self, allowed: bool) {
134        self.no_expiry.store(allowed, Ordering::Relaxed);
135    }
136
137    /// Notes that a request by the key `id` was accepted now, given the
138    /// last-used time read with the key: writes the minute of now when it
139    /// is later than the one stored, and nothing otherwise. Whether a row
140    /// was changed. A failure to write is not an error of the request: the
141    /// time is written by a later request.
142    pub(crate) fn key_used(&self, id: KeyId, stored: Option<i64>) -> bool {
143        let Some(due) = last_used_due(stored, nanos(self.now())) else {
144            return false;
145        };
146        let written = || {
147            let mut tx = self.registry.immediate()?;
148            let changed = tx.touch_key(id, due)?;
149            commit(tx)?;
150            Ok::<bool, TenantError>(changed)
151        };
152        written().unwrap_or(false)
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use time::Duration;
159    use time::macros::datetime;
160
161    use super::*;
162    use crate::access::{self, AuthError, Scope, Scopes};
163    use crate::audit::Actor;
164    use crate::backend::{CommitError, KeyRow};
165    use crate::clock::from_nanos;
166    use crate::ids::TenantId;
167    use crate::tenants::NewKey;
168    use crate::tenants::tests::{Fixture, fixture};
169
170    /// The fixture's clock starts here.
171    const START: time::OffsetDateTime = datetime!(2026-10-23 12:00 UTC);
172
173    fn start() -> i64 {
174        nanos(START)
175    }
176
177    fn vcon_scopes() -> Scopes {
178        Scopes::of(&[Scope::Write, Scope::Read])
179    }
180
181    fn tenant(f: &Fixture) -> TenantId {
182        f.tenants.create(Actor::Cli, "acme", None).expect("made")
183    }
184
185    fn key(f: &Fixture, life: KeyLife) -> NewKey {
186        let t = tenant(f);
187        f.tenants
188            .create_key_for(Actor::Cli, Some(t), vcon_scopes(), "ingest", life)
189            .expect("made")
190    }
191
192    fn row(f: &Fixture, id: KeyId) -> KeyRow {
193        f.tenants
194            .registry
195            .snapshot()
196            .expect("a snapshot")
197            .key(id)
198            .expect("read")
199            .expect("the key's row")
200    }
201
202    fn auth(f: &Fixture, key: &NewKey) -> Result<access::Caller, AuthError> {
203        access::authenticate(&f.tenants, Some(&format!("Bearer {}", key.token)))
204    }
205
206    /// The failed authentications counted in the tenant's log.
207    fn failures(f: &Fixture, tenant: TenantId) -> i64 {
208        f.tenant_catalog(tenant)
209            .query_row(
210                "SELECT count(*) FROM audit WHERE action = 'auth_failed'",
211                [],
212                |r| r.get(0),
213            )
214            .expect("counted")
215    }
216
217    // What must work: the request's fields.
218
219    #[test]
220    fn a_request_that_names_no_expiry_field_asks_for_the_default() {
221        assert_eq!(KeyLife::asked(None, None), KeyLife::Default, "none");
222        assert_eq!(
223            KeyLife::asked(None, Some(false)),
224            KeyLife::Default,
225            "no_expiry false is the same as absent"
226        );
227    }
228
229    #[test]
230    fn a_request_may_ask_for_any_number_of_days_from_1_to_365() {
231        for days in [1, 2, 30, 90, 364, 365] {
232            assert_eq!(
233                KeyLife::asked(Some(i64::from(days)), None),
234                KeyLife::Days(days),
235                "{days} days"
236            );
237        }
238    }
239
240    #[test]
241    fn a_request_may_ask_for_no_expiry() {
242        assert_eq!(
243            KeyLife::asked(None, Some(true)),
244            KeyLife::Never,
245            "no_expiry true"
246        );
247    }
248
249    #[test]
250    fn days_with_no_expiry_false_are_days() {
251        assert_eq!(
252            KeyLife::asked(Some(7), Some(false)),
253            KeyLife::Days(7),
254            "the false changes nothing"
255        );
256    }
257
258    // What must work: the expiry of a new key.
259
260    #[test]
261    fn the_default_life_is_90_days() {
262        assert_eq!(DEFAULT_DAYS, 90, "the approved default");
263        assert_eq!(
264            KeyLife::Default.expires_at(1_000 * SECOND, true),
265            Ok(Some(1_000 * SECOND + 90 * DAY)),
266            "90 days after the key is made"
267        );
268        assert_eq!(
269            KeyLife::Default.expires_at(1_000 * SECOND, false),
270            Ok(Some(1_000 * SECOND + 90 * DAY)),
271            "the same where no expiry is refused"
272        );
273    }
274
275    #[test]
276    fn a_life_in_days_ends_that_many_days_after_the_key_is_made() {
277        for days in [1_u32, 30, 365] {
278            assert_eq!(
279                KeyLife::Days(days).expires_at(5 * SECOND, true),
280                Ok(Some(5 * SECOND + i64::from(days) * DAY)),
281                "{days} days"
282            );
283        }
284    }
285
286    // An expiry is a whole second, so the answer that carries it has one
287    // length whenever the key is made.
288
289    #[test]
290    fn an_expiry_is_cut_to_the_whole_second() {
291        assert_eq!(
292            KeyLife::Default.expires_at(7 * SECOND + 999_999_999, true),
293            Ok(Some(7 * SECOND + 90 * DAY)),
294            "the last nanosecond of a second"
295        );
296        assert_eq!(
297            KeyLife::Days(1).expires_at(7 * SECOND + 1, true),
298            Ok(Some(7 * SECOND + DAY)),
299            "the first nanosecond after a second"
300        );
301    }
302
303    #[test]
304    fn an_expiry_made_on_the_second_is_not_moved() {
305        assert_eq!(
306            KeyLife::Days(30).expires_at(7 * SECOND, true),
307            Ok(Some(7 * SECOND + 30 * DAY)),
308            "nothing to cut"
309        );
310    }
311
312    #[test]
313    fn an_expiry_is_never_after_the_days_asked() {
314        for nanos in [0, 1, 500_000_000, 999_999_999] {
315            let now = 1_762_000_000 * SECOND + nanos;
316            let at = KeyLife::Days(2)
317                .expires_at(now, true)
318                .expect("two days")
319                .expect("a time");
320            assert_eq!(at % SECOND, 0, "a whole second at {nanos} ns");
321            assert!(
322                at <= now + 2 * DAY && now + 2 * DAY - at < SECOND,
323                "cut down, by less than a second, at {nanos} ns"
324            );
325        }
326    }
327
328    #[test]
329    fn an_expiry_before_1970_is_cut_down_too() {
330        assert_eq!(
331            KeyLife::Days(1).expires_at(-2 * DAY - 1, true),
332            Ok(Some(-DAY - SECOND)),
333            "toward the earlier second, not toward zero"
334        );
335    }
336
337    #[test]
338    fn a_key_made_within_a_second_expires_on_a_whole_second() {
339        let f = fixture();
340        let t = tenant(&f);
341        f.clock.set(START + Duration::nanoseconds(123_456_789));
342        let made = f
343            .tenants
344            .create_key(Actor::Cli, Some(t), vcon_scopes(), "ingest")
345            .expect("made");
346        assert_eq!(
347            row(&f, made.id).expires_at,
348            Some(start() + 90 * DAY),
349            "the stored expiry has no part of a second"
350        );
351        assert_eq!(
352            made.expires_at,
353            Some(START + Duration::days(90)),
354            "nor has the expiry its maker is told"
355        );
356    }
357
358    #[test]
359    fn the_longest_life_in_days_is_365() {
360        assert_eq!(MAX_DAYS, 365, "the approved maximum, one year");
361        assert!(
362            KeyLife::Days(MAX_DAYS).expires_at(0, false).is_ok(),
363            "the maximum itself is allowed"
364        );
365    }
366
367    #[test]
368    fn a_key_with_no_expiry_has_no_time_where_that_is_allowed() {
369        assert_eq!(KeyLife::Never.expires_at(77, true), Ok(None), "no time");
370    }
371
372    #[test]
373    fn a_key_is_not_expired_before_its_time_and_never_without_one() {
374        assert!(!expired(Some(100), 99), "one nanosecond before");
375        assert!(!expired(Some(100), i64::MIN), "long before");
376        assert!(!expired(None, i64::MAX), "no expiry, at the end of time");
377    }
378
379    // What must work: the last-used time.
380
381    #[test]
382    fn a_time_is_cut_to_the_start_of_its_minute() {
383        assert_eq!(minute(0), 0, "the epoch");
384        assert_eq!(minute(MINUTE), MINUTE, "the start of a minute");
385        assert_eq!(minute(MINUTE + 1), MINUTE, "just inside it");
386        assert_eq!(minute(2 * MINUTE - 1), MINUTE, "its last nanosecond");
387        assert_eq!(minute(start() + 59 * 1_000_000_000), start(), "59 s in");
388    }
389
390    #[test]
391    fn a_key_never_used_is_due_the_minute_of_its_first_request() {
392        assert_eq!(
393            last_used_due(None, 3 * MINUTE + 5),
394            Some(3 * MINUTE),
395            "the minute of now"
396        );
397    }
398
399    #[test]
400    fn a_request_in_a_later_minute_is_due_that_minute() {
401        assert_eq!(
402            last_used_due(Some(3 * MINUTE), 4 * MINUTE),
403            Some(4 * MINUTE),
404            "the first nanosecond of the next minute"
405        );
406        assert_eq!(
407            last_used_due(Some(3 * MINUTE), 90 * MINUTE + 17),
408            Some(90 * MINUTE),
409            "much later"
410        );
411    }
412
413    // What must be refused: the request's fields and the life.
414
415    #[test]
416    fn days_below_1_are_refused() {
417        for days in [0, -1, -365, i64::MIN] {
418            assert_eq!(
419                KeyLife::asked(Some(days), None),
420                KeyLife::Invalid,
421                "{days} days"
422            );
423        }
424    }
425
426    #[test]
427    fn days_above_365_are_refused() {
428        for days in [366, 367, 1_000, i64::from(u32::MAX) + 90, i64::MAX] {
429            assert_eq!(
430                KeyLife::asked(Some(days), None),
431                KeyLife::Invalid,
432                "{days} days"
433            );
434        }
435    }
436
437    #[test]
438    fn days_and_no_expiry_together_are_refused() {
439        assert_eq!(
440            KeyLife::asked(Some(30), Some(true)),
441            KeyLife::Invalid,
442            "the two contradict each other"
443        );
444    }
445
446    #[test]
447    fn no_expiry_is_refused_where_the_configuration_refuses_it() {
448        assert_eq!(
449            KeyLife::Never.expires_at(77, false),
450            Err(TenantError::BadExpiry),
451            "keys.no_expiry is false"
452        );
453    }
454
455    #[test]
456    fn an_invalid_life_makes_no_expiry_and_no_key() {
457        for allowed in [true, false] {
458            assert_eq!(
459                KeyLife::Invalid.expires_at(0, allowed),
460                Err(TenantError::BadExpiry),
461                "no expiry allowed: {allowed}"
462            );
463        }
464    }
465
466    #[test]
467    fn a_life_of_days_outside_the_range_is_refused_however_it_was_made() {
468        for days in [0, 366, u32::MAX] {
469            assert_eq!(
470                KeyLife::Days(days).expires_at(0, true),
471                Err(TenantError::BadExpiry),
472                "{days} days"
473            );
474        }
475    }
476
477    #[test]
478    fn a_key_is_expired_from_the_instant_of_its_expiry() {
479        assert!(expired(Some(100), 100), "at the instant");
480        assert!(expired(Some(100), 101), "one nanosecond after");
481        assert!(expired(Some(100), i64::MAX), "long after");
482    }
483
484    // The edges of the pure rules.
485
486    #[test]
487    fn an_expiry_past_the_range_of_the_clock_is_refused_not_wrapped() {
488        assert_eq!(
489            KeyLife::Default.expires_at(i64::MAX, true),
490            Err(TenantError::BadExpiry),
491            "the default from the last instant"
492        );
493        assert_eq!(
494            KeyLife::Days(1).expires_at(i64::MAX - DAY + 1, true),
495            Err(TenantError::BadExpiry),
496            "one nanosecond too far"
497        );
498        assert_eq!(
499            KeyLife::Days(1).expires_at(i64::MAX - DAY, true),
500            Ok(Some(i64::MAX - i64::MAX % SECOND)),
501            "the second of the last instant"
502        );
503    }
504
505    #[test]
506    fn a_request_in_the_stored_minute_is_due_nothing() {
507        assert_eq!(last_used_due(Some(3 * MINUTE), 3 * MINUTE), None, "start");
508        assert_eq!(
509            last_used_due(Some(3 * MINUTE), 4 * MINUTE - 1),
510            None,
511            "the minute's last nanosecond"
512        );
513    }
514
515    #[test]
516    fn a_clock_that_went_back_is_due_nothing() {
517        assert_eq!(
518            last_used_due(Some(10 * MINUTE), 3 * MINUTE),
519            None,
520            "the stored time is later than now"
521        );
522    }
523
524    #[test]
525    fn a_time_before_the_epoch_is_cut_toward_the_past() {
526        assert_eq!(minute(-1), -MINUTE, "the minute before the epoch");
527        assert_eq!(minute(-MINUTE), -MINUTE, "its start");
528        assert_eq!(minute(-MINUTE - 1), -2 * MINUTE, "the one before");
529    }
530
531    #[test]
532    fn the_default_is_the_life_a_caller_gets_without_asking() {
533        assert_eq!(KeyLife::default(), KeyLife::Default, "Default");
534    }
535
536    // What must work: keys in the registry.
537
538    #[test]
539    fn a_key_made_without_a_life_expires_90_days_after_the_clock() {
540        let f = fixture();
541        let t = tenant(&f);
542        let made = f
543            .tenants
544            .create_key(Actor::Cli, Some(t), vcon_scopes(), "ingest")
545            .expect("made");
546        assert_eq!(
547            row(&f, made.id).expires_at,
548            Some(start() + 90 * DAY),
549            "the stored expiry"
550        );
551        assert_eq!(
552            made.expires_at,
553            Some(START + Duration::days(90)),
554            "the expiry its maker is told"
555        );
556        assert_eq!(row(&f, made.id).last_used_at, None, "never used");
557    }
558
559    #[test]
560    fn a_key_made_for_30_days_expires_then() {
561        let f = fixture();
562        let made = key(&f, KeyLife::Days(30));
563        assert_eq!(
564            row(&f, made.id).expires_at,
565            Some(start() + 30 * DAY),
566            "the stored expiry"
567        );
568        assert_eq!(
569            made.expires_at,
570            Some(START + Duration::days(30)),
571            "the expiry its maker is told"
572        );
573    }
574
575    #[test]
576    fn a_key_made_with_no_expiry_stores_none() {
577        let f = fixture();
578        let made = key(&f, KeyLife::Never);
579        assert_eq!(row(&f, made.id).expires_at, None, "the stored expiry");
580        assert_eq!(made.expires_at, None, "the expiry its maker is told");
581        f.clock.set(START + Duration::days(4_000));
582        assert!(auth(&f, &made).is_ok(), "accepted years later");
583    }
584
585    #[test]
586    fn an_operator_key_has_an_expiry_as_a_tenant_key_has() {
587        let f = fixture();
588        let made = f
589            .tenants
590            .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "operator")
591            .expect("made");
592        assert_eq!(
593            row(&f, made.id).expires_at,
594            Some(start() + 90 * DAY),
595            "90 days"
596        );
597    }
598
599    #[test]
600    fn a_key_is_accepted_until_the_nanosecond_before_its_expiry() {
601        let f = fixture();
602        let made = key(&f, KeyLife::Days(1));
603        f.clock
604            .set(START + Duration::days(1) - Duration::nanoseconds(1));
605        assert!(auth(&f, &made).is_ok(), "the last instant of its life");
606    }
607
608    #[test]
609    fn a_list_shows_each_keys_expiry_and_last_used_time() {
610        let f = fixture();
611        let made = key(&f, KeyLife::Days(10));
612        f.clock.set(START + Duration::seconds(125));
613        assert!(auth(&f, &made).is_ok(), "used");
614        let listed = f.tenants.list_keys(Actor::Cli, None).expect("listed");
615        assert_eq!(listed.len(), 1, "one key");
616        assert_eq!(
617            listed[0].expires_at,
618            Some(START + Duration::days(10)),
619            "the expiry"
620        );
621        assert_eq!(
622            listed[0].last_used_at,
623            Some(START + Duration::minutes(2)),
624            "the minute of its use"
625        );
626        let json = listed[0].to_json().expect("written");
627        assert_eq!(json["expires_at"], "2026-11-02T12:00:00Z", "as JSON");
628        assert_eq!(json["last_used_at"], "2026-10-23T12:02:00Z", "as JSON");
629    }
630
631    #[test]
632    fn a_key_never_used_and_with_no_expiry_lists_both_as_null() {
633        let f = fixture();
634        key(&f, KeyLife::Never);
635        let listed = f.tenants.list_keys(Actor::Cli, None).expect("listed");
636        let json = listed[0].to_json().expect("written");
637        assert!(json["expires_at"].is_null(), "no expiry is null");
638        assert!(json["last_used_at"].is_null(), "never used is null");
639        assert!(
640            json.as_object()
641                .expect("an object")
642                .contains_key("expires_at")
643                && json
644                    .as_object()
645                    .expect("an object")
646                    .contains_key("last_used_at"),
647            "both names are present"
648        );
649    }
650
651    #[test]
652    fn the_first_accepted_request_writes_the_minute_it_came_in() {
653        let f = fixture();
654        let made = key(&f, KeyLife::Default);
655        f.clock.set(START + Duration::seconds(61));
656        assert!(auth(&f, &made).is_ok(), "accepted");
657        assert_eq!(
658            row(&f, made.id).last_used_at,
659            Some(start() + MINUTE),
660            "the start of the minute of the request"
661        );
662    }
663
664    #[test]
665    fn a_request_in_a_later_minute_moves_the_time() {
666        let f = fixture();
667        let made = key(&f, KeyLife::Default);
668        assert!(auth(&f, &made).is_ok(), "the first");
669        f.clock.set(START + Duration::minutes(7));
670        assert!(auth(&f, &made).is_ok(), "the second");
671        assert_eq!(
672            row(&f, made.id).last_used_at,
673            Some(start() + 7 * MINUTE),
674            "the later minute"
675        );
676    }
677
678    #[test]
679    fn the_times_are_kept_over_a_restart() {
680        let mut f = fixture();
681        let made = key(&f, KeyLife::Days(5));
682        assert!(auth(&f, &made).is_ok(), "used");
683        let before = row(&f, made.id);
684        f.restart();
685        assert_eq!(row(&f, made.id), before, "the row after a restart");
686        assert_eq!(before.last_used_at, Some(start()), "the minute of the use");
687    }
688
689    #[test]
690    fn using_a_key_changes_no_other_column_of_its_row() {
691        let f = fixture();
692        let made = key(&f, KeyLife::Days(5));
693        let before = row(&f, made.id);
694        f.clock.set(START + Duration::minutes(3));
695        assert!(auth(&f, &made).is_ok(), "used");
696        let after = row(&f, made.id);
697        assert_eq!(
698            KeyRow {
699                last_used_at: None,
700                ..after
701            },
702            before,
703            "everything but the last-used time"
704        );
705    }
706
707    #[test]
708    fn a_last_used_write_is_not_an_audit_record() {
709        let f = fixture();
710        let made = key(&f, KeyLife::Default);
711        let before = f.count("SELECT count(*) FROM audit");
712        assert!(auth(&f, &made).is_ok(), "used");
713        assert!(row(&f, made.id).last_used_at.is_some(), "written");
714        assert_eq!(
715            f.count("SELECT count(*) FROM audit"),
716            before,
717            "the admin log is as it was"
718        );
719    }
720
721    // What must be refused: keys in the registry.
722
723    #[test]
724    fn an_expired_key_is_refused_as_expired() {
725        let f = fixture();
726        let made = key(&f, KeyLife::Days(1));
727        f.clock.set(START + Duration::days(1));
728        assert_eq!(
729            auth(&f, &made),
730            Err(AuthError::Expired),
731            "at the instant of its expiry"
732        );
733        f.clock.set(START + Duration::days(400));
734        assert_eq!(auth(&f, &made), Err(AuthError::Expired), "long after");
735    }
736
737    #[test]
738    fn a_key_made_by_default_is_refused_after_90_days() {
739        let f = fixture();
740        let made = key(&f, KeyLife::Default);
741        f.clock.set(START + Duration::days(89));
742        assert!(auth(&f, &made).is_ok(), "on day 89");
743        f.clock.set(START + Duration::days(90));
744        assert_eq!(auth(&f, &made), Err(AuthError::Expired), "on day 90");
745    }
746
747    #[test]
748    fn an_expired_keys_refusal_is_counted_under_the_key() {
749        let f = fixture();
750        let made = key(&f, KeyLife::Days(1));
751        f.clock.set(START + Duration::days(2));
752        let t = row(&f, made.id).tenant.expect("a tenant key");
753        let before = failures(&f, t);
754        assert_eq!(auth(&f, &made), Err(AuthError::Expired), "refused");
755        assert_eq!(failures(&f, t), before + 1, "one failed authentication");
756    }
757
758    #[test]
759    fn a_wrong_secret_for_an_expired_key_learns_nothing_of_the_expiry() {
760        let f = fixture();
761        let made = key(&f, KeyLife::Days(1));
762        f.clock.set(START + Duration::days(2));
763        let mut token = made.token.clone();
764        // The first character of the secret, after `vcs_`, the id and `_`.
765        let first = token.remove(21);
766        token.insert(21, if first == 'A' { 'B' } else { 'A' });
767        assert_eq!(
768            access::authenticate(&f.tenants, Some(&format!("Bearer {token}"))),
769            Err(AuthError::Unknown),
770            "the same answer as for a key nobody has"
771        );
772    }
773
774    #[test]
775    fn a_key_both_revoked_and_expired_is_refused_as_revoked() {
776        let f = fixture();
777        let made = key(&f, KeyLife::Days(1));
778        f.tenants.revoke_key(Actor::Cli, made.id).expect("revoked");
779        f.clock.set(START + Duration::days(2));
780        assert_eq!(
781            auth(&f, &made),
782            Err(AuthError::Revoked),
783            "revocation is told first"
784        );
785    }
786
787    #[test]
788    fn a_key_with_no_expiry_is_refused_and_recorded_where_the_configuration_refuses_it() {
789        let f = fixture();
790        let t = tenant(&f);
791        f.tenants.allow_no_expiry(false);
792        let refused = f.tenants.create_key_for(
793            Actor::Cli,
794            Some(t),
795            vcon_scopes(),
796            "forever",
797            KeyLife::Never,
798        );
799        assert_eq!(refused.err(), Some(TenantError::BadExpiry), "refused");
800        assert_eq!(f.count("SELECT count(*) FROM api_key"), 0, "no key is made");
801        let recorded = f.admin_records("key_create");
802        assert_eq!(recorded.len(), 1, "one record");
803        assert_eq!(recorded[0]["status"], 422, "the refusal's status");
804    }
805
806    #[test]
807    fn a_life_of_days_outside_the_range_makes_no_key() {
808        let f = fixture();
809        let t = tenant(&f);
810        for days in [0, 366] {
811            let refused = f.tenants.create_key_for(
812                Actor::Cli,
813                Some(t),
814                vcon_scopes(),
815                "ingest",
816                KeyLife::Days(days),
817            );
818            assert_eq!(refused.err(), Some(TenantError::BadExpiry), "{days} days");
819        }
820        assert_eq!(f.count("SELECT count(*) FROM api_key"), 0, "no key is made");
821    }
822
823    #[test]
824    fn an_operator_key_with_no_expiry_is_refused_where_the_configuration_refuses_it() {
825        let f = fixture();
826        f.tenants.allow_no_expiry(false);
827        let refused = f.tenants.create_key_for(
828            Actor::Cli,
829            None,
830            Scopes::of(&[Scope::Admin]),
831            "operator",
832            KeyLife::Never,
833        );
834        assert_eq!(refused.err(), Some(TenantError::BadExpiry), "refused");
835    }
836
837    #[test]
838    fn a_refused_request_does_not_move_the_last_used_time() {
839        let f = fixture();
840        let made = key(&f, KeyLife::Days(1));
841        assert!(auth(&f, &made).is_ok(), "used once");
842        let used = row(&f, made.id).last_used_at;
843        f.clock.set(START + Duration::days(3));
844        assert_eq!(auth(&f, &made), Err(AuthError::Expired), "expired");
845        assert_eq!(row(&f, made.id).last_used_at, used, "after the expiry");
846    }
847
848    #[test]
849    fn a_wrong_secret_does_not_move_the_last_used_time() {
850        let f = fixture();
851        let made = key(&f, KeyLife::Default);
852        let mut token = made.token.clone();
853        // The first character of the secret, after `vcs_`, the id and `_`.
854        let first = token.remove(21);
855        token.insert(21, if first == 'A' { 'B' } else { 'A' });
856        assert!(
857            access::authenticate(&f.tenants, Some(&format!("Bearer {token}"))).is_err(),
858            "refused"
859        );
860        assert_eq!(row(&f, made.id).last_used_at, None, "never used");
861    }
862
863    #[test]
864    fn a_revoked_key_does_not_move_the_last_used_time() {
865        let f = fixture();
866        let made = key(&f, KeyLife::Default);
867        f.tenants.revoke_key(Actor::Cli, made.id).expect("revoked");
868        assert_eq!(auth(&f, &made), Err(AuthError::Revoked), "refused");
869        assert_eq!(row(&f, made.id).last_used_at, None, "never used");
870    }
871
872    // The edges: keys in the registry.
873
874    #[test]
875    fn requests_in_one_minute_write_once() {
876        let f = fixture();
877        let made = key(&f, KeyLife::Default);
878        assert!(f.tenants.key_used(made.id, None), "the first writes");
879        let stored = row(&f, made.id).last_used_at;
880        assert_eq!(stored, Some(start()), "the minute");
881        f.clock.set(START + Duration::seconds(59));
882        assert!(
883            !f.tenants.key_used(made.id, stored),
884            "a request 59 s later writes nothing"
885        );
886        assert!(auth(&f, &made).is_ok(), "and is accepted");
887        assert_eq!(
888            row(&f, made.id).last_used_at,
889            stored,
890            "the time is the same"
891        );
892    }
893
894    #[test]
895    fn two_servers_that_read_the_same_row_write_the_minute_once() {
896        let f = fixture();
897        let made = key(&f, KeyLife::Default);
898        assert!(
899            f.tenants.key_used(made.id, None),
900            "the first changes the row"
901        );
902        assert!(
903            !f.tenants.key_used(made.id, None),
904            "the second read the row before the first wrote, and changes nothing"
905        );
906    }
907
908    #[test]
909    fn a_clock_that_went_back_does_not_move_the_time_back() {
910        let f = fixture();
911        let made = key(&f, KeyLife::Default);
912        f.clock.set(START + Duration::minutes(10));
913        assert!(auth(&f, &made).is_ok(), "used");
914        f.clock.set(START + Duration::minutes(2));
915        assert!(auth(&f, &made).is_ok(), "used at an earlier time");
916        assert!(
917            !f.tenants.key_used(made.id, None),
918            "even a writer that read no time changes nothing"
919        );
920        assert_eq!(
921            row(&f, made.id).last_used_at,
922            Some(start() + 10 * MINUTE),
923            "the later time is kept"
924        );
925    }
926
927    #[test]
928    fn a_last_used_write_that_fails_does_not_refuse_the_request() {
929        let f = fixture();
930        let made = key(&f, KeyLife::Default);
931        f.tenants.registry.fail_commit(1, CommitError::RolledBack);
932        assert!(auth(&f, &made).is_ok(), "accepted all the same");
933        assert_eq!(row(&f, made.id).last_used_at, None, "nothing was written");
934        f.clock.set(START + Duration::seconds(5));
935        assert!(auth(&f, &made).is_ok(), "the next request");
936        assert_eq!(
937            row(&f, made.id).last_used_at,
938            Some(start()),
939            "the next request writes the time"
940        );
941    }
942
943    #[test]
944    fn a_write_that_fails_is_reported_as_no_write() {
945        let f = fixture();
946        let made = key(&f, KeyLife::Default);
947        f.tenants.registry.fail_commit(1, CommitError::RolledBack);
948        assert!(
949            !f.tenants.key_used(made.id, None),
950            "the commit failed, so no row was changed"
951        );
952    }
953
954    #[test]
955    fn a_second_request_in_the_minute_commits_nothing_to_the_registry() {
956        let f = fixture();
957        let made = key(&f, KeyLife::Default);
958        let t = row(&f, made.id).tenant.expect("a tenant key");
959        assert!(auth(&f, &made).is_ok(), "the first request writes the time");
960        // The next commit on the registry fails, whichever it is.
961        f.tenants.registry.fail_commit(1, CommitError::RolledBack);
962        f.clock.set(START + Duration::seconds(30));
963        assert!(auth(&f, &made).is_ok(), "the second request is accepted");
964        assert!(
965            f.tenants
966                .create_key(Actor::Cli, Some(t), vcon_scopes(), "next")
967                .is_err(),
968            "the failure was still waiting: the second request committed nothing"
969        );
970    }
971
972    #[test]
973    fn using_a_key_nobody_has_writes_nothing() {
974        let f = fixture();
975        assert!(
976            !f.tenants.key_used(KeyId([7; 8]), None),
977            "no row has the id"
978        );
979    }
980
981    #[test]
982    fn a_key_stored_without_an_expiry_is_accepted_as_one_made_before_version_9() {
983        let f = fixture();
984        let t = tenant(&f);
985        let (id, token) = access::new_token();
986        let mut tx = f.tenants.registry.immediate().expect("a transaction");
987        tx.insert_key(&KeyRow {
988            id,
989            tenant: Some(t),
990            token_hash: access::token_hash(&token).to_vec(),
991            scopes: vcon_scopes().to_string(),
992            label: "old".to_owned(),
993            created_at: start(),
994            revoked_at: None,
995            expires_at: None,
996            last_used_at: None,
997        })
998        .expect("inserted");
999        commit(tx).expect("committed");
1000        f.clock.set(START + Duration::days(3_650));
1001        assert!(
1002            access::authenticate(&f.tenants, Some(&format!("Bearer {token}"))).is_ok(),
1003            "ten years later"
1004        );
1005        assert_eq!(
1006            row(&f, id).last_used_at.and_then(from_nanos),
1007            Some(START + Duration::days(3_650)),
1008            "and its use is written"
1009        );
1010    }
1011
1012    #[test]
1013    fn allowing_no_expiry_again_makes_such_a_key_and_changes_no_other() {
1014        let f = fixture();
1015        let t = tenant(&f);
1016        f.tenants.allow_no_expiry(false);
1017        let dated = f
1018            .tenants
1019            .create_key(Actor::Cli, Some(t), vcon_scopes(), "dated")
1020            .expect("a dated key is made while no expiry is refused");
1021        f.tenants.allow_no_expiry(true);
1022        let forever = f
1023            .tenants
1024            .create_key_for(
1025                Actor::Cli,
1026                Some(t),
1027                vcon_scopes(),
1028                "forever",
1029                KeyLife::Never,
1030            )
1031            .expect("made");
1032        assert_eq!(row(&f, forever.id).expires_at, None, "no expiry");
1033        assert_eq!(
1034            row(&f, dated.id).expires_at,
1035            Some(start() + 90 * DAY),
1036            "the earlier key keeps its expiry"
1037        );
1038    }
1039
1040    #[test]
1041    fn a_key_with_no_expiry_made_earlier_still_works_after_the_configuration_refuses_them() {
1042        let f = fixture();
1043        let made = key(&f, KeyLife::Never);
1044        f.tenants.allow_no_expiry(false);
1045        assert!(auth(&f, &made).is_ok(), "the setting is about new keys");
1046    }
1047}