1use crate::{Error, TokenSet};
3use async_trait::async_trait;
4use std::sync::{
5 atomic::{AtomicBool, Ordering},
6 Arc,
7};
8
9#[derive(Debug)]
12pub enum AuthorityState {
13 Ready(TokenSet),
14 Missing,
15 RotationPending,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
20pub enum TokenAuthorityError {
21 #[error("token_authority_unavailable")]
22 Unavailable,
23 #[error("token_authority_missing")]
24 Missing,
25 #[error("token_authority_rotation_pending")]
26 RotationPending,
27 #[error("token_authority_reconciliation_required")]
28 ReconciliationRequired,
29 #[error("token_authority_commit_unverified")]
30 CommitUnverified,
31}
32impl From<TokenAuthorityError> for Error {
33 fn from(value: TokenAuthorityError) -> Self {
34 Error::other(value.to_string())
35 }
36}
37
38pub type AuthorityResult<T> = std::result::Result<T, TokenAuthorityError>;
39
40#[async_trait]
56pub trait StrictTokenAuthority: Send + Sync {
57 async fn lock(&self) -> AuthorityResult<Box<dyn Send>>;
58 async fn load(&self) -> AuthorityResult<AuthorityState>;
59 async fn begin_rotation(&self) -> AuthorityResult<()>;
60 async fn commit_rotation(&self, tokens: &TokenSet) -> AuthorityResult<()>;
61 async fn clear(&self) -> AuthorityResult<()>;
62}
63
64pub(crate) struct StrictState {
65 pub authority: Arc<dyn StrictTokenAuthority>,
66 blocked: AtomicBool,
67}
68impl StrictState {
69 pub fn new(authority: Arc<dyn StrictTokenAuthority>) -> Self {
70 Self {
71 authority,
72 blocked: AtomicBool::new(false),
73 }
74 }
75 pub fn check(&self) -> AuthorityResult<()> {
76 if self.blocked.load(Ordering::SeqCst) {
77 Err(TokenAuthorityError::ReconciliationRequired)
78 } else {
79 Ok(())
80 }
81 }
82 pub fn block(&self) {
83 self.blocked.store(true, Ordering::SeqCst);
84 }
85 pub fn reconcile(&self) {
86 self.blocked.store(false, Ordering::SeqCst);
87 }
88}
89
90pub(crate) fn tokens_equal(a: &TokenSet, b: &TokenSet) -> bool {
91 a.access_token == b.access_token
92 && a.refresh_token == b.refresh_token
93 && a.expires_at == b.expires_at
94 && a.scope == b.scope
95 && a.client_id == b.client_id
96 && a.server_url == b.server_url
97}