spiral-auth 0.1.12

Spiral credentials: bearer tokens and the providers that obtain them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Spiral credentials: bearer tokens, the providers that obtain them, and default discovery.
//!
//! A [`TokenSource`] supplies the token for each request; every provider converts into one.
//! Providers that need extra dependencies, such as a cloud SDK or a browser, are behind
//! features. Signing and TLS use the rustls crypto provider that the `aws-lc` or `ring`
//! feature selects, unless the application installed one first.

use std::env;
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::sync::Arc;

use futures::FutureExt as _;
use futures::future::BoxFuture;
pub use reqwest::Url;
use reqwest_middleware::ClientWithMiddleware;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;

/// A [`CredentialError::Invalid`] with a `format!` message.
macro_rules! invalid {
    ($($arg:tt)*) => {
        $crate::CredentialError::invalid(format!($($arg)*))
    };
}

/// Return a [`CredentialError::Invalid`] with a `format!` message.
macro_rules! bail {
    ($($arg:tt)*) => {
        return Err(invalid!($($arg)*))
    };
}

/// Convert a provider with inherent async `token` (and, with `cached`, `cached_token`) methods
/// into a [`TokenSource`].
macro_rules! impl_token_source {
    ($provider:ty) => {
        impl From<$provider> for $crate::TokenSource {
            fn from(provider: $provider) -> Self {
                let provider = ::std::sync::Arc::new(provider);
                $crate::TokenSource::named(::std::any::type_name::<$provider>(), move || {
                    let provider = ::std::sync::Arc::clone(&provider);
                    async move { provider.token().await }
                })
            }
        }
    };
    ($provider:ty,cached) => {
        impl From<$provider> for $crate::TokenSource {
            fn from(provider: $provider) -> Self {
                let provider = ::std::sync::Arc::new(provider);
                let cached = ::std::sync::Arc::clone(&provider);
                $crate::TokenSource::named(::std::any::type_name::<$provider>(), move || {
                    let provider = ::std::sync::Arc::clone(&provider);
                    async move { provider.token().await }
                })
                .with_cached(move || {
                    let provider = ::std::sync::Arc::clone(&cached);
                    async move { provider.cached_token().await }
                })
            }
        }
    };
}

mod error;
mod http;
mod providers;
mod tls;
mod token;

pub use error::{CredentialError, CredentialResult};
#[cfg(feature = "aws")]
pub use providers::AwsAuthProvider;
#[cfg(feature = "kubernetes")]
pub use providers::KubernetesAuthProvider;
#[cfg(feature = "modal")]
pub use providers::ModalAuthProvider;
pub use providers::{
    ClientCredentials, ClientCredentialsProvider, ClientGrant, FallbackAuthn, OidcAuthProvider,
    RefreshingAuthTokenProvider, WorkloadAuthn, default_auth_url, exchange_for_jwt, exchange_token,
    resolve_workload_id, token_endpoint,
};
#[cfg(feature = "device-auth")]
pub use providers::{
    DeviceAuthBuilder, DeviceAuthn, DeviceCodeAuth, DeviceTokenStore, FileTokenStore, TokensModel,
};
#[cfg(feature = "gcp")]
pub use providers::{GcpAuthProvider, GcpServiceAuthProvider};
#[cfg(feature = "github")]
pub use providers::{GitHubAuthProvider, fetch_github_oidc_token};
#[cfg(feature = "private-key-auth")]
pub use providers::{PrivateKeyCredentials, PrivateKeyJwtProvider};
pub use tls::install_default_crypto_provider;
pub use token::Token;

/// RFC 8693 §3 token type of an OAuth access token.
pub(crate) const TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token";

/// RFC 8693 §3 token type of a JWT that is not an access token, such as an identity token
/// for another cloud.
pub(crate) const TOKEN_TYPE_JWT: &str = "urn:ietf:params:oauth:token-type:jwt";

/// RFC 7523 client authentication using a JWT bearer assertion.
pub const CLIENT_ASSERTION_TYPE_JWT_BEARER: &str =
    "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";

