Skip to main content

stack_auth/
lib.rs

1#![doc(html_favicon_url = "https://cipherstash.com/favicon.ico")]
2#![doc = include_str!("../README.md")]
3// Security lints
4#![deny(unsafe_code)]
5#![warn(clippy::unwrap_used)]
6#![warn(clippy::expect_used)]
7#![warn(clippy::panic)]
8// Prevent mem::forget from bypassing ZeroizeOnDrop
9#![warn(clippy::mem_forget)]
10// Prevent accidental data leaks via output
11#![warn(clippy::print_stdout)]
12#![warn(clippy::print_stderr)]
13#![warn(clippy::dbg_macro)]
14// Code quality
15#![warn(unreachable_pub)]
16#![warn(unused_results)]
17#![warn(clippy::todo)]
18#![warn(clippy::unimplemented)]
19// Relax in tests
20#![cfg_attr(test, allow(clippy::unwrap_used))]
21#![cfg_attr(test, allow(clippy::expect_used))]
22#![cfg_attr(test, allow(clippy::panic))]
23#![cfg_attr(test, allow(unused_results))]
24
25use std::convert::Infallible;
26use std::future::Future;
27#[cfg(not(any(test, feature = "test-utils")))]
28use std::time::Duration;
29
30use vitaminc::protected::OpaqueDebug;
31use zeroize::ZeroizeOnDrop;
32
33mod access_key;
34mod access_key_refresher;
35mod access_key_strategy;
36mod auto_refresh;
37mod auto_strategy;
38mod device_code;
39mod oauth_refresher;
40mod oauth_strategy;
41mod refresher;
42mod service_token;
43mod token;
44
45#[cfg(any(test, feature = "test-utils"))]
46mod static_token_strategy;
47
48pub use access_key::{AccessKey, InvalidAccessKey};
49pub use access_key_strategy::{AccessKeyStrategy, AccessKeyStrategyBuilder};
50pub use auto_strategy::{AutoStrategy, AutoStrategyBuilder};
51pub use device_code::{DeviceCodeStrategy, DeviceCodeStrategyBuilder, PendingDeviceCode};
52pub use oauth_strategy::{OAuthStrategy, OAuthStrategyBuilder};
53pub use service_token::ServiceToken;
54#[cfg(any(test, feature = "test-utils"))]
55pub use static_token_strategy::StaticTokenStrategy;
56pub use token::Token;
57
58// Re-exports from stack-profile for backward compatibility.
59pub use stack_profile::DeviceIdentity;
60
61/// A strategy for obtaining access tokens.
62///
63/// Implementations handle all details of authentication, token caching, and
64/// refresh. Callers just call [`get_token`](AuthStrategy::get_token) whenever
65/// they need a valid token.
66///
67/// The trait is designed to be implemented for `&T`, so that callers can use
68/// shared references (e.g. `&OAuthStrategy`) without consuming the strategy.
69///
70/// # Token refresh
71///
72/// All strategies that cache tokens ([`AccessKeyStrategy`], [`OAuthStrategy`],
73/// [`AutoStrategy`]) share the same internal refresh engine. Understanding the
74/// refresh model helps predict how [`get_token`](AuthStrategy::get_token)
75/// behaves under concurrent access.
76///
77/// ## Expiry vs usability
78///
79/// A token has two time thresholds:
80///
81/// - **Expired** — the token is within **90 seconds** of its `expires_at`
82///   timestamp. This triggers a preemptive refresh attempt.
83/// - **Usable** — the token has **not yet reached** its `expires_at` timestamp.
84///   A token can be "expired" (in the preemptive sense) but still "usable"
85///   (the server will still accept it).
86///
87/// ## Concurrent refresh strategies
88///
89/// The gap between "expired" and "unusable" enables two refresh modes:
90///
91/// 1. **Expiring but still usable** — The first caller triggers a background
92///    refresh. Concurrent callers receive the current (still-valid) token
93///    immediately without blocking.
94/// 2. **Fully expired** — The first caller blocks while refreshing. Concurrent
95///    callers wait until the refresh completes, then all receive the new token.
96///
97/// Only one refresh runs at a time, regardless of how many callers request a
98/// token concurrently.
99///
100/// ## Flow diagram
101///
102/// ```mermaid
103/// flowchart TD
104///     Start["get_token()"] --> Lock["Acquire lock"]
105///     Lock --> Cached{Token cached?}
106///     Cached -- No --> InitAuth["Authenticate
107///     (lock held)"]
108///     InitAuth -- OK --> ReturnNew["Return new token"]
109///     InitAuth -- NotFound --> ErrNotFound["NotAuthenticated"]
110///     InitAuth -- Err --> ErrAuth["Return error"]
111///     Cached -- Yes --> CheckRefresh{Expired?}
112///
113///     CheckRefresh -- "No (fresh)" --> ReturnOk["Return cached token"]
114///
115///     CheckRefresh -- "Yes (needs refresh)" --> InProgress{Refresh in progress?}
116///     InProgress -- Yes --> WaitOrReturn["Return token if usable,
117///     else wait for refresh"]
118///     WaitOrReturn -- OK --> ReturnOk
119///     WaitOrReturn -- "refresh failed" --> ErrExpired["TokenExpired"]
120///
121///     InProgress -- No --> HasCred{Refresh credential?}
122///     HasCred -- None --> CheckUsable["Return token if usable,
123///     else TokenExpired"]
124///
125///     HasCred -- Yes --> Usable{Still usable?}
126///
127///     Usable -- "Yes (preemptive)" --> NonBlocking["Refresh in background
128///     (lock released)"]
129///     NonBlocking --> ReturnOld["Return current token"]
130///
131///     Usable -- "No (fully expired)" --> Blocking["Refresh
132///     (lock held)"]
133///     Blocking -- OK --> ReturnNew2["Return new token"]
134///     Blocking -- Err --> ErrExpired["TokenExpired"]
135/// ```
136#[cfg_attr(doc, aquamarine::aquamarine)]
137pub trait AuthStrategy: Send {
138    /// Retrieve a valid access token, refreshing or re-authenticating as needed.
139    fn get_token(self) -> impl Future<Output = Result<ServiceToken, AuthError>> + Send;
140}
141
142/// A sensitive token string that is zeroized on drop and hidden from debug output.
143///
144/// `SecretToken` wraps a `String` and enforces two invariants:
145///
146/// - **Zeroized on drop**: the backing memory is overwritten with zeros when
147///   the token goes out of scope, preventing it from lingering in memory.
148/// - **Opaque debug**: the [`Debug`] implementation prints `"***"` instead of
149///   the actual value, so tokens won't leak into logs or error messages.
150///
151/// Use [`SecretToken::new`] to wrap a string value (e.g. an access key
152/// loaded from configuration or an environment variable).
153#[derive(Clone, OpaqueDebug, ZeroizeOnDrop, serde::Deserialize, serde::Serialize)]
154#[serde(transparent)]
155pub struct SecretToken(String);
156
157impl SecretToken {
158    /// Create a new `SecretToken` from a string value.
159    pub fn new(value: impl Into<String>) -> Self {
160        Self(value.into())
161    }
162
163    /// Expose the inner token string for FFI boundaries.
164    pub fn as_str(&self) -> &str {
165        &self.0
166    }
167}
168
169/// Errors that can occur during an authentication flow.
170#[derive(Debug, thiserror::Error, miette::Diagnostic)]
171#[non_exhaustive]
172pub enum AuthError {
173    /// The HTTP request to the auth server failed (network error, timeout, etc.).
174    #[error("HTTP request failed: {0}")]
175    Request(#[from] reqwest::Error),
176    /// The user denied the authorization request.
177    #[error("Authorization was denied")]
178    AccessDenied,
179    /// The grant type was rejected by the server.
180    #[error("Invalid grant")]
181    InvalidGrant,
182    /// The client ID is not recognized.
183    #[error("Invalid client")]
184    InvalidClient,
185    /// A URL could not be parsed.
186    #[error("Invalid URL: {0}")]
187    InvalidUrl(#[from] url::ParseError),
188    /// The requested region is not supported.
189    #[error("Unsupported region: {0}")]
190    Region(#[from] cts_common::RegionError),
191    /// The workspace CRN could not be parsed.
192    #[error("Invalid workspace CRN: {0}")]
193    InvalidCrn(cts_common::InvalidCrn),
194    /// An access key was provided but the workspace CRN is missing.
195    ///
196    /// Set the `CS_WORKSPACE_CRN` environment variable or call
197    /// [`AutoStrategyBuilder::with_workspace_crn`](crate::AutoStrategyBuilder::with_workspace_crn).
198    #[error("Workspace CRN is required when using an access key — set CS_WORKSPACE_CRN or call AutoStrategyBuilder::with_workspace_crn")]
199    MissingWorkspaceCrn,
200    /// No credentials are available (e.g. not logged in, no access key configured).
201    #[error("Not authenticated")]
202    NotAuthenticated,
203    /// A token (access token or device code) has expired.
204    #[error("Token expired")]
205    TokenExpired,
206    /// The access key string is malformed (e.g. missing `CSAK` prefix or `.` separator).
207    #[error("Invalid access key: {0}")]
208    InvalidAccessKey(#[from] access_key::InvalidAccessKey),
209    /// The JWT could not be decoded or its claims are malformed.
210    #[error("Invalid token: {0}")]
211    InvalidToken(String),
212    /// An unexpected error was returned by the auth server.
213    #[error("Server error: {0}")]
214    Server(String),
215    /// A token store operation failed.
216    #[error("Token store error: {0}")]
217    Store(#[from] stack_profile::ProfileError),
218}
219
220impl From<Infallible> for AuthError {
221    fn from(never: Infallible) -> Self {
222        match never {}
223    }
224}
225
226/// Read the `CS_CTS_HOST` environment variable and parse it as a URL.
227///
228/// Returns `Ok(None)` if the variable is not set or empty.
229/// Returns `Ok(Some(url))` if the variable is set and valid.
230/// Returns `Err(_)` if the variable is set but not a valid URL.
231pub(crate) fn cts_base_url_from_env() -> Result<Option<url::Url>, AuthError> {
232    match std::env::var("CS_CTS_HOST") {
233        Ok(val) if !val.is_empty() => Ok(Some(val.parse()?)),
234        _ => Ok(None),
235    }
236}
237
238/// Ensure a URL has a trailing slash so that `Url::join` with relative paths
239/// appends to the path rather than replacing the last segment.
240pub(crate) fn ensure_trailing_slash(mut url: url::Url) -> url::Url {
241    if !url.path().ends_with('/') {
242        url.set_path(&format!("{}/", url.path()));
243    }
244    url
245}
246
247/// Create a [`reqwest::Client`] with standard timeouts.
248///
249/// In test builds, timeouts are omitted so that `tokio::test(start_paused = true)`
250/// does not auto-advance time past the connect timeout before the mock server
251/// can respond.
252pub(crate) fn http_client() -> reqwest::Client {
253    #[cfg(any(test, feature = "test-utils"))]
254    {
255        reqwest::Client::builder()
256            .pool_max_idle_per_host(10)
257            .build()
258            .unwrap_or_else(|_| reqwest::Client::new())
259    }
260    #[cfg(not(any(test, feature = "test-utils")))]
261    {
262        reqwest::Client::builder()
263            .connect_timeout(Duration::from_secs(10))
264            .timeout(Duration::from_secs(30))
265            .pool_idle_timeout(Duration::from_secs(5))
266            .pool_max_idle_per_host(10)
267            .build()
268            .unwrap_or_else(|_| reqwest::Client::new())
269    }
270}