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 secret in secrets {
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), "{token}");
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 token in malformed {
522            assert_eq!(parse(&token), Err(AuthError::Malformed), "{token:?}");
523        }
524    }
525
526    #[test]
527    fn scopes_are_a_set_written_in_a_fixed_order() {
528        let none = Scopes::of(&[]);
529        assert!(none.is_empty(), "no scopes given, none held");
530        let scopes = Scopes::of(&[Scope::Delete, Scope::Write, Scope::Delete]);
531        assert!(
532            !scopes.is_empty(),
533            "two scopes given, so the set is not empty"
534        );
535        for scope in Scope::ALL {
536            assert_eq!(
537                scopes.contains(scope),
538                matches!(scope, Scope::Write | Scope::Delete),
539                "{scope:?}"
540            );
541        }
542        assert_eq!(
543            scopes.to_string(),
544            "write,delete",
545            "a repeated scope is held once, and written in the fixed order"
546        );
547        assert_eq!(
548            Scopes::of(&Scope::ALL).to_string(),
549            "write,read,delete,legal,audit,admin,tenant_admin",
550            "every scope, in the fixed order"
551        );
552        assert_eq!(
553            Scopes::of(&[Scope::Legal, Scope::Write, Scope::Read]).names(),
554            ["write", "read", "legal"],
555            "names come in Scope::ALL's order, not the order given"
556        );
557        for scope in Scope::ALL {
558            let one = Scopes::of(&[scope]);
559            assert_eq!(Scopes::parse(&one.to_string()), Some(one), "{scope:?}");
560        }
561        let all = Scopes::of(&Scope::ALL);
562        assert_eq!(
563            Scopes::parse(&all.to_string()),
564            Some(all),
565            "parse reads every scope back from its written form"
566        );
567    }
568
569    /// The scope of a tenant's administrator, which the role
570    /// `tenant-admin` gives.
571    mod tenant_admin {
572        use super::*;
573
574        fn holder(tenant: Option<TenantId>, scopes: &[Scope]) -> Caller {
575            Caller {
576                key: KeyId([5; 8]),
577                tenant,
578                scopes: Scopes::of(scopes),
579            }
580        }
581
582        const TENANT: Option<TenantId> = Some(TenantId([6; 16]));
583
584        #[test]
585        fn the_scope_is_named_with_an_underscore() {
586            assert_eq!(
587                Scope::named("tenant_admin"),
588                Some(Scope::TenantAdmin),
589                "the name a key's scopes are given by"
590            );
591            assert_eq!(
592                Scopes::of(&[Scope::TenantAdmin]).to_string(),
593                "tenant_admin",
594                "the name a row keeps"
595            );
596        }
597
598        #[test]
599        fn the_roles_spelling_and_other_spellings_name_no_scope() {
600            for name in [
601                "tenant-admin",
602                "tenantadmin",
603                "Tenant_Admin",
604                "tenant_admin ",
605                "tenant",
606            ] {
607                assert_eq!(Scope::named(name), None, "{name:?}");
608            }
609        }
610
611        #[test]
612        fn it_is_written_last_after_admin() {
613            assert_eq!(
614                Scopes::of(&[Scope::TenantAdmin, Scope::Audit, Scope::Write]).names(),
615                ["write", "audit", "tenant_admin"],
616                "the fixed order ends with tenant_admin"
617            );
618            assert_eq!(
619                Scope::ALL.last(),
620                Some(&Scope::TenantAdmin),
621                "the scopes of every earlier release keep their places"
622            );
623        }
624
625        #[test]
626        fn it_reads_back_alone_and_with_the_other_tenant_scopes() {
627            for text in [
628                "tenant_admin",
629                "read,tenant_admin",
630                "write,audit,tenant_admin",
631            ] {
632                assert_eq!(
633                    Scopes::parse(text).map(|s| s.to_string()),
634                    Some(text.to_owned()),
635                    "{text}"
636                );
637            }
638            assert_eq!(
639                Scopes::parse("tenant_admin,read"),
640                None,
641                "only the written order is read"
642            );
643        }
644
645        #[test]
646        fn a_tenant_key_holding_it_is_let_through() {
647            let caller = holder(TENANT, &[Scope::TenantAdmin]);
648            assert_eq!(
649                require(&caller, Scope::TenantAdmin),
650                Ok(()),
651                "a tenant key with the scope"
652            );
653            assert_eq!(
654                tenant_for(&caller, Scope::TenantAdmin),
655                Ok(TenantId([6; 16])),
656                "and it acts in its own tenant"
657            );
658        }
659
660        #[test]
661        fn it_gives_none_of_the_other_scopes() {
662            let caller = holder(TENANT, &[Scope::TenantAdmin]);
663            for scope in Scope::ALL {
664                if scope != Scope::TenantAdmin {
665                    assert_eq!(
666                        require(&caller, scope),
667                        Err(AuthError::Forbidden(scope)),
668                        "{scope:?}"
669                    );
670                }
671            }
672        }
673
674        #[test]
675        fn none_of_the_other_scopes_gives_it() {
676            let others = [
677                Scope::Write,
678                Scope::Read,
679                Scope::Delete,
680                Scope::Legal,
681                Scope::Audit,
682            ];
683            assert_eq!(
684                require(&holder(TENANT, &others), Scope::TenantAdmin),
685                Err(AuthError::Forbidden(Scope::TenantAdmin)),
686                "every other tenant scope together"
687            );
688            assert_eq!(
689                require(&holder(TENANT, &[]), Scope::TenantAdmin),
690                Err(AuthError::Forbidden(Scope::TenantAdmin)),
691                "no scope"
692            );
693        }
694
695        /// It is a tenant key's scope, as audit is: a key with no tenant
696        /// is refused it whatever its row says.
697        #[test]
698        fn a_key_with_no_tenant_is_refused_it() {
699            for scopes in [
700                &[Scope::Admin][..],
701                &[Scope::TenantAdmin][..],
702                &[Scope::Admin, Scope::TenantAdmin][..],
703            ] {
704                let caller = holder(None, scopes);
705                assert_eq!(
706                    require(&caller, Scope::TenantAdmin),
707                    Err(AuthError::Forbidden(Scope::TenantAdmin)),
708                    "{scopes:?}"
709                );
710                assert_eq!(
711                    tenant_for(&caller, Scope::TenantAdmin),
712                    Err(AuthError::Forbidden(Scope::TenantAdmin)),
713                    "{scopes:?}"
714                );
715            }
716        }
717
718        #[test]
719        fn it_does_not_give_admin_to_a_tenant_key() {
720            assert_eq!(
721                require(
722                    &holder(TENANT, &[Scope::TenantAdmin, Scope::Admin]),
723                    Scope::Admin
724                ),
725                Err(AuthError::Forbidden(Scope::Admin)),
726                "admin is an operator key's"
727            );
728        }
729
730        #[test]
731        fn the_sets_of_two_keys_join_with_each_scope_once() {
732            let joined = Scopes::of(&[Scope::Read, Scope::Audit])
733                .with(Scopes::of(&[Scope::Read, Scope::TenantAdmin]));
734            assert_eq!(joined.to_string(), "read,audit,tenant_admin", "the union");
735            assert_eq!(
736                Scopes::default().with(Scopes::default()),
737                Scopes::default(),
738                "two empty sets join to the empty set"
739            );
740        }
741    }
742
743    #[test]
744    fn only_the_written_spelling_of_scopes_is_read() {
745        for text in [
746            "",
747            "delete,write",
748            "write,write",
749            "write,",
750            ",write",
751            "write, read",
752            "Write",
753            "owner",
754            "write,read,",
755        ] {
756            assert_eq!(Scopes::parse(text), None, "{text:?}");
757        }
758    }
759
760    /// audit is a tenant key's scope: it reads the tenant's own log.
761    #[test]
762    fn audit_is_required_of_a_tenant_key_only() {
763        let tenant = Caller {
764            key: KeyId::generate(),
765            tenant: Some(TenantId::generate()),
766            scopes: Scopes::of(&[Scope::Audit]),
767        };
768        assert_eq!(
769            Scope::named("audit"),
770            Some(Scope::Audit),
771            "the scope is named audit"
772        );
773        assert_eq!(
774            require(&tenant, Scope::Audit),
775            Ok(()),
776            "a tenant key with the audit scope may read its log"
777        );
778        assert_eq!(
779            tenant_for(&tenant, Scope::Audit),
780            Ok(tenant.tenant.expect("one")),
781            "and the log it reads is its own tenant's"
782        );
783        assert_eq!(
784            require(&tenant, Scope::Read),
785            Err(AuthError::Forbidden(Scope::Read)),
786            "audit grants no other scope"
787        );
788        let operator = Caller {
789            tenant: None,
790            scopes: Scopes::of(&[Scope::Admin, Scope::Audit]),
791            ..tenant
792        };
793        assert_eq!(
794            require(&operator, Scope::Audit),
795            Err(AuthError::Forbidden(Scope::Audit)),
796            "an operator key has no tenant log to read, even with the audit scope"
797        );
798    }
799
800    #[test]
801    fn a_scope_is_found_by_its_exact_name() {
802        for scope in Scope::ALL {
803            assert_eq!(Scope::named(scope.name()), Some(scope), "{scope:?}");
804        }
805        for name in ["", "Read", "READ", " read", "read,write", "superuser"] {
806            assert_eq!(Scope::named(name), None, "{name:?}");
807        }
808    }
809
810    #[test]
811    fn a_new_token_is_well_formed_and_new_each_time() {
812        let (id, token) = new_token();
813        assert_eq!(
814            parse(&token),
815            Ok(id),
816            "a new token parses to the id it was made with"
817        );
818        let (other_id, other) = new_token();
819        assert_ne!(other_id, id, "each new token has a new random key id");
820        assert_ne!(other[21..], token[21..], "a new secret");
821    }
822
823    /// RFC 6234's SHA-256 test vector for "abc".
824    #[test]
825    fn a_token_is_stored_as_its_sha_256() {
826        assert_eq!(
827            token_hash("abc")
828                .iter()
829                .map(|b| format!("{b:02x}"))
830                .collect::<String>(),
831            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
832            "the hash is plain SHA-256, as the RFC's vector shows"
833        );
834    }
835
836    mod authenticate {
837        use super::*;
838        use crate::audit::Actor;
839        use crate::tenants::{Fixture, NewKey, fixture};
840
841        fn vcon_scopes() -> Scopes {
842            Scopes::of(&[Scope::Write, Scope::Read])
843        }
844
845        fn key(f: &Fixture) -> (TenantId, NewKey) {
846            let t = f.tenants.create(Actor::Cli, "acme", None).expect("made");
847            let key = f
848                .tenants
849                .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
850                .expect("made");
851            (t, key)
852        }
853
854        fn auth(f: &Fixture, header: &str) -> Result<Caller, AuthError> {
855            authenticate(&f.tenants, Some(header))
856        }
857
858        #[test]
859        fn a_valid_token_names_its_caller() {
860            let f = fixture();
861            let (t, key) = key(&f);
862            let caller = Caller {
863                key: key.id,
864                tenant: Some(t),
865                scopes: vcon_scopes(),
866            };
867            for header in [
868                format!("Bearer {}", key.token),
869                format!("bearer {}", key.token),
870                format!("BEARER   {}", key.token),
871            ] {
872                assert_eq!(auth(&f, &header), Ok(caller), "{header}");
873            }
874            let operator = f
875                .tenants
876                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
877                .expect("made");
878            assert_eq!(
879                auth(&f, &format!("Bearer {}", operator.token)),
880                Ok(Caller {
881                    key: operator.id,
882                    tenant: None,
883                    scopes: Scopes::of(&[Scope::Admin]),
884                }),
885                "an operator key's caller has no tenant"
886            );
887        }
888
889        #[test]
890        fn a_missing_or_malformed_header_is_refused() {
891            let f = fixture();
892            let (_, key) = key(&f);
893            assert_eq!(
894                authenticate(&f.tenants, None),
895                Err(AuthError::Missing),
896                "no Authorization header is told apart from a bad one"
897            );
898            for header in [
899                String::new(),
900                "Bearer".to_owned(),
901                "Bearer ".to_owned(),
902                format!("Bearer{}", key.token),
903                format!("Basic {}", key.token),
904                format!("Bearers {}", key.token),
905                format!("Bearer {} ", key.token),
906                format!("Bearer\t{}", key.token),
907                "Bearer vcs_0123456789abcdef_short".to_owned(),
908            ] {
909                assert_eq!(auth(&f, &header), Err(AuthError::Malformed), "{header:?}");
910            }
911        }
912
913        #[test]
914        fn an_unknown_key_or_a_wrong_secret_is_unknown() {
915            let f = fixture();
916            let (_, key) = key(&f);
917            let (_, stranger) = new_token();
918            assert_eq!(
919                auth(&f, &format!("Bearer {stranger}")),
920                Err(AuthError::Unknown),
921                "a well-formed token whose key id no catalog holds"
922            );
923            let (_, other) = new_token();
924            let forged = format!("{}{}", &key.token[..21], &other[21..]);
925            assert_eq!(
926                auth(&f, &format!("Bearer {forged}")),
927                Err(AuthError::Unknown),
928                "a real key id with another secret is answered as an unknown key"
929            );
930            f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
931            assert_eq!(
932                auth(&f, &format!("Bearer {forged}")),
933                Err(AuthError::Unknown),
934                "a wrong secret learns nothing about revocation"
935            );
936        }
937
938        #[test]
939        fn a_revoked_key_is_refused_on_its_next_call() {
940            let f = fixture();
941            let (_, key) = key(&f);
942            let header = format!("Bearer {}", key.token);
943            assert!(
944                auth(&f, &header).is_ok(),
945                "the key works before it is revoked"
946            );
947            f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
948            assert_eq!(
949                auth(&f, &header),
950                Err(AuthError::Revoked),
951                "the next call after revocation is refused: no cache keeps it alive"
952            );
953        }
954
955        fn admin_failures(f: &Fixture) -> Vec<serde_json::Value> {
956            f.admin_records("auth_failed")
957        }
958
959        fn tenant_failures(f: &Fixture, t: TenantId) -> Vec<serde_json::Value> {
960            crate::audit::testing::exported(&f.tenant_catalog(t), None)
961                .into_iter()
962                .filter(|r| r["action"] == "auth_failed")
963                .collect()
964        }
965
966        fn forged(key: &NewKey) -> String {
967            let (_, other) = new_token();
968            format!("Bearer {}{}", &key.token[..21], &other[21..])
969        }
970
971        #[test]
972        fn a_burst_of_bad_tokens_leaves_one_counted_record() {
973            let f = fixture();
974            let (t, _) = key(&f);
975            for _ in 0..20 {
976                assert!(auth(&f, "Bearer not-a-token").is_err(), "a malformed token");
977            }
978            for _ in 0..5 {
979                assert!(authenticate(&f.tenants, None).is_err(), "no header");
980                let (_, made_up) = new_token();
981                assert!(
982                    auth(&f, &format!("Bearer {made_up}")).is_err(),
983                    "a key id no catalog holds"
984                );
985            }
986            let records = admin_failures(&f);
987            assert_eq!(records.len(), 1, "{records:?}");
988            assert_eq!(
989                records[0]["actor"], "",
990                "no key is known, so no actor is named"
991            );
992            assert_eq!(
993                records[0]["status"], 401,
994                "each was refused as unauthenticated"
995            );
996            assert_eq!(
997                records[0]["count"], 30,
998                "20 malformed, 5 missing, 5 unknown"
999            );
1000            assert_eq!(
1001                records[0]["at"], "2026-10-23T12:00:00Z",
1002                "the record is stamped with the fixture clock's minute"
1003            );
1004            assert_eq!(
1005                tenant_failures(&f, t),
1006                Vec::<serde_json::Value>::new(),
1007                "no failure named this tenant's key"
1008            );
1009
1010            f.clock
1011                .set(time::macros::datetime!(2026-10-23 12:01:30 UTC));
1012            assert!(auth(&f, "Bearer not-a-token").is_err(), "a malformed token");
1013            let records = admin_failures(&f);
1014            assert_eq!(records.len(), 2, "a new minute, a new record");
1015            assert_eq!(
1016                records[1]["count"], 1,
1017                "the new record counts only the new failure"
1018            );
1019        }
1020
1021        #[test]
1022        fn a_known_key_that_fails_is_counted_in_its_tenants_log() {
1023            let f = fixture();
1024            let (t, key) = key(&f);
1025            for _ in 0..3 {
1026                assert_eq!(
1027                    auth(&f, &forged(&key)),
1028                    Err(AuthError::Unknown),
1029                    "a wrong secret for a real key"
1030                );
1031            }
1032            f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
1033            for _ in 0..2 {
1034                assert_eq!(
1035                    auth(&f, &format!("Bearer {}", key.token)),
1036                    Err(AuthError::Revoked),
1037                    "the right secret for a revoked key"
1038                );
1039            }
1040            let records = tenant_failures(&f, t);
1041            assert_eq!(records.len(), 1, "{records:?}");
1042            assert_eq!(
1043                records[0]["actor"],
1044                key.id.to_string(),
1045                "the failures name the key they tried"
1046            );
1047            assert_eq!(
1048                records[0]["status"], 401,
1049                "each was refused as unauthenticated"
1050            );
1051            assert_eq!(
1052                records[0]["count"], 5,
1053                "3 wrong secrets and 2 calls after revocation"
1054            );
1055            assert_eq!(
1056                admin_failures(&f),
1057                Vec::<serde_json::Value>::new(),
1058                "a tenant key's failures go to its tenant's log only"
1059            );
1060        }
1061
1062        #[test]
1063        fn an_operator_key_that_fails_is_counted_in_the_admin_log() {
1064            let f = fixture();
1065            let operator = f
1066                .tenants
1067                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
1068                .expect("made");
1069            assert!(auth(&f, &forged(&operator)).is_err(), "a wrong secret");
1070            let records = admin_failures(&f);
1071            assert_eq!(
1072                records.len(),
1073                1,
1074                "an operator key has no tenant log: {records:?}"
1075            );
1076            assert_eq!(
1077                records[0]["actor"],
1078                operator.id.to_string(),
1079                "the record names the operator key tried"
1080            );
1081        }
1082
1083        #[test]
1084        fn a_known_key_whose_tenant_log_is_gone_is_counted_in_the_admin_log() {
1085            let f = fixture();
1086            let (t, key) = key(&f);
1087            f.tenants
1088                .remove(Actor::Cli, t, crate::tenants::Removal::Force)
1089                .expect("removed");
1090            assert_eq!(
1091                auth(&f, &format!("Bearer {}", key.token)),
1092                Err(AuthError::Revoked),
1093                "removing a tenant revokes its keys"
1094            );
1095            let records = admin_failures(&f);
1096            assert_eq!(records.len(), 1, "with the tenant's log gone: {records:?}");
1097            assert_eq!(
1098                records[0]["actor"],
1099                key.id.to_string(),
1100                "the record still names the key tried"
1101            );
1102        }
1103
1104        #[test]
1105        fn a_failure_that_cannot_be_counted_is_refused_all_the_same() {
1106            let f = fixture();
1107            f.conn()
1108                .execute_batch(
1109                    "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1110                     BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
1111                )
1112                .expect("trigger");
1113            assert_eq!(
1114                auth(&f, "Bearer not-a-token"),
1115                Err(AuthError::Malformed),
1116                "a failed audit write does not turn a refusal into a pass"
1117            );
1118        }
1119
1120        #[test]
1121        fn a_successful_check_counts_nothing() {
1122            let f = fixture();
1123            let (t, key) = key(&f);
1124            assert!(
1125                auth(&f, &format!("Bearer {}", key.token)).is_ok(),
1126                "the right token"
1127            );
1128            assert_eq!(
1129                admin_failures(&f),
1130                Vec::<serde_json::Value>::new(),
1131                "a success is not a failure to count"
1132            );
1133            assert_eq!(
1134                tenant_failures(&f, t),
1135                Vec::<serde_json::Value>::new(),
1136                "a success is not a failure to count"
1137            );
1138        }
1139
1140        #[test]
1141        fn a_key_table_that_cannot_be_read_lets_nothing_through() {
1142            let f = fixture();
1143            let (_, key) = key(&f);
1144            let header = format!("Bearer {}", key.token);
1145            f.conn()
1146                .execute(
1147                    "UPDATE api_key SET scopes = 'owner' WHERE id = ?1",
1148                    [key.id.bytes()],
1149                )
1150                .expect("damage");
1151            assert_eq!(auth(&f, &header), Err(AuthError::Io), "damaged scopes");
1152            f.conn()
1153                .execute_batch("ALTER TABLE api_key RENAME TO gone")
1154                .expect("lose the table");
1155            assert_eq!(auth(&f, &header), Err(AuthError::Io), "no table");
1156            assert_eq!(
1157                admin_failures(&f),
1158                Vec::<serde_json::Value>::new(),
1159                "an unreadable table is not a failed check"
1160            );
1161        }
1162    }
1163
1164    mod scopes {
1165        use super::*;
1166
1167        const TENANT: TenantId = TenantId([1; 16]);
1168
1169        fn caller(tenant: Option<TenantId>, scopes: &[Scope]) -> Caller {
1170            Caller {
1171                key: KeyId([2; 8]),
1172                tenant,
1173                scopes: Scopes::of(scopes),
1174            }
1175        }
1176
1177        /// Which scopes each key may use: (key, scopes it allows).
1178        #[test]
1179        fn each_key_may_use_only_the_scopes_it_holds_of_its_kind() {
1180            let vcon = [Scope::Write, Scope::Read, Scope::Delete, Scope::Legal];
1181            let matrix = [
1182                (caller(Some(TENANT), &[Scope::Write]), vec![Scope::Write]),
1183                (
1184                    caller(Some(TENANT), &[Scope::Read, Scope::Delete]),
1185                    vec![Scope::Read, Scope::Delete],
1186                ),
1187                (caller(Some(TENANT), &[Scope::Legal]), vec![Scope::Legal]),
1188                (caller(Some(TENANT), &vcon), vcon.to_vec()),
1189                (caller(None, &[Scope::Admin]), vec![Scope::Admin]),
1190                // A key of one kind holding a scope of the other, as only a
1191                // damaged table could, is refused it.
1192                (
1193                    caller(Some(TENANT), &[Scope::Admin, Scope::Read]),
1194                    vec![Scope::Read],
1195                ),
1196                (
1197                    caller(None, &[Scope::Admin, Scope::Write]),
1198                    vec![Scope::Admin],
1199                ),
1200            ];
1201            for (who, allowed) in matrix {
1202                for scope in Scope::ALL {
1203                    let expected = if allowed.contains(&scope) {
1204                        Ok(())
1205                    } else {
1206                        Err(AuthError::Forbidden(scope))
1207                    };
1208                    assert_eq!(require(&who, scope), expected, "{who:?} {scope:?}");
1209                }
1210            }
1211        }
1212
1213        #[test]
1214        fn a_request_acts_on_the_tenant_of_its_key() {
1215            let tenant_key = caller(Some(TENANT), &[Scope::Write]);
1216            assert_eq!(
1217                tenant_for(&tenant_key, Scope::Write),
1218                Ok(TENANT),
1219                "a tenant key acts on its own tenant"
1220            );
1221            assert_eq!(
1222                tenant_for(&tenant_key, Scope::Read),
1223                Err(AuthError::Forbidden(Scope::Read)),
1224                "only with a scope it holds"
1225            );
1226        }
1227
1228        #[test]
1229        fn an_operator_key_acts_on_no_tenant() {
1230            let operator = caller(None, &[Scope::Admin, Scope::Write]);
1231            for scope in Scope::ALL {
1232                assert_eq!(
1233                    tenant_for(&operator, scope),
1234                    Err(AuthError::Forbidden(scope)),
1235                    "{scope:?}"
1236                );
1237            }
1238        }
1239    }
1240}