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