/// OAuth client IDs of Spiral's first-party applications, registered on every stack.
pub mod oauth_clients {
    /// The Spiral CLI and the SDKs built on this crate.
    pub const SPIRAL_SDK: &str = "client_01m3xejegfehktm0ddjcyam4g8";
    /// The Spiral Studio desktop application.
    pub const SPIRAL_STUDIO_DESKTOP: &str = "client_01m3xejegffrsb50dbgwm422xd";
    /// The Spiral Studio web application.
    pub const SPIRAL_STUDIO_WEB: &str = "client_01m3xejegfemf9q41vmzj289r9";
    /// Local web development against Spiral stacks.
    pub const SPIRAL_STUDIO_DEV: &str = "client_ZRfbyzcUxVyi";
}

/// A request to Spiral's RFC 6749 token endpoint.
#[derive(Debug, Serialize, Deserialize)]
pub struct OAuth2TokenRequest {
    #[serde(flatten)]
    pub client: OAuth2ClientAuthentication,
    #[serde(flatten)]
    pub grant: OAuth2Grant,
}

impl OAuth2TokenRequest {
    /// A grant requested by a public client, which identifies itself only by `client_id`.
    #[cfg(feature = "device-auth")]
    pub(crate) fn public(client_id: &str, grant: OAuth2Grant) -> Self {
        Self {
            client: OAuth2ClientAuthentication {
                client_id: Some(client_id.to_owned()),
                ..Default::default()
            },
            grant,
        }
    }
}

/// Client authentication parameters sent in the token request body.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct OAuth2ClientAuthentication {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_secret: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_assertion_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_assertion: Option<String>,
}

/// The authorization grant presented to the token endpoint.
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "grant_type")]
pub enum OAuth2Grant {
    /// RFC 6749 §4.1.3 authorization code bound to a callback and PKCE verifier.
    #[serde(rename = "authorization_code")]
    AuthorizationCode {
        code: String,
        redirect_uri: String,
        code_verifier: String,
    },
    #[serde(rename = "client_credentials")]
    ClientCredentials {
        /// RFC 8707: the resource server, such as a stack, that the token is for.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        resource: Option<String>,
        /// RFC 9396 §6: a JSON array of authorization details.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        authorization_details: Option<String>,
    },
    /// RFC 7523 §2.1: a JWT from an issuer the client trusts, such as its host's workload
    /// identity token, is the grant.
    #[serde(rename = "urn:ietf:params:oauth:grant-type:jwt-bearer")]
    JwtBearer {
        assertion: String,
        /// RFC 8707: the resource server, such as a stack, that the token is for.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        resource: Option<String>,
        /// RFC 9396 §6: a JSON array of authorization details.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        authorization_details: Option<String>,
    },
    #[serde(rename = "refresh_token")]
    RefreshToken {
        refresh_token: String,
        /// Extension: switch the session to another organization the user belongs to.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        organization_id: Option<String>,
    },
    #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
    DeviceCode { device_code: String },
    /// RFC 8693 §2.1: an access token for a token to another resource or audience.
    #[serde(rename = "urn:ietf:params:oauth:grant-type:token-exchange")]
    TokenExchange {
        subject_token: String,
        subject_token_type: String,
        /// RFC 8707: the resource server the token is for.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        resource: Option<String>,
        /// RFC 8693 §2.1: the logical name of the token's audience, for one that is not a URL.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        audience: Option<String>,
        /// RFC 8693 §2.1: an access token unless named.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        requested_token_type: Option<String>,
        /// RFC 9396 §6: a JSON array of authorization details.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        authorization_details: Option<String>,
    },
}

/// An RFC 6749 §5.1 token response.
#[derive(Debug, Serialize, Deserialize)]
pub struct OAuth2TokenResponse {
    pub access_token: Token,
    pub token_type: String,
    pub expires_in: Option<u64>,
    pub refresh_token: Option<String>,
    /// The resource the access token is for: the API URL to call. An extension response
    /// parameter (RFC 6749 §5.1) of Spiral's authorization server.
    #[serde(default)]
    pub resource: Option<String>,
}

impl OAuth2TokenResponse {
    /// The access token, carrying the resource it is for.
    pub(crate) fn into_access_token(self) -> Token {
        self.access_token.with_resource(self.resource)
    }
}

type FetchToken = dyn Fn() -> BoxFuture<'static, CredentialResult<Option<Token>>> + Send + Sync;

/// A source of bearer tokens, consulted immediately before each authenticated request.
///
/// A source wraps an async closure, so any function can supply credentials. The providers in
/// this crate convert into one with `From`. Clones share the closure.
#[derive(Clone)]
pub struct TokenSource {
    name: &'static str,
    token: Arc<FetchToken>,
    cached: Option<Arc<FetchToken>>,
}

