Skip to main content

basecamp_sdk/
auth.rs

1//! SPEC §4: how credentials get onto a request, and how a refreshed token replaces a
2//! rejected one.
3
4use std::panic::AssertUnwindSafe;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Mutex};
7
8use async_trait::async_trait;
9use bytes::Bytes;
10use futures_util::FutureExt;
11use futures_util::future::{BoxFuture, Shared};
12
13use crate::error::Error;
14use crate::http::header::AUTHORIZATION;
15use crate::http::{HeaderValue, Request};
16use crate::types::SensitiveString;
17
18/// Supplies the access token each request goes out with.
19#[async_trait]
20pub trait TokenProvider: Send + Sync {
21    /// The token to send now.
22    async fn access_token(&self) -> Result<String, Error>;
23
24    /// Whether [`TokenProvider::refresh`] can do anything. A provider that answers `false`
25    /// is never asked, and a 401 surfaces at once.
26    fn refreshable(&self) -> bool {
27        false
28    }
29
30    /// Asked once when a request is answered with 401. Answer `true` when the next
31    /// [`TokenProvider::access_token`] hands out renewed credentials, and the request is
32    /// sent again. Concurrent 401s are coalesced by the client: only one refresh runs at a
33    /// time, and a request that arrives while one is in flight waits for its outcome.
34    async fn refresh(&self) -> Result<bool, Error> {
35        Ok(false)
36    }
37}
38
39/// A fixed token — a personal access token, or one read from the environment. It prints as
40/// `[REDACTED]`, so a `{:?}` of the provider cannot put the token in a log.
41#[derive(Debug, Clone)]
42pub struct StaticTokenProvider {
43    token: SensitiveString,
44}
45
46impl StaticTokenProvider {
47    /// A provider over one token.
48    pub fn new(token: impl Into<SensitiveString>) -> StaticTokenProvider {
49        StaticTokenProvider {
50            token: token.into(),
51        }
52    }
53}
54
55#[async_trait]
56impl TokenProvider for StaticTokenProvider {
57    async fn access_token(&self) -> Result<String, Error> {
58        if self.token.is_empty() {
59            Err(Error::new(
60                crate::ErrorCode::AuthRequired,
61                "no access token configured",
62            ))
63        } else {
64            Ok(self.token.expose().to_string())
65        }
66    }
67}
68
69/// Puts credentials on a request. The default, [`BearerAuth`], sets an `Authorization`
70/// header from a [`TokenProvider`]; anything else can plug in here.
71#[async_trait]
72pub trait AuthStrategy: Send + Sync {
73    /// Applies credentials to the request.
74    async fn authenticate(&self, request: &mut Request<Bytes>) -> Result<(), Error>;
75
76    /// Whether a 401 is worth a [`AuthStrategy::refresh`].
77    fn refreshable(&self) -> bool {
78        false
79    }
80
81    /// A counter that moves every time a refresh completes, whichever way. The client
82    /// reads it before authenticating a request and hands it back to
83    /// [`AuthStrategy::refresh`], which is how concurrent 401s coalesce into one refresh.
84    fn generation(&self) -> u64 {
85        0
86    }
87
88    /// Asked at most once per request when it is answered with 401, and only while the
89    /// attempt budget has another attempt left. `seen` is the generation the rejected
90    /// request was authenticated under. Answers `true` when the request should be replayed
91    /// with fresh credentials.
92    async fn refresh(&self, seen: u64) -> Result<bool, Error> {
93        let _ = seen;
94        Ok(false)
95    }
96}
97
98/// `Authorization: Bearer {token}` from a [`TokenProvider`], with concurrent refreshes
99/// coalesced: whichever request meets the 401 first starts the refresh, and every request
100/// that meets one while it runs waits on the same refresh and shares its answer rather than
101/// refreshing again. The refresh outlives the request that started it: a request dropped
102/// mid-refresh — an operation deadline shorter than the token endpoint's round trip — leaves
103/// the refresh in flight for the next request to finish, not a second refresh to start.
104pub struct BearerAuth<P: TokenProvider> {
105    provider: Arc<P>,
106    /// Moves once per completed refresh attempt, success or failure.
107    generation: AtomicU64,
108    state: Mutex<RefreshState>,
109}
110
111/// The outcome every waiter on one refresh shares.
112type RefreshOutcome = Result<bool, Arc<Error>>;
113
114struct RefreshState {
115    /// Whether the last completed refresh renewed the credentials. A request authenticated
116    /// before that attempt shares its verdict; one authenticated after it may start another.
117    last_renewed: bool,
118    /// The refresh under way for the current generation, if one is.
119    in_flight: Option<Shared<BoxFuture<'static, RefreshOutcome>>>,
120}
121
122impl<P: TokenProvider> BearerAuth<P> {
123    /// Bearer authentication over a provider.
124    pub fn new(provider: P) -> BearerAuth<P> {
125        BearerAuth {
126            provider: Arc::new(provider),
127            generation: AtomicU64::new(0),
128            state: Mutex::new(RefreshState {
129                last_renewed: false,
130                in_flight: None,
131            }),
132        }
133    }
134
135    /// The provider the tokens come from.
136    pub fn provider(&self) -> &P {
137        &self.provider
138    }
139}
140
141impl<P: TokenProvider + std::fmt::Debug> std::fmt::Debug for BearerAuth<P> {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        f.debug_struct("BearerAuth")
144            .field("provider", &self.provider)
145            .finish_non_exhaustive()
146    }
147}
148
149#[async_trait]
150impl<P: TokenProvider + 'static> AuthStrategy for BearerAuth<P> {
151    async fn authenticate(&self, request: &mut Request<Bytes>) -> Result<(), Error> {
152        let token = self.provider.access_token().await?;
153        let mut value = HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| {
154            Error::new(
155                crate::ErrorCode::AuthRequired,
156                "access token is not a valid header value",
157            )
158        })?;
159        value.set_sensitive(true);
160        request.headers_mut().insert(AUTHORIZATION, value);
161        Ok(())
162    }
163
164    fn refreshable(&self) -> bool {
165        self.provider.refreshable()
166    }
167
168    fn generation(&self) -> u64 {
169        self.generation.load(Ordering::Acquire)
170    }
171
172    async fn refresh(&self, seen: u64) -> Result<bool, Error> {
173        // One refresh per generation. A request authenticated before the attempt that just
174        // completed shares its verdict — renewed or not — rather than refreshing again; a
175        // request authenticated after a failed attempt may start the next one. The refresh
176        // itself is a shared future: whoever polls it drives it, so a starter that is
177        // dropped leaves it for the next waiter rather than abandoning it.
178        let refresh = {
179            let mut state = self
180                .state
181                .lock()
182                .unwrap_or_else(std::sync::PoisonError::into_inner);
183            if self.generation.load(Ordering::Acquire) != seen {
184                return Ok(state.last_renewed);
185            }
186            state
187                .in_flight
188                .get_or_insert_with(|| {
189                    let provider = self.provider.clone();
190                    AssertUnwindSafe(async move { provider.refresh().await })
191                        .catch_unwind()
192                        .map(|caught| match caught {
193                            Ok(outcome) => outcome.map_err(Arc::new),
194                            Err(_) => Err(Arc::new(Error::new(
195                                crate::ErrorCode::AuthRequired,
196                                "the token provider panicked while refreshing",
197                            ))),
198                        })
199                        .boxed()
200                        .shared()
201                })
202                .clone()
203        };
204        let outcome = refresh.await;
205        {
206            let mut state = self
207                .state
208                .lock()
209                .unwrap_or_else(std::sync::PoisonError::into_inner);
210            if self.generation.load(Ordering::Acquire) == seen {
211                state.last_renewed = matches!(outcome, Ok(true));
212                state.in_flight = None;
213                self.generation.fetch_add(1, Ordering::AcqRel);
214            }
215        }
216        outcome.map_err(|error| {
217            Error::new(error.code(), error.message())
218                .with_status(error.http_status().unwrap_or(401))
219                .with_source(error)
220        })
221    }
222}
223
224#[async_trait]
225impl<S: AuthStrategy + ?Sized> AuthStrategy for Arc<S> {
226    async fn authenticate(&self, request: &mut Request<Bytes>) -> Result<(), Error> {
227        (**self).authenticate(request).await
228    }
229
230    fn refreshable(&self) -> bool {
231        (**self).refreshable()
232    }
233
234    fn generation(&self) -> u64 {
235        (**self).generation()
236    }
237
238    async fn refresh(&self, seen: u64) -> Result<bool, Error> {
239        (**self).refresh(seen).await
240    }
241}
242
243#[async_trait]
244impl<P: TokenProvider + ?Sized> TokenProvider for Arc<P> {
245    async fn access_token(&self) -> Result<String, Error> {
246        (**self).access_token().await
247    }
248
249    fn refreshable(&self) -> bool {
250        (**self).refreshable()
251    }
252
253    async fn refresh(&self) -> Result<bool, Error> {
254        (**self).refresh().await
255    }
256}