Skip to main content

acosmi/core/
authority.rs

1//! Opt-in external token authority. Legacy TokenStore behavior is unchanged.
2use crate::{Error, TokenSet};
3use async_trait::async_trait;
4use std::sync::{
5    atomic::{AtomicBool, Ordering},
6    Arc,
7};
8
9/// A pending rotation is durable state, including across clients and restarts.
10/// Implementations must never return Ready for an unresolved pending rotation.
11#[derive(Debug)]
12pub enum AuthorityState {
13    Ready(TokenSet),
14    Missing,
15    RotationPending,
16}
17
18/// Stable errors without storage, URL, token or backend diagnostic payloads.
19#[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/// Caller-owned durable authority; there is deliberately no default lock.
41///
42/// All methods run under lock, including the OAuth request between begin/commit.
43/// The returned guard must serialize every client/process sharing this authority.
44/// begin_rotation must durably mark RotationPending before returning success;
45/// failures/cancellation may have committed and require host reconciliation.
46/// commit_rotation must atomically persist the new tokens and change Pending to
47/// Ready, returning success only after confirmed durable commit. clear must also
48/// confirm durability. load must distinguish errors, Missing and Pending; it may
49/// not return a stale Ready snapshot for a deleted or pending authority.
50///
51/// The SDK verifies call ordering and readback, not an arbitrary implementation's
52/// durability. The host owns storage transactions, CAS, actor/revision fencing,
53/// revocation and resolution of uncertain transactions. The SDK never resolves
54/// durable Pending. Call reconcile_authority only after the host has resolved it.
55#[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}