impl TokenSource {
    /// A source that calls `token` before each request. `token` returns `None` when it has no
    /// credentials to offer.
    pub fn new<F, Fut>(token: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = CredentialResult<Option<Token>>> + Send + 'static,
    {
        Self::named("closure", token)
    }

    /// A source that always returns `token`.
    pub fn fixed(token: Token) -> Self {
        Self::named("fixed", move || {
            let token = token.clone();
            async move { Ok(Some(token)) }
        })
    }

    /// Answer [`cached_token`](Self::cached_token) with `cached`, which must neither make
    /// network requests nor prompt.
    pub fn with_cached<F, Fut>(mut self, cached: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = CredentialResult<Option<Token>>> + Send + 'static,
    {
        self.cached = Some(fetch_token(cached));
        self
    }

    /// A usable token, or `None` when this source has no credentials to offer.
    pub async fn token(&self) -> CredentialResult<Option<Token>> {
        (self.token)().await
    }

    /// A token this source already holds, without network requests or prompts.
    pub async fn cached_token(&self) -> CredentialResult<Option<Token>> {
        match &self.cached {
            Some(cached) => cached().await,
            None => Ok(None),
        }
    }

    pub(crate) fn named<F, Fut>(name: &'static str, token: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = CredentialResult<Option<Token>>> + Send + 'static,
    {
        Self {
            name,
            token: fetch_token(token),
            cached: None,
        }
    }
}

fn fetch_token<F, Fut>(fetch: F) -> Arc<FetchToken>
where
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = CredentialResult<Option<Token>>> + Send + 'static,
{
    Arc::new(move || fetch().boxed())
}

impl Debug for TokenSource {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter
            .debug_tuple("TokenSource")
            .field(&self.name)
            .finish()
    }
}

impl_token_source!(CredentialChain, cached);

struct SelectedCredentials {
    provider: TokenSource,
    token: Token,
}

/// Ordered credential sources, with one selected identity retained during refresh.
///
/// Sources return `None` when unavailable. Errors stop discovery. Concurrent callers share
/// discovery and refresh, and a selected source is never replaced by another identity.
pub struct CredentialChain {
    providers: Vec<TokenSource>,
    selected: Mutex<Option<SelectedCredentials>>,
}

impl CredentialChain {
    /// Search these providers in order, stopping at the first usable credential.
    pub fn new(providers: Vec<TokenSource>) -> Self {
        Self {
            providers,
            selected: Mutex::new(None),
        }
    }
}

impl Debug for CredentialChain {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter
            .debug_struct("CredentialChain")
            .field("sources", &self.providers.len())
            .finish_non_exhaustive()
    }
}

impl CredentialChain {
    /// The selected source's token, choosing the first source with credentials on first use.
    pub async fn token(&self) -> CredentialResult<Option<Token>> {
        let mut selected = self.selected.lock().await;
        if let Some(credentials) = selected.as_mut() {
            if !credentials.token.needs_refresh()? {
                return Ok(Some(credentials.token.clone()));
            }
            let Some(token) = credentials.provider.token().await? else {
                return Err(CredentialError::invalid(
                    "the selected credential source no longer supplies credentials; refusing to switch identities",
                ));
            };
            if token.is_expired()? {
                return Err(CredentialError::invalid(
                    "the selected credential source returned an expired token",
                ));
            }
            credentials.token = token.clone();
            return Ok(Some(token));
        }
        for provider in &self.providers {
            if let Some(token) = provider.token().await? {
                if token.is_expired()? {
                    return Err(CredentialError::invalid(
                        "the credential source returned an expired token",
                    ));
                }
                *selected = Some(SelectedCredentials {
                    provider: provider.clone(),
                    token: token.clone(),
                });
                return Ok(Some(token));
            }
        }
        Ok(None)
    }

