Skip to main content

origincloud_core/
credentials.rs

1//! Credentials: where the access token each call is sent with comes from.
2//!
3//! In a browser (`wasm32-unknown-unknown`) there are [`AccessToken`] and
4//! the [`Credentials`] trait, for credentials of the page's own. The
5//! providers that read the environment, files, a CI job's token or an
6//! instance's metadata service, and `default_credentials`, which chains
7//! them, are native only: a browser has none of these, and
8//! [`ClientBuilder::build`](crate::ClientBuilder::build) without
9//! credentials fails with [`Error::NoCredentials`] there. `ServiceAccount`
10//! is there only with the feature `service-account-wasm`, for runtimes
11//! that aren't a browser.
12
13use std::fmt;
14#[cfg(not(target_arch = "wasm32"))]
15use std::path::PathBuf;
16use std::sync::Arc;
17#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
18use std::sync::OnceLock;
19#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
20use std::time::{Duration, SystemTime};
21
22#[cfg(not(target_arch = "wasm32"))]
23use chrono::{DateTime, Utc};
24#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
25use serde::Deserialize;
26
27use crate::Error;
28use crate::runtime::MaybeSendFuture;
29#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
30use crate::runtime::{Mutex, now};
31#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
32use crate::transport::read_capped;
33
34/// The identity provider's token endpoint, where service account
35/// credentials and the CLI's session are exchanged for access tokens.
36pub const TOKEN_URL: &str =
37    "https://auth.origincloud.eu/realms/origincloud/protocol/openid-connect/token";
38
39#[cfg(not(target_arch = "wasm32"))]
40const ENV_ACCESS_TOKEN: &str = "ORIGINCLOUD_ACCESS_TOKEN";
41#[cfg(not(target_arch = "wasm32"))]
42const ENV_CLIENT_ID: &str = "ORIGINCLOUD_CLIENT_ID";
43#[cfg(not(target_arch = "wasm32"))]
44const ENV_CLIENT_SECRET: &str = "ORIGINCLOUD_CLIENT_SECRET";
45#[cfg(not(target_arch = "wasm32"))]
46const ENV_METADATA_DISABLED: &str = "ORIGINCLOUD_METADATA_DISABLED";
47#[cfg(not(target_arch = "wasm32"))]
48const ENV_METADATA_ENDPOINT: &str = "ORIGINCLOUD_METADATA_ENDPOINT";
49#[cfg(not(target_arch = "wasm32"))]
50const ENV_OIDC_DISABLED: &str = "ORIGINCLOUD_OIDC_DISABLED";
51#[cfg(not(target_arch = "wasm32"))]
52const ENV_OIDC_TOKEN_FILE: &str = "ORIGINCLOUD_OIDC_TOKEN_FILE";
53#[cfg(not(target_arch = "wasm32"))]
54const ENV_OIDC_TOKEN: &str = "ORIGINCLOUD_OIDC_TOKEN";
55#[cfg(not(target_arch = "wasm32"))]
56const ENV_OIDC_AUDIENCE: &str = "ORIGINCLOUD_OIDC_AUDIENCE";
57#[cfg(not(target_arch = "wasm32"))]
58const ENV_STS_ENDPOINT: &str = "ORIGINCLOUD_STS_ENDPOINT";
59/// What an HCP Terraform workspace with dynamic credentials sets in a run:
60/// the workload identity token in `ENV_TFC_TOKEN`, or, for an audience
61/// variable with a tag (`TFC_WORKLOAD_IDENTITY_AUDIENCE_<TAG>`), in
62/// `ENV_TFC_TOKEN_<TAG>`. `ENV_TFC_TAG` names the tag to read.
63#[cfg(not(target_arch = "wasm32"))]
64const ENV_TFC_TOKEN: &str = "TFC_WORKLOAD_IDENTITY_TOKEN";
65#[cfg(not(target_arch = "wasm32"))]
66const ENV_TFC_TAG: &str = "ORIGINCLOUD_TFC_WORKLOAD_IDENTITY_TAG";
67#[cfg(not(target_arch = "wasm32"))]
68const ENV_GITHUB_REQUEST_URL: &str = "ACTIONS_ID_TOKEN_REQUEST_URL";
69#[cfg(not(target_arch = "wasm32"))]
70const ENV_GITHUB_REQUEST_TOKEN: &str = "ACTIONS_ID_TOKEN_REQUEST_TOKEN";
71
72/// The security token service, where a CI job's OIDC token is exchanged
73/// for an access token.
74pub const STS_ENDPOINT: &str = "https://sts.origincloudapis.eu";
75
76/// The audience a GitHub Actions job's OIDC token is requested for.
77pub const OIDC_AUDIENCE: &str = "https://sts.origincloudapis.eu";
78
79/// How long before its expiry an exchanged access token is replaced.
80#[cfg(not(target_arch = "wasm32"))]
81const FEDERATED_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
82
83/// The waits before an exchange the STS answered with `503` (it can't
84/// check the token right now) is sent again.
85#[cfg(not(target_arch = "wasm32"))]
86const STS_RETRY_DELAYS: [Duration; 2] = [Duration::from_millis(200), Duration::from_millis(400)];
87
88#[cfg(not(target_arch = "wasm32"))]
89const TOKEN_EXCHANGE_GRANT: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
90#[cfg(not(target_arch = "wasm32"))]
91const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";
92
93/// The instance metadata service, which software on an instance reaches
94/// at this link-local address.
95pub const METADATA_ENDPOINT: &str = "http://169.254.169.254";
96
97/// How long a metadata-service session is asked for: the most it grants.
98#[cfg(not(target_arch = "wasm32"))]
99const METADATA_SESSION_TTL: Duration = Duration::from_secs(6 * 60 * 60);
100#[cfg(not(target_arch = "wasm32"))]
101const METADATA_SESSION_TTL_HEADER: &str = "x-origincloud-metadata-token-ttl-seconds";
102#[cfg(not(target_arch = "wasm32"))]
103const METADATA_SESSION_HEADER: &str = "x-origincloud-metadata-token";
104
105/// How long reaching the metadata service may take, and opening a session
106/// in all: off an instance, the chain's last step fails within them.
107#[cfg(not(target_arch = "wasm32"))]
108const METADATA_CONNECT_TIMEOUT: Duration = Duration::from_secs(1);
109#[cfg(not(target_arch = "wasm32"))]
110const METADATA_SESSION_TIMEOUT: Duration = Duration::from_secs(2);
111
112/// How long a credential request may take.
113#[cfg(not(target_arch = "wasm32"))]
114const METADATA_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
115
116/// How long before its expiry the metadata service's credential, which
117/// lives five minutes, is replaced.
118#[cfg(not(target_arch = "wasm32"))]
119const METADATA_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
120
121/// The waits before a request the metadata service answered with `503`
122/// (it can't sign right now) is sent again.
123#[cfg(not(target_arch = "wasm32"))]
124const METADATA_RETRY_DELAYS: [Duration; 2] =
125    [Duration::from_millis(100), Duration::from_millis(200)];
126
127/// The OAuth client the CLI logs in as, which its refresh token belongs to.
128#[cfg(not(target_arch = "wasm32"))]
129const CLI_CLIENT_ID: &str = "origin-cli";
130
131/// How long before its expiry a token is replaced, so that it doesn't
132/// expire on the way.
133#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
134const EXPIRY_MARGIN: Duration = Duration::from_secs(30);
135
136/// The most of a token response that is read.
137#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
138const MAX_TOKEN_RESPONSE_BYTES: usize = 1 << 20;
139
140/// How long a token request may take.
141#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
142const TOKEN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
143
144/// What [`Credentials::token`] returns: `Send` natively; not in a
145/// browser, where a fetch is a JavaScript promise.
146pub type TokenFuture<'a> = MaybeSendFuture<'a, Result<String, Error>>;
147
148/// Credentials supply the access token each call is sent with. `Send +
149/// Sync` on every target, so a client can live in a UI framework's
150/// reactive state (Leptos 0.8 keeps memo values `Send + Sync` even in a
151/// browser); only the future [`token`](Self::token) returns is `!Send` there.
152pub trait Credentials: Send + Sync + fmt::Debug {
153    /// A valid access token.
154    fn token(&self) -> TokenFuture<'_>;
155}
156
157/// The first credentials found, in this order:
158///
159/// 1. `ORIGINCLOUD_ACCESS_TOKEN`: an access token, sent as it is.
160/// 2. `ORIGINCLOUD_CLIENT_ID` and `ORIGINCLOUD_CLIENT_SECRET`: a service
161///    account's credential, exchanged for access tokens as they expire.
162///    Only one of the two set is an error.
163/// 3. A CI job's OIDC token, exchanged at the security token service
164///    ([`Federated`]): from the file `ORIGINCLOUD_OIDC_TOKEN_FILE` names,
165///    or else from `ORIGINCLOUD_OIDC_TOKEN`, which holds the token itself
166///    (as GitLab CI's `id_tokens` set it), or else from an HCP Terraform
167///    run's workload identity token, `TFC_WORKLOAD_IDENTITY_TOKEN`, or
168///    `TFC_WORKLOAD_IDENTITY_TOKEN_<TAG>` when
169///    `ORIGINCLOUD_TFC_WORKLOAD_IDENTITY_TAG` names the tag of a tagged
170///    audience, or else from GitHub Actions, in a job granted `permissions: id-token: write`. Once found, its errors
171///    are returned, not passed over. `ORIGINCLOUD_OIDC_DISABLED=true`
172///    leaves this step out; `ORIGINCLOUD_STS_ENDPOINT` asks another address
173///    than [`STS_ENDPOINT`], and `ORIGINCLOUD_OIDC_AUDIENCE` requests
174///    GitHub's token for another audience than [`OIDC_AUDIENCE`].
175/// 4. The session the `origin` CLI stored at its last login
176///    (`origin id login`).
177/// 5. The instance's metadata service, on an instance that runs as a
178///    service account ([`InstanceMetadata`]). Nothing is requested until a
179///    token is; off an instance, that fails with [`Error::NoCredentials`]
180///    within about two seconds. `ORIGINCLOUD_METADATA_DISABLED=true` leaves
181///    this step out; `ORIGINCLOUD_METADATA_ENDPOINT` asks another address
182///    than [`METADATA_ENDPOINT`].
183///
184/// It fails with [`Error::NoCredentials`] when the metadata service is
185/// left out and there are no others.
186#[cfg(not(target_arch = "wasm32"))]
187pub fn default_credentials() -> Result<Arc<dyn Credentials>, Error> {
188    from_environment(&|name| std::env::var(name).ok())
189}
190
191/// [`default_credentials`] with the environment read through `env`.
192#[cfg(not(target_arch = "wasm32"))]
193pub(crate) fn from_environment(
194    env: &dyn Fn(&str) -> Option<String>,
195) -> Result<Arc<dyn Credentials>, Error> {
196    let var = |name: &str| env(name).filter(|v| !v.is_empty());
197    if let Some(token) = var(ENV_ACCESS_TOKEN) {
198        return Ok(Arc::new(AccessToken::new(token)));
199    }
200    match (var(ENV_CLIENT_ID), var(ENV_CLIENT_SECRET)) {
201        (Some(id), Some(secret)) => return Ok(Arc::new(ServiceAccount::new(id, secret))),
202        (None, None) => {}
203        _ => {
204            return Err(Error::Config(format!(
205                "{ENV_CLIENT_ID} and {ENV_CLIENT_SECRET} must be set together"
206            )));
207        }
208    }
209    if let Some(federated) = federated_from(&var) {
210        return Ok(Arc::new(federated));
211    }
212    if let Some(path) = cli_session_path(env)
213        && let Some(session) = CliSession::load_from(path)?
214    {
215        return Ok(Arc::new(session));
216    }
217    if var(ENV_METADATA_DISABLED).is_some_and(|v| v.eq_ignore_ascii_case("true")) {
218        return Err(Error::NoCredentials);
219    }
220    let metadata = InstanceMetadata::new();
221    Ok(Arc::new(match var(ENV_METADATA_ENDPOINT) {
222        Some(endpoint) => metadata.with_endpoint(endpoint),
223        None => metadata,
224    }))
225}
226
227/// In a browser there is no environment, no file system and no metadata
228/// service, and a secret in a page is anybody's: the page supplies its own
229/// [`Credentials`] (an [`AccessToken`], or one that refreshes its session).
230#[cfg(target_arch = "wasm32")]
231pub(crate) fn from_environment(
232    _env: &dyn Fn(&str) -> Option<String>,
233) -> Result<Arc<dyn Credentials>, Error> {
234    Err(Error::NoCredentials)
235}
236
237/// The federated step of the chain, when the environment holds a CI job's
238/// OIDC token: a token file, which can be rotated in place, before a token
239/// given as it is, before an HCP Terraform run's workload identity token,
240/// before GitHub Actions.
241#[cfg(not(target_arch = "wasm32"))]
242fn federated_from(var: &dyn Fn(&str) -> Option<String>) -> Option<Federated> {
243    if var(ENV_OIDC_DISABLED).is_some_and(|v| v.eq_ignore_ascii_case("true")) {
244        return None;
245    }
246    let mut federated = if let Some(path) = var(ENV_OIDC_TOKEN_FILE) {
247        Federated::from_file(path)
248    } else if let Some(token) = var(ENV_OIDC_TOKEN) {
249        Federated::with_source(JobToken::Given {
250            token,
251            variable: Some(ENV_OIDC_TOKEN.to_owned()),
252        })
253    } else if let Some(variable) = tfc_token_variable(var) {
254        Federated::with_source(JobToken::Given {
255            token: var(&variable).unwrap_or_default(),
256            variable: Some(variable),
257        })
258    } else if let (Some(url), Some(token)) =
259        (var(ENV_GITHUB_REQUEST_URL), var(ENV_GITHUB_REQUEST_TOKEN))
260    {
261        Federated::github_actions(url, token)
262    } else {
263        return None;
264    };
265    if let Some(endpoint) = var(ENV_STS_ENDPOINT) {
266        federated = federated.with_endpoint(endpoint);
267    }
268    if let Some(audience) = var(ENV_OIDC_AUDIENCE) {
269        federated = federated.with_audience(audience);
270    }
271    Some(federated)
272}
273
274/// The variable an HCP Terraform run's workload identity token is read
275/// from: the tagged one when `ORIGINCLOUD_TFC_WORKLOAD_IDENTITY_TAG` names a
276/// tag, even if that variable is unset, so that the error names it; the
277/// untagged one otherwise, when it is set. `None` when the run has none.
278#[cfg(not(target_arch = "wasm32"))]
279fn tfc_token_variable(var: &dyn Fn(&str) -> Option<String>) -> Option<String> {
280    match var(ENV_TFC_TAG).map(|tag| tag.trim().to_owned()) {
281        Some(tag) if !tag.is_empty() => Some(format!("{ENV_TFC_TOKEN}_{tag}")),
282        _ => var(ENV_TFC_TOKEN).map(|_| ENV_TFC_TOKEN.to_owned()),
283    }
284}
285
286/// An access token, sent as it is. It is not renewed: a service account's
287/// lives five minutes.
288#[derive(Clone)]
289pub struct AccessToken(String);
290
291impl AccessToken {
292    /// Credentials that always send `token`.
293    pub fn new(token: impl Into<String>) -> Self {
294        Self(token.into())
295    }
296}
297
298impl fmt::Debug for AccessToken {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        f.write_str("AccessToken(..)")
301    }
302}
303
304impl Credentials for AccessToken {
305    fn token(&self) -> TokenFuture<'_> {
306        Box::pin(async move { Ok(self.0.clone()) })
307    }
308}
309
310/// A service account's client ID and secret, exchanged for access tokens
311/// with the client credentials grant as they expire.
312///
313/// On `wasm32-unknown-unknown` it exists only with the feature
314/// `service-account-wasm`, for runtimes that aren't a browser: a web
315/// page, and a Web Worker too, is shipped to whoever loads it, secret and
316/// all.
317#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
318pub struct ServiceAccount {
319    client_id: String,
320    client_secret: String,
321    token_url: String,
322    http: Option<reqwest::Client>,
323    cache: Mutex<Cached>,
324}
325
326#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
327impl ServiceAccount {
328    /// The service account `client_id` with the secret `client_secret`.
329    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
330        Self {
331            client_id: client_id.into(),
332            client_secret: client_secret.into(),
333            token_url: TOKEN_URL.to_owned(),
334            http: None,
335            cache: Mutex::default(),
336        }
337    }
338
339    /// Requests tokens at `url` instead of [`TOKEN_URL`].
340    pub fn with_token_url(mut self, url: impl Into<String>) -> Self {
341        self.token_url = url.into();
342        self
343    }
344
345    /// Sends the token requests with `http`, instead of the client all
346    /// credentials share. Each request is bounded by 30 seconds either way.
347    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
348        self.http = Some(http);
349        self
350    }
351}
352
353#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
354impl fmt::Debug for ServiceAccount {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        f.debug_struct("ServiceAccount")
357            .field("client_id", &self.client_id)
358            .field("token_url", &self.token_url)
359            .finish_non_exhaustive()
360    }
361}
362
363#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
364impl Credentials for ServiceAccount {
365    fn token(&self) -> TokenFuture<'_> {
366        Box::pin(async move {
367            let mut cache = self.cache.lock().await;
368            if let Some(token) = cache.valid() {
369                return Ok(token);
370            }
371            let granted = request_token(
372                self.http.as_ref(),
373                &self.token_url,
374                &[
375                    ("grant_type", "client_credentials"),
376                    ("client_id", &self.client_id),
377                    ("client_secret", &self.client_secret),
378                ],
379            )
380            .await?;
381            cache.token = granted.access_token.clone();
382            cache.expiry = Some(granted.expiry());
383            Ok(granted.access_token)
384        })
385    }
386}
387
388/// The session the `origin` CLI stored at its last login, renewed from its
389/// refresh token when its access token has expired. The renewed session
390/// stays in memory: the CLI's file is never written.
391#[cfg(not(target_arch = "wasm32"))]
392pub struct CliSession {
393    token_url: String,
394    http: Option<reqwest::Client>,
395    state: Mutex<SessionState>,
396}
397
398#[cfg(not(target_arch = "wasm32"))]
399struct SessionState {
400    cached: Cached,
401    refresh_token: String,
402    refresh_expiry: Option<SystemTime>,
403}
404
405/// The file the CLI stores its session in.
406#[cfg(not(target_arch = "wasm32"))]
407#[derive(Deserialize)]
408struct StoredSession {
409    #[serde(default)]
410    access_token: String,
411    #[serde(default)]
412    expires: Option<DateTime<Utc>>,
413    #[serde(default)]
414    refresh_token: String,
415    #[serde(default)]
416    refresh_expires: Option<DateTime<Utc>>,
417}
418
419#[cfg(not(target_arch = "wasm32"))]
420impl CliSession {
421    /// The session the CLI stored, or `None` when it stored none: under
422    /// `$XDG_DATA_HOME`, or `~/.local/share`, on every platform, at
423    /// `origincloud/session.json`.
424    pub fn load() -> Result<Option<Self>, Error> {
425        match cli_session_path(&|name| std::env::var(name).ok()) {
426            Some(path) => Self::load_from(path),
427            None => Ok(None),
428        }
429    }
430
431    /// The session stored at `path`, or `None` when there is no file.
432    pub fn load_from(path: impl Into<PathBuf>) -> Result<Option<Self>, Error> {
433        let path = path.into();
434        let data = match std::fs::read(&path) {
435            Ok(data) => data,
436            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
437            Err(e) => return Err(Error::Credentials(format!("reading the CLI session: {e}"))),
438        };
439        let stored: StoredSession = serde_json::from_slice(&data).map_err(|e| {
440            Error::Credentials(format!("reading the CLI session {}: {e}", path.display()))
441        })?;
442        Ok(Some(Self {
443            token_url: TOKEN_URL.to_owned(),
444            http: None,
445            state: Mutex::new(SessionState {
446                cached: Cached {
447                    token: stored.access_token,
448                    expiry: stored.expires.map(SystemTime::from),
449                },
450                refresh_token: stored.refresh_token,
451                refresh_expiry: stored.refresh_expires.map(SystemTime::from),
452            }),
453        }))
454    }
455
456    /// Renews the session at `url` instead of [`TOKEN_URL`].
457    pub fn with_token_url(mut self, url: impl Into<String>) -> Self {
458        self.token_url = url.into();
459        self
460    }
461
462    /// Sends the renewals with `http`, instead of the client all
463    /// credentials share. Each renewal is bounded by 30 seconds either way.
464    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
465        self.http = Some(http);
466        self
467    }
468}
469
470#[cfg(not(target_arch = "wasm32"))]
471impl fmt::Debug for CliSession {
472    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
473        f.debug_struct("CliSession")
474            .field("token_url", &self.token_url)
475            .finish_non_exhaustive()
476    }
477}
478
479#[cfg(not(target_arch = "wasm32"))]
480impl Credentials for CliSession {
481    fn token(&self) -> TokenFuture<'_> {
482        Box::pin(async move {
483            let mut state = self.state.lock().await;
484            if let Some(token) = state.cached.valid() {
485                return Ok(token);
486            }
487            if state
488                .refresh_expiry
489                .is_none_or(|expiry| SystemTime::now() >= expiry)
490            {
491                return Err(Error::Credentials(
492                    "the CLI session has expired: log in again with `origin id login`".to_owned(),
493                ));
494            }
495            let refresh_token = state.refresh_token.clone();
496            let granted = request_token(
497                self.http.as_ref(),
498                &self.token_url,
499                &[
500                    ("grant_type", "refresh_token"),
501                    ("client_id", CLI_CLIENT_ID),
502                    ("refresh_token", &refresh_token),
503                ],
504            )
505            .await
506            .map_err(|e| match e {
507                Error::Credentials(message) => {
508                    Error::Credentials(format!("renewing the CLI session: {message}"))
509                }
510                other => other,
511            })?;
512            if !granted.refresh_token.is_empty() {
513                state.refresh_token = granted.refresh_token.clone();
514                state.refresh_expiry =
515                    Some(SystemTime::now() + seconds(granted.refresh_expires_in));
516            }
517            state.cached = Cached {
518                token: granted.access_token.clone(),
519                expiry: Some(granted.expiry()),
520            };
521            Ok(granted.access_token)
522        })
523    }
524}
525
526/// The credential of the service account the instance runs as, from the
527/// instance's metadata service: a session is opened for six hours, and each
528/// access token, which lives five minutes, requested with it a minute
529/// before the last one expires. The requests never go through a proxy,
530/// which the metadata service refuses, and one it can't answer right now
531/// (`503`) is sent again twice.
532#[cfg(not(target_arch = "wasm32"))]
533pub struct InstanceMetadata {
534    endpoint: String,
535    http: Option<reqwest::Client>,
536    state: Mutex<MetadataState>,
537}
538
539#[cfg(not(target_arch = "wasm32"))]
540#[derive(Default)]
541struct MetadataState {
542    session: Cached,
543    cached: Cached,
544}
545
546/// The metadata service's credential.
547#[cfg(not(target_arch = "wasm32"))]
548#[derive(Deserialize)]
549struct Issued {
550    access_token: String,
551    expires_at: DateTime<Utc>,
552}
553
554#[cfg(not(target_arch = "wasm32"))]
555impl InstanceMetadata {
556    /// The metadata service at [`METADATA_ENDPOINT`].
557    pub fn new() -> Self {
558        Self {
559            endpoint: METADATA_ENDPOINT.to_owned(),
560            http: None,
561            state: Mutex::default(),
562        }
563    }
564
565    /// Asks the metadata service at `url` instead of [`METADATA_ENDPOINT`].
566    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
567        self.endpoint = url.into().trim_end_matches('/').to_owned();
568        self
569    }
570
571    /// Sends the requests with `http`, as it is configured, instead of a
572    /// client without a proxy that gives up connecting after a second.
573    /// Opening a session is bounded by two seconds either way, and
574    /// requesting a credential by five.
575    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
576        self.http = Some(http);
577        self
578    }
579
580    fn http(&self) -> Result<&reqwest::Client, Error> {
581        static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
582        if let Some(http) = &self.http {
583            return Ok(http);
584        }
585        CLIENT
586            .get_or_init(|| {
587                reqwest::Client::builder()
588                    .no_proxy()
589                    .connect_timeout(METADATA_CONNECT_TIMEOUT)
590                    .build()
591                    .map_err(|e| e.to_string())
592            })
593            .as_ref()
594            .map_err(|e| Error::Credentials(format!("reaching the metadata service: {e}")))
595    }
596
597    /// A new session. Off an instance, there is no metadata service to
598    /// answer, or another one: another cloud's, at the same address, which
599    /// refuses the request as one it doesn't know. Either way, no
600    /// credentials.
601    async fn open_session(&self) -> Result<String, Error> {
602        let request = self
603            .http()?
604            .put(format!("{}/latest/api/token", self.endpoint))
605            .timeout(METADATA_SESSION_TIMEOUT)
606            .header(
607                METADATA_SESSION_TTL_HEADER,
608                METADATA_SESSION_TTL.as_secs().to_string(),
609            );
610        let (status, body) = send_retrying(request, &METADATA_RETRY_DELAYS)
611            .await
612            .map_err(|_| Error::NoCredentials)?;
613        match status.as_u16() {
614            200 => Ok(String::from_utf8_lossy(&body).trim().to_owned()),
615            403 => Err(refused_through_a_proxy()),
616            503 => Err(Error::Credentials(
617                "the metadata service refused a session (HTTP 503)".to_owned(),
618            )),
619            _ => Err(Error::NoCredentials),
620        }
621    }
622
623    /// The credential, or `None` when the session is no longer valid.
624    async fn request_credential(&self, session: &str) -> Result<Option<Issued>, Error> {
625        let failed =
626            |e: reqwest::Error| Error::Credentials(format!("reaching the metadata service: {e}"));
627        let request = self
628            .http()?
629            .get(format!(
630                "{}/latest/meta-data/service-account/token",
631                self.endpoint
632            ))
633            .timeout(METADATA_REQUEST_TIMEOUT)
634            .header(METADATA_SESSION_HEADER, session)
635            .header(reqwest::header::ACCEPT, "application/json");
636        let (status, body) = send_retrying(request, &METADATA_RETRY_DELAYS)
637            .await
638            .map_err(failed)?;
639        match status.as_u16() {
640            200 => {}
641            401 => return Ok(None),
642            404 => {
643                return Err(Error::Credentials(
644                    "the instance runs as no service account".to_owned(),
645                ));
646            }
647            403 => return Err(refused_through_a_proxy()),
648            status => {
649                return Err(Error::Credentials(format!(
650                    "the metadata service answered HTTP {status}"
651                )));
652            }
653        }
654        match serde_json::from_slice::<Issued>(&body) {
655            Ok(issued) if !issued.access_token.is_empty() => Ok(Some(issued)),
656            _ => Err(Error::Credentials(
657                "the metadata service's answer is not a credential".to_owned(),
658            )),
659        }
660    }
661}
662
663/// Sends `request`, and again after each of `delays` while it is answered
664/// with `503`.
665#[cfg(not(target_arch = "wasm32"))]
666async fn send_retrying(
667    request: reqwest::RequestBuilder,
668    delays: &[Duration],
669) -> Result<(reqwest::StatusCode, Vec<u8>), reqwest::Error> {
670    let mut delays = delays.iter();
671    loop {
672        let attempt = request
673            .try_clone()
674            .expect("a credential request has no streamed body");
675        let answer = read_bounded(attempt.send().await?).await?;
676        match delays.next() {
677            Some(delay) if answer.0 == reqwest::StatusCode::SERVICE_UNAVAILABLE => {
678                tokio::time::sleep(*delay).await;
679            }
680            _ => return Ok(answer),
681        }
682    }
683}
684
685#[cfg(not(target_arch = "wasm32"))]
686fn refused_through_a_proxy() -> Error {
687    Error::Credentials(
688        "the metadata service refused a request that came through a proxy".to_owned(),
689    )
690}
691
692#[cfg(not(target_arch = "wasm32"))]
693impl Default for InstanceMetadata {
694    fn default() -> Self {
695        Self::new()
696    }
697}
698
699#[cfg(not(target_arch = "wasm32"))]
700impl fmt::Debug for InstanceMetadata {
701    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702        f.debug_struct("InstanceMetadata")
703            .field("endpoint", &self.endpoint)
704            .finish_non_exhaustive()
705    }
706}
707
708#[cfg(not(target_arch = "wasm32"))]
709impl Credentials for InstanceMetadata {
710    fn token(&self) -> TokenFuture<'_> {
711        Box::pin(async move {
712            let mut state = self.state.lock().await;
713            if let Some(token) = state.cached.valid_for(METADATA_EXPIRY_MARGIN) {
714                return Ok(token);
715            }
716            // A session refused as no longer valid is opened again, once.
717            for _ in 0..2 {
718                let session = match state.session.valid() {
719                    Some(session) => session,
720                    None => {
721                        let session = self.open_session().await?;
722                        state.session = Cached {
723                            token: session.clone(),
724                            expiry: Some(SystemTime::now() + METADATA_SESSION_TTL),
725                        };
726                        session
727                    }
728                };
729                match self.request_credential(&session).await? {
730                    Some(issued) => {
731                        state.cached = Cached {
732                            token: issued.access_token.clone(),
733                            expiry: Some(issued.expires_at.into()),
734                        };
735                        return Ok(issued.access_token);
736                    }
737                    None => state.session = Cached::default(),
738                }
739            }
740            Err(Error::Credentials(
741                "the metadata service answered HTTP 401".to_owned(),
742            ))
743        })
744    }
745}
746
747/// A CI job's OIDC token, exchanged at the security token service for the
748/// access token of the `WORKLOAD` service account a federated credential
749/// trusts the job as. The access token is reused until a minute before it
750/// expires; then a fresh job token is fetched and exchanged again, or a
751/// token given as it is ([`Federated::from_token`]) exchanged again. An
752/// exchange the STS can't check right now (`503`) is sent again twice.
753#[cfg(not(target_arch = "wasm32"))]
754pub struct Federated {
755    source: JobToken,
756    endpoint: String,
757    audience: String,
758    http: Option<reqwest::Client>,
759    cache: Mutex<Cached>,
760}
761
762/// Where the job's token comes from.
763#[cfg(not(target_arch = "wasm32"))]
764enum JobToken {
765    File(PathBuf),
766    /// A token given as it is, from the environment variable `variable`
767    /// names, if any.
768    Given {
769        token: String,
770        variable: Option<String>,
771    },
772    GitHubActions {
773        request_url: String,
774        request_token: String,
775    },
776}
777
778/// The claims of a job token that are read before it is exchanged.
779#[cfg(not(target_arch = "wasm32"))]
780#[derive(Deserialize)]
781struct JobTokenClaims {
782    exp: Option<f64>,
783}
784
785/// GitHub's answer to a job token request.
786#[cfg(not(target_arch = "wasm32"))]
787#[derive(Deserialize)]
788struct GitHubToken {
789    value: String,
790}
791
792#[cfg(not(target_arch = "wasm32"))]
793impl Federated {
794    /// The token in the file at `path`, read again at every exchange, so
795    /// that a rotated token is picked up: any CI provider's, or a
796    /// Kubernetes projected service account token.
797    pub fn from_file(path: impl Into<PathBuf>) -> Self {
798        Self::with_source(JobToken::File(path.into()))
799    }
800
801    /// The token `token`, exchanged as it is: any CI provider's, such as the
802    /// one GitLab CI sets in the variable its `id_tokens` names. It can't
803    /// be renewed: each renewal of the access token exchanges it again,
804    /// until it expires itself, and from then on fails without asking the
805    /// STS.
806    pub fn from_token(token: impl Into<String>) -> Self {
807        Self::with_source(JobToken::Given {
808            token: token.into(),
809            variable: None,
810        })
811    }
812
813    /// A GitHub Actions job's token, requested at `request_url` with
814    /// `request_token`: the values of `ACTIONS_ID_TOKEN_REQUEST_URL` and
815    /// `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, which GitHub sets in a job
816    /// granted `permissions: id-token: write`.
817    pub fn github_actions(
818        request_url: impl Into<String>,
819        request_token: impl Into<String>,
820    ) -> Self {
821        Self::with_source(JobToken::GitHubActions {
822            request_url: request_url.into(),
823            request_token: request_token.into(),
824        })
825    }
826
827    fn with_source(source: JobToken) -> Self {
828        Self {
829            source,
830            endpoint: STS_ENDPOINT.to_owned(),
831            audience: OIDC_AUDIENCE.to_owned(),
832            http: None,
833            cache: Mutex::default(),
834        }
835    }
836
837    /// Exchanges the token at the STS at `url` instead of [`STS_ENDPOINT`].
838    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
839        self.endpoint = url.into().trim_end_matches('/').to_owned();
840        self
841    }
842
843    /// Requests GitHub's token for `audience` instead of [`OIDC_AUDIENCE`].
844    /// A token file's or a given token's audience is whatever its issuer
845    /// put in it.
846    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
847        self.audience = audience.into();
848        self
849    }
850
851    /// Sends the requests with `http`, instead of the client all
852    /// credentials share. Each request is bounded by 30 seconds either way.
853    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
854        self.http = Some(http);
855        self
856    }
857
858    fn http(&self) -> Result<&reqwest::Client, Error> {
859        match &self.http {
860            Some(http) => Ok(http),
861            None => default_http_client()
862                .map_err(|e| Error::Credentials(format!("exchanging the CI job's token: {e}"))),
863        }
864    }
865
866    /// A fresh job token.
867    async fn job_token(&self, http: &reqwest::Client) -> Result<String, Error> {
868        match &self.source {
869            JobToken::File(path) => {
870                let read = std::fs::read_to_string(path).map_err(|e| {
871                    Error::Credentials(format!(
872                        "reading the OIDC token file {}: {e}",
873                        path.display()
874                    ))
875                })?;
876                let token = read.trim();
877                if token.is_empty() {
878                    return Err(Error::Credentials(format!(
879                        "the OIDC token file {} is empty",
880                        path.display()
881                    )));
882                }
883                Ok(token.to_owned())
884            }
885            JobToken::Given { token, variable } => {
886                let token = token.trim();
887                if token.is_empty() {
888                    return Err(Error::Credentials(format!(
889                        "the CI job's OIDC token{} is empty{}",
890                        in_variable(variable.as_deref()),
891                        if variable.is_some() {
892                            " or not set"
893                        } else {
894                            ""
895                        }
896                    )));
897                }
898                if let Some(expiry) = job_token_expiry(token)
899                    && expiry <= SystemTime::now()
900                {
901                    let expiry = DateTime::<Utc>::from(expiry)
902                        .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
903                    return Err(Error::Credentials(format!(
904                        "the CI job's OIDC token{} expired at {expiry}; a token given as it is \
905                         can't be renewed: ask the CI provider for a longer-lived one, or use \
906                         {ENV_OIDC_TOKEN_FILE}",
907                        in_variable(variable.as_deref())
908                    )));
909                }
910                Ok(token.to_owned())
911            }
912            JobToken::GitHubActions {
913                request_url,
914                request_token,
915            } => {
916                let failed = |reason: &dyn fmt::Display| {
917                    Error::Credentials(format!(
918                        "requesting the GitHub Actions job's OIDC token: {reason}; \
919                         the workflow needs `permissions: id-token: write`"
920                    ))
921                };
922                let separator = if request_url.contains('?') { '&' } else { '?' };
923                let audience: String =
924                    url::form_urlencoded::byte_serialize(self.audience.as_bytes()).collect();
925                let response = http
926                    .get(format!("{request_url}{separator}audience={audience}"))
927                    .timeout(TOKEN_REQUEST_TIMEOUT)
928                    .header(
929                        reqwest::header::AUTHORIZATION,
930                        format!("bearer {request_token}"),
931                    )
932                    .header(reqwest::header::ACCEPT, "application/json")
933                    .send()
934                    .await
935                    .map_err(|e| failed(&e))?;
936                let (status, body) = read_bounded(response).await.map_err(|e| failed(&e))?;
937                if status != reqwest::StatusCode::OK {
938                    return Err(failed(&format_args!("HTTP {}", status.as_u16())));
939                }
940                match serde_json::from_slice::<GitHubToken>(&body) {
941                    Ok(token) if !token.value.is_empty() => Ok(token.value),
942                    _ => Err(Error::Credentials(
943                        "requesting the GitHub Actions job's OIDC token: the answer holds no token"
944                            .to_owned(),
945                    )),
946                }
947            }
948        }
949    }
950
951    /// The job's token exchanged for an access token.
952    async fn exchange(&self, http: &reqwest::Client, job_token: &str) -> Result<Granted, Error> {
953        let request = http
954            .post(format!("{}/v1/token", self.endpoint))
955            .timeout(TOKEN_REQUEST_TIMEOUT)
956            .header(reqwest::header::ACCEPT, "application/json")
957            .form(&[
958                ("grant_type", TOKEN_EXCHANGE_GRANT),
959                ("subject_token", job_token),
960                ("subject_token_type", JWT_TOKEN_TYPE),
961            ]);
962        let (status, body) = send_retrying(request, &STS_RETRY_DELAYS)
963            .await
964            .map_err(|e| Error::Credentials(format!("exchanging the CI job's token: {e}")))?;
965        let parsed = serde_json::from_slice::<Granted>(&body);
966        let granted = parsed.as_ref().ok();
967        let error = granted.map_or("", |g| g.error.as_str());
968        match status.as_u16() {
969            200 => match parsed {
970                Ok(granted) if !granted.access_token.is_empty() => Ok(granted),
971                _ => Err(Error::Credentials(
972                    "exchanging the CI job's token: the STS's answer is not a token response"
973                        .to_owned(),
974                )),
975            },
976            503 => Err(Error::Credentials(
977                "exchanging the CI job's token: the STS can't check it right now \
978                 (HTTP 503, 3 attempts); try again later"
979                    .to_owned(),
980            )),
981            _ if error == "invalid_grant" => Err(Error::Credentials(
982                "the STS refused the CI job's token (invalid_grant): check the federated \
983                 credential's issuer, audience and conditions against the token's claims"
984                    .to_owned(),
985            )),
986            status => {
987                let reason = match granted {
988                    Some(g) if !g.error_description.is_empty() => &g.error_description,
989                    Some(g) if !g.error.is_empty() => &g.error,
990                    _ => "not a token response",
991                };
992                Err(Error::Credentials(format!(
993                    "exchanging the CI job's token: the STS answered HTTP {status}: {reason}"
994                )))
995            }
996        }
997    }
998}
999
1000#[cfg(not(target_arch = "wasm32"))]
1001impl fmt::Debug for Federated {
1002    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1003        let mut debug = f.debug_struct("Federated");
1004        match &self.source {
1005            JobToken::File(path) => debug.field("token_file", path),
1006            JobToken::Given { .. } => debug.field("source", &"token"),
1007            JobToken::GitHubActions { .. } => debug.field("source", &"GitHub Actions"),
1008        };
1009        debug
1010            .field("endpoint", &self.endpoint)
1011            .field("audience", &self.audience)
1012            .finish_non_exhaustive()
1013    }
1014}
1015
1016#[cfg(not(target_arch = "wasm32"))]
1017impl Credentials for Federated {
1018    fn token(&self) -> TokenFuture<'_> {
1019        Box::pin(async move {
1020            let mut cache = self.cache.lock().await;
1021            if let Some(token) = cache.valid_for(FEDERATED_EXPIRY_MARGIN) {
1022                return Ok(token);
1023            }
1024            let http = self.http()?;
1025            let job_token = self.job_token(http).await?;
1026            let granted = self.exchange(http, &job_token).await?;
1027            *cache = Cached {
1028                token: granted.access_token.clone(),
1029                expiry: Some(granted.expiry()),
1030            };
1031            Ok(granted.access_token)
1032        })
1033    }
1034}
1035
1036/// ` in VARIABLE`, naming where a given job token came from, if anywhere.
1037#[cfg(not(target_arch = "wasm32"))]
1038fn in_variable(variable: Option<&str>) -> String {
1039    variable.map_or_else(String::new, |name| format!(" in {name}"))
1040}
1041
1042/// When a job token (a JWT) expires, as its unverified `exp` claim says:
1043/// `None` when it has none, or isn't a JWT whose claims can be read, which
1044/// is left to the STS to judge.
1045#[cfg(not(target_arch = "wasm32"))]
1046fn job_token_expiry(token: &str) -> Option<SystemTime> {
1047    use base64::Engine as _;
1048    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
1049
1050    const BASE64URL: GeneralPurpose = GeneralPurpose::new(
1051        &base64::alphabet::URL_SAFE,
1052        GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
1053    );
1054    let payload = token.split('.').nth(1)?;
1055    let claims: JobTokenClaims = serde_json::from_slice(&BASE64URL.decode(payload).ok()?).ok()?;
1056    let exp = claims.exp?;
1057    if !exp.is_finite() || exp < 0.0 {
1058        return None;
1059    }
1060    SystemTime::UNIX_EPOCH.checked_add(Duration::try_from_secs_f64(exp).ok()?)
1061}
1062
1063/// Where the CLI stores its session: under `XDG_DATA_HOME`, or
1064/// `~/.local/share`, on every platform.
1065#[cfg(not(target_arch = "wasm32"))]
1066fn cli_session_path(env: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
1067    let base = match env("XDG_DATA_HOME").filter(|v| !v.is_empty()) {
1068        Some(base) => PathBuf::from(base),
1069        None => home_dir(env)?.join(".local").join("share"),
1070    };
1071    Some(base.join("origincloud").join("session.json"))
1072}
1073
1074#[cfg(not(target_arch = "wasm32"))]
1075fn home_dir(env: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
1076    let name = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
1077    env(name).filter(|v| !v.is_empty()).map(PathBuf::from)
1078}
1079
1080/// One access token, replaced once it is about to expire.
1081#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1082#[derive(Default)]
1083struct Cached {
1084    token: String,
1085    expiry: Option<SystemTime>,
1086}
1087
1088#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1089impl Cached {
1090    fn valid(&self) -> Option<String> {
1091        self.valid_for(EXPIRY_MARGIN)
1092    }
1093
1094    /// The token, unless it expires within `margin`.
1095    fn valid_for(&self, margin: Duration) -> Option<String> {
1096        let expiry = self.expiry?;
1097        (!self.token.is_empty() && now() + margin < expiry).then(|| self.token.clone())
1098    }
1099}
1100
1101/// A token endpoint's answer.
1102#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1103#[derive(Deserialize, Default)]
1104#[serde(default)]
1105struct Granted {
1106    access_token: String,
1107    expires_in: i64,
1108    refresh_token: String,
1109    refresh_expires_in: i64,
1110    error: String,
1111    error_description: String,
1112}
1113
1114#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1115impl Granted {
1116    fn expiry(&self) -> SystemTime {
1117        now() + seconds(self.expires_in)
1118    }
1119}
1120
1121#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1122fn seconds(n: i64) -> Duration {
1123    Duration::from_secs(u64::try_from(n).unwrap_or_default())
1124}
1125
1126/// The HTTP client token requests are sent with unless the credentials
1127/// name one: one for the process, created by the first request.
1128#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1129fn default_http_client() -> Result<&'static reqwest::Client, &'static str> {
1130    static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
1131    CLIENT
1132        .get_or_init(|| {
1133            reqwest::Client::builder()
1134                .build()
1135                .map_err(|e| e.to_string())
1136        })
1137        .as_ref()
1138        .map_err(String::as_str)
1139}
1140
1141#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1142async fn request_token(
1143    http: Option<&reqwest::Client>,
1144    url: &str,
1145    form: &[(&str, &str)],
1146) -> Result<Granted, Error> {
1147    let failed = |e: &dyn fmt::Display| Error::Credentials(format!("requesting a token: {e}"));
1148    let http = match http {
1149        Some(http) => http,
1150        None => default_http_client().map_err(|e| failed(&e))?,
1151    };
1152    let response = http
1153        .post(url)
1154        .timeout(TOKEN_REQUEST_TIMEOUT)
1155        .header(reqwest::header::ACCEPT, "application/json")
1156        .form(form)
1157        .send()
1158        .await
1159        .map_err(|e| failed(&e))?;
1160    let (status, body) = read_bounded(response).await.map_err(|e| failed(&e))?;
1161    let granted: Granted = serde_json::from_slice(&body).map_err(|_| {
1162        Error::Credentials(format!(
1163            "requesting a token: HTTP {}, not a token response",
1164            status.as_u16()
1165        ))
1166    })?;
1167    if status != reqwest::StatusCode::OK || granted.access_token.is_empty() {
1168        let reason = if granted.error_description.is_empty() {
1169            &granted.error
1170        } else {
1171            &granted.error_description
1172        };
1173        return Err(Error::Credentials(format!(
1174            "the token request was refused (HTTP {}): {reason}",
1175            status.as_u16()
1176        )));
1177    }
1178    Ok(granted)
1179}
1180
1181/// A response's status and its body, up to the most of a token response
1182/// that is read.
1183#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1184async fn read_bounded(
1185    response: reqwest::Response,
1186) -> Result<(reqwest::StatusCode, Vec<u8>), reqwest::Error> {
1187    let status = response.status();
1188    let (body, _truncated) = read_capped(response, MAX_TOKEN_RESPONSE_BYTES).await?;
1189    Ok((status, body))
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194    use super::*;
1195    use std::collections::HashMap;
1196
1197    fn env(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
1198        let vars: HashMap<String, String> = vars
1199            .iter()
1200            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1201            .collect();
1202        move |name| vars.get(name).cloned()
1203    }
1204
1205    fn now() -> DateTime<Utc> {
1206        SystemTime::now().into()
1207    }
1208
1209    fn data_home() -> PathBuf {
1210        let dir =
1211            std::env::temp_dir().join(format!("origincloud-sdk-test-{}", uuid::Uuid::new_v4()));
1212        std::fs::create_dir_all(dir.join("origincloud")).unwrap();
1213        dir
1214    }
1215
1216    fn write_session(
1217        dir: &std::path::Path,
1218        expires: DateTime<Utc>,
1219        refresh_expires: DateTime<Utc>,
1220    ) -> PathBuf {
1221        let path = dir.join("origincloud").join("session.json");
1222        let data = serde_json::json!({
1223            "version": 1,
1224            "access_token": "stored-access",
1225            "expires": expires.to_rfc3339(),
1226            "refresh_token": "stored-refresh",
1227            "refresh_expires": refresh_expires.to_rfc3339(),
1228            "token_type": "Bearer",
1229        });
1230        std::fs::write(&path, data.to_string()).unwrap();
1231        path
1232    }
1233
1234    #[tokio::test]
1235    async fn an_access_token_in_the_environment_comes_first() {
1236        let credentials = from_environment(&env(&[
1237            (ENV_ACCESS_TOKEN, "from-env"),
1238            (ENV_CLIENT_ID, "id"),
1239            (ENV_CLIENT_SECRET, "secret"),
1240        ]))
1241        .unwrap();
1242        assert_eq!(credentials.token().await.unwrap(), "from-env");
1243    }
1244
1245    #[test]
1246    fn a_service_account_in_the_environment_comes_before_the_cli_session() {
1247        let dir = data_home();
1248        let hour = chrono::Duration::hours(1);
1249        write_session(&dir, now() + hour, now() + hour);
1250        let credentials = from_environment(&env(&[
1251            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1252            (ENV_CLIENT_ID, "id"),
1253            (ENV_CLIENT_SECRET, "secret"),
1254        ]))
1255        .unwrap();
1256        assert!(
1257            format!("{credentials:?}").starts_with("ServiceAccount"),
1258            "{credentials:?}"
1259        );
1260    }
1261
1262    const GITHUB: [(&str, &str); 2] = [
1263        (
1264            ENV_GITHUB_REQUEST_URL,
1265            "https://github.invalid/idtoken?api-version=2.0",
1266        ),
1267        (ENV_GITHUB_REQUEST_TOKEN, "github-request-token"),
1268    ];
1269
1270    fn with<'a>(
1271        base: &[(&'a str, &'a str)],
1272        more: &[(&'a str, &'a str)],
1273    ) -> Vec<(&'a str, &'a str)> {
1274        base.iter().chain(more).copied().collect()
1275    }
1276
1277    #[test]
1278    fn a_service_account_comes_before_a_ci_job_s_token() {
1279        let credentials = from_environment(&env(&with(
1280            &GITHUB,
1281            &[(ENV_CLIENT_ID, "id"), (ENV_CLIENT_SECRET, "secret")],
1282        )))
1283        .unwrap();
1284        assert!(
1285            format!("{credentials:?}").starts_with("ServiceAccount"),
1286            "{credentials:?}"
1287        );
1288    }
1289
1290    #[test]
1291    fn a_ci_job_s_token_comes_before_the_cli_session() {
1292        let dir = data_home();
1293        let hour = chrono::Duration::hours(1);
1294        write_session(&dir, now() + hour, now() + hour);
1295        let credentials = from_environment(&env(&with(
1296            &GITHUB,
1297            &[("XDG_DATA_HOME", dir.to_str().unwrap())],
1298        )))
1299        .unwrap();
1300        let debug = format!("{credentials:?}");
1301        assert!(debug.starts_with("Federated"), "{debug}");
1302        assert!(debug.contains("GitHub Actions"), "{debug}");
1303        assert!(debug.contains(&format!("{STS_ENDPOINT:?}")), "{debug}");
1304        assert!(!debug.contains("github-request-token"), "{debug}");
1305        assert!(!debug.contains("github.invalid"), "{debug}");
1306    }
1307
1308    #[test]
1309    fn a_token_file_comes_before_github_actions() {
1310        let credentials = from_environment(&env(&with(
1311            &GITHUB,
1312            &[(ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token")],
1313        )))
1314        .unwrap();
1315        let debug = format!("{credentials:?}");
1316        assert!(
1317            debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1318            "{debug}"
1319        );
1320    }
1321
1322    #[test]
1323    fn a_token_in_the_environment_is_exchanged() {
1324        let credentials = from_environment(&env(&[(ENV_OIDC_TOKEN, "gitlab-job-token")])).unwrap();
1325        let debug = format!("{credentials:?}");
1326        assert!(
1327            debug.starts_with(r#"Federated { source: "token""#),
1328            "{debug}"
1329        );
1330        assert!(!debug.contains("gitlab-job-token"), "{debug}");
1331    }
1332
1333    #[test]
1334    fn a_token_file_comes_before_a_token_in_the_environment() {
1335        let credentials = from_environment(&env(&[
1336            (ENV_OIDC_TOKEN, "gitlab-job-token"),
1337            (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
1338        ]))
1339        .unwrap();
1340        let debug = format!("{credentials:?}");
1341        assert!(
1342            debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1343            "{debug}"
1344        );
1345    }
1346
1347    #[test]
1348    fn a_token_in_the_environment_comes_before_github_actions() {
1349        let credentials = from_environment(&env(&with(
1350            &GITHUB,
1351            &[(ENV_OIDC_TOKEN, "gitlab-job-token")],
1352        )))
1353        .unwrap();
1354        let debug = format!("{credentials:?}");
1355        assert!(
1356            debug.starts_with(r#"Federated { source: "token""#),
1357            "{debug}"
1358        );
1359    }
1360
1361    #[test]
1362    fn a_token_in_the_environment_is_left_out_with_the_federated_step() {
1363        let dir = data_home();
1364        let credentials = from_environment(&env(&[
1365            (ENV_OIDC_TOKEN, "gitlab-job-token"),
1366            (ENV_OIDC_DISABLED, "true"),
1367            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1368        ]))
1369        .unwrap();
1370        assert!(
1371            format!("{credentials:?}").starts_with("InstanceMetadata"),
1372            "{credentials:?}"
1373        );
1374    }
1375
1376    /// An unsigned JWT with the claims `claims`.
1377    fn jwt(claims: &str) -> String {
1378        use base64::Engine as _;
1379        let encode = |part: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(part);
1380        format!(
1381            "{}.{}.",
1382            encode(r#"{"alg":"none","typ":"JWT"}"#),
1383            encode(claims)
1384        )
1385    }
1386
1387    #[tokio::test]
1388    async fn an_expired_token_in_the_environment_names_the_variable() {
1389        let token = jwt(r#"{"sub":"project_path:group/project","exp":1577836800}"#);
1390        let credentials = from_environment(&env(&[
1391            (ENV_OIDC_TOKEN, &token),
1392            (ENV_STS_ENDPOINT, "http://127.0.0.1:9"),
1393        ]))
1394        .unwrap();
1395        let message = credentials.token().await.unwrap_err().to_string();
1396        assert!(
1397            message.contains(
1398                "the CI job's OIDC token in ORIGINCLOUD_OIDC_TOKEN expired at 2020-01-01T00:00:00Z"
1399            ),
1400            "{message}"
1401        );
1402        assert!(message.contains("ORIGINCLOUD_OIDC_TOKEN_FILE"), "{message}");
1403        assert!(!message.contains(&token), "{message}");
1404    }
1405
1406    /// The error of exchanging the token the environment `vars` holds: an
1407    /// expired one, so that nothing is sent, which names the variable it
1408    /// was read from.
1409    async fn exchange_error(vars: &[(&str, &str)]) -> String {
1410        let credentials = from_environment(&env(&with(
1411            vars,
1412            &[(ENV_STS_ENDPOINT, "http://127.0.0.1:9")],
1413        )))
1414        .unwrap();
1415        credentials.token().await.unwrap_err().to_string()
1416    }
1417
1418    fn expired() -> String {
1419        jwt(r#"{"sub":"organization:org:project:p:workspace:w:run_phase:plan","exp":1577836800}"#)
1420    }
1421
1422    #[test]
1423    fn an_hcp_terraform_token_is_exchanged() {
1424        let credentials = from_environment(&env(&[(ENV_TFC_TOKEN, "tfc-token")])).unwrap();
1425        let debug = format!("{credentials:?}");
1426        assert!(
1427            debug.starts_with(r#"Federated { source: "token""#),
1428            "{debug}"
1429        );
1430        assert!(!debug.contains("tfc-token"), "{debug}");
1431    }
1432
1433    #[tokio::test]
1434    async fn an_expired_hcp_terraform_token_names_its_variable() {
1435        let token = expired();
1436        let message = exchange_error(&[(ENV_TFC_TOKEN, &token)]).await;
1437        assert!(
1438            message.contains(
1439                "the CI job's OIDC token in TFC_WORKLOAD_IDENTITY_TOKEN expired at 2020-01-01T00:00:00Z"
1440            ),
1441            "{message}"
1442        );
1443        assert!(!message.contains(&token), "{message}");
1444    }
1445
1446    #[tokio::test]
1447    async fn a_tagged_hcp_terraform_token_is_read_by_its_tag_alone() {
1448        let token = expired();
1449        let message = exchange_error(&[
1450            (ENV_TFC_TAG, " ORIGIN "),
1451            (ENV_TFC_TOKEN, "untagged-token"),
1452            ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", &token),
1453            ("TFC_WORKLOAD_IDENTITY_TOKEN_OTHER", "other-token"),
1454        ])
1455        .await;
1456        assert!(
1457            message.contains("OIDC token in TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN expired"),
1458            "{message}"
1459        );
1460    }
1461
1462    #[tokio::test]
1463    async fn a_tag_without_its_token_fails_naming_the_variable() {
1464        for vars in [
1465            vec![(ENV_TFC_TAG, "ORIGIN"), (ENV_TFC_TOKEN, "untagged-token")],
1466            vec![
1467                (ENV_TFC_TAG, "ORIGIN"),
1468                (ENV_TFC_TOKEN, "untagged-token"),
1469                ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", ""),
1470            ],
1471        ] {
1472            let message = exchange_error(&vars).await;
1473            assert!(
1474                message.contains("in TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN is empty or not set"),
1475                "{message}"
1476            );
1477            assert!(!message.contains("untagged-token"), "{message}");
1478        }
1479    }
1480
1481    #[test]
1482    fn a_tagged_hcp_terraform_token_without_its_tag_is_left_out() {
1483        let dir = data_home();
1484        let credentials = from_environment(&env(&[
1485            ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", "tagged-token"),
1486            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1487        ]))
1488        .unwrap();
1489        assert!(
1490            format!("{credentials:?}").starts_with("InstanceMetadata"),
1491            "{credentials:?}"
1492        );
1493    }
1494
1495    #[test]
1496    fn an_hcp_terraform_token_is_left_out_with_the_federated_step() {
1497        let dir = data_home();
1498        let credentials = from_environment(&env(&[
1499            (ENV_TFC_TOKEN, "tfc-token"),
1500            (ENV_TFC_TAG, "ORIGIN"),
1501            (ENV_OIDC_DISABLED, "true"),
1502            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1503        ]))
1504        .unwrap();
1505        assert!(
1506            format!("{credentials:?}").starts_with("InstanceMetadata"),
1507            "{credentials:?}"
1508        );
1509    }
1510
1511    #[test]
1512    fn an_hcp_terraform_token_comes_before_github_actions() {
1513        let credentials =
1514            from_environment(&env(&with(&GITHUB, &[(ENV_TFC_TOKEN, "tfc-token")]))).unwrap();
1515        let debug = format!("{credentials:?}");
1516        assert!(
1517            debug.starts_with(r#"Federated { source: "token""#),
1518            "{debug}"
1519        );
1520    }
1521
1522    #[test]
1523    fn an_hcp_terraform_token_comes_after_a_token_file() {
1524        let credentials = from_environment(&env(&[
1525            (ENV_TFC_TOKEN, "tfc-token"),
1526            (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
1527        ]))
1528        .unwrap();
1529        let debug = format!("{credentials:?}");
1530        assert!(
1531            debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1532            "{debug}"
1533        );
1534    }
1535
1536    #[tokio::test]
1537    async fn an_hcp_terraform_token_comes_after_a_token_in_the_environment() {
1538        let token = expired();
1539        let message =
1540            exchange_error(&[(ENV_OIDC_TOKEN, &token), (ENV_TFC_TOKEN, "tfc-token")]).await;
1541        assert!(
1542            message.contains("in ORIGINCLOUD_OIDC_TOKEN expired"),
1543            "{message}"
1544        );
1545    }
1546
1547    #[test]
1548    fn a_job_token_s_expiry_is_read_from_its_claims() {
1549        let at = |secs| Some(SystemTime::UNIX_EPOCH + Duration::from_secs(secs));
1550        assert_eq!(
1551            job_token_expiry(&jwt(r#"{"exp":1577836800}"#)),
1552            at(1577836800)
1553        );
1554        assert_eq!(
1555            job_token_expiry(&jwt(r#"{"exp":1577836800.5}"#)),
1556            at(1577836800).map(|t| t + Duration::from_millis(500))
1557        );
1558        // Padded base64url, as some issuers write it.
1559        let padded = {
1560            use base64::Engine as _;
1561            let claims = base64::engine::general_purpose::URL_SAFE.encode(r#"{"exp":12}"#);
1562            assert!(claims.ends_with("=="), "{claims}");
1563            format!("e30.{claims}.")
1564        };
1565        assert_eq!(job_token_expiry(&padded), at(12));
1566        for unreadable in [
1567            jwt(r#"{"sub":"no expiry"}"#),
1568            jwt(r#"{"exp":"tomorrow"}"#),
1569            jwt(r#"{"exp":-1}"#),
1570            jwt("not json"),
1571            "not-a-jwt".to_owned(),
1572            "a.%%%.c".to_owned(),
1573        ] {
1574            assert_eq!(job_token_expiry(&unreadable), None, "{unreadable}");
1575        }
1576    }
1577
1578    #[test]
1579    fn github_actions_needs_both_its_variables() {
1580        let dir = data_home();
1581        for half in GITHUB {
1582            let credentials =
1583                from_environment(&env(&[half, ("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
1584            assert!(
1585                format!("{credentials:?}").starts_with("InstanceMetadata"),
1586                "{credentials:?}"
1587            );
1588        }
1589    }
1590
1591    #[test]
1592    fn the_federated_step_can_be_left_out() {
1593        let dir = data_home();
1594        let credentials = from_environment(&env(&with(
1595            &GITHUB,
1596            &[
1597                (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
1598                (ENV_OIDC_DISABLED, "True"),
1599                ("XDG_DATA_HOME", dir.to_str().unwrap()),
1600            ],
1601        )))
1602        .unwrap();
1603        assert!(
1604            format!("{credentials:?}").starts_with("InstanceMetadata"),
1605            "{credentials:?}"
1606        );
1607    }
1608
1609    #[test]
1610    fn the_sts_and_the_audience_can_be_named() {
1611        let credentials = from_environment(&env(&with(
1612            &GITHUB,
1613            &[
1614                (ENV_STS_ENDPOINT, "http://127.0.0.1:8080/"),
1615                (ENV_OIDC_AUDIENCE, "https://sts.example"),
1616            ],
1617        )))
1618        .unwrap();
1619        let debug = format!("{credentials:?}");
1620        assert!(
1621            debug.contains(r#"endpoint: "http://127.0.0.1:8080", audience: "https://sts.example""#),
1622            "{debug}"
1623        );
1624    }
1625
1626    #[test]
1627    fn half_a_service_account_is_refused() {
1628        let err = from_environment(&env(&[(ENV_CLIENT_ID, "id")])).unwrap_err();
1629        assert!(err.to_string().contains("must be set together"), "{err}");
1630        let err = from_environment(&env(&[(ENV_CLIENT_SECRET, "secret")])).unwrap_err();
1631        assert!(err.to_string().contains("must be set together"), "{err}");
1632    }
1633
1634    #[test]
1635    fn without_others_the_metadata_service_comes_last() {
1636        let dir = data_home();
1637        let credentials =
1638            from_environment(&env(&[("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
1639        assert!(
1640            format!("{credentials:?}").starts_with("InstanceMetadata"),
1641            "{credentials:?}"
1642        );
1643    }
1644
1645    #[test]
1646    fn the_metadata_service_s_address_can_be_named() {
1647        let dir = data_home();
1648        let credentials = from_environment(&env(&[
1649            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1650            (ENV_METADATA_ENDPOINT, "http://127.0.0.1:8080/"),
1651        ]))
1652        .unwrap();
1653        assert!(
1654            format!("{credentials:?}").contains(r#"endpoint: "http://127.0.0.1:8080""#),
1655            "{credentials:?}"
1656        );
1657    }
1658
1659    #[test]
1660    fn no_credentials_at_all_without_the_metadata_service() {
1661        let dir = data_home();
1662        let err = from_environment(&env(&[
1663            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1664            (ENV_METADATA_DISABLED, "TRUE"),
1665        ]))
1666        .unwrap_err();
1667        assert!(matches!(err, Error::NoCredentials), "{err}");
1668    }
1669
1670    #[test]
1671    fn the_session_is_found_under_the_home_directory_without_xdg_data_home() {
1672        let path = cli_session_path(&env(&[
1673            ("HOME", "/home/someone"),
1674            ("USERPROFILE", "/home/someone"),
1675        ]))
1676        .unwrap();
1677        assert_eq!(
1678            path,
1679            PathBuf::from("/home/someone/.local/share/origincloud/session.json")
1680        );
1681    }
1682
1683    #[tokio::test]
1684    async fn the_cli_session_is_used_as_stored() {
1685        let dir = data_home();
1686        write_session(
1687            &dir,
1688            now() + chrono::Duration::hours(1),
1689            now() + chrono::Duration::hours(2),
1690        );
1691        let credentials =
1692            from_environment(&env(&[("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
1693        assert_eq!(credentials.token().await.unwrap(), "stored-access");
1694    }
1695
1696    #[tokio::test]
1697    async fn a_cli_session_past_its_refresh_expiry_asks_to_log_in() {
1698        let dir = data_home();
1699        let path = write_session(
1700            &dir,
1701            now() - chrono::Duration::hours(1),
1702            now() - chrono::Duration::minutes(1),
1703        );
1704        let session = CliSession::load_from(path).unwrap().unwrap();
1705        let err = session.token().await.unwrap_err();
1706        assert!(err.to_string().contains("origin id login"), "{err}");
1707    }
1708}