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