Skip to main content

vcon_server/
access.rs

1//! Turns the bearer token on a request into a caller, or refuses it.
2
3use std::fmt;
4
5use aws_lc_rs::constant_time;
6use aws_lc_rs::digest::{SHA256, digest};
7use base64::Engine;
8use base64::engine::general_purpose::URL_SAFE_NO_PAD;
9
10use crate::ids::{KeyId, TenantId};
11use crate::tenants::Tenants;
12
13/// The fixed start of every token, so secret scanners can spot a leaked
14/// one.
15const PREFIX: &str = "vcs_";
16
17/// A secret is 256 random bits.
18const SECRET_LEN: usize = 32;
19
20/// What a key may do.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum Scope {
23    /// Stores vCons: `POST /vcons` and `PUT /vcons/{uuid}`.
24    Write,
25    /// Lists and reads vCons: `GET /vcons` and `GET /vcons/{uuid}`.
26    Read,
27    /// Deletes vCons: `DELETE /vcons/{uuid}`.
28    Delete,
29    /// The `/legal/` routes: deleted vCons, old versions, restore, holds.
30    Legal,
31    /// Reads the tenant's own audit log.
32    Audit,
33    /// Manages tenants and keys; held only by an operator key.
34    Admin,
35}
36
37impl Scope {
38    /// Every scope, in the order a key's scopes are written.
39    const ALL: [Scope; 6] = [
40        Scope::Write,
41        Scope::Read,
42        Scope::Delete,
43        Scope::Legal,
44        Scope::Audit,
45        Scope::Admin,
46    ];
47
48    /// The scope with this exact name.
49    #[must_use]
50    pub fn named(name: &str) -> Option<Scope> {
51        Scope::ALL.into_iter().find(|s| s.name() == name)
52    }
53
54    fn bit(self) -> u8 {
55        1 << self as u8
56    }
57
58    fn name(self) -> &'static str {
59        match self {
60            Scope::Write => "write",
61            Scope::Read => "read",
62            Scope::Delete => "delete",
63            Scope::Legal => "legal",
64            Scope::Audit => "audit",
65            Scope::Admin => "admin",
66        }
67    }
68}
69
70/// A set of scopes.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72pub struct Scopes(u8);
73
74impl Scopes {
75    /// The set of `scopes`; a scope given twice is held once.
76    #[must_use]
77    pub fn of(scopes: &[Scope]) -> Scopes {
78        Scopes(scopes.iter().fold(0, |bits, scope| bits | scope.bit()))
79    }
80
81    /// Whether the set holds `scope`.
82    #[must_use]
83    pub fn contains(self, scope: Scope) -> bool {
84        self.0 & scope.bit() != 0
85    }
86
87    /// Whether the set holds no scope.
88    #[must_use]
89    pub fn is_empty(self) -> bool {
90        self.0 == 0
91    }
92
93    /// The scopes a list names, or None when one is unknown or named twice,
94    /// so a list means one thing. Which scopes a key may hold is Tenants'
95    /// rule.
96    #[must_use]
97    pub fn named(names: &[String]) -> Option<Scopes> {
98        let mut held = Vec::new();
99        for name in names {
100            let scope = Scope::named(name)?;
101            if held.contains(&scope) {
102                return None;
103            }
104            held.push(scope);
105        }
106        Some(Scopes::of(&held))
107    }
108
109    /// Reads scopes written by `Display`: names in the fixed order, comma
110    /// separated, each once.
111    pub fn parse(text: &str) -> Option<Scopes> {
112        let scopes: Vec<Scope> = text.split(',').map(Scope::named).collect::<Option<_>>()?;
113        let read = Scopes::of(&scopes);
114        (read.to_string() == text).then_some(read)
115    }
116}
117
118impl Scopes {
119    /// The names of the scopes held, in the fixed order of `Scope::ALL`,
120    /// as the API and the command line list them.
121    pub fn names(self) -> Vec<&'static str> {
122        Scope::ALL
123            .into_iter()
124            .filter(|s| self.contains(*s))
125            .map(Scope::name)
126            .collect()
127    }
128}
129
130impl std::fmt::Display for Scopes {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        f.write_str(&self.names().join(","))
133    }
134}
135
136/// A new token for a new key: `vcs_<key id>_<secret>`, with a random id
137/// and a random 256-bit secret.
138pub(crate) fn new_token() -> (KeyId, String) {
139    let id = KeyId::generate();
140    let mut secret = [0; SECRET_LEN];
141    // AWS-LC's RAND_bytes aborts the process when it cannot get enough
142    // randomness, so `fill` never returns its error.
143    aws_lc_rs::rand::fill(&mut secret).expect("AWS-LC aborts instead of failing");
144    let token = format!("{PREFIX}{id}_{}", URL_SAFE_NO_PAD.encode(secret));
145    (id, token)
146}
147
148/// The SHA-256 of a whole token, as the key table stores it.
149pub(crate) fn token_hash(token: &str) -> [u8; 32] {
150    digest(&SHA256, token.as_bytes())
151        .as_ref()
152        .try_into()
153        .expect("SHA-256 is 32 bytes")
154}
155
156/// Who a request comes from: a tenant's key, or with no tenant the
157/// operator's.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub struct Caller {
160    /// The id of the key the request's token names.
161    pub key: KeyId,
162    /// The key's tenant, or None for an operator key.
163    pub tenant: Option<TenantId>,
164    /// The scopes the key holds.
165    pub scopes: Scopes,
166}
167
168/// Which keys a listener serves. With one listener, it serves both
169/// kinds. With an operator listener beside it, each serves one kind: a
170/// tenant key on the tenant listener and an operator key on the operator
171/// listener, and a valid key of the other kind is refused before any
172/// route sees it.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
174pub enum Plane {
175    /// The one listener of a server with no operator listener.
176    #[default]
177    Both,
178    /// The tenant listener of a server that has an operator listener.
179    Tenant,
180    /// The operator listener.
181    Operator,
182}
183
184impl Plane {
185    /// Whether a listener of this plane serves `caller`.
186    #[must_use]
187    pub fn admits(self, caller: &Caller) -> bool {
188        match self {
189            Plane::Both => true,
190            Plane::Tenant => caller.tenant.is_some(),
191            Plane::Operator => caller.tenant.is_none(),
192        }
193    }
194}
195
196/// Why a request's token was refused.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub enum AuthError {
199    /// No Authorization header.
200    Missing,
201    /// The key does not hold the scope the request needs.
202    Forbidden(Scope),
203    /// Not `Bearer` and a token as `new_token` writes one.
204    Malformed,
205    /// No key has this id, or the secret is not its own.
206    Unknown,
207    /// The key was revoked.
208    Revoked,
209    /// The key table could not be read, so nothing is let through.
210    Io,
211}
212
213impl fmt::Display for AuthError {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        match self {
216            AuthError::Missing => f.write_str("no Authorization header"),
217            AuthError::Forbidden(scope) => {
218                write!(f, "the key does not hold the {} scope", scope.name())
219            }
220            AuthError::Malformed => {
221                f.write_str("the Authorization header is not Bearer and a token")
222            }
223            AuthError::Unknown => f.write_str("no key has this id and secret"),
224            AuthError::Revoked => f.write_str("the key was revoked"),
225            AuthError::Io => f.write_str("the key table could not be read"),
226        }
227    }
228}
229
230impl std::error::Error for AuthError {}
231
232/// The caller a request's Authorization header names. The key is looked up
233/// on every call, with no cache, so a revoked key fails on its next
234/// request.
235///
236/// A failed check is counted in the audit (`Tenants::count_auth_failure`),
237/// except when the key table could not be read.
238///
239/// # Errors
240///
241/// [`AuthError::Missing`] with no header, [`AuthError::Malformed`] when it
242/// is not `Bearer` and a token, [`AuthError::Unknown`] for a key id no key
243/// has or a wrong secret, [`AuthError::Revoked`] for a revoked key, and
244/// [`AuthError::Io`] when the key table cannot be read.
245pub fn authenticate(keys: &Tenants, authorization: Option<&str>) -> Result<Caller, AuthError> {
246    match check(keys, authorization) {
247        Ok(caller) => Ok(caller),
248        Err((error, known)) => {
249            if error != AuthError::Io {
250                keys.count_auth_failure(known);
251            }
252            Err(error)
253        }
254    }
255}
256
257/// A failed check, with the key it named if that key is known.
258type Failure = (AuthError, Option<(KeyId, Option<TenantId>)>);
259
260fn check(keys: &Tenants, authorization: Option<&str>) -> Result<Caller, Failure> {
261    let unknown = |error| (error, None);
262    let header = authorization.ok_or(unknown(AuthError::Missing))?;
263    let token = bearer(header).ok_or(unknown(AuthError::Malformed))?;
264    let id = parse(token).map_err(unknown)?;
265    let key = keys
266        .stored_key(id)
267        .map_err(|_| unknown(AuthError::Io))?
268        .ok_or(unknown(AuthError::Unknown))?;
269    let known = |error| (error, Some((id, key.tenant)));
270    // The secret is checked before revocation, so a wrong secret learns
271    // nothing about the key.
272    constant_time::verify_slices_are_equal(&token_hash(token), &key.hash)
273        .map_err(|_| known(AuthError::Unknown))?;
274    if key.revoked {
275        return Err(known(AuthError::Revoked));
276    }
277    Ok(Caller {
278        key: id,
279        tenant: key.tenant,
280        scopes: key.scopes,
281    })
282}
283
284/// Refuses a caller whose key does not hold `scope`. Admin belongs only to
285/// an operator key, and the vCon, legal and audit scopes only to a tenant
286/// key, so a key holding a scope of the other kind is still refused it.
287///
288/// # Errors
289///
290/// [`AuthError::Forbidden`] naming `scope`.
291pub fn require(caller: &Caller, scope: Scope) -> Result<(), AuthError> {
292    let of_its_kind = (scope == Scope::Admin) == caller.tenant.is_none();
293    if of_its_kind && caller.scopes.contains(scope) {
294        Ok(())
295    } else {
296        Err(AuthError::Forbidden(scope))
297    }
298}
299
300/// The tenant a vCon or legal request acts on: the caller's own, from its
301/// key, never from the request.
302///
303/// # Errors
304///
305/// [`AuthError::Forbidden`] naming `scope` when [`require`] refuses it or
306/// the key has no tenant.
307pub fn tenant_for(caller: &Caller, scope: Scope) -> Result<TenantId, AuthError> {
308    require(caller, scope)?;
309    caller.tenant.ok_or(AuthError::Forbidden(scope))
310}
311
312/// The token in `Bearer <token>`. The scheme's case does not matter, and
313/// one or more spaces may follow it (RFC 7235).
314fn bearer(header: &str) -> Option<&str> {
315    let (scheme, rest) = header.split_once(' ')?;
316    scheme
317        .eq_ignore_ascii_case("Bearer")
318        .then(|| rest.trim_start_matches(' '))
319}
320
321/// Reads a token written as `vcs_<key id>_<secret>`: the key id is 16
322/// lowercase hex digits, and the secret is 256 bits in base64url without
323/// padding. The secret may hold `_`, so the parts are found by position.
324///
325/// # Errors
326///
327/// [`AuthError::Malformed`] for any other text.
328pub fn parse(token: &str) -> Result<KeyId, AuthError> {
329    let malformed = AuthError::Malformed;
330    let rest = token.strip_prefix(PREFIX).ok_or(malformed)?;
331    let (id, rest) = rest.split_at_checked(16).ok_or(malformed)?;
332    let secret = rest.strip_prefix('_').ok_or(malformed)?;
333    let id = KeyId::parse(id).ok_or(malformed)?;
334    // The decoding refuses padding, other alphabets and stray trailing
335    // bits, so each secret has one spelling.
336    let secret = URL_SAFE_NO_PAD.decode(secret).map_err(|_| malformed)?;
337    if secret.len() != SECRET_LEN {
338        return Err(malformed);
339    }
340    Ok(id)
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    const ID: &str = "0123456789abcdef";
348
349    mod planes {
350        use super::*;
351
352        fn tenant_key(scopes: &[Scope]) -> Caller {
353            Caller {
354                key: KeyId([1; 8]),
355                tenant: Some(TenantId([2; 16])),
356                scopes: Scopes::of(scopes),
357            }
358        }
359
360        fn operator_key() -> Caller {
361            Caller {
362                key: KeyId([3; 8]),
363                tenant: None,
364                scopes: Scopes::of(&[Scope::Admin]),
365            }
366        }
367
368        #[test]
369        fn the_one_listener_admits_both_kinds_of_key() {
370            assert!(
371                Plane::Both.admits(&tenant_key(&[Scope::Read])),
372                "a tenant key"
373            );
374            assert!(Plane::Both.admits(&operator_key()), "an operator key");
375        }
376
377        #[test]
378        fn the_tenant_listener_admits_tenant_keys_only() {
379            assert!(
380                Plane::Tenant.admits(&tenant_key(&[Scope::Read])),
381                "a tenant key"
382            );
383            assert!(!Plane::Tenant.admits(&operator_key()), "an operator key");
384        }
385
386        #[test]
387        fn the_operator_listener_admits_operator_keys_only() {
388            assert!(Plane::Operator.admits(&operator_key()), "an operator key");
389            assert!(
390                !Plane::Operator.admits(&tenant_key(&[Scope::Read])),
391                "a tenant key"
392            );
393        }
394
395        /// The kind of a key is whether it has a tenant, never what its
396        /// scopes say: a tenant key with no scope, or with every scope, is
397        /// a tenant key, and a key with no tenant is an operator key
398        /// whatever it holds.
399        #[test]
400        fn the_kind_of_a_key_is_its_tenant_not_its_scopes() {
401            let every = [
402                Scope::Write,
403                Scope::Read,
404                Scope::Delete,
405                Scope::Legal,
406                Scope::Audit,
407                Scope::Admin,
408            ];
409            for scopes in [&[][..], &every[..], &[Scope::Admin][..]] {
410                let of_a_tenant = tenant_key(scopes);
411                assert!(Plane::Tenant.admits(&of_a_tenant), "{scopes:?}");
412                assert!(!Plane::Operator.admits(&of_a_tenant), "{scopes:?}");
413                let of_none = Caller {
414                    tenant: None,
415                    ..of_a_tenant
416                };
417                assert!(Plane::Operator.admits(&of_none), "{scopes:?}");
418                assert!(!Plane::Tenant.admits(&of_none), "{scopes:?}");
419            }
420        }
421
422        #[test]
423        fn a_listener_is_the_one_listener_unless_said_otherwise() {
424            assert_eq!(Plane::default(), Plane::Both, "the default plane");
425        }
426    }
427
428    fn secret(byte: u8) -> String {
429        URL_SAFE_NO_PAD.encode([byte; 32])
430    }
431
432    #[test]
433    fn a_well_formed_token_gives_its_key_id() {
434        let id = KeyId([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
435        let secrets = [
436            secret(0x00),
437            secret(0xff),
438            // 0xfb gives '-' and 0xff gives '_' in base64url.
439            URL_SAFE_NO_PAD.encode([0xfb; 32]),
440            URL_SAFE_NO_PAD.encode([[0xff; 16], [0x00; 16]].concat()),
441        ];
442        for secret in secrets {
443            assert_eq!(
444                secret.len(),
445                43,
446                "32 bytes are 43 base64url characters without padding"
447            );
448            let token = format!("vcs_{ID}_{secret}");
449            assert_eq!(parse(&token), Ok(id), "{token}");
450        }
451        assert!(
452            secret(0xff).contains('_'),
453            "a secret may hold the separator"
454        );
455    }
456
457    #[test]
458    fn a_malformed_token_is_refused() {
459        let good = secret(0x42);
460        let malformed = [
461            String::new(),
462            "vcs_".to_owned(),
463            format!("{ID}_{good}"),
464            format!("vck_{ID}_{good}"),
465            format!("VCS_{ID}_{good}"),
466            format!("vcs_{}_{good}", &ID[..15]),
467            format!("vcs_{ID}0_{good}"),
468            format!("vcs_{}_{good}", ID.to_uppercase()),
469            format!("vcs_0123456789abcdeg_{good}"),
470            format!("vcs_{ID}{good}"),
471            format!("vcs_{ID}-{good}"),
472            format!("vcs_{ID}_{}", &good[..42]),
473            format!("vcs_{ID}_{good}A"),
474            format!("vcs_{ID}_{good}="),
475            format!("vcs_{ID}_{}", good.replace('Q', "+")),
476            format!("vcs_{ID}_{}+", &good[..42]),
477            format!("vcs_{ID}_{}B", &good[..42]),
478            format!(" vcs_{ID}_{good}"),
479            format!("vcs_{ID}_{good} "),
480            format!("vcs_{ID}__{good}"),
481            format!("vcs_\u{0661}123456789abcdef_{good}"),
482        ];
483        for token in malformed {
484            assert_eq!(parse(&token), Err(AuthError::Malformed), "{token:?}");
485        }
486    }
487
488    #[test]
489    fn scopes_are_a_set_written_in_a_fixed_order() {
490        let none = Scopes::of(&[]);
491        assert!(none.is_empty(), "no scopes given, none held");
492        let scopes = Scopes::of(&[Scope::Delete, Scope::Write, Scope::Delete]);
493        assert!(
494            !scopes.is_empty(),
495            "two scopes given, so the set is not empty"
496        );
497        for scope in Scope::ALL {
498            assert_eq!(
499                scopes.contains(scope),
500                matches!(scope, Scope::Write | Scope::Delete),
501                "{scope:?}"
502            );
503        }
504        assert_eq!(
505            scopes.to_string(),
506            "write,delete",
507            "a repeated scope is held once, and written in the fixed order"
508        );
509        assert_eq!(
510            Scopes::of(&Scope::ALL).to_string(),
511            "write,read,delete,legal,audit,admin",
512            "every scope, in the fixed order"
513        );
514        assert_eq!(
515            Scopes::of(&[Scope::Legal, Scope::Write, Scope::Read]).names(),
516            ["write", "read", "legal"],
517            "names come in Scope::ALL's order, not the order given"
518        );
519        for scope in Scope::ALL {
520            let one = Scopes::of(&[scope]);
521            assert_eq!(Scopes::parse(&one.to_string()), Some(one), "{scope:?}");
522        }
523        let all = Scopes::of(&Scope::ALL);
524        assert_eq!(
525            Scopes::parse(&all.to_string()),
526            Some(all),
527            "parse reads every scope back from its written form"
528        );
529    }
530
531    #[test]
532    fn only_the_written_spelling_of_scopes_is_read() {
533        for text in [
534            "",
535            "delete,write",
536            "write,write",
537            "write,",
538            ",write",
539            "write, read",
540            "Write",
541            "owner",
542            "write,read,",
543        ] {
544            assert_eq!(Scopes::parse(text), None, "{text:?}");
545        }
546    }
547
548    /// audit is a tenant key's scope: it reads the tenant's own log.
549    #[test]
550    fn audit_is_required_of_a_tenant_key_only() {
551        let tenant = Caller {
552            key: KeyId::generate(),
553            tenant: Some(TenantId::generate()),
554            scopes: Scopes::of(&[Scope::Audit]),
555        };
556        assert_eq!(
557            Scope::named("audit"),
558            Some(Scope::Audit),
559            "the scope is named audit"
560        );
561        assert_eq!(
562            require(&tenant, Scope::Audit),
563            Ok(()),
564            "a tenant key with the audit scope may read its log"
565        );
566        assert_eq!(
567            tenant_for(&tenant, Scope::Audit),
568            Ok(tenant.tenant.expect("one")),
569            "and the log it reads is its own tenant's"
570        );
571        assert_eq!(
572            require(&tenant, Scope::Read),
573            Err(AuthError::Forbidden(Scope::Read)),
574            "audit grants no other scope"
575        );
576        let operator = Caller {
577            tenant: None,
578            scopes: Scopes::of(&[Scope::Admin, Scope::Audit]),
579            ..tenant
580        };
581        assert_eq!(
582            require(&operator, Scope::Audit),
583            Err(AuthError::Forbidden(Scope::Audit)),
584            "an operator key has no tenant log to read, even with the audit scope"
585        );
586    }
587
588    #[test]
589    fn a_scope_is_found_by_its_exact_name() {
590        for scope in Scope::ALL {
591            assert_eq!(Scope::named(scope.name()), Some(scope), "{scope:?}");
592        }
593        for name in ["", "Read", "READ", " read", "read,write", "superuser"] {
594            assert_eq!(Scope::named(name), None, "{name:?}");
595        }
596    }
597
598    #[test]
599    fn a_new_token_is_well_formed_and_new_each_time() {
600        let (id, token) = new_token();
601        assert_eq!(
602            parse(&token),
603            Ok(id),
604            "a new token parses to the id it was made with"
605        );
606        let (other_id, other) = new_token();
607        assert_ne!(other_id, id, "each new token has a new random key id");
608        assert_ne!(other[21..], token[21..], "a new secret");
609    }
610
611    /// RFC 6234's SHA-256 test vector for "abc".
612    #[test]
613    fn a_token_is_stored_as_its_sha_256() {
614        assert_eq!(
615            token_hash("abc")
616                .iter()
617                .map(|b| format!("{b:02x}"))
618                .collect::<String>(),
619            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
620            "the hash is plain SHA-256, as the RFC's vector shows"
621        );
622    }
623
624    mod authenticate {
625        use super::*;
626        use crate::audit::Actor;
627        use crate::tenants::{Fixture, NewKey, fixture};
628
629        fn vcon_scopes() -> Scopes {
630            Scopes::of(&[Scope::Write, Scope::Read])
631        }
632
633        fn key(f: &Fixture) -> (TenantId, NewKey) {
634            let t = f.tenants.create(Actor::Cli, "acme", None).expect("made");
635            let key = f
636                .tenants
637                .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
638                .expect("made");
639            (t, key)
640        }
641
642        fn auth(f: &Fixture, header: &str) -> Result<Caller, AuthError> {
643            authenticate(&f.tenants, Some(header))
644        }
645
646        #[test]
647        fn a_valid_token_names_its_caller() {
648            let f = fixture();
649            let (t, key) = key(&f);
650            let caller = Caller {
651                key: key.id,
652                tenant: Some(t),
653                scopes: vcon_scopes(),
654            };
655            for header in [
656                format!("Bearer {}", key.token),
657                format!("bearer {}", key.token),
658                format!("BEARER   {}", key.token),
659            ] {
660                assert_eq!(auth(&f, &header), Ok(caller), "{header}");
661            }
662            let operator = f
663                .tenants
664                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
665                .expect("made");
666            assert_eq!(
667                auth(&f, &format!("Bearer {}", operator.token)),
668                Ok(Caller {
669                    key: operator.id,
670                    tenant: None,
671                    scopes: Scopes::of(&[Scope::Admin]),
672                }),
673                "an operator key's caller has no tenant"
674            );
675        }
676
677        #[test]
678        fn a_missing_or_malformed_header_is_refused() {
679            let f = fixture();
680            let (_, key) = key(&f);
681            assert_eq!(
682                authenticate(&f.tenants, None),
683                Err(AuthError::Missing),
684                "no Authorization header is told apart from a bad one"
685            );
686            for header in [
687                String::new(),
688                "Bearer".to_owned(),
689                "Bearer ".to_owned(),
690                format!("Bearer{}", key.token),
691                format!("Basic {}", key.token),
692                format!("Bearers {}", key.token),
693                format!("Bearer {} ", key.token),
694                format!("Bearer\t{}", key.token),
695                "Bearer vcs_0123456789abcdef_short".to_owned(),
696            ] {
697                assert_eq!(auth(&f, &header), Err(AuthError::Malformed), "{header:?}");
698            }
699        }
700
701        #[test]
702        fn an_unknown_key_or_a_wrong_secret_is_unknown() {
703            let f = fixture();
704            let (_, key) = key(&f);
705            let (_, stranger) = new_token();
706            assert_eq!(
707                auth(&f, &format!("Bearer {stranger}")),
708                Err(AuthError::Unknown),
709                "a well-formed token whose key id no catalog holds"
710            );
711            let (_, other) = new_token();
712            let forged = format!("{}{}", &key.token[..21], &other[21..]);
713            assert_eq!(
714                auth(&f, &format!("Bearer {forged}")),
715                Err(AuthError::Unknown),
716                "a real key id with another secret is answered as an unknown key"
717            );
718            f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
719            assert_eq!(
720                auth(&f, &format!("Bearer {forged}")),
721                Err(AuthError::Unknown),
722                "a wrong secret learns nothing about revocation"
723            );
724        }
725
726        #[test]
727        fn a_revoked_key_is_refused_on_its_next_call() {
728            let f = fixture();
729            let (_, key) = key(&f);
730            let header = format!("Bearer {}", key.token);
731            assert!(
732                auth(&f, &header).is_ok(),
733                "the key works before it is revoked"
734            );
735            f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
736            assert_eq!(
737                auth(&f, &header),
738                Err(AuthError::Revoked),
739                "the next call after revocation is refused: no cache keeps it alive"
740            );
741        }
742
743        fn admin_failures(f: &Fixture) -> Vec<serde_json::Value> {
744            f.admin_records("auth_failed")
745        }
746
747        fn tenant_failures(f: &Fixture, t: TenantId) -> Vec<serde_json::Value> {
748            crate::audit::testing::exported(&f.tenant_catalog(t), None)
749                .into_iter()
750                .filter(|r| r["action"] == "auth_failed")
751                .collect()
752        }
753
754        fn forged(key: &NewKey) -> String {
755            let (_, other) = new_token();
756            format!("Bearer {}{}", &key.token[..21], &other[21..])
757        }
758
759        #[test]
760        fn a_burst_of_bad_tokens_leaves_one_counted_record() {
761            let f = fixture();
762            let (t, _) = key(&f);
763            for _ in 0..20 {
764                assert!(auth(&f, "Bearer not-a-token").is_err(), "a malformed token");
765            }
766            for _ in 0..5 {
767                assert!(authenticate(&f.tenants, None).is_err(), "no header");
768                let (_, made_up) = new_token();
769                assert!(
770                    auth(&f, &format!("Bearer {made_up}")).is_err(),
771                    "a key id no catalog holds"
772                );
773            }
774            let records = admin_failures(&f);
775            assert_eq!(records.len(), 1, "{records:?}");
776            assert_eq!(
777                records[0]["actor"], "",
778                "no key is known, so no actor is named"
779            );
780            assert_eq!(
781                records[0]["status"], 401,
782                "each was refused as unauthenticated"
783            );
784            assert_eq!(
785                records[0]["count"], 30,
786                "20 malformed, 5 missing, 5 unknown"
787            );
788            assert_eq!(
789                records[0]["at"], "2026-10-23T12:00:00Z",
790                "the record is stamped with the fixture clock's minute"
791            );
792            assert_eq!(
793                tenant_failures(&f, t),
794                Vec::<serde_json::Value>::new(),
795                "no failure named this tenant's key"
796            );
797
798            f.clock
799                .set(time::macros::datetime!(2026-10-23 12:01:30 UTC));
800            assert!(auth(&f, "Bearer not-a-token").is_err(), "a malformed token");
801            let records = admin_failures(&f);
802            assert_eq!(records.len(), 2, "a new minute, a new record");
803            assert_eq!(
804                records[1]["count"], 1,
805                "the new record counts only the new failure"
806            );
807        }
808
809        #[test]
810        fn a_known_key_that_fails_is_counted_in_its_tenants_log() {
811            let f = fixture();
812            let (t, key) = key(&f);
813            for _ in 0..3 {
814                assert_eq!(
815                    auth(&f, &forged(&key)),
816                    Err(AuthError::Unknown),
817                    "a wrong secret for a real key"
818                );
819            }
820            f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
821            for _ in 0..2 {
822                assert_eq!(
823                    auth(&f, &format!("Bearer {}", key.token)),
824                    Err(AuthError::Revoked),
825                    "the right secret for a revoked key"
826                );
827            }
828            let records = tenant_failures(&f, t);
829            assert_eq!(records.len(), 1, "{records:?}");
830            assert_eq!(
831                records[0]["actor"],
832                key.id.to_string(),
833                "the failures name the key they tried"
834            );
835            assert_eq!(
836                records[0]["status"], 401,
837                "each was refused as unauthenticated"
838            );
839            assert_eq!(
840                records[0]["count"], 5,
841                "3 wrong secrets and 2 calls after revocation"
842            );
843            assert_eq!(
844                admin_failures(&f),
845                Vec::<serde_json::Value>::new(),
846                "a tenant key's failures go to its tenant's log only"
847            );
848        }
849
850        #[test]
851        fn an_operator_key_that_fails_is_counted_in_the_admin_log() {
852            let f = fixture();
853            let operator = f
854                .tenants
855                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
856                .expect("made");
857            assert!(auth(&f, &forged(&operator)).is_err(), "a wrong secret");
858            let records = admin_failures(&f);
859            assert_eq!(
860                records.len(),
861                1,
862                "an operator key has no tenant log: {records:?}"
863            );
864            assert_eq!(
865                records[0]["actor"],
866                operator.id.to_string(),
867                "the record names the operator key tried"
868            );
869        }
870
871        #[test]
872        fn a_known_key_whose_tenant_log_is_gone_is_counted_in_the_admin_log() {
873            let f = fixture();
874            let (t, key) = key(&f);
875            f.tenants
876                .remove(Actor::Cli, t, crate::tenants::Removal::Force)
877                .expect("removed");
878            assert_eq!(
879                auth(&f, &format!("Bearer {}", key.token)),
880                Err(AuthError::Revoked),
881                "removing a tenant revokes its keys"
882            );
883            let records = admin_failures(&f);
884            assert_eq!(records.len(), 1, "with the tenant's log gone: {records:?}");
885            assert_eq!(
886                records[0]["actor"],
887                key.id.to_string(),
888                "the record still names the key tried"
889            );
890        }
891
892        #[test]
893        fn a_failure_that_cannot_be_counted_is_refused_all_the_same() {
894            let f = fixture();
895            f.conn()
896                .execute_batch(
897                    "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
898                     BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
899                )
900                .expect("trigger");
901            assert_eq!(
902                auth(&f, "Bearer not-a-token"),
903                Err(AuthError::Malformed),
904                "a failed audit write does not turn a refusal into a pass"
905            );
906        }
907
908        #[test]
909        fn a_successful_check_counts_nothing() {
910            let f = fixture();
911            let (t, key) = key(&f);
912            assert!(
913                auth(&f, &format!("Bearer {}", key.token)).is_ok(),
914                "the right token"
915            );
916            assert_eq!(
917                admin_failures(&f),
918                Vec::<serde_json::Value>::new(),
919                "a success is not a failure to count"
920            );
921            assert_eq!(
922                tenant_failures(&f, t),
923                Vec::<serde_json::Value>::new(),
924                "a success is not a failure to count"
925            );
926        }
927
928        #[test]
929        fn a_key_table_that_cannot_be_read_lets_nothing_through() {
930            let f = fixture();
931            let (_, key) = key(&f);
932            let header = format!("Bearer {}", key.token);
933            f.conn()
934                .execute(
935                    "UPDATE api_key SET scopes = 'owner' WHERE id = ?1",
936                    [key.id.bytes()],
937                )
938                .expect("damage");
939            assert_eq!(auth(&f, &header), Err(AuthError::Io), "damaged scopes");
940            f.conn()
941                .execute_batch("ALTER TABLE api_key RENAME TO gone")
942                .expect("lose the table");
943            assert_eq!(auth(&f, &header), Err(AuthError::Io), "no table");
944            assert_eq!(
945                admin_failures(&f),
946                Vec::<serde_json::Value>::new(),
947                "an unreadable table is not a failed check"
948            );
949        }
950    }
951
952    mod scopes {
953        use super::*;
954
955        const TENANT: TenantId = TenantId([1; 16]);
956
957        fn caller(tenant: Option<TenantId>, scopes: &[Scope]) -> Caller {
958            Caller {
959                key: KeyId([2; 8]),
960                tenant,
961                scopes: Scopes::of(scopes),
962            }
963        }
964
965        /// Which scopes each key may use: (key, scopes it allows).
966        #[test]
967        fn each_key_may_use_only_the_scopes_it_holds_of_its_kind() {
968            let vcon = [Scope::Write, Scope::Read, Scope::Delete, Scope::Legal];
969            let matrix = [
970                (caller(Some(TENANT), &[Scope::Write]), vec![Scope::Write]),
971                (
972                    caller(Some(TENANT), &[Scope::Read, Scope::Delete]),
973                    vec![Scope::Read, Scope::Delete],
974                ),
975                (caller(Some(TENANT), &[Scope::Legal]), vec![Scope::Legal]),
976                (caller(Some(TENANT), &vcon), vcon.to_vec()),
977                (caller(None, &[Scope::Admin]), vec![Scope::Admin]),
978                // A key of one kind holding a scope of the other, as only a
979                // damaged table could, is refused it.
980                (
981                    caller(Some(TENANT), &[Scope::Admin, Scope::Read]),
982                    vec![Scope::Read],
983                ),
984                (
985                    caller(None, &[Scope::Admin, Scope::Write]),
986                    vec![Scope::Admin],
987                ),
988            ];
989            for (who, allowed) in matrix {
990                for scope in Scope::ALL {
991                    let expected = if allowed.contains(&scope) {
992                        Ok(())
993                    } else {
994                        Err(AuthError::Forbidden(scope))
995                    };
996                    assert_eq!(require(&who, scope), expected, "{who:?} {scope:?}");
997                }
998            }
999        }
1000
1001        #[test]
1002        fn a_request_acts_on_the_tenant_of_its_key() {
1003            let tenant_key = caller(Some(TENANT), &[Scope::Write]);
1004            assert_eq!(
1005                tenant_for(&tenant_key, Scope::Write),
1006                Ok(TENANT),
1007                "a tenant key acts on its own tenant"
1008            );
1009            assert_eq!(
1010                tenant_for(&tenant_key, Scope::Read),
1011                Err(AuthError::Forbidden(Scope::Read)),
1012                "only with a scope it holds"
1013            );
1014        }
1015
1016        #[test]
1017        fn an_operator_key_acts_on_no_tenant() {
1018            let operator = caller(None, &[Scope::Admin, Scope::Write]);
1019            for scope in Scope::ALL {
1020                assert_eq!(
1021                    tenant_for(&operator, scope),
1022                    Err(AuthError::Forbidden(scope)),
1023                    "{scope:?}"
1024                );
1025            }
1026        }
1027    }
1028}