1use 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
14const PREFIX: &str = "vcs_";
17
18const SECRET_LEN: usize = 32;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Scope {
24 Write,
26 Read,
28 Delete,
30 Legal,
32 Audit,
34 Admin,
36 TenantAdmin,
39}
40
41impl Scope {
42 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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
78pub struct Scopes(u8);
79
80impl Scopes {
81 #[must_use]
83 pub fn of(scopes: &[Scope]) -> Scopes {
84 Scopes(scopes.iter().fold(0, |bits, scope| bits | scope.bit()))
85 }
86
87 #[must_use]
89 pub fn contains(self, scope: Scope) -> bool {
90 self.0 & scope.bit() != 0
91 }
92
93 #[must_use]
95 pub fn is_empty(self) -> bool {
96 self.0 == 0
97 }
98
99 #[must_use]
101 pub fn with(self, other: Scopes) -> Scopes {
102 Scopes(self.0 | other.0)
103 }
104
105 #[must_use]
107 pub fn within(self, other: Scopes) -> bool {
108 self.0 & !other.0 == 0
109 }
110
111 #[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 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 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
154pub(crate) fn new_token() -> (KeyId, String) {
157 let id = KeyId::generate();
158 let mut secret = [0; SECRET_LEN];
159 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
166pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub struct Caller {
178 pub key: KeyId,
180 pub tenant: Option<TenantId>,
182 pub scopes: Scopes,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
192pub enum Plane {
193 #[default]
195 Both,
196 Tenant,
198 Operator,
200}
201
202impl Plane {
203 #[must_use]
205 pub fn admits(self, caller: &Caller) -> bool {
206 self.serves(caller.tenant)
207 }
208
209 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub enum AuthError {
224 Missing,
226 Forbidden(Scope),
228 Malformed,
230 Unknown,
232 Revoked,
234 Expired,
236 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
260pub fn authenticate(keys: &Tenants, authorization: Option<&str>) -> Result<Caller, AuthError> {
274 match check(keys, authorization) {
275 Ok((caller, last_used)) => {
276 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
289type Failure = (AuthError, Option<(KeyId, Option<TenantId>)>);
291
292fn 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 constant_time::verify_slices_are_equal(&token_hash(token), &key.hash)
306 .map_err(|_| known(AuthError::Unknown))?;
307 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
322pub 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
338pub fn tenant_for(caller: &Caller, scope: Scope) -> Result<TenantId, AuthError> {
346 require(caller, scope)?;
347 caller.tenant.ok_or(AuthError::Forbidden(scope))
348}
349
350fn 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
359pub 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 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 #[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 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 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 #[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 #[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 #[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 #[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 (
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}