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, and only from a credentials file's content
12//! (`ServiceAccount::from_json`).
13
14use std::fmt;
15#[cfg(not(target_arch = "wasm32"))]
16use std::path::PathBuf;
17use std::sync::Arc;
18#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
19use std::sync::OnceLock;
20#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
21use std::time::{Duration, SystemTime};
22
23#[cfg(not(target_arch = "wasm32"))]
24use chrono::{DateTime, Utc};
25#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
26use serde::Deserialize;
27
28use crate::Error;
29use crate::runtime::MaybeSendFuture;
30#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
31use crate::runtime::{Mutex, now};
32#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
33use crate::transport::read_capped;
34
35/// The identity provider's token endpoint, where the CLI's session is
36/// renewed.
37pub const TOKEN_URL: &str =
38    "https://auth.origincloud.eu/realms/origincloud/protocol/openid-connect/token";
39
40#[cfg(not(target_arch = "wasm32"))]
41const ENV_ACCESS_TOKEN: &str = "ORIGINCLOUD_ACCESS_TOKEN";
42#[cfg(not(target_arch = "wasm32"))]
43const ENV_CREDENTIALS_FILE: &str = "ORIGINCLOUD_CREDENTIALS_FILE";
44#[cfg(not(target_arch = "wasm32"))]
45const ENV_METADATA_DISABLED: &str = "ORIGINCLOUD_METADATA_DISABLED";
46#[cfg(not(target_arch = "wasm32"))]
47const ENV_METADATA_ENDPOINT: &str = "ORIGINCLOUD_METADATA_ENDPOINT";
48#[cfg(not(target_arch = "wasm32"))]
49const ENV_OIDC_DISABLED: &str = "ORIGINCLOUD_OIDC_DISABLED";
50#[cfg(not(target_arch = "wasm32"))]
51const ENV_OIDC_TOKEN_FILE: &str = "ORIGINCLOUD_OIDC_TOKEN_FILE";
52#[cfg(not(target_arch = "wasm32"))]
53const ENV_OIDC_TOKEN: &str = "ORIGINCLOUD_OIDC_TOKEN";
54#[cfg(not(target_arch = "wasm32"))]
55const ENV_OIDC_AUDIENCE: &str = "ORIGINCLOUD_OIDC_AUDIENCE";
56#[cfg(not(target_arch = "wasm32"))]
57const ENV_STS_ENDPOINT: &str = "ORIGINCLOUD_STS_ENDPOINT";
58/// What an HCP Terraform workspace with dynamic credentials sets in a run:
59/// the workload identity token in `ENV_TFC_TOKEN`, or, for an audience
60/// variable with a tag (`TFC_WORKLOAD_IDENTITY_AUDIENCE_<TAG>`), in
61/// `ENV_TFC_TOKEN_<TAG>`. `ENV_TFC_TAG` names the tag to read.
62#[cfg(not(target_arch = "wasm32"))]
63const ENV_TFC_TOKEN: &str = "TFC_WORKLOAD_IDENTITY_TOKEN";
64#[cfg(not(target_arch = "wasm32"))]
65const ENV_TFC_TAG: &str = "ORIGINCLOUD_TFC_WORKLOAD_IDENTITY_TAG";
66#[cfg(not(target_arch = "wasm32"))]
67const ENV_GITHUB_REQUEST_URL: &str = "ACTIONS_ID_TOKEN_REQUEST_URL";
68#[cfg(not(target_arch = "wasm32"))]
69const ENV_GITHUB_REQUEST_TOKEN: &str = "ACTIONS_ID_TOKEN_REQUEST_TOKEN";
70
71/// The security token service, where a CI job's OIDC token is exchanged
72/// for an access token. A service account key's assertions are exchanged
73/// where its credentials file says.
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/// The `type` of a service account key's credentials file.
89#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
90const CREDENTIALS_FILE_TYPE: &str = "service_account_key";
91
92/// The algorithm a service account key's assertions are signed with.
93#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
94const ASSERTION_ALGORITHM: &str = "ES256";
95
96/// How long an assertion is valid: the STS refuses one valid for longer
97/// than an hour, and each is sent at once.
98#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
99const ASSERTION_LIFETIME: Duration = Duration::from_secs(5 * 60);
100
101/// How long before its expiry a service account's access token is
102/// replaced.
103#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
104const SERVICE_ACCOUNT_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
105
106#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
107const JWT_BEARER_GRANT: &str = "urn:ietf:params:oauth:grant-type:jwt-bearer";
108#[cfg(not(target_arch = "wasm32"))]
109const TOKEN_EXCHANGE_GRANT: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
110#[cfg(not(target_arch = "wasm32"))]
111const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";
112#[cfg(not(target_arch = "wasm32"))]
113const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
114
115/// How long before its expiry an impersonated service account's access
116/// token, which lives five minutes at most, is replaced.
117#[cfg(not(target_arch = "wasm32"))]
118const IMPERSONATED_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
119
120/// The environment variable naming a service account to impersonate.
121#[cfg(not(target_arch = "wasm32"))]
122pub(crate) const ENV_IMPERSONATE_SERVICE_ACCOUNT: &str = "ORIGINCLOUD_IMPERSONATE_SERVICE_ACCOUNT";
123
124/// The instance metadata service, which software on an instance reaches
125/// at this link-local address.
126pub const METADATA_ENDPOINT: &str = "http://169.254.169.254";
127
128/// How long a metadata-service session is asked for: the most it grants.
129#[cfg(not(target_arch = "wasm32"))]
130const METADATA_SESSION_TTL: Duration = Duration::from_secs(6 * 60 * 60);
131#[cfg(not(target_arch = "wasm32"))]
132const METADATA_SESSION_TTL_HEADER: &str = "x-origincloud-metadata-token-ttl-seconds";
133#[cfg(not(target_arch = "wasm32"))]
134const METADATA_SESSION_HEADER: &str = "x-origincloud-metadata-token";
135
136/// How long reaching the metadata service may take, and opening a session
137/// in all: off an instance, the chain's last step fails within them.
138#[cfg(not(target_arch = "wasm32"))]
139const METADATA_CONNECT_TIMEOUT: Duration = Duration::from_secs(1);
140#[cfg(not(target_arch = "wasm32"))]
141const METADATA_SESSION_TIMEOUT: Duration = Duration::from_secs(2);
142
143/// How long a credential request may take.
144#[cfg(not(target_arch = "wasm32"))]
145const METADATA_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
146
147/// How long before its expiry the metadata service's credential, which
148/// lives five minutes, is replaced.
149#[cfg(not(target_arch = "wasm32"))]
150const METADATA_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
151
152/// The waits before a request the metadata service answered with `503`
153/// (it can't sign right now) is sent again.
154#[cfg(not(target_arch = "wasm32"))]
155const METADATA_RETRY_DELAYS: [Duration; 2] =
156    [Duration::from_millis(100), Duration::from_millis(200)];
157
158/// The OAuth client the CLI logs in as, which its refresh token belongs to.
159#[cfg(not(target_arch = "wasm32"))]
160const CLI_CLIENT_ID: &str = "origin-cli";
161
162/// How long before its expiry a token is replaced, so that it doesn't
163/// expire on the way.
164#[cfg(not(target_arch = "wasm32"))]
165const EXPIRY_MARGIN: Duration = Duration::from_secs(30);
166
167/// The most of a token response that is read.
168#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
169const MAX_TOKEN_RESPONSE_BYTES: usize = 1 << 20;
170
171/// How long a token request may take.
172#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
173const TOKEN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
174
175/// What [`Credentials::token`] returns: `Send` natively; not in a
176/// browser, where a fetch is a JavaScript promise.
177pub type TokenFuture<'a> = MaybeSendFuture<'a, Result<String, Error>>;
178
179/// Credentials supply the access token each call is sent with. `Send +
180/// Sync` on every target, so a client can live in a UI framework's
181/// reactive state (Leptos 0.8 keeps memo values `Send + Sync` even in a
182/// browser); only the future [`token`](Self::token) returns is `!Send` there.
183pub trait Credentials: Send + Sync + fmt::Debug {
184    /// A valid access token.
185    fn token(&self) -> TokenFuture<'_>;
186}
187
188/// The first credentials found, in this order:
189///
190/// 1. `ORIGINCLOUD_ACCESS_TOKEN`: an access token, sent as it is.
191/// 2. `ORIGINCLOUD_CREDENTIALS_FILE`: the path of a service account key's
192///    credentials file ([`ServiceAccount`]), whose assertions are exchanged
193///    for access tokens as they expire. A file that can't be read is an
194///    error, not passed over.
195/// 3. A CI job's OIDC token, exchanged at the security token service
196///    ([`Federated`]): from the file `ORIGINCLOUD_OIDC_TOKEN_FILE` names,
197///    or else from `ORIGINCLOUD_OIDC_TOKEN`, which holds the token itself
198///    (as GitLab CI's `id_tokens` set it), or else from an HCP Terraform
199///    run's workload identity token, `TFC_WORKLOAD_IDENTITY_TOKEN`, or
200///    `TFC_WORKLOAD_IDENTITY_TOKEN_<TAG>` when
201///    `ORIGINCLOUD_TFC_WORKLOAD_IDENTITY_TAG` names the tag of a tagged
202///    audience, or else from GitHub Actions, in a job granted `permissions: id-token: write`. Once found, its errors
203///    are returned, not passed over. `ORIGINCLOUD_OIDC_DISABLED=true`
204///    leaves this step out; `ORIGINCLOUD_STS_ENDPOINT` asks another address
205///    than [`STS_ENDPOINT`], and `ORIGINCLOUD_OIDC_AUDIENCE` requests
206///    GitHub's token for another audience than [`OIDC_AUDIENCE`].
207/// 4. The session the `origin` CLI stored at its last login
208///    (`origin id login`).
209/// 5. The instance's metadata service, on an instance that runs as a
210///    service account ([`InstanceMetadata`]). Nothing is requested until a
211///    token is; off an instance, that fails with [`Error::NoCredentials`]
212///    within about two seconds. `ORIGINCLOUD_METADATA_DISABLED=true` leaves
213///    this step out; `ORIGINCLOUD_METADATA_ENDPOINT` asks another address
214///    than [`METADATA_ENDPOINT`].
215///
216/// It fails with [`Error::NoCredentials`] when the metadata service is
217/// left out and there are no others.
218#[cfg(not(target_arch = "wasm32"))]
219pub fn default_credentials() -> Result<Arc<dyn Credentials>, Error> {
220    from_environment(&|name| std::env::var(name).ok())
221}
222
223/// [`default_credentials`] with the environment read through `env`.
224#[cfg(not(target_arch = "wasm32"))]
225pub(crate) fn from_environment(
226    env: &dyn Fn(&str) -> Option<String>,
227) -> Result<Arc<dyn Credentials>, Error> {
228    let var = |name: &str| env(name).filter(|v| !v.is_empty());
229    if let Some(token) = var(ENV_ACCESS_TOKEN) {
230        return Ok(Arc::new(AccessToken::new(token)));
231    }
232    if let Some(path) = var(ENV_CREDENTIALS_FILE) {
233        return Ok(Arc::new(ServiceAccount::from_file(path)?));
234    }
235    if let Some(federated) = federated_from(&var) {
236        return Ok(Arc::new(federated));
237    }
238    if let Some(path) = cli_session_path(env)
239        && let Some(session) = CliSession::load_from(path)?
240    {
241        return Ok(Arc::new(session));
242    }
243    if var(ENV_METADATA_DISABLED).is_some_and(|v| v.eq_ignore_ascii_case("true")) {
244        return Err(Error::NoCredentials);
245    }
246    let metadata = InstanceMetadata::new();
247    Ok(Arc::new(match var(ENV_METADATA_ENDPOINT) {
248        Some(endpoint) => metadata.with_endpoint(endpoint),
249        None => metadata,
250    }))
251}
252
253/// `credentials`, impersonating the service account `chosen` names (from
254/// the builder), or else `ORIGINCLOUD_IMPERSONATE_SERVICE_ACCOUNT` does,
255/// at the STS `ORIGINCLOUD_STS_ENDPOINT` names, if any. An empty name
256/// impersonates no one.
257#[cfg(not(target_arch = "wasm32"))]
258pub(crate) fn impersonating(
259    credentials: Arc<dyn Credentials>,
260    chosen: Option<String>,
261    env: &dyn Fn(&str) -> Option<String>,
262) -> Result<Arc<dyn Credentials>, Error> {
263    let var = |name: &str| env(name).filter(|v| !v.is_empty());
264    let Some(service_account) = chosen
265        .or_else(|| var(ENV_IMPERSONATE_SERVICE_ACCOUNT))
266        .map(|name| name.trim().to_owned())
267        .filter(|name| !name.is_empty())
268    else {
269        return Ok(credentials);
270    };
271    let mut impersonated = Impersonated::new(credentials, service_account)?;
272    if let Some(endpoint) = var(ENV_STS_ENDPOINT) {
273        impersonated = impersonated.with_endpoint(endpoint);
274    }
275    Ok(Arc::new(impersonated))
276}
277
278/// In a browser there is no environment, no file system and no metadata
279/// service, and a private key in a page is anybody's: the page supplies its own
280/// [`Credentials`] (an [`AccessToken`], or one that refreshes its session).
281#[cfg(target_arch = "wasm32")]
282pub(crate) fn from_environment(
283    _env: &dyn Fn(&str) -> Option<String>,
284) -> Result<Arc<dyn Credentials>, Error> {
285    Err(Error::NoCredentials)
286}
287
288/// The federated step of the chain, when the environment holds a CI job's
289/// OIDC token: a token file, which can be rotated in place, before a token
290/// given as it is, before an HCP Terraform run's workload identity token,
291/// before GitHub Actions.
292#[cfg(not(target_arch = "wasm32"))]
293fn federated_from(var: &dyn Fn(&str) -> Option<String>) -> Option<Federated> {
294    if var(ENV_OIDC_DISABLED).is_some_and(|v| v.eq_ignore_ascii_case("true")) {
295        return None;
296    }
297    let mut federated = if let Some(path) = var(ENV_OIDC_TOKEN_FILE) {
298        Federated::from_file(path)
299    } else if let Some(token) = var(ENV_OIDC_TOKEN) {
300        Federated::with_source(JobToken::Given {
301            token,
302            variable: Some(ENV_OIDC_TOKEN.to_owned()),
303        })
304    } else if let Some(variable) = tfc_token_variable(var) {
305        Federated::with_source(JobToken::Given {
306            token: var(&variable).unwrap_or_default(),
307            variable: Some(variable),
308        })
309    } else if let (Some(url), Some(token)) =
310        (var(ENV_GITHUB_REQUEST_URL), var(ENV_GITHUB_REQUEST_TOKEN))
311    {
312        Federated::github_actions(url, token)
313    } else {
314        return None;
315    };
316    if let Some(endpoint) = var(ENV_STS_ENDPOINT) {
317        federated = federated.with_endpoint(endpoint);
318    }
319    if let Some(audience) = var(ENV_OIDC_AUDIENCE) {
320        federated = federated.with_audience(audience);
321    }
322    Some(federated)
323}
324
325/// The variable an HCP Terraform run's workload identity token is read
326/// from: the tagged one when `ORIGINCLOUD_TFC_WORKLOAD_IDENTITY_TAG` names a
327/// tag, even if that variable is unset, so that the error names it; the
328/// untagged one otherwise, when it is set. `None` when the run has none.
329#[cfg(not(target_arch = "wasm32"))]
330fn tfc_token_variable(var: &dyn Fn(&str) -> Option<String>) -> Option<String> {
331    match var(ENV_TFC_TAG).map(|tag| tag.trim().to_owned()) {
332        Some(tag) if !tag.is_empty() => Some(format!("{ENV_TFC_TOKEN}_{tag}")),
333        _ => var(ENV_TFC_TOKEN).map(|_| ENV_TFC_TOKEN.to_owned()),
334    }
335}
336
337/// An access token, sent as it is. It is not renewed: a service account's
338/// lives five minutes.
339#[derive(Clone)]
340pub struct AccessToken(String);
341
342impl AccessToken {
343    /// Credentials that always send `token`.
344    pub fn new(token: impl Into<String>) -> Self {
345        Self(token.into())
346    }
347}
348
349impl fmt::Debug for AccessToken {
350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351        f.write_str("AccessToken(..)")
352    }
353}
354
355impl Credentials for AccessToken {
356    fn token(&self) -> TokenFuture<'_> {
357        Box::pin(async move { Ok(self.0.clone()) })
358    }
359}
360
361/// A service account key's credentials file, as IAM returns it once when
362/// the key is created: the key's and the account's full names, the private
363/// key, and the security token service its assertions are exchanged at.
364#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
365#[derive(Deserialize)]
366struct CredentialsFile {
367    #[serde(rename = "type", default)]
368    kind: String,
369    #[serde(default)]
370    name: String,
371    #[serde(default)]
372    service_account: String,
373    #[serde(default)]
374    algorithm: String,
375    #[serde(default)]
376    private_key: String,
377    #[serde(default)]
378    sts_endpoint: String,
379}
380
381/// An `EXTERNAL` service account, authenticated with one of its keys: an
382/// assertion signed with the key from its credentials file (RFC 7523,
383/// `ES256`) is exchanged at the security token service for the account's
384/// access token, which is reused until a minute before it expires. Callers
385/// that need a token while it is being renewed wait for that renewal and
386/// share its token.
387///
388/// On `wasm32-unknown-unknown` it exists only with the feature
389/// `service-account-wasm`, for runtimes that aren't a browser: a web
390/// page, and a Web Worker too, is shipped to whoever loads it, private key
391/// and all.
392#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
393pub struct ServiceAccount {
394    key: String,
395    service_account: String,
396    signing_key: p256::ecdsa::SigningKey,
397    sts_endpoint: String,
398    http: Option<reqwest::Client>,
399    cache: Mutex<Cached>,
400}
401
402#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
403impl ServiceAccount {
404    /// The service account whose key's credentials file is at `path`.
405    #[cfg(not(target_arch = "wasm32"))]
406    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, Error> {
407        let path = path.as_ref();
408        let data = std::fs::read(path).map_err(|e| {
409            Error::Credentials(format!(
410                "reading the credentials file {}: {e}",
411                path.display()
412            ))
413        })?;
414        Self::parse(&data).map_err(|reason| {
415            Error::Credentials(format!(
416                "reading the credentials file {}: {reason}",
417                path.display()
418            ))
419        })
420    }
421
422    /// The service account whose key's credentials file is `json`, such as
423    /// the `credentialsFile` a key's creation answers with.
424    pub fn from_json(json: impl AsRef<[u8]>) -> Result<Self, Error> {
425        Self::parse(json.as_ref())
426            .map_err(|reason| Error::Credentials(format!("reading the credentials file: {reason}")))
427    }
428
429    fn parse(json: &[u8]) -> Result<Self, String> {
430        use p256::pkcs8::DecodePrivateKey as _;
431
432        // serde_json's errors name a position, never the file's content.
433        let file: CredentialsFile = serde_json::from_slice(json).map_err(|e| e.to_string())?;
434        if file.kind != CREDENTIALS_FILE_TYPE {
435            return Err(format!(
436                "its type is {:?}, not {CREDENTIALS_FILE_TYPE:?}",
437                file.kind
438            ));
439        }
440        if file.algorithm != ASSERTION_ALGORITHM {
441            return Err(format!(
442                "its algorithm is {:?}; this SDK signs with {ASSERTION_ALGORITHM}",
443                file.algorithm
444            ));
445        }
446        for (field, value) in [
447            ("name", &file.name),
448            ("service_account", &file.service_account),
449            ("private_key", &file.private_key),
450            ("sts_endpoint", &file.sts_endpoint),
451        ] {
452            if value.is_empty() {
453                return Err(format!("it has no {field}"));
454            }
455        }
456        if !secure_endpoint(&file.sts_endpoint) {
457            return Err(format!(
458                "its sts_endpoint {:?} is not an https URL",
459                file.sts_endpoint
460            ));
461        }
462        let signing_key = p256::ecdsa::SigningKey::from_pkcs8_pem(&file.private_key)
463            .map_err(|_| "its private_key is not a PKCS #8 P-256 key in PEM".to_owned())?;
464        Ok(Self {
465            key: file.name,
466            service_account: file.service_account,
467            signing_key,
468            sts_endpoint: file.sts_endpoint,
469            http: None,
470            cache: Mutex::default(),
471        })
472    }
473
474    /// The service account's full name, as the file names it.
475    pub fn service_account(&self) -> &str {
476        &self.service_account
477    }
478
479    /// The key's full name, as the file names it.
480    pub fn key(&self) -> &str {
481        &self.key
482    }
483
484    /// Sends the token requests with `http`, instead of the client all
485    /// credentials share. Each request is bounded by 30 seconds either way.
486    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
487        self.http = Some(http);
488        self
489    }
490
491    /// A fresh assertion: a JWT signed with the key, for the STS the file
492    /// names, valid for five minutes, with an ID never used before.
493    fn assertion(&self) -> String {
494        use base64::Engine as _;
495        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
496        use p256::ecdsa::signature::Signer as _;
497
498        let issued = now()
499            .duration_since(SystemTime::UNIX_EPOCH)
500            .unwrap_or_default()
501            .as_secs();
502        let header = serde_json::json!({
503            "alg": ASSERTION_ALGORITHM,
504            "typ": "JWT",
505            "kid": self.key,
506        });
507        let claims = serde_json::json!({
508            "iss": self.service_account,
509            "sub": self.service_account,
510            "aud": self.sts_endpoint,
511            "iat": issued,
512            "exp": issued + ASSERTION_LIFETIME.as_secs(),
513            "jti": uuid::Uuid::new_v4().to_string(),
514        });
515        let signed = format!(
516            "{}.{}",
517            URL_SAFE_NO_PAD.encode(header.to_string()),
518            URL_SAFE_NO_PAD.encode(claims.to_string())
519        );
520        let signature: p256::ecdsa::Signature = self.signing_key.sign(signed.as_bytes());
521        format!("{signed}.{}", URL_SAFE_NO_PAD.encode(signature.to_bytes()))
522    }
523}
524
525#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
526impl fmt::Debug for ServiceAccount {
527    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528        f.debug_struct("ServiceAccount")
529            .field("service_account", &self.service_account)
530            .field("key", &self.key)
531            .field("sts_endpoint", &self.sts_endpoint)
532            .finish_non_exhaustive()
533    }
534}
535
536#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
537impl Credentials for ServiceAccount {
538    fn token(&self) -> TokenFuture<'_> {
539        Box::pin(async move {
540            let mut cache = self.cache.lock().await;
541            if let Some(token) = cache.valid_for(SERVICE_ACCOUNT_EXPIRY_MARGIN) {
542                return Ok(token);
543            }
544            let assertion = self.assertion();
545            let granted = request_token(
546                self.http.as_ref(),
547                &format!("{}/v1/token", self.sts_endpoint.trim_end_matches('/')),
548                &[("grant_type", JWT_BEARER_GRANT), ("assertion", &assertion)],
549            )
550            .await
551            .map_err(|e| match e {
552                Error::Credentials(message) => Error::Credentials(format!(
553                    "exchanging an assertion of the service account key {}: {message}",
554                    self.key
555                )),
556                other => other,
557            })?;
558            *cache = Cached {
559                token: granted.access_token.clone(),
560                expiry: Some(granted.expiry()),
561            };
562            Ok(granted.access_token)
563        })
564    }
565}
566
567/// The session the `origin` CLI stored at its last login, renewed from its
568/// refresh token when its access token has expired. The renewed session
569/// stays in memory: the CLI's file is never written.
570#[cfg(not(target_arch = "wasm32"))]
571pub struct CliSession {
572    token_url: String,
573    http: Option<reqwest::Client>,
574    state: Mutex<SessionState>,
575}
576
577#[cfg(not(target_arch = "wasm32"))]
578struct SessionState {
579    cached: Cached,
580    refresh_token: String,
581    refresh_expiry: Option<SystemTime>,
582}
583
584/// The file the CLI stores its session in.
585#[cfg(not(target_arch = "wasm32"))]
586#[derive(Deserialize)]
587struct StoredSession {
588    #[serde(default)]
589    access_token: String,
590    #[serde(default)]
591    expires: Option<DateTime<Utc>>,
592    #[serde(default)]
593    refresh_token: String,
594    #[serde(default)]
595    refresh_expires: Option<DateTime<Utc>>,
596}
597
598#[cfg(not(target_arch = "wasm32"))]
599impl CliSession {
600    /// The session the CLI stored, or `None` when it stored none: under
601    /// `$XDG_DATA_HOME`, or `~/.local/share`, on every platform, at
602    /// `origincloud/session.json`.
603    pub fn load() -> Result<Option<Self>, Error> {
604        match cli_session_path(&|name| std::env::var(name).ok()) {
605            Some(path) => Self::load_from(path),
606            None => Ok(None),
607        }
608    }
609
610    /// The session stored at `path`, or `None` when there is no file.
611    pub fn load_from(path: impl Into<PathBuf>) -> Result<Option<Self>, Error> {
612        let path = path.into();
613        let data = match std::fs::read(&path) {
614            Ok(data) => data,
615            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
616            Err(e) => return Err(Error::Credentials(format!("reading the CLI session: {e}"))),
617        };
618        let stored: StoredSession = serde_json::from_slice(&data).map_err(|e| {
619            Error::Credentials(format!("reading the CLI session {}: {e}", path.display()))
620        })?;
621        Ok(Some(Self {
622            token_url: TOKEN_URL.to_owned(),
623            http: None,
624            state: Mutex::new(SessionState {
625                cached: Cached {
626                    token: stored.access_token,
627                    expiry: stored.expires.map(SystemTime::from),
628                },
629                refresh_token: stored.refresh_token,
630                refresh_expiry: stored.refresh_expires.map(SystemTime::from),
631            }),
632        }))
633    }
634
635    /// Renews the session at `url` instead of [`TOKEN_URL`].
636    pub fn with_token_url(mut self, url: impl Into<String>) -> Self {
637        self.token_url = url.into();
638        self
639    }
640
641    /// Sends the renewals with `http`, instead of the client all
642    /// credentials share. Each renewal is bounded by 30 seconds either way.
643    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
644        self.http = Some(http);
645        self
646    }
647}
648
649#[cfg(not(target_arch = "wasm32"))]
650impl fmt::Debug for CliSession {
651    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652        f.debug_struct("CliSession")
653            .field("token_url", &self.token_url)
654            .finish_non_exhaustive()
655    }
656}
657
658#[cfg(not(target_arch = "wasm32"))]
659impl Credentials for CliSession {
660    fn token(&self) -> TokenFuture<'_> {
661        Box::pin(async move {
662            let mut state = self.state.lock().await;
663            if let Some(token) = state.cached.valid() {
664                return Ok(token);
665            }
666            if state
667                .refresh_expiry
668                .is_none_or(|expiry| SystemTime::now() >= expiry)
669            {
670                return Err(Error::Credentials(
671                    "the CLI session has expired: log in again with `origin id login`".to_owned(),
672                ));
673            }
674            let refresh_token = state.refresh_token.clone();
675            let granted = request_token(
676                self.http.as_ref(),
677                &self.token_url,
678                &[
679                    ("grant_type", "refresh_token"),
680                    ("client_id", CLI_CLIENT_ID),
681                    ("refresh_token", &refresh_token),
682                ],
683            )
684            .await
685            .map_err(|e| match e {
686                Error::Credentials(message) => {
687                    Error::Credentials(format!("renewing the CLI session: {message}"))
688                }
689                other => other,
690            })?;
691            if !granted.refresh_token.is_empty() {
692                state.refresh_token = granted.refresh_token.clone();
693                state.refresh_expiry =
694                    Some(SystemTime::now() + seconds(granted.refresh_expires_in));
695            }
696            state.cached = Cached {
697                token: granted.access_token.clone(),
698                expiry: Some(granted.expiry()),
699            };
700            Ok(granted.access_token)
701        })
702    }
703}
704
705/// The credential of the service account the instance runs as, from the
706/// instance's metadata service: a session is opened for six hours, and each
707/// access token, which lives five minutes, requested with it a minute
708/// before the last one expires. The requests never go through a proxy,
709/// which the metadata service refuses, and one it can't answer right now
710/// (`503`) is sent again twice.
711#[cfg(not(target_arch = "wasm32"))]
712pub struct InstanceMetadata {
713    endpoint: String,
714    http: Option<reqwest::Client>,
715    state: Mutex<MetadataState>,
716}
717
718#[cfg(not(target_arch = "wasm32"))]
719#[derive(Default)]
720struct MetadataState {
721    session: Cached,
722    cached: Cached,
723}
724
725/// The metadata service's credential.
726#[cfg(not(target_arch = "wasm32"))]
727#[derive(Deserialize)]
728struct Issued {
729    access_token: String,
730    expires_at: DateTime<Utc>,
731}
732
733#[cfg(not(target_arch = "wasm32"))]
734impl InstanceMetadata {
735    /// The metadata service at [`METADATA_ENDPOINT`].
736    pub fn new() -> Self {
737        Self {
738            endpoint: METADATA_ENDPOINT.to_owned(),
739            http: None,
740            state: Mutex::default(),
741        }
742    }
743
744    /// Asks the metadata service at `url` instead of [`METADATA_ENDPOINT`].
745    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
746        self.endpoint = url.into().trim_end_matches('/').to_owned();
747        self
748    }
749
750    /// Sends the requests with `http`, as it is configured, instead of a
751    /// client without a proxy that gives up connecting after a second.
752    /// Opening a session is bounded by two seconds either way, and
753    /// requesting a credential by five.
754    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
755        self.http = Some(http);
756        self
757    }
758
759    fn http(&self) -> Result<&reqwest::Client, Error> {
760        static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
761        if let Some(http) = &self.http {
762            return Ok(http);
763        }
764        CLIENT
765            .get_or_init(|| {
766                reqwest::Client::builder()
767                    .no_proxy()
768                    .connect_timeout(METADATA_CONNECT_TIMEOUT)
769                    .build()
770                    .map_err(|e| e.to_string())
771            })
772            .as_ref()
773            .map_err(|e| Error::Credentials(format!("reaching the metadata service: {e}")))
774    }
775
776    /// A new session. Off an instance, there is no metadata service to
777    /// answer, or another one: another cloud's, at the same address, which
778    /// refuses the request as one it doesn't know. Either way, no
779    /// credentials.
780    async fn open_session(&self) -> Result<String, Error> {
781        let request = self
782            .http()?
783            .put(format!("{}/latest/api/token", self.endpoint))
784            .timeout(METADATA_SESSION_TIMEOUT)
785            .header(
786                METADATA_SESSION_TTL_HEADER,
787                METADATA_SESSION_TTL.as_secs().to_string(),
788            );
789        let (status, body) = send_retrying(request, &METADATA_RETRY_DELAYS)
790            .await
791            .map_err(|_| Error::NoCredentials)?;
792        match status.as_u16() {
793            200 => Ok(String::from_utf8_lossy(&body).trim().to_owned()),
794            403 => Err(refused_through_a_proxy()),
795            503 => Err(Error::Credentials(
796                "the metadata service refused a session (HTTP 503)".to_owned(),
797            )),
798            _ => Err(Error::NoCredentials),
799        }
800    }
801
802    /// The credential, or `None` when the session is no longer valid.
803    async fn request_credential(&self, session: &str) -> Result<Option<Issued>, Error> {
804        let failed =
805            |e: reqwest::Error| Error::Credentials(format!("reaching the metadata service: {e}"));
806        let request = self
807            .http()?
808            .get(format!(
809                "{}/latest/meta-data/service-account/token",
810                self.endpoint
811            ))
812            .timeout(METADATA_REQUEST_TIMEOUT)
813            .header(METADATA_SESSION_HEADER, session)
814            .header(reqwest::header::ACCEPT, "application/json");
815        let (status, body) = send_retrying(request, &METADATA_RETRY_DELAYS)
816            .await
817            .map_err(failed)?;
818        match status.as_u16() {
819            200 => {}
820            401 => return Ok(None),
821            404 => {
822                return Err(Error::Credentials(
823                    "the instance runs as no service account".to_owned(),
824                ));
825            }
826            403 => return Err(refused_through_a_proxy()),
827            status => {
828                return Err(Error::Credentials(format!(
829                    "the metadata service answered HTTP {status}"
830                )));
831            }
832        }
833        match serde_json::from_slice::<Issued>(&body) {
834            Ok(issued) if !issued.access_token.is_empty() => Ok(Some(issued)),
835            _ => Err(Error::Credentials(
836                "the metadata service's answer is not a credential".to_owned(),
837            )),
838        }
839    }
840}
841
842/// Sends `request`, and again after each of `delays` while it is answered
843/// with `503`.
844#[cfg(not(target_arch = "wasm32"))]
845async fn send_retrying(
846    request: reqwest::RequestBuilder,
847    delays: &[Duration],
848) -> Result<(reqwest::StatusCode, Vec<u8>), reqwest::Error> {
849    let mut delays = delays.iter();
850    loop {
851        let attempt = request
852            .try_clone()
853            .expect("a credential request has no streamed body");
854        let answer = read_bounded(attempt.send().await?).await?;
855        match delays.next() {
856            Some(delay) if answer.0 == reqwest::StatusCode::SERVICE_UNAVAILABLE => {
857                tokio::time::sleep(*delay).await;
858            }
859            _ => return Ok(answer),
860        }
861    }
862}
863
864#[cfg(not(target_arch = "wasm32"))]
865fn refused_through_a_proxy() -> Error {
866    Error::Credentials(
867        "the metadata service refused a request that came through a proxy".to_owned(),
868    )
869}
870
871#[cfg(not(target_arch = "wasm32"))]
872impl Default for InstanceMetadata {
873    fn default() -> Self {
874        Self::new()
875    }
876}
877
878#[cfg(not(target_arch = "wasm32"))]
879impl fmt::Debug for InstanceMetadata {
880    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
881        f.debug_struct("InstanceMetadata")
882            .field("endpoint", &self.endpoint)
883            .finish_non_exhaustive()
884    }
885}
886
887#[cfg(not(target_arch = "wasm32"))]
888impl Credentials for InstanceMetadata {
889    fn token(&self) -> TokenFuture<'_> {
890        Box::pin(async move {
891            let mut state = self.state.lock().await;
892            if let Some(token) = state.cached.valid_for(METADATA_EXPIRY_MARGIN) {
893                return Ok(token);
894            }
895            // A session refused as no longer valid is opened again, once.
896            for _ in 0..2 {
897                let session = match state.session.valid() {
898                    Some(session) => session,
899                    None => {
900                        let session = self.open_session().await?;
901                        state.session = Cached {
902                            token: session.clone(),
903                            expiry: Some(SystemTime::now() + METADATA_SESSION_TTL),
904                        };
905                        session
906                    }
907                };
908                match self.request_credential(&session).await? {
909                    Some(issued) => {
910                        state.cached = Cached {
911                            token: issued.access_token.clone(),
912                            expiry: Some(issued.expires_at.into()),
913                        };
914                        return Ok(issued.access_token);
915                    }
916                    None => state.session = Cached::default(),
917                }
918            }
919            Err(Error::Credentials(
920                "the metadata service answered HTTP 401".to_owned(),
921            ))
922        })
923    }
924}
925
926/// A CI job's OIDC token, exchanged at the security token service for the
927/// access token of the `WORKLOAD` service account a federated credential
928/// trusts the job as. The access token is reused until a minute before it
929/// expires; then a fresh job token is fetched and exchanged again, or a
930/// token given as it is ([`Federated::from_token`]) exchanged again. An
931/// exchange the STS can't check right now (`503`) is sent again twice.
932#[cfg(not(target_arch = "wasm32"))]
933pub struct Federated {
934    source: JobToken,
935    endpoint: String,
936    audience: String,
937    http: Option<reqwest::Client>,
938    cache: Mutex<Cached>,
939}
940
941/// Where the job's token comes from.
942#[cfg(not(target_arch = "wasm32"))]
943enum JobToken {
944    File(PathBuf),
945    /// A token given as it is, from the environment variable `variable`
946    /// names, if any.
947    Given {
948        token: String,
949        variable: Option<String>,
950    },
951    GitHubActions {
952        request_url: String,
953        request_token: String,
954    },
955}
956
957/// The claims of a job token that are read before it is exchanged.
958#[cfg(not(target_arch = "wasm32"))]
959#[derive(Deserialize)]
960struct JobTokenClaims {
961    exp: Option<f64>,
962}
963
964/// GitHub's answer to a job token request.
965#[cfg(not(target_arch = "wasm32"))]
966#[derive(Deserialize)]
967struct GitHubToken {
968    value: String,
969}
970
971#[cfg(not(target_arch = "wasm32"))]
972impl Federated {
973    /// The token in the file at `path`, read again at every exchange, so
974    /// that a rotated token is picked up: any CI provider's, or a
975    /// Kubernetes projected service account token.
976    pub fn from_file(path: impl Into<PathBuf>) -> Self {
977        Self::with_source(JobToken::File(path.into()))
978    }
979
980    /// The token `token`, exchanged as it is: any CI provider's, such as the
981    /// one GitLab CI sets in the variable its `id_tokens` names. It can't
982    /// be renewed: each renewal of the access token exchanges it again,
983    /// until it expires itself, and from then on fails without asking the
984    /// STS.
985    pub fn from_token(token: impl Into<String>) -> Self {
986        Self::with_source(JobToken::Given {
987            token: token.into(),
988            variable: None,
989        })
990    }
991
992    /// A GitHub Actions job's token, requested at `request_url` with
993    /// `request_token`: the values of `ACTIONS_ID_TOKEN_REQUEST_URL` and
994    /// `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, which GitHub sets in a job
995    /// granted `permissions: id-token: write`.
996    pub fn github_actions(
997        request_url: impl Into<String>,
998        request_token: impl Into<String>,
999    ) -> Self {
1000        Self::with_source(JobToken::GitHubActions {
1001            request_url: request_url.into(),
1002            request_token: request_token.into(),
1003        })
1004    }
1005
1006    fn with_source(source: JobToken) -> Self {
1007        Self {
1008            source,
1009            endpoint: STS_ENDPOINT.to_owned(),
1010            audience: OIDC_AUDIENCE.to_owned(),
1011            http: None,
1012            cache: Mutex::default(),
1013        }
1014    }
1015
1016    /// Exchanges the token at the STS at `url` instead of [`STS_ENDPOINT`].
1017    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
1018        self.endpoint = url.into().trim_end_matches('/').to_owned();
1019        self
1020    }
1021
1022    /// Requests GitHub's token for `audience` instead of [`OIDC_AUDIENCE`].
1023    /// A token file's or a given token's audience is whatever its issuer
1024    /// put in it.
1025    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
1026        self.audience = audience.into();
1027        self
1028    }
1029
1030    /// Sends the requests with `http`, instead of the client all
1031    /// credentials share. Each request is bounded by 30 seconds either way.
1032    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
1033        self.http = Some(http);
1034        self
1035    }
1036
1037    fn http(&self) -> Result<&reqwest::Client, Error> {
1038        match &self.http {
1039            Some(http) => Ok(http),
1040            None => default_http_client()
1041                .map_err(|e| Error::Credentials(format!("exchanging the CI job's token: {e}"))),
1042        }
1043    }
1044
1045    /// A fresh job token.
1046    async fn job_token(&self, http: &reqwest::Client) -> Result<String, Error> {
1047        match &self.source {
1048            JobToken::File(path) => {
1049                let read = std::fs::read_to_string(path).map_err(|e| {
1050                    Error::Credentials(format!(
1051                        "reading the OIDC token file {}: {e}",
1052                        path.display()
1053                    ))
1054                })?;
1055                let token = read.trim();
1056                if token.is_empty() {
1057                    return Err(Error::Credentials(format!(
1058                        "the OIDC token file {} is empty",
1059                        path.display()
1060                    )));
1061                }
1062                Ok(token.to_owned())
1063            }
1064            JobToken::Given { token, variable } => {
1065                let token = token.trim();
1066                if token.is_empty() {
1067                    return Err(Error::Credentials(format!(
1068                        "the CI job's OIDC token{} is empty{}",
1069                        in_variable(variable.as_deref()),
1070                        if variable.is_some() {
1071                            " or not set"
1072                        } else {
1073                            ""
1074                        }
1075                    )));
1076                }
1077                if let Some(expiry) = job_token_expiry(token)
1078                    && expiry <= SystemTime::now()
1079                {
1080                    let expiry = DateTime::<Utc>::from(expiry)
1081                        .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
1082                    return Err(Error::Credentials(format!(
1083                        "the CI job's OIDC token{} expired at {expiry}; a token given as it is \
1084                         can't be renewed: ask the CI provider for a longer-lived one, or use \
1085                         {ENV_OIDC_TOKEN_FILE}",
1086                        in_variable(variable.as_deref())
1087                    )));
1088                }
1089                Ok(token.to_owned())
1090            }
1091            JobToken::GitHubActions {
1092                request_url,
1093                request_token,
1094            } => {
1095                let failed = |reason: &dyn fmt::Display| {
1096                    Error::Credentials(format!(
1097                        "requesting the GitHub Actions job's OIDC token: {reason}; \
1098                         the workflow needs `permissions: id-token: write`"
1099                    ))
1100                };
1101                let separator = if request_url.contains('?') { '&' } else { '?' };
1102                let audience: String =
1103                    url::form_urlencoded::byte_serialize(self.audience.as_bytes()).collect();
1104                let response = http
1105                    .get(format!("{request_url}{separator}audience={audience}"))
1106                    .timeout(TOKEN_REQUEST_TIMEOUT)
1107                    .header(
1108                        reqwest::header::AUTHORIZATION,
1109                        format!("bearer {request_token}"),
1110                    )
1111                    .header(reqwest::header::ACCEPT, "application/json")
1112                    .send()
1113                    .await
1114                    .map_err(|e| failed(&e))?;
1115                let (status, body) = read_bounded(response).await.map_err(|e| failed(&e))?;
1116                if status != reqwest::StatusCode::OK {
1117                    return Err(failed(&format_args!("HTTP {}", status.as_u16())));
1118                }
1119                match serde_json::from_slice::<GitHubToken>(&body) {
1120                    Ok(token) if !token.value.is_empty() => Ok(token.value),
1121                    _ => Err(Error::Credentials(
1122                        "requesting the GitHub Actions job's OIDC token: the answer holds no token"
1123                            .to_owned(),
1124                    )),
1125                }
1126            }
1127        }
1128    }
1129
1130    /// The job's token exchanged for an access token.
1131    async fn exchange(&self, http: &reqwest::Client, job_token: &str) -> Result<Granted, Error> {
1132        let request = http
1133            .post(format!("{}/v1/token", self.endpoint))
1134            .timeout(TOKEN_REQUEST_TIMEOUT)
1135            .header(reqwest::header::ACCEPT, "application/json")
1136            .form(&[
1137                ("grant_type", TOKEN_EXCHANGE_GRANT),
1138                ("subject_token", job_token),
1139                ("subject_token_type", JWT_TOKEN_TYPE),
1140            ]);
1141        let (status, body) = send_retrying(request, &STS_RETRY_DELAYS)
1142            .await
1143            .map_err(|e| Error::Credentials(format!("exchanging the CI job's token: {e}")))?;
1144        let parsed = serde_json::from_slice::<Granted>(&body);
1145        let granted = parsed.as_ref().ok();
1146        let error = granted.map_or("", |g| g.error.as_str());
1147        match status.as_u16() {
1148            200 => match parsed {
1149                Ok(granted) if !granted.access_token.is_empty() => Ok(granted),
1150                _ => Err(Error::Credentials(
1151                    "exchanging the CI job's token: the STS's answer is not a token response"
1152                        .to_owned(),
1153                )),
1154            },
1155            503 => Err(Error::Credentials(
1156                "exchanging the CI job's token: the STS can't check it right now \
1157                 (HTTP 503, 3 attempts); try again later"
1158                    .to_owned(),
1159            )),
1160            _ if error == "invalid_grant" => Err(Error::Credentials(
1161                "the STS refused the CI job's token (invalid_grant): check the federated \
1162                 credential's issuer, audience and conditions against the token's claims"
1163                    .to_owned(),
1164            )),
1165            status => {
1166                let reason = match granted {
1167                    Some(g) if !g.error_description.is_empty() => &g.error_description,
1168                    Some(g) if !g.error.is_empty() => &g.error,
1169                    _ => "not a token response",
1170                };
1171                Err(Error::Credentials(format!(
1172                    "exchanging the CI job's token: the STS answered HTTP {status}: {reason}"
1173                )))
1174            }
1175        }
1176    }
1177}
1178
1179#[cfg(not(target_arch = "wasm32"))]
1180impl fmt::Debug for Federated {
1181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1182        let mut debug = f.debug_struct("Federated");
1183        match &self.source {
1184            JobToken::File(path) => debug.field("token_file", path),
1185            JobToken::Given { .. } => debug.field("source", &"token"),
1186            JobToken::GitHubActions { .. } => debug.field("source", &"GitHub Actions"),
1187        };
1188        debug
1189            .field("endpoint", &self.endpoint)
1190            .field("audience", &self.audience)
1191            .finish_non_exhaustive()
1192    }
1193}
1194
1195#[cfg(not(target_arch = "wasm32"))]
1196impl Credentials for Federated {
1197    fn token(&self) -> TokenFuture<'_> {
1198        Box::pin(async move {
1199            let mut cache = self.cache.lock().await;
1200            if let Some(token) = cache.valid_for(FEDERATED_EXPIRY_MARGIN) {
1201                return Ok(token);
1202            }
1203            let http = self.http()?;
1204            let job_token = self.job_token(http).await?;
1205            let granted = self.exchange(http, &job_token).await?;
1206            *cache = Cached {
1207                token: granted.access_token.clone(),
1208                expiry: Some(granted.expiry()),
1209            };
1210            Ok(granted.access_token)
1211        })
1212    }
1213}
1214
1215/// Another credential's token exchanged at the security token service for
1216/// a service account's (impersonation, RFC 8693): the caller, typically a
1217/// person logged in with `origin id login`, acts as the account, with the
1218/// account's roles alone, and the audit log names both. The STS issues the
1219/// token only to a caller granted `roles/iam.service-account-token-creator`
1220/// on the account (or its project or organization), and only for an
1221/// `EXTERNAL` or `WORKLOAD` account that is active.
1222///
1223/// The account's token lives five minutes at most, and is reused until a
1224/// minute before it expires; then the underlying credential's current
1225/// token is exchanged again. Callers that need a token while it is being
1226/// renewed wait for that renewal and share its token. A refused exchange is
1227/// an error naming the account: the caller's own token is never sent in
1228/// its place. An exchange the STS can't answer right now (`503`) is sent
1229/// again twice.
1230///
1231/// [`ClientBuilder::impersonate_service_account`](crate::ClientBuilder::impersonate_service_account),
1232/// or `ORIGINCLOUD_IMPERSONATE_SERVICE_ACCOUNT`, wraps a client's
1233/// credentials in it.
1234#[cfg(not(target_arch = "wasm32"))]
1235pub struct Impersonated {
1236    base: Arc<dyn Credentials>,
1237    service_account: String,
1238    endpoint: String,
1239    http: Option<reqwest::Client>,
1240    cache: Mutex<Cached>,
1241}
1242
1243#[cfg(not(target_arch = "wasm32"))]
1244impl Impersonated {
1245    /// Acts as the service account `service_account`, its full name
1246    /// (`//iam.origincloudapis.eu/organizations/{organization}/serviceAccounts/{service_account}`),
1247    /// with the tokens `base` supplies, such as those
1248    /// [`default_credentials`] finds. A name that isn't a service
1249    /// account's is refused.
1250    pub fn new(
1251        base: Arc<dyn Credentials>,
1252        service_account: impl Into<String>,
1253    ) -> Result<Self, Error> {
1254        let service_account = service_account.into();
1255        let is_account = crate::FullName::parse(&service_account)
1256            .ok()
1257            .is_some_and(|name| {
1258                matches!(
1259                    name.principal(),
1260                    Some(crate::names::Principal::ServiceAccount { .. })
1261                )
1262            });
1263        if !is_account {
1264            return Err(Error::Config(format!(
1265                "the service account to impersonate must be its full name, \
1266                 //iam.origincloudapis.eu/organizations/{{organization}}/serviceAccounts/{{service_account}}, \
1267                 got {service_account:?}"
1268            )));
1269        }
1270        Ok(Self {
1271            base,
1272            service_account,
1273            endpoint: STS_ENDPOINT.to_owned(),
1274            http: None,
1275            cache: Mutex::default(),
1276        })
1277    }
1278
1279    /// The full name of the service account it acts as.
1280    pub fn service_account(&self) -> &str {
1281        &self.service_account
1282    }
1283
1284    /// Exchanges the tokens at the STS at `url` instead of
1285    /// [`STS_ENDPOINT`]: an https URL, or http to the loopback interface,
1286    /// as the caller's token must not travel in the clear.
1287    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
1288        self.endpoint = url.into().trim_end_matches('/').to_owned();
1289        self
1290    }
1291
1292    /// Sends the exchanges with `http`, instead of the client all
1293    /// credentials share. Each exchange is bounded by 30 seconds either way.
1294    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
1295        self.http = Some(http);
1296        self
1297    }
1298
1299    /// `message` about impersonating the account, as an error.
1300    fn failed(&self, message: impl fmt::Display) -> Error {
1301        Error::Credentials(format!(
1302            "impersonating the service account {}: {message}",
1303            self.service_account
1304        ))
1305    }
1306
1307    /// The caller's token `subject_token` exchanged for the account's.
1308    async fn exchange(&self, subject_token: &str) -> Result<Granted, Error> {
1309        let http = match &self.http {
1310            Some(http) => http,
1311            None => default_http_client().map_err(|e| self.failed(e))?,
1312        };
1313        let request = http
1314            .post(format!("{}/v1/token", self.endpoint))
1315            .timeout(TOKEN_REQUEST_TIMEOUT)
1316            .header(reqwest::header::ACCEPT, "application/json")
1317            .form(&[
1318                ("grant_type", TOKEN_EXCHANGE_GRANT),
1319                ("subject_token", subject_token),
1320                ("subject_token_type", ACCESS_TOKEN_TYPE),
1321                ("service_account", &self.service_account),
1322            ]);
1323        let (status, body) = send_retrying(request, &STS_RETRY_DELAYS)
1324            .await
1325            .map_err(|e| self.failed(e))?;
1326        let parsed = serde_json::from_slice::<Granted>(&body);
1327        let granted = parsed.as_ref().ok();
1328        let error = granted.map_or("", |g| g.error.as_str());
1329        match status.as_u16() {
1330            200 => match parsed {
1331                Ok(granted) if !granted.access_token.is_empty() => Ok(granted),
1332                _ => Err(self.failed("the STS's answer is not a token response")),
1333            },
1334            503 => Err(self
1335                .failed("the STS can't answer right now (HTTP 503, 3 attempts); try again later")),
1336            _ if error == "invalid_grant" => Err(Error::Credentials(format!(
1337                "the STS refused to impersonate the service account {} (invalid_grant): \
1338                 the caller must be a person (a service account's or a workload's token \
1339                 can't impersonate), such as the session of `origin id login`, holding \
1340                 roles/iam.service-account-token-creator on it, and the account must exist \
1341                 and be active",
1342                self.service_account
1343            ))),
1344            status => {
1345                let reason = match granted {
1346                    Some(g) if !g.error_description.is_empty() => &g.error_description,
1347                    Some(g) if !g.error.is_empty() => &g.error,
1348                    _ => "not a token response",
1349                };
1350                Err(self.failed(format_args!("the STS answered HTTP {status}: {reason}")))
1351            }
1352        }
1353    }
1354}
1355
1356#[cfg(not(target_arch = "wasm32"))]
1357impl fmt::Debug for Impersonated {
1358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1359        f.debug_struct("Impersonated")
1360            .field("service_account", &self.service_account)
1361            .field("base", &self.base)
1362            .field("endpoint", &self.endpoint)
1363            .finish_non_exhaustive()
1364    }
1365}
1366
1367#[cfg(not(target_arch = "wasm32"))]
1368impl Credentials for Impersonated {
1369    fn token(&self) -> TokenFuture<'_> {
1370        Box::pin(async move {
1371            let mut cache = self.cache.lock().await;
1372            if let Some(token) = cache.valid_for(IMPERSONATED_EXPIRY_MARGIN) {
1373                return Ok(token);
1374            }
1375            if !secure_endpoint(&self.endpoint) {
1376                return Err(self.failed(format_args!(
1377                    "the STS endpoint {:?} is not an https URL",
1378                    self.endpoint
1379                )));
1380            }
1381            let subject_token = self.base.token().await?;
1382            let granted = self.exchange(&subject_token).await?;
1383            *cache = Cached {
1384                token: granted.access_token.clone(),
1385                expiry: Some(granted.expiry()),
1386            };
1387            Ok(granted.access_token)
1388        })
1389    }
1390}
1391
1392/// ` in VARIABLE`, naming where a given job token came from, if anywhere.
1393#[cfg(not(target_arch = "wasm32"))]
1394fn in_variable(variable: Option<&str>) -> String {
1395    variable.map_or_else(String::new, |name| format!(" in {name}"))
1396}
1397
1398/// When a job token (a JWT) expires, as its unverified `exp` claim says:
1399/// `None` when it has none, or isn't a JWT whose claims can be read, which
1400/// is left to the STS to judge.
1401#[cfg(not(target_arch = "wasm32"))]
1402fn job_token_expiry(token: &str) -> Option<SystemTime> {
1403    use base64::Engine as _;
1404    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
1405
1406    const BASE64URL: GeneralPurpose = GeneralPurpose::new(
1407        &base64::alphabet::URL_SAFE,
1408        GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
1409    );
1410    let payload = token.split('.').nth(1)?;
1411    let claims: JobTokenClaims = serde_json::from_slice(&BASE64URL.decode(payload).ok()?).ok()?;
1412    let exp = claims.exp?;
1413    if !exp.is_finite() || exp < 0.0 {
1414        return None;
1415    }
1416    SystemTime::UNIX_EPOCH.checked_add(Duration::try_from_secs_f64(exp).ok()?)
1417}
1418
1419/// Where the CLI stores its session: under `XDG_DATA_HOME`, or
1420/// `~/.local/share`, on every platform.
1421#[cfg(not(target_arch = "wasm32"))]
1422fn cli_session_path(env: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
1423    let base = match env("XDG_DATA_HOME").filter(|v| !v.is_empty()) {
1424        Some(base) => PathBuf::from(base),
1425        None => home_dir(env)?.join(".local").join("share"),
1426    };
1427    Some(base.join("origincloud").join("session.json"))
1428}
1429
1430#[cfg(not(target_arch = "wasm32"))]
1431fn home_dir(env: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
1432    let name = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
1433    env(name).filter(|v| !v.is_empty()).map(PathBuf::from)
1434}
1435
1436/// One access token, replaced once it is about to expire.
1437#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1438#[derive(Default)]
1439struct Cached {
1440    token: String,
1441    expiry: Option<SystemTime>,
1442}
1443
1444#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1445impl Cached {
1446    #[cfg(not(target_arch = "wasm32"))]
1447    fn valid(&self) -> Option<String> {
1448        self.valid_for(EXPIRY_MARGIN)
1449    }
1450
1451    /// The token, unless it expires within `margin`.
1452    fn valid_for(&self, margin: Duration) -> Option<String> {
1453        let expiry = self.expiry?;
1454        (!self.token.is_empty() && now() + margin < expiry).then(|| self.token.clone())
1455    }
1456}
1457
1458/// A token endpoint's answer.
1459#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1460#[derive(Deserialize, Default)]
1461#[serde(default)]
1462struct Granted {
1463    access_token: String,
1464    expires_in: i64,
1465    refresh_token: String,
1466    refresh_expires_in: i64,
1467    error: String,
1468    error_description: String,
1469}
1470
1471#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1472impl Granted {
1473    fn expiry(&self) -> SystemTime {
1474        now() + seconds(self.expires_in)
1475    }
1476}
1477
1478#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1479fn seconds(n: i64) -> Duration {
1480    Duration::from_secs(u64::try_from(n).unwrap_or_default())
1481}
1482
1483/// The HTTP client token requests are sent with unless the credentials
1484/// name one: one for the process, created by the first request.
1485#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1486fn default_http_client() -> Result<&'static reqwest::Client, &'static str> {
1487    static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
1488    CLIENT
1489        .get_or_init(|| {
1490            reqwest::Client::builder()
1491                .build()
1492                .map_err(|e| e.to_string())
1493        })
1494        .as_ref()
1495        .map_err(String::as_str)
1496}
1497
1498#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1499async fn request_token(
1500    http: Option<&reqwest::Client>,
1501    url: &str,
1502    form: &[(&str, &str)],
1503) -> Result<Granted, Error> {
1504    let failed = |e: &dyn fmt::Display| Error::Credentials(format!("requesting a token: {e}"));
1505    let http = match http {
1506        Some(http) => http,
1507        None => default_http_client().map_err(|e| failed(&e))?,
1508    };
1509    let response = http
1510        .post(url)
1511        .timeout(TOKEN_REQUEST_TIMEOUT)
1512        .header(reqwest::header::ACCEPT, "application/json")
1513        .form(form)
1514        .send()
1515        .await
1516        .map_err(|e| failed(&e))?;
1517    let (status, body) = read_bounded(response).await.map_err(|e| failed(&e))?;
1518    let granted: Granted = serde_json::from_slice(&body).map_err(|_| {
1519        Error::Credentials(format!(
1520            "requesting a token: HTTP {}, not a token response",
1521            status.as_u16()
1522        ))
1523    })?;
1524    if status != reqwest::StatusCode::OK || granted.access_token.is_empty() {
1525        let reason = if granted.error_description.is_empty() {
1526            &granted.error
1527        } else {
1528            &granted.error_description
1529        };
1530        return Err(Error::Credentials(format!(
1531            "the token request was refused (HTTP {}): {reason}",
1532            status.as_u16()
1533        )));
1534    }
1535    Ok(granted)
1536}
1537
1538/// A response's status and its body, up to the most of a token response
1539/// that is read.
1540#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1541async fn read_bounded(
1542    response: reqwest::Response,
1543) -> Result<(reqwest::StatusCode, Vec<u8>), reqwest::Error> {
1544    let status = response.status();
1545    let (body, _truncated) = read_capped(response, MAX_TOKEN_RESPONSE_BYTES).await?;
1546    Ok((status, body))
1547}
1548
1549/// Whether an assertion may be sent to `endpoint`: over https, or over http
1550/// to the loopback interface, as a local test server answers. An assertion
1551/// sent in the clear could be replayed until it expires.
1552#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1553fn secure_endpoint(endpoint: &str) -> bool {
1554    let Ok(url) = url::Url::parse(endpoint) else {
1555        return false;
1556    };
1557    match (url.scheme(), url.host()) {
1558        ("https", Some(_)) => true,
1559        ("http", Some(url::Host::Domain(host))) => host == "localhost",
1560        ("http", Some(url::Host::Ipv4(ip))) => ip.is_loopback(),
1561        ("http", Some(url::Host::Ipv6(ip))) => ip.is_loopback(),
1562        _ => false,
1563    }
1564}
1565
1566#[cfg(test)]
1567mod tests {
1568    use super::*;
1569    use std::collections::HashMap;
1570
1571    fn env(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
1572        let vars: HashMap<String, String> = vars
1573            .iter()
1574            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1575            .collect();
1576        move |name| vars.get(name).cloned()
1577    }
1578
1579    fn now() -> DateTime<Utc> {
1580        SystemTime::now().into()
1581    }
1582
1583    fn data_home() -> PathBuf {
1584        let dir =
1585            std::env::temp_dir().join(format!("origincloud-sdk-test-{}", uuid::Uuid::new_v4()));
1586        std::fs::create_dir_all(dir.join("origincloud")).unwrap();
1587        dir
1588    }
1589
1590    fn write_session(
1591        dir: &std::path::Path,
1592        expires: DateTime<Utc>,
1593        refresh_expires: DateTime<Utc>,
1594    ) -> PathBuf {
1595        let path = dir.join("origincloud").join("session.json");
1596        let data = serde_json::json!({
1597            "version": 1,
1598            "access_token": "stored-access",
1599            "expires": expires.to_rfc3339(),
1600            "refresh_token": "stored-refresh",
1601            "refresh_expires": refresh_expires.to_rfc3339(),
1602            "token_type": "Bearer",
1603        });
1604        std::fs::write(&path, data.to_string()).unwrap();
1605        path
1606    }
1607
1608    /// A P-256 key for the tests alone, in PKCS #8 PEM.
1609    const TEST_KEY: &str = "-----BEGIN PRIVATE KEY-----
1610MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgyHvHtkzp0fjy/hHK
1611/yt/j0yihbwhkfpFzHsrSjh6OqOhRANCAARxfaIx32RdN3JO0GPH8ght/CFjaoE3
1612ao6XiaIxhBdJ6jPPWX/9086Bti4LIfP+qzNTxPn85k7f+yGc6aQoBkr1
1613-----END PRIVATE KEY-----
1614";
1615
1616    fn credentials_file(fields: serde_json::Value) -> serde_json::Value {
1617        let mut file = serde_json::json!({
1618            "type": "service_account_key",
1619            "name": "//iam.origincloudapis.eu/organizations/o/serviceAccounts/s/keys/k",
1620            "service_account": "//iam.origincloudapis.eu/organizations/o/serviceAccounts/s",
1621            "algorithm": "ES256",
1622            "private_key": TEST_KEY,
1623            "sts_endpoint": "https://sts.origincloudapis.eu",
1624        });
1625        for (k, v) in fields.as_object().unwrap() {
1626            file[k] = v.clone();
1627        }
1628        file
1629    }
1630
1631    /// A credentials file in a directory of its own, and its path.
1632    fn write_credentials_file(file: &serde_json::Value) -> String {
1633        let path = data_home().join("credentials.json");
1634        std::fs::write(&path, file.to_string()).unwrap();
1635        path.to_str().unwrap().to_owned()
1636    }
1637
1638    #[tokio::test]
1639    async fn an_access_token_in_the_environment_comes_first() {
1640        let file = write_credentials_file(&credentials_file(serde_json::json!({})));
1641        let credentials = from_environment(&env(&[
1642            (ENV_ACCESS_TOKEN, "from-env"),
1643            (ENV_CREDENTIALS_FILE, &file),
1644        ]))
1645        .unwrap();
1646        assert_eq!(credentials.token().await.unwrap(), "from-env");
1647    }
1648
1649    #[test]
1650    fn a_credentials_file_comes_before_the_cli_session() {
1651        let dir = data_home();
1652        let hour = chrono::Duration::hours(1);
1653        write_session(&dir, now() + hour, now() + hour);
1654        let file = write_credentials_file(&credentials_file(serde_json::json!({})));
1655        let credentials = from_environment(&env(&[
1656            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1657            (ENV_CREDENTIALS_FILE, &file),
1658        ]))
1659        .unwrap();
1660        assert!(
1661            format!("{credentials:?}").starts_with("ServiceAccount"),
1662            "{credentials:?}"
1663        );
1664    }
1665
1666    const GITHUB: [(&str, &str); 2] = [
1667        (
1668            ENV_GITHUB_REQUEST_URL,
1669            "https://github.invalid/idtoken?api-version=2.0",
1670        ),
1671        (ENV_GITHUB_REQUEST_TOKEN, "github-request-token"),
1672    ];
1673
1674    fn with<'a>(
1675        base: &[(&'a str, &'a str)],
1676        more: &[(&'a str, &'a str)],
1677    ) -> Vec<(&'a str, &'a str)> {
1678        base.iter().chain(more).copied().collect()
1679    }
1680
1681    #[test]
1682    fn a_credentials_file_comes_before_a_ci_job_s_token() {
1683        let file = write_credentials_file(&credentials_file(serde_json::json!({})));
1684        let credentials = from_environment(&env(&with(
1685            &GITHUB,
1686            &[(ENV_OIDC_TOKEN, "job-token"), (ENV_CREDENTIALS_FILE, &file)],
1687        )))
1688        .unwrap();
1689        assert!(
1690            format!("{credentials:?}").starts_with("ServiceAccount"),
1691            "{credentials:?}"
1692        );
1693    }
1694
1695    #[test]
1696    fn a_ci_job_s_token_comes_before_the_cli_session() {
1697        let dir = data_home();
1698        let hour = chrono::Duration::hours(1);
1699        write_session(&dir, now() + hour, now() + hour);
1700        let credentials = from_environment(&env(&with(
1701            &GITHUB,
1702            &[("XDG_DATA_HOME", dir.to_str().unwrap())],
1703        )))
1704        .unwrap();
1705        let debug = format!("{credentials:?}");
1706        assert!(debug.starts_with("Federated"), "{debug}");
1707        assert!(debug.contains("GitHub Actions"), "{debug}");
1708        assert!(debug.contains(&format!("{STS_ENDPOINT:?}")), "{debug}");
1709        assert!(!debug.contains("github-request-token"), "{debug}");
1710        assert!(!debug.contains("github.invalid"), "{debug}");
1711    }
1712
1713    #[test]
1714    fn a_token_file_comes_before_github_actions() {
1715        let credentials = from_environment(&env(&with(
1716            &GITHUB,
1717            &[(ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token")],
1718        )))
1719        .unwrap();
1720        let debug = format!("{credentials:?}");
1721        assert!(
1722            debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1723            "{debug}"
1724        );
1725    }
1726
1727    #[test]
1728    fn a_token_in_the_environment_is_exchanged() {
1729        let credentials = from_environment(&env(&[(ENV_OIDC_TOKEN, "gitlab-job-token")])).unwrap();
1730        let debug = format!("{credentials:?}");
1731        assert!(
1732            debug.starts_with(r#"Federated { source: "token""#),
1733            "{debug}"
1734        );
1735        assert!(!debug.contains("gitlab-job-token"), "{debug}");
1736    }
1737
1738    #[test]
1739    fn a_token_file_comes_before_a_token_in_the_environment() {
1740        let credentials = from_environment(&env(&[
1741            (ENV_OIDC_TOKEN, "gitlab-job-token"),
1742            (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
1743        ]))
1744        .unwrap();
1745        let debug = format!("{credentials:?}");
1746        assert!(
1747            debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1748            "{debug}"
1749        );
1750    }
1751
1752    #[test]
1753    fn a_token_in_the_environment_comes_before_github_actions() {
1754        let credentials = from_environment(&env(&with(
1755            &GITHUB,
1756            &[(ENV_OIDC_TOKEN, "gitlab-job-token")],
1757        )))
1758        .unwrap();
1759        let debug = format!("{credentials:?}");
1760        assert!(
1761            debug.starts_with(r#"Federated { source: "token""#),
1762            "{debug}"
1763        );
1764    }
1765
1766    #[test]
1767    fn a_token_in_the_environment_is_left_out_with_the_federated_step() {
1768        let dir = data_home();
1769        let credentials = from_environment(&env(&[
1770            (ENV_OIDC_TOKEN, "gitlab-job-token"),
1771            (ENV_OIDC_DISABLED, "true"),
1772            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1773        ]))
1774        .unwrap();
1775        assert!(
1776            format!("{credentials:?}").starts_with("InstanceMetadata"),
1777            "{credentials:?}"
1778        );
1779    }
1780
1781    /// An unsigned JWT with the claims `claims`.
1782    fn jwt(claims: &str) -> String {
1783        use base64::Engine as _;
1784        let encode = |part: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(part);
1785        format!(
1786            "{}.{}.",
1787            encode(r#"{"alg":"none","typ":"JWT"}"#),
1788            encode(claims)
1789        )
1790    }
1791
1792    #[tokio::test]
1793    async fn an_expired_token_in_the_environment_names_the_variable() {
1794        let token = jwt(r#"{"sub":"project_path:group/project","exp":1577836800}"#);
1795        let credentials = from_environment(&env(&[
1796            (ENV_OIDC_TOKEN, &token),
1797            (ENV_STS_ENDPOINT, "http://127.0.0.1:9"),
1798        ]))
1799        .unwrap();
1800        let message = credentials.token().await.unwrap_err().to_string();
1801        assert!(
1802            message.contains(
1803                "the CI job's OIDC token in ORIGINCLOUD_OIDC_TOKEN expired at 2020-01-01T00:00:00Z"
1804            ),
1805            "{message}"
1806        );
1807        assert!(message.contains("ORIGINCLOUD_OIDC_TOKEN_FILE"), "{message}");
1808        assert!(!message.contains(&token), "{message}");
1809    }
1810
1811    /// The error of exchanging the token the environment `vars` holds: an
1812    /// expired one, so that nothing is sent, which names the variable it
1813    /// was read from.
1814    async fn exchange_error(vars: &[(&str, &str)]) -> String {
1815        let credentials = from_environment(&env(&with(
1816            vars,
1817            &[(ENV_STS_ENDPOINT, "http://127.0.0.1:9")],
1818        )))
1819        .unwrap();
1820        credentials.token().await.unwrap_err().to_string()
1821    }
1822
1823    fn expired() -> String {
1824        jwt(r#"{"sub":"organization:org:project:p:workspace:w:run_phase:plan","exp":1577836800}"#)
1825    }
1826
1827    #[test]
1828    fn an_hcp_terraform_token_is_exchanged() {
1829        let credentials = from_environment(&env(&[(ENV_TFC_TOKEN, "tfc-token")])).unwrap();
1830        let debug = format!("{credentials:?}");
1831        assert!(
1832            debug.starts_with(r#"Federated { source: "token""#),
1833            "{debug}"
1834        );
1835        assert!(!debug.contains("tfc-token"), "{debug}");
1836    }
1837
1838    #[tokio::test]
1839    async fn an_expired_hcp_terraform_token_names_its_variable() {
1840        let token = expired();
1841        let message = exchange_error(&[(ENV_TFC_TOKEN, &token)]).await;
1842        assert!(
1843            message.contains(
1844                "the CI job's OIDC token in TFC_WORKLOAD_IDENTITY_TOKEN expired at 2020-01-01T00:00:00Z"
1845            ),
1846            "{message}"
1847        );
1848        assert!(!message.contains(&token), "{message}");
1849    }
1850
1851    #[tokio::test]
1852    async fn a_tagged_hcp_terraform_token_is_read_by_its_tag_alone() {
1853        let token = expired();
1854        let message = exchange_error(&[
1855            (ENV_TFC_TAG, " ORIGIN "),
1856            (ENV_TFC_TOKEN, "untagged-token"),
1857            ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", &token),
1858            ("TFC_WORKLOAD_IDENTITY_TOKEN_OTHER", "other-token"),
1859        ])
1860        .await;
1861        assert!(
1862            message.contains("OIDC token in TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN expired"),
1863            "{message}"
1864        );
1865    }
1866
1867    #[tokio::test]
1868    async fn a_tag_without_its_token_fails_naming_the_variable() {
1869        for vars in [
1870            vec![(ENV_TFC_TAG, "ORIGIN"), (ENV_TFC_TOKEN, "untagged-token")],
1871            vec![
1872                (ENV_TFC_TAG, "ORIGIN"),
1873                (ENV_TFC_TOKEN, "untagged-token"),
1874                ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", ""),
1875            ],
1876        ] {
1877            let message = exchange_error(&vars).await;
1878            assert!(
1879                message.contains("in TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN is empty or not set"),
1880                "{message}"
1881            );
1882            assert!(!message.contains("untagged-token"), "{message}");
1883        }
1884    }
1885
1886    #[test]
1887    fn a_tagged_hcp_terraform_token_without_its_tag_is_left_out() {
1888        let dir = data_home();
1889        let credentials = from_environment(&env(&[
1890            ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", "tagged-token"),
1891            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1892        ]))
1893        .unwrap();
1894        assert!(
1895            format!("{credentials:?}").starts_with("InstanceMetadata"),
1896            "{credentials:?}"
1897        );
1898    }
1899
1900    #[test]
1901    fn an_hcp_terraform_token_is_left_out_with_the_federated_step() {
1902        let dir = data_home();
1903        let credentials = from_environment(&env(&[
1904            (ENV_TFC_TOKEN, "tfc-token"),
1905            (ENV_TFC_TAG, "ORIGIN"),
1906            (ENV_OIDC_DISABLED, "true"),
1907            ("XDG_DATA_HOME", dir.to_str().unwrap()),
1908        ]))
1909        .unwrap();
1910        assert!(
1911            format!("{credentials:?}").starts_with("InstanceMetadata"),
1912            "{credentials:?}"
1913        );
1914    }
1915
1916    #[test]
1917    fn an_hcp_terraform_token_comes_before_github_actions() {
1918        let credentials =
1919            from_environment(&env(&with(&GITHUB, &[(ENV_TFC_TOKEN, "tfc-token")]))).unwrap();
1920        let debug = format!("{credentials:?}");
1921        assert!(
1922            debug.starts_with(r#"Federated { source: "token""#),
1923            "{debug}"
1924        );
1925    }
1926
1927    #[test]
1928    fn an_hcp_terraform_token_comes_after_a_token_file() {
1929        let credentials = from_environment(&env(&[
1930            (ENV_TFC_TOKEN, "tfc-token"),
1931            (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
1932        ]))
1933        .unwrap();
1934        let debug = format!("{credentials:?}");
1935        assert!(
1936            debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1937            "{debug}"
1938        );
1939    }
1940
1941    #[tokio::test]
1942    async fn an_hcp_terraform_token_comes_after_a_token_in_the_environment() {
1943        let token = expired();
1944        let message =
1945            exchange_error(&[(ENV_OIDC_TOKEN, &token), (ENV_TFC_TOKEN, "tfc-token")]).await;
1946        assert!(
1947            message.contains("in ORIGINCLOUD_OIDC_TOKEN expired"),
1948            "{message}"
1949        );
1950    }
1951
1952    #[test]
1953    fn a_job_token_s_expiry_is_read_from_its_claims() {
1954        let at = |secs| Some(SystemTime::UNIX_EPOCH + Duration::from_secs(secs));
1955        assert_eq!(
1956            job_token_expiry(&jwt(r#"{"exp":1577836800}"#)),
1957            at(1577836800)
1958        );
1959        assert_eq!(
1960            job_token_expiry(&jwt(r#"{"exp":1577836800.5}"#)),
1961            at(1577836800).map(|t| t + Duration::from_millis(500))
1962        );
1963        // Padded base64url, as some issuers write it.
1964        let padded = {
1965            use base64::Engine as _;
1966            let claims = base64::engine::general_purpose::URL_SAFE.encode(r#"{"exp":12}"#);
1967            assert!(claims.ends_with("=="), "{claims}");
1968            format!("e30.{claims}.")
1969        };
1970        assert_eq!(job_token_expiry(&padded), at(12));
1971        for unreadable in [
1972            jwt(r#"{"sub":"no expiry"}"#),
1973            jwt(r#"{"exp":"tomorrow"}"#),
1974            jwt(r#"{"exp":-1}"#),
1975            jwt("not json"),
1976            "not-a-jwt".to_owned(),
1977            "a.%%%.c".to_owned(),
1978        ] {
1979            assert_eq!(job_token_expiry(&unreadable), None, "{unreadable}");
1980        }
1981    }
1982
1983    #[test]
1984    fn github_actions_needs_both_its_variables() {
1985        let dir = data_home();
1986        for half in GITHUB {
1987            let credentials =
1988                from_environment(&env(&[half, ("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
1989            assert!(
1990                format!("{credentials:?}").starts_with("InstanceMetadata"),
1991                "{credentials:?}"
1992            );
1993        }
1994    }
1995
1996    #[test]
1997    fn the_federated_step_can_be_left_out() {
1998        let dir = data_home();
1999        let credentials = from_environment(&env(&with(
2000            &GITHUB,
2001            &[
2002                (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
2003                (ENV_OIDC_DISABLED, "True"),
2004                ("XDG_DATA_HOME", dir.to_str().unwrap()),
2005            ],
2006        )))
2007        .unwrap();
2008        assert!(
2009            format!("{credentials:?}").starts_with("InstanceMetadata"),
2010            "{credentials:?}"
2011        );
2012    }
2013
2014    #[test]
2015    fn the_sts_and_the_audience_can_be_named() {
2016        let credentials = from_environment(&env(&with(
2017            &GITHUB,
2018            &[
2019                (ENV_STS_ENDPOINT, "http://127.0.0.1:8080/"),
2020                (ENV_OIDC_AUDIENCE, "https://sts.example"),
2021            ],
2022        )))
2023        .unwrap();
2024        let debug = format!("{credentials:?}");
2025        assert!(
2026            debug.contains(r#"endpoint: "http://127.0.0.1:8080", audience: "https://sts.example""#),
2027            "{debug}"
2028        );
2029    }
2030
2031    #[test]
2032    fn a_credentials_file_that_cant_be_read_is_an_error_not_passed_over() {
2033        let missing = data_home().join("missing.json");
2034        let err = from_environment(&env(&with(
2035            &GITHUB,
2036            &[(ENV_CREDENTIALS_FILE, missing.to_str().unwrap())],
2037        )))
2038        .unwrap_err();
2039        assert!(
2040            err.to_string().contains(&format!(
2041                "reading the credentials file {}",
2042                missing.display()
2043            )),
2044            "{err}"
2045        );
2046    }
2047
2048    #[test]
2049    fn a_credentials_file_is_checked_when_it_is_read() {
2050        let refused = |fields: serde_json::Value| {
2051            ServiceAccount::from_json(credentials_file(fields).to_string())
2052                .unwrap_err()
2053                .to_string()
2054        };
2055        let err = refused(serde_json::json!({"type": "authorized_user"}));
2056        assert!(err.contains(r#"its type is "authorized_user""#), "{err}");
2057        let err = refused(serde_json::json!({"algorithm": "RS256"}));
2058        assert!(err.contains(r#"its algorithm is "RS256""#), "{err}");
2059        let err = refused(serde_json::json!({"sts_endpoint": ""}));
2060        assert!(err.contains("it has no sts_endpoint"), "{err}");
2061        let err = refused(serde_json::json!({"sts_endpoint": "http://sts.example.com"}));
2062        assert!(err.contains("is not an https URL"), "{err}");
2063        let err = refused(serde_json::json!({"sts_endpoint": "sts.origincloudapis.eu"}));
2064        assert!(err.contains("is not an https URL"), "{err}");
2065        let err = refused(
2066            serde_json::json!({"private_key": "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n"}),
2067        );
2068        assert!(err.contains("not a PKCS #8 P-256 key"), "{err}");
2069        let err = ServiceAccount::from_json("not json")
2070            .unwrap_err()
2071            .to_string();
2072        assert!(
2073            err.starts_with("origincloud: reading the credentials file: "),
2074            "{err}"
2075        );
2076    }
2077
2078    #[test]
2079    fn a_service_account_s_debug_names_the_key_but_shows_no_private_key() {
2080        let account =
2081            ServiceAccount::from_json(credentials_file(serde_json::json!({})).to_string()).unwrap();
2082        let debug = format!("{account:?}");
2083        assert!(
2084            debug.contains(
2085                r#"key: "//iam.origincloudapis.eu/organizations/o/serviceAccounts/s/keys/k""#
2086            ),
2087            "{debug}"
2088        );
2089        assert!(
2090            !debug.contains("PRIVATE KEY") && !debug.contains("MIGHAgEA"),
2091            "{debug}"
2092        );
2093    }
2094
2095    #[test]
2096    fn without_others_the_metadata_service_comes_last() {
2097        let dir = data_home();
2098        let credentials =
2099            from_environment(&env(&[("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
2100        assert!(
2101            format!("{credentials:?}").starts_with("InstanceMetadata"),
2102            "{credentials:?}"
2103        );
2104    }
2105
2106    #[test]
2107    fn the_metadata_service_s_address_can_be_named() {
2108        let dir = data_home();
2109        let credentials = from_environment(&env(&[
2110            ("XDG_DATA_HOME", dir.to_str().unwrap()),
2111            (ENV_METADATA_ENDPOINT, "http://127.0.0.1:8080/"),
2112        ]))
2113        .unwrap();
2114        assert!(
2115            format!("{credentials:?}").contains(r#"endpoint: "http://127.0.0.1:8080""#),
2116            "{credentials:?}"
2117        );
2118    }
2119
2120    #[test]
2121    fn no_credentials_at_all_without_the_metadata_service() {
2122        let dir = data_home();
2123        let err = from_environment(&env(&[
2124            ("XDG_DATA_HOME", dir.to_str().unwrap()),
2125            (ENV_METADATA_DISABLED, "TRUE"),
2126        ]))
2127        .unwrap_err();
2128        assert!(matches!(err, Error::NoCredentials), "{err}");
2129    }
2130
2131    #[test]
2132    fn the_session_is_found_under_the_home_directory_without_xdg_data_home() {
2133        let path = cli_session_path(&env(&[
2134            ("HOME", "/home/someone"),
2135            ("USERPROFILE", "/home/someone"),
2136        ]))
2137        .unwrap();
2138        assert_eq!(
2139            path,
2140            PathBuf::from("/home/someone/.local/share/origincloud/session.json")
2141        );
2142    }
2143
2144    #[tokio::test]
2145    async fn the_cli_session_is_used_as_stored() {
2146        let dir = data_home();
2147        write_session(
2148            &dir,
2149            now() + chrono::Duration::hours(1),
2150            now() + chrono::Duration::hours(2),
2151        );
2152        let credentials =
2153            from_environment(&env(&[("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
2154        assert_eq!(credentials.token().await.unwrap(), "stored-access");
2155    }
2156
2157    #[tokio::test]
2158    async fn a_cli_session_past_its_refresh_expiry_asks_to_log_in() {
2159        let dir = data_home();
2160        let path = write_session(
2161            &dir,
2162            now() - chrono::Duration::hours(1),
2163            now() - chrono::Duration::minutes(1),
2164        );
2165        let session = CliSession::load_from(path).unwrap().unwrap();
2166        let err = session.token().await.unwrap_err();
2167        assert!(err.to_string().contains("origin id login"), "{err}");
2168    }
2169
2170    const IMPERSONATED: &str = "//iam.origincloudapis.eu/organizations/o/serviceAccounts/deployer";
2171
2172    /// The chain's credentials for `vars`, impersonating as the builder
2173    /// would without a name of its own.
2174    fn chain_impersonating(vars: &[(&str, &str)]) -> Arc<dyn Credentials> {
2175        let env = env(vars);
2176        impersonating(from_environment(&env).unwrap(), None, &env).unwrap()
2177    }
2178
2179    #[test]
2180    fn every_step_of_the_chain_can_be_impersonated_from() {
2181        let dir = data_home();
2182        let hour = chrono::Duration::hours(1);
2183        write_session(&dir, now() + hour, now() + hour);
2184        let file = write_credentials_file(&credentials_file(serde_json::json!({})));
2185        let data_home = dir.to_str().unwrap();
2186        let impersonate = (ENV_IMPERSONATE_SERVICE_ACCOUNT, IMPERSONATED);
2187        for (vars, base) in [
2188            (vec![(ENV_ACCESS_TOKEN, "t")], "AccessToken"),
2189            (
2190                vec![(ENV_CREDENTIALS_FILE, file.as_str())],
2191                "ServiceAccount",
2192            ),
2193            (vec![(ENV_OIDC_TOKEN, "job-token")], "Federated"),
2194            (vec![("XDG_DATA_HOME", data_home)], "CliSession"),
2195            (
2196                vec![(ENV_METADATA_ENDPOINT, "http://127.0.0.1:1")],
2197                "InstanceMetadata",
2198            ),
2199        ] {
2200            let credentials = chain_impersonating(&with(&vars, &[impersonate]));
2201            let debug = format!("{credentials:?}");
2202            assert!(debug.starts_with("Impersonated"), "{debug}");
2203            assert!(debug.contains(IMPERSONATED), "{debug}");
2204            assert!(debug.contains(&format!("base: {base}")), "{debug}");
2205            assert!(debug.contains(&format!("{STS_ENDPOINT:?}")), "{debug}");
2206        }
2207    }
2208
2209    #[test]
2210    fn without_the_variable_no_one_is_impersonated() {
2211        for value in ["", "  "] {
2212            let credentials = chain_impersonating(&[
2213                (ENV_ACCESS_TOKEN, "t"),
2214                (ENV_IMPERSONATE_SERVICE_ACCOUNT, value),
2215            ]);
2216            assert!(format!("{credentials:?}").starts_with("AccessToken"));
2217        }
2218    }
2219
2220    #[test]
2221    fn the_builder_s_name_overrides_the_variable() {
2222        let env = env(&[
2223            (ENV_ACCESS_TOKEN, "t"),
2224            (ENV_IMPERSONATE_SERVICE_ACCOUNT, "not a name"),
2225        ]);
2226        let base = || from_environment(&env).unwrap();
2227        let chosen = impersonating(base(), Some(IMPERSONATED.to_owned()), &env).unwrap();
2228        assert!(format!("{chosen:?}").contains(IMPERSONATED));
2229        let off = impersonating(base(), Some(String::new()), &env).unwrap();
2230        assert!(format!("{off:?}").starts_with("AccessToken"));
2231        let refused = impersonating(base(), None, &env).unwrap_err();
2232        assert!(matches!(refused, Error::Config(_)), "{refused:?}");
2233        assert!(refused.to_string().contains("not a name"), "{refused}");
2234    }
2235
2236    /// A person logged in with `origin id login` acts as the account: the
2237    /// CLI session's token is what the STS gets, at the address
2238    /// `ORIGINCLOUD_STS_ENDPOINT` names.
2239    #[tokio::test]
2240    async fn a_person_s_cli_login_is_exchanged_for_the_account_s_token() {
2241        let form = Arc::new(std::sync::Mutex::new(Vec::new()));
2242        let seen = Arc::clone(&form);
2243        let sts = fake_server::FakeServer::start(move |r| {
2244            *seen.lock().unwrap() = fake_server::Received {
2245                query: r.text(),
2246                ..r
2247            }
2248            .query_pairs();
2249            async {
2250                fake_server::Response::json(
2251                    serde_json::json!({"access_token": "account-token", "expires_in": 300})
2252                        .to_string(),
2253                )
2254            }
2255        })
2256        .await;
2257        let dir = data_home();
2258        let hour = chrono::Duration::hours(1);
2259        write_session(&dir, now() + hour, now() + hour);
2260        let credentials = chain_impersonating(&[
2261            ("XDG_DATA_HOME", dir.to_str().unwrap()),
2262            (ENV_IMPERSONATE_SERVICE_ACCOUNT, IMPERSONATED),
2263            (ENV_STS_ENDPOINT, &sts.url()),
2264            (ENV_METADATA_DISABLED, "true"),
2265        ]);
2266
2267        assert_eq!(credentials.token().await.unwrap(), "account-token");
2268        let form = form.lock().unwrap();
2269        let field = |name: &str| {
2270            form.iter()
2271                .find(|(k, _)| k == name)
2272                .map(|(_, v)| v.as_str())
2273        };
2274        assert_eq!(field("subject_token"), Some("stored-access"));
2275        assert_eq!(field("service_account"), Some(IMPERSONATED));
2276    }
2277}