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(all(not(any(test, feature = "test-utils")), not(target_arch = "wasm32")))]
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 auth_strategy_fn;
37mod auto_refresh;
38mod auto_strategy;
39mod oauth_refresher;
40mod oauth_strategy;
41mod refresher;
42mod service_token;
43mod token;
44mod token_store;
45
46// Filesystem-backed device identity and the interactive device-code flow are
47// native-only — both pull `stack-profile` (which uses `dirs` + `gethostname`)
48// and the device-code flow launches a browser via `open::that`. Wasm consumers
49// use `OAuthStrategy::with_token` or `AccessKeyStrategy`.
50#[cfg(not(target_arch = "wasm32"))]
51mod device_client;
52#[cfg(not(target_arch = "wasm32"))]
53mod device_code;
54
55#[cfg(any(test, feature = "test-utils"))]
56mod static_token_strategy;
57
58pub use access_key::{AccessKey, InvalidAccessKey};
59pub use access_key_strategy::{AccessKeyStrategy, AccessKeyStrategyBuilder};
60pub use auth_strategy_fn::AuthStrategyFn;
61pub use auto_strategy::{AutoStrategy, AutoStrategyBuilder};
62pub use oauth_strategy::{OAuthStrategy, OAuthStrategyBuilder};
63pub use service_token::ServiceToken;
64#[cfg(any(test, feature = "test-utils"))]
65pub use static_token_strategy::StaticTokenStrategy;
66pub use token::Token;
67pub use token_store::{InMemoryTokenStore, NoStore, TokenStore, TokenStoreFn};
68
69#[cfg(not(target_arch = "wasm32"))]
70pub use device_client::{bind_client_device, DeviceClientError};
71#[cfg(not(target_arch = "wasm32"))]
72pub use device_code::{DeviceCodeStrategy, DeviceCodeStrategyBuilder, PendingDeviceCode};
73
74// Re-exports from stack-profile for backward compatibility.
75#[cfg(not(target_arch = "wasm32"))]
76pub use stack_profile::DeviceIdentity;
77
78/// Token *acquisition* — strategies that produce a [`ServiceToken`].
79///
80/// Use [`AuthStrategy`] as the consumer-facing trait (e.g. when wiring
81/// strategies into `cipherstash-client`). [`AuthStrategyFn`] is the
82/// closure-shaped impl for callers that source tokens externally
83/// (FFI, custom IPC).
84///
85/// For the *persistence layer* — pluggable storage that slots into an
86/// existing strategy — see [`crate::store`].
87///
88/// All items in this module are also re-exported at the crate root.
89pub mod auth {
90 pub use crate::{
91 AccessKey, AccessKeyStrategy, AccessKeyStrategyBuilder, AuthError, AuthStrategy,
92 AuthStrategyFn, AutoStrategy, AutoStrategyBuilder, InvalidAccessKey, OAuthStrategy,
93 OAuthStrategyBuilder, SecretToken, ServiceToken,
94 };
95
96 #[cfg(not(target_arch = "wasm32"))]
97 pub use crate::{
98 bind_client_device, DeviceClientError, DeviceCodeStrategy, DeviceCodeStrategyBuilder,
99 DeviceIdentity, PendingDeviceCode,
100 };
101
102 #[cfg(any(test, feature = "test-utils"))]
103 pub use crate::StaticTokenStrategy;
104}
105
106/// Token *persistence* — pluggable backends for the service-token cache.
107///
108/// Use [`TokenStore`] as the trait, [`TokenStoreFn`] for closure-shaped
109/// impls (cookies, KV blobs, Redis), and [`InMemoryTokenStore`] / [`NoStore`]
110/// for ready-made implementations.
111///
112/// A `TokenStore` plugs into a concrete strategy via that strategy's
113/// builder (e.g.
114/// [`AccessKeyStrategyBuilder::with_token_store`](crate::AccessKeyStrategyBuilder::with_token_store))
115/// — it does *not* replace the strategy. For full token acquisition (custom
116/// fetcher, FFI-hosted strategy), see [`crate::auth`].
117///
118/// All items in this module are also re-exported at the crate root.
119pub mod store {
120 pub use crate::{InMemoryTokenStore, NoStore, Token, TokenStore, TokenStoreFn};
121}
122
123/// A strategy for obtaining access tokens.
124///
125/// Implementations handle all details of authentication, token caching, and
126/// refresh. Callers just call [`get_token`](AuthStrategy::get_token) whenever
127/// they need a valid token.
128///
129/// The trait is designed to be implemented for `&T`, so that callers can use
130/// shared references (e.g. `&OAuthStrategy`) without consuming the strategy.
131///
132/// # Token refresh
133///
134/// All strategies that cache tokens ([`AccessKeyStrategy`], [`OAuthStrategy`],
135/// [`AutoStrategy`]) share the same internal refresh engine. Understanding the
136/// refresh model helps predict how [`get_token`](AuthStrategy::get_token)
137/// behaves under concurrent access.
138///
139/// ## Expiry vs usability
140///
141/// A token has two time thresholds:
142///
143/// - **Expired** — the token is within **90 seconds** of its `expires_at`
144/// timestamp. This triggers a preemptive refresh attempt.
145/// - **Usable** — the token has **not yet reached** its `expires_at` timestamp.
146/// A token can be "expired" (in the preemptive sense) but still "usable"
147/// (the server will still accept it).
148///
149/// ## Concurrent refresh strategies
150///
151/// The gap between "expired" and "unusable" enables two refresh modes:
152///
153/// 1. **Expiring but still usable** — The first caller triggers a background
154/// refresh. Concurrent callers receive the current (still-valid) token
155/// immediately without blocking.
156/// 2. **Fully expired** — The first caller blocks while refreshing. Concurrent
157/// callers wait until the refresh completes, then all receive the new token.
158///
159/// Only one refresh runs at a time, regardless of how many callers request a
160/// token concurrently.
161///
162/// ## Flow diagram
163///
164/// ```mermaid
165/// flowchart TD
166/// Start["get_token()"] --> Lock["Acquire lock"]
167/// Lock --> Cached{Token cached?}
168/// Cached -- No --> InitAuth["Authenticate
169/// (lock held)"]
170/// InitAuth -- OK --> ReturnNew["Return new token"]
171/// InitAuth -- NotFound --> ErrNotFound["NotAuthenticated"]
172/// InitAuth -- Err --> ErrAuth["Return error"]
173/// Cached -- Yes --> CheckRefresh{Expired?}
174///
175/// CheckRefresh -- "No (fresh)" --> ReturnOk["Return cached token"]
176///
177/// CheckRefresh -- "Yes (needs refresh)" --> InProgress{Refresh in progress?}
178/// InProgress -- Yes --> WaitOrReturn["Return token if usable,
179/// else wait for refresh"]
180/// WaitOrReturn -- OK --> ReturnOk
181/// WaitOrReturn -- "refresh failed" --> ErrExpired["TokenExpired"]
182///
183/// InProgress -- No --> HasCred{Refresh credential?}
184/// HasCred -- None --> CheckUsable["Return token if usable,
185/// else TokenExpired"]
186///
187/// HasCred -- Yes --> Usable{Still usable?}
188///
189/// Usable -- "Yes (preemptive)" --> NonBlocking["Refresh in background
190/// (lock released)"]
191/// NonBlocking --> ReturnOld["Return current token"]
192///
193/// Usable -- "No (fully expired)" --> Blocking["Refresh
194/// (lock held)"]
195/// Blocking -- OK --> ReturnNew2["Return new token"]
196/// Blocking -- Err --> ErrExpired["TokenExpired"]
197/// ```
198#[cfg_attr(doc, aquamarine::aquamarine)]
199#[cfg(not(target_arch = "wasm32"))]
200pub trait AuthStrategy: Send {
201 /// Retrieve a valid access token, refreshing or re-authenticating as needed.
202 fn get_token(self) -> impl Future<Output = Result<ServiceToken, AuthError>> + Send;
203}
204
205/// Wasm32 variant of [`AuthStrategy`] — drops the `Send` bounds because
206/// reqwest's fetch-backed futures aren't `Send` and edge runtimes are
207/// single-threaded.
208#[cfg(target_arch = "wasm32")]
209pub trait AuthStrategy {
210 /// Retrieve a valid access token, refreshing or re-authenticating as needed.
211 fn get_token(self) -> impl Future<Output = Result<ServiceToken, AuthError>>;
212}
213
214/// A sensitive token string that is zeroized on drop and hidden from debug output.
215///
216/// `SecretToken` wraps a `String` and enforces two invariants:
217///
218/// - **Zeroized on drop**: the backing memory is overwritten with zeros when
219/// the token goes out of scope, preventing it from lingering in memory.
220/// - **Opaque debug**: the [`Debug`] implementation prints `"***"` instead of
221/// the actual value, so tokens won't leak into logs or error messages.
222///
223/// Use [`SecretToken::new`] to wrap a string value (e.g. an access key
224/// loaded from configuration or an environment variable).
225#[derive(Clone, OpaqueDebug, ZeroizeOnDrop, serde::Deserialize, serde::Serialize)]
226#[serde(transparent)]
227pub struct SecretToken(String);
228
229impl SecretToken {
230 /// Create a new `SecretToken` from a string value.
231 pub fn new(value: impl Into<String>) -> Self {
232 Self(value.into())
233 }
234
235 /// Expose the inner token string for FFI boundaries.
236 pub fn as_str(&self) -> &str {
237 &self.0
238 }
239}
240
241/// Errors that can occur during an authentication flow.
242#[derive(Debug, thiserror::Error, miette::Diagnostic)]
243#[non_exhaustive]
244pub enum AuthError {
245 /// The HTTP request to the auth server failed (network error, timeout, etc.).
246 #[error("HTTP request failed: {0}")]
247 Request(#[from] reqwest::Error),
248 /// The user denied the authorization request.
249 #[error("Authorization was denied")]
250 AccessDenied,
251 /// The grant type was rejected by the server.
252 #[error("Invalid grant")]
253 InvalidGrant,
254 /// The client ID is not recognized.
255 #[error("Invalid client")]
256 InvalidClient,
257 /// A URL could not be parsed.
258 #[error("Invalid URL: {0}")]
259 InvalidUrl(#[from] url::ParseError),
260 /// The requested region is not supported.
261 #[error("Unsupported region: {0}")]
262 Region(#[from] cts_common::RegionError),
263 /// The workspace CRN could not be parsed.
264 #[error("Invalid workspace CRN: {0}")]
265 InvalidCrn(cts_common::InvalidCrn),
266 /// An access key was provided but the workspace CRN is missing.
267 ///
268 /// Set the `CS_WORKSPACE_CRN` environment variable or call
269 /// [`AutoStrategyBuilder::with_workspace_crn`](crate::AutoStrategyBuilder::with_workspace_crn).
270 #[error("Workspace CRN is required when using an access key — set CS_WORKSPACE_CRN or call AutoStrategyBuilder::with_workspace_crn")]
271 MissingWorkspaceCrn,
272 /// No credentials are available (e.g. not logged in, no access key configured).
273 #[error("Not authenticated")]
274 NotAuthenticated,
275 /// A token (access token or device code) has expired.
276 #[error("Token expired")]
277 TokenExpired,
278 /// The access key string is malformed (e.g. missing `CSAK` prefix or `.` separator).
279 #[error("Invalid access key: {0}")]
280 InvalidAccessKey(#[from] access_key::InvalidAccessKey),
281 /// The JWT could not be decoded or its claims are malformed.
282 #[error("Invalid token: {0}")]
283 InvalidToken(String),
284 /// An unexpected error was returned by the auth server.
285 #[error("Server error: {0}")]
286 Server(String),
287 /// A token store operation failed.
288 #[cfg(not(target_arch = "wasm32"))]
289 #[error("Token store error: {0}")]
290 Store(#[from] stack_profile::ProfileError),
291}
292
293impl AuthError {
294 /// Stable machine-readable identifier for surfacing across FFI boundaries
295 /// (e.g. JS `Error.code`, Node-API error codes). Named `error_code` rather
296 /// than `code` to avoid colliding with `miette::Diagnostic::code`, which
297 /// is inherited via `#[derive(Diagnostic)]`.
298 pub fn error_code(&self) -> &'static str {
299 match self {
300 Self::Request(_) => "REQUEST_ERROR",
301 Self::AccessDenied => "ACCESS_DENIED",
302 Self::TokenExpired => "EXPIRED_TOKEN",
303 Self::InvalidGrant => "INVALID_GRANT",
304 Self::InvalidClient => "INVALID_CLIENT",
305 Self::InvalidUrl(_) => "INVALID_URL",
306 Self::Region(_) => "INVALID_REGION",
307 Self::InvalidToken(_) => "INVALID_TOKEN",
308 Self::Server(_) => "SERVER_ERROR",
309 Self::NotAuthenticated => "NOT_AUTHENTICATED",
310 Self::MissingWorkspaceCrn => "MISSING_WORKSPACE_CRN",
311 Self::InvalidAccessKey(_) => "INVALID_ACCESS_KEY",
312 Self::InvalidCrn(_) => "INVALID_CRN",
313 #[cfg(not(target_arch = "wasm32"))]
314 Self::Store(_) => "STORE_ERROR",
315 }
316 }
317}
318
319impl From<Infallible> for AuthError {
320 fn from(never: Infallible) -> Self {
321 match never {}
322 }
323}
324
325/// Read the `CS_CTS_HOST` environment variable and parse it as a URL.
326///
327/// Returns `Ok(None)` if the variable is not set or empty.
328/// Returns `Ok(Some(url))` if the variable is set and valid.
329/// Returns `Err(_)` if the variable is set but not a valid URL.
330pub(crate) fn cts_base_url_from_env() -> Result<Option<url::Url>, AuthError> {
331 match std::env::var("CS_CTS_HOST") {
332 Ok(val) if !val.is_empty() => Ok(Some(val.parse()?)),
333 _ => Ok(None),
334 }
335}
336
337/// Ensure a URL has a trailing slash so that `Url::join` with relative paths
338/// appends to the path rather than replacing the last segment.
339pub(crate) fn ensure_trailing_slash(mut url: url::Url) -> url::Url {
340 if !url.path().ends_with('/') {
341 url.set_path(&format!("{}/", url.path()));
342 }
343 url
344}
345
346/// Decode a JWT payload by splitting on `.`, base64-decoding the middle
347/// segment, and deserializing the JSON. Used on wasm32 to avoid `jsonwebtoken`
348/// (which pulls `ring`). Signatures are not verified — same posture as the
349/// native path, which calls `insecure_disable_signature_validation()`.
350#[cfg(target_arch = "wasm32")]
351pub(crate) fn decode_jwt_payload_wasm<C>(token: &str) -> Result<C, AuthError>
352where
353 C: serde::de::DeserializeOwned,
354{
355 use base64::Engine;
356 let segments: Vec<&str> = token.split('.').collect();
357 if segments.len() != 3 {
358 return Err(AuthError::InvalidToken(
359 "JWT must have three segments".to_string(),
360 ));
361 }
362 let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
363 .decode(segments[1])
364 .map_err(|e| AuthError::InvalidToken(format!("base64 decode failed: {e}")))?;
365 serde_json::from_slice(&payload)
366 .map_err(|e| AuthError::InvalidToken(format!("failed to decode JWT claims: {e}")))
367}
368
369/// Create a [`reqwest::Client`] with standard timeouts.
370///
371/// In test builds, timeouts are omitted so that `tokio::test(start_paused = true)`
372/// does not auto-advance time past the connect timeout before the mock server
373/// can respond. On wasm32, reqwest's fetch backend doesn't expose
374/// `connect_timeout`/`pool_*` — the host runtime owns those concerns.
375#[cfg(any(test, feature = "test-utils"))]
376pub(crate) fn http_client() -> reqwest::Client {
377 reqwest::Client::builder()
378 .build()
379 .unwrap_or_else(|_| reqwest::Client::new())
380}
381
382#[cfg(all(not(any(test, feature = "test-utils")), not(target_arch = "wasm32")))]
383pub(crate) fn http_client() -> reqwest::Client {
384 reqwest::Client::builder()
385 .connect_timeout(Duration::from_secs(10))
386 .timeout(Duration::from_secs(30))
387 .pool_idle_timeout(Duration::from_secs(5))
388 .pool_max_idle_per_host(10)
389 .build()
390 .unwrap_or_else(|_| reqwest::Client::new())
391}
392
393#[cfg(all(not(any(test, feature = "test-utils")), target_arch = "wasm32"))]
394pub(crate) fn http_client() -> reqwest::Client {
395 // Wasm32 reqwest uses the host's `fetch`; timeouts and pooling are owned
396 // by the runtime, so `ClientBuilder` doesn't expose them here.
397 reqwest::Client::builder()
398 .build()
399 .unwrap_or_else(|_| reqwest::Client::new())
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 #[test]
407 fn auth_error_code_known_variants() {
408 assert_eq!(AuthError::AccessDenied.error_code(), "ACCESS_DENIED");
409 assert_eq!(AuthError::TokenExpired.error_code(), "EXPIRED_TOKEN");
410 assert_eq!(AuthError::InvalidGrant.error_code(), "INVALID_GRANT");
411 assert_eq!(AuthError::InvalidClient.error_code(), "INVALID_CLIENT");
412 assert_eq!(
413 AuthError::NotAuthenticated.error_code(),
414 "NOT_AUTHENTICATED"
415 );
416 assert_eq!(
417 AuthError::MissingWorkspaceCrn.error_code(),
418 "MISSING_WORKSPACE_CRN"
419 );
420 assert_eq!(AuthError::Server("x".into()).error_code(), "SERVER_ERROR");
421 assert_eq!(
422 AuthError::InvalidToken("malformed".into()).error_code(),
423 "INVALID_TOKEN"
424 );
425 }
426}