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