    /// The selected source's unexpired token, without consulting any source.
    pub async fn cached_token(&self) -> CredentialResult<Option<Token>> {
        Ok(self
            .selected
            .lock()
            .await
            .as_ref()
            .filter(|credentials| !credentials.token.is_expired().unwrap_or(true))
            .map(|credentials| credentials.token.clone()))
    }
}

/// Private-key JWT credentials from `SPIRAL_CLIENT_ID` and `SPIRAL_PRIVATE_KEY`.
#[cfg(feature = "private-key-auth")]
fn private_key_credentials(
    client: &ClientWithMiddleware,
    auth_url: &Url,
) -> CredentialResult<Option<TokenSource>> {
    Ok(Some(
        PrivateKeyJwtProvider::new(client.clone(), auth_url)?.into(),
    ))
}

#[cfg(not(feature = "private-key-auth"))]
fn private_key_credentials(
    _client: &ClientWithMiddleware,
    _auth_url: &Url,
) -> CredentialResult<Option<TokenSource>> {
    if env::var_os("SPIRAL_PRIVATE_KEY").is_some() {
        return Err(CredentialError::invalid(
            "SPIRAL_PRIVATE_KEY requires the private-key-auth feature",
        ));
    }
    Ok(None)
}

/// The default credential chain: `SPIRAL_TOKEN`, then a private key (`SPIRAL_CLIENT_ID` with
/// `SPIRAL_PRIVATE_KEY`), then client credentials (`SPIRAL_CLIENT_SECRET`), then the host's
/// workload identity, then `fallback`.
pub fn default_credentials(
    client: impl Into<ClientWithMiddleware>,
    api_url: &Url,
    auth_url: &Url,
    fallback: Option<TokenSource>,
) -> CredentialResult<TokenSource> {
    if env::var_os("SPIRAL_CLIENT_SECRET").is_some() && env::var_os("SPIRAL_CLIENT_ID").is_none() {
        return Err(CredentialError::invalid(
            "SPIRAL_CLIENT_SECRET requires SPIRAL_CLIENT_ID",
        ));
    }
    let client = client.into();
    let mut providers: Vec<TokenSource> = env::var("SPIRAL_TOKEN")
        .ok()
        .filter(|token| !token.is_empty())
        .map(|token| TokenSource::fixed(token.into()))
        .into_iter()
        .collect();
    providers.extend(private_key_credentials(&client, auth_url)?);
    if env::var_os("SPIRAL_CLIENT_SECRET").is_some() {
        providers.push(ClientCredentialsProvider::new(client.clone(), api_url.clone()).into());
    }
    providers.extend(workload_credentials(&client, api_url, auth_url)?);
    if let Some(fallback) = fallback {
        providers.push(fallback);
    }
    Ok(CredentialChain::new(providers).into())
}

#[cfg(not(feature = "workload-auth"))]
fn workload_credentials(
    _client: &ClientWithMiddleware,
    _api_url: &Url,
    _auth_url: &Url,
) -> CredentialResult<Option<TokenSource>> {
    if env::var_os("SPIRAL_WORKLOAD_ID").is_some() {
        return Err(CredentialError::invalid(
            "SPIRAL_WORKLOAD_ID requires the workload-auth feature and the host's platform feature (for example gcp)",
        ));
    }
    Ok(None)
}

#[cfg(feature = "workload-auth")]
fn workload_credentials(
    client: &ClientWithMiddleware,
    _api_url: &Url,
    auth_url: &Url,
) -> CredentialResult<Option<TokenSource>> {
    let workload_id = resolve_workload_id();
    let wid = workload_id.clone().unwrap_or_default();
    let token_url = token_endpoint(auth_url)?;
    let mut providers: Vec<TokenSource> = vec![
        #[cfg(feature = "kubernetes")]
        KubernetesAuthProvider::new(client.clone(), token_url.clone(), wid.clone()).into(),
        #[cfg(feature = "modal")]
        ModalAuthProvider::new(client.clone(), token_url.clone(), wid.clone()).into(),
        #[cfg(feature = "github")]
        GitHubAuthProvider::new(client.clone(), token_url.clone(), wid.clone()).into(),
        #[cfg(feature = "gcp")]
        GcpAuthProvider::new(client.clone(), token_url.clone(), wid.clone())
            .with_resource(_api_url.as_str())
            .into(),
        #[cfg(feature = "aws")]
        AwsAuthProvider::new(client.clone(), token_url.clone(), wid.clone()).into(),
    ];
    let oidc_position = usize::from(cfg!(feature = "kubernetes"));
    providers.insert(
        oidc_position,
        OidcAuthProvider::new(client.clone(), token_url, wid).into(),
    );
    Ok(Some(
        WorkloadAuthn::new(workload_id, vec![CredentialChain::new(providers).into()]).into(),
    ))
}