1use 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
35pub 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#[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
71pub const STS_ENDPOINT: &str = "https://sts.origincloudapis.eu";
75
76pub const OIDC_AUDIENCE: &str = "https://sts.origincloudapis.eu";
78
79#[cfg(not(target_arch = "wasm32"))]
81const FEDERATED_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
82
83#[cfg(not(target_arch = "wasm32"))]
86const STS_RETRY_DELAYS: [Duration; 2] = [Duration::from_millis(200), Duration::from_millis(400)];
87
88#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
90const CREDENTIALS_FILE_TYPE: &str = "service_account_key";
91
92#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
94const ASSERTION_ALGORITHM: &str = "ES256";
95
96#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
99const ASSERTION_LIFETIME: Duration = Duration::from_secs(5 * 60);
100
101#[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
113pub const METADATA_ENDPOINT: &str = "http://169.254.169.254";
116
117#[cfg(not(target_arch = "wasm32"))]
119const METADATA_SESSION_TTL: Duration = Duration::from_secs(6 * 60 * 60);
120#[cfg(not(target_arch = "wasm32"))]
121const METADATA_SESSION_TTL_HEADER: &str = "x-origincloud-metadata-token-ttl-seconds";
122#[cfg(not(target_arch = "wasm32"))]
123const METADATA_SESSION_HEADER: &str = "x-origincloud-metadata-token";
124
125#[cfg(not(target_arch = "wasm32"))]
128const METADATA_CONNECT_TIMEOUT: Duration = Duration::from_secs(1);
129#[cfg(not(target_arch = "wasm32"))]
130const METADATA_SESSION_TIMEOUT: Duration = Duration::from_secs(2);
131
132#[cfg(not(target_arch = "wasm32"))]
134const METADATA_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
135
136#[cfg(not(target_arch = "wasm32"))]
139const METADATA_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
140
141#[cfg(not(target_arch = "wasm32"))]
144const METADATA_RETRY_DELAYS: [Duration; 2] =
145 [Duration::from_millis(100), Duration::from_millis(200)];
146
147#[cfg(not(target_arch = "wasm32"))]
149const CLI_CLIENT_ID: &str = "origin-cli";
150
151#[cfg(not(target_arch = "wasm32"))]
154const EXPIRY_MARGIN: Duration = Duration::from_secs(30);
155
156#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
158const MAX_TOKEN_RESPONSE_BYTES: usize = 1 << 20;
159
160#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
162const TOKEN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
163
164pub type TokenFuture<'a> = MaybeSendFuture<'a, Result<String, Error>>;
167
168pub trait Credentials: Send + Sync + fmt::Debug {
173 fn token(&self) -> TokenFuture<'_>;
175}
176
177#[cfg(not(target_arch = "wasm32"))]
208pub fn default_credentials() -> Result<Arc<dyn Credentials>, Error> {
209 from_environment(&|name| std::env::var(name).ok())
210}
211
212#[cfg(not(target_arch = "wasm32"))]
214pub(crate) fn from_environment(
215 env: &dyn Fn(&str) -> Option<String>,
216) -> Result<Arc<dyn Credentials>, Error> {
217 let var = |name: &str| env(name).filter(|v| !v.is_empty());
218 if let Some(token) = var(ENV_ACCESS_TOKEN) {
219 return Ok(Arc::new(AccessToken::new(token)));
220 }
221 if let Some(path) = var(ENV_CREDENTIALS_FILE) {
222 return Ok(Arc::new(ServiceAccount::from_file(path)?));
223 }
224 if let Some(federated) = federated_from(&var) {
225 return Ok(Arc::new(federated));
226 }
227 if let Some(path) = cli_session_path(env)
228 && let Some(session) = CliSession::load_from(path)?
229 {
230 return Ok(Arc::new(session));
231 }
232 if var(ENV_METADATA_DISABLED).is_some_and(|v| v.eq_ignore_ascii_case("true")) {
233 return Err(Error::NoCredentials);
234 }
235 let metadata = InstanceMetadata::new();
236 Ok(Arc::new(match var(ENV_METADATA_ENDPOINT) {
237 Some(endpoint) => metadata.with_endpoint(endpoint),
238 None => metadata,
239 }))
240}
241
242#[cfg(target_arch = "wasm32")]
246pub(crate) fn from_environment(
247 _env: &dyn Fn(&str) -> Option<String>,
248) -> Result<Arc<dyn Credentials>, Error> {
249 Err(Error::NoCredentials)
250}
251
252#[cfg(not(target_arch = "wasm32"))]
257fn federated_from(var: &dyn Fn(&str) -> Option<String>) -> Option<Federated> {
258 if var(ENV_OIDC_DISABLED).is_some_and(|v| v.eq_ignore_ascii_case("true")) {
259 return None;
260 }
261 let mut federated = if let Some(path) = var(ENV_OIDC_TOKEN_FILE) {
262 Federated::from_file(path)
263 } else if let Some(token) = var(ENV_OIDC_TOKEN) {
264 Federated::with_source(JobToken::Given {
265 token,
266 variable: Some(ENV_OIDC_TOKEN.to_owned()),
267 })
268 } else if let Some(variable) = tfc_token_variable(var) {
269 Federated::with_source(JobToken::Given {
270 token: var(&variable).unwrap_or_default(),
271 variable: Some(variable),
272 })
273 } else if let (Some(url), Some(token)) =
274 (var(ENV_GITHUB_REQUEST_URL), var(ENV_GITHUB_REQUEST_TOKEN))
275 {
276 Federated::github_actions(url, token)
277 } else {
278 return None;
279 };
280 if let Some(endpoint) = var(ENV_STS_ENDPOINT) {
281 federated = federated.with_endpoint(endpoint);
282 }
283 if let Some(audience) = var(ENV_OIDC_AUDIENCE) {
284 federated = federated.with_audience(audience);
285 }
286 Some(federated)
287}
288
289#[cfg(not(target_arch = "wasm32"))]
294fn tfc_token_variable(var: &dyn Fn(&str) -> Option<String>) -> Option<String> {
295 match var(ENV_TFC_TAG).map(|tag| tag.trim().to_owned()) {
296 Some(tag) if !tag.is_empty() => Some(format!("{ENV_TFC_TOKEN}_{tag}")),
297 _ => var(ENV_TFC_TOKEN).map(|_| ENV_TFC_TOKEN.to_owned()),
298 }
299}
300
301#[derive(Clone)]
304pub struct AccessToken(String);
305
306impl AccessToken {
307 pub fn new(token: impl Into<String>) -> Self {
309 Self(token.into())
310 }
311}
312
313impl fmt::Debug for AccessToken {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 f.write_str("AccessToken(..)")
316 }
317}
318
319impl Credentials for AccessToken {
320 fn token(&self) -> TokenFuture<'_> {
321 Box::pin(async move { Ok(self.0.clone()) })
322 }
323}
324
325#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
329#[derive(Deserialize)]
330struct CredentialsFile {
331 #[serde(rename = "type", default)]
332 kind: String,
333 #[serde(default)]
334 name: String,
335 #[serde(default)]
336 service_account: String,
337 #[serde(default)]
338 algorithm: String,
339 #[serde(default)]
340 private_key: String,
341 #[serde(default)]
342 sts_endpoint: String,
343}
344
345#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
357pub struct ServiceAccount {
358 key: String,
359 service_account: String,
360 signing_key: p256::ecdsa::SigningKey,
361 sts_endpoint: String,
362 http: Option<reqwest::Client>,
363 cache: Mutex<Cached>,
364}
365
366#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
367impl ServiceAccount {
368 #[cfg(not(target_arch = "wasm32"))]
370 pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, Error> {
371 let path = path.as_ref();
372 let data = std::fs::read(path).map_err(|e| {
373 Error::Credentials(format!(
374 "reading the credentials file {}: {e}",
375 path.display()
376 ))
377 })?;
378 Self::parse(&data).map_err(|reason| {
379 Error::Credentials(format!(
380 "reading the credentials file {}: {reason}",
381 path.display()
382 ))
383 })
384 }
385
386 pub fn from_json(json: impl AsRef<[u8]>) -> Result<Self, Error> {
389 Self::parse(json.as_ref())
390 .map_err(|reason| Error::Credentials(format!("reading the credentials file: {reason}")))
391 }
392
393 fn parse(json: &[u8]) -> Result<Self, String> {
394 use p256::pkcs8::DecodePrivateKey as _;
395
396 let file: CredentialsFile = serde_json::from_slice(json).map_err(|e| e.to_string())?;
398 if file.kind != CREDENTIALS_FILE_TYPE {
399 return Err(format!(
400 "its type is {:?}, not {CREDENTIALS_FILE_TYPE:?}",
401 file.kind
402 ));
403 }
404 if file.algorithm != ASSERTION_ALGORITHM {
405 return Err(format!(
406 "its algorithm is {:?}; this SDK signs with {ASSERTION_ALGORITHM}",
407 file.algorithm
408 ));
409 }
410 for (field, value) in [
411 ("name", &file.name),
412 ("service_account", &file.service_account),
413 ("private_key", &file.private_key),
414 ("sts_endpoint", &file.sts_endpoint),
415 ] {
416 if value.is_empty() {
417 return Err(format!("it has no {field}"));
418 }
419 }
420 if !secure_endpoint(&file.sts_endpoint) {
421 return Err(format!(
422 "its sts_endpoint {:?} is not an https URL",
423 file.sts_endpoint
424 ));
425 }
426 let signing_key = p256::ecdsa::SigningKey::from_pkcs8_pem(&file.private_key)
427 .map_err(|_| "its private_key is not a PKCS #8 P-256 key in PEM".to_owned())?;
428 Ok(Self {
429 key: file.name,
430 service_account: file.service_account,
431 signing_key,
432 sts_endpoint: file.sts_endpoint,
433 http: None,
434 cache: Mutex::default(),
435 })
436 }
437
438 pub fn service_account(&self) -> &str {
440 &self.service_account
441 }
442
443 pub fn key(&self) -> &str {
445 &self.key
446 }
447
448 pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
451 self.http = Some(http);
452 self
453 }
454
455 fn assertion(&self) -> String {
458 use base64::Engine as _;
459 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
460 use p256::ecdsa::signature::Signer as _;
461
462 let issued = now()
463 .duration_since(SystemTime::UNIX_EPOCH)
464 .unwrap_or_default()
465 .as_secs();
466 let header = serde_json::json!({
467 "alg": ASSERTION_ALGORITHM,
468 "typ": "JWT",
469 "kid": self.key,
470 });
471 let claims = serde_json::json!({
472 "iss": self.service_account,
473 "sub": self.service_account,
474 "aud": self.sts_endpoint,
475 "iat": issued,
476 "exp": issued + ASSERTION_LIFETIME.as_secs(),
477 "jti": uuid::Uuid::new_v4().to_string(),
478 });
479 let signed = format!(
480 "{}.{}",
481 URL_SAFE_NO_PAD.encode(header.to_string()),
482 URL_SAFE_NO_PAD.encode(claims.to_string())
483 );
484 let signature: p256::ecdsa::Signature = self.signing_key.sign(signed.as_bytes());
485 format!("{signed}.{}", URL_SAFE_NO_PAD.encode(signature.to_bytes()))
486 }
487}
488
489#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
490impl fmt::Debug for ServiceAccount {
491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492 f.debug_struct("ServiceAccount")
493 .field("service_account", &self.service_account)
494 .field("key", &self.key)
495 .field("sts_endpoint", &self.sts_endpoint)
496 .finish_non_exhaustive()
497 }
498}
499
500#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
501impl Credentials for ServiceAccount {
502 fn token(&self) -> TokenFuture<'_> {
503 Box::pin(async move {
504 let mut cache = self.cache.lock().await;
505 if let Some(token) = cache.valid_for(SERVICE_ACCOUNT_EXPIRY_MARGIN) {
506 return Ok(token);
507 }
508 let assertion = self.assertion();
509 let granted = request_token(
510 self.http.as_ref(),
511 &format!("{}/v1/token", self.sts_endpoint.trim_end_matches('/')),
512 &[("grant_type", JWT_BEARER_GRANT), ("assertion", &assertion)],
513 )
514 .await
515 .map_err(|e| match e {
516 Error::Credentials(message) => Error::Credentials(format!(
517 "exchanging an assertion of the service account key {}: {message}",
518 self.key
519 )),
520 other => other,
521 })?;
522 *cache = Cached {
523 token: granted.access_token.clone(),
524 expiry: Some(granted.expiry()),
525 };
526 Ok(granted.access_token)
527 })
528 }
529}
530
531#[cfg(not(target_arch = "wasm32"))]
535pub struct CliSession {
536 token_url: String,
537 http: Option<reqwest::Client>,
538 state: Mutex<SessionState>,
539}
540
541#[cfg(not(target_arch = "wasm32"))]
542struct SessionState {
543 cached: Cached,
544 refresh_token: String,
545 refresh_expiry: Option<SystemTime>,
546}
547
548#[cfg(not(target_arch = "wasm32"))]
550#[derive(Deserialize)]
551struct StoredSession {
552 #[serde(default)]
553 access_token: String,
554 #[serde(default)]
555 expires: Option<DateTime<Utc>>,
556 #[serde(default)]
557 refresh_token: String,
558 #[serde(default)]
559 refresh_expires: Option<DateTime<Utc>>,
560}
561
562#[cfg(not(target_arch = "wasm32"))]
563impl CliSession {
564 pub fn load() -> Result<Option<Self>, Error> {
568 match cli_session_path(&|name| std::env::var(name).ok()) {
569 Some(path) => Self::load_from(path),
570 None => Ok(None),
571 }
572 }
573
574 pub fn load_from(path: impl Into<PathBuf>) -> Result<Option<Self>, Error> {
576 let path = path.into();
577 let data = match std::fs::read(&path) {
578 Ok(data) => data,
579 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
580 Err(e) => return Err(Error::Credentials(format!("reading the CLI session: {e}"))),
581 };
582 let stored: StoredSession = serde_json::from_slice(&data).map_err(|e| {
583 Error::Credentials(format!("reading the CLI session {}: {e}", path.display()))
584 })?;
585 Ok(Some(Self {
586 token_url: TOKEN_URL.to_owned(),
587 http: None,
588 state: Mutex::new(SessionState {
589 cached: Cached {
590 token: stored.access_token,
591 expiry: stored.expires.map(SystemTime::from),
592 },
593 refresh_token: stored.refresh_token,
594 refresh_expiry: stored.refresh_expires.map(SystemTime::from),
595 }),
596 }))
597 }
598
599 pub fn with_token_url(mut self, url: impl Into<String>) -> Self {
601 self.token_url = url.into();
602 self
603 }
604
605 pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
608 self.http = Some(http);
609 self
610 }
611}
612
613#[cfg(not(target_arch = "wasm32"))]
614impl fmt::Debug for CliSession {
615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616 f.debug_struct("CliSession")
617 .field("token_url", &self.token_url)
618 .finish_non_exhaustive()
619 }
620}
621
622#[cfg(not(target_arch = "wasm32"))]
623impl Credentials for CliSession {
624 fn token(&self) -> TokenFuture<'_> {
625 Box::pin(async move {
626 let mut state = self.state.lock().await;
627 if let Some(token) = state.cached.valid() {
628 return Ok(token);
629 }
630 if state
631 .refresh_expiry
632 .is_none_or(|expiry| SystemTime::now() >= expiry)
633 {
634 return Err(Error::Credentials(
635 "the CLI session has expired: log in again with `origin id login`".to_owned(),
636 ));
637 }
638 let refresh_token = state.refresh_token.clone();
639 let granted = request_token(
640 self.http.as_ref(),
641 &self.token_url,
642 &[
643 ("grant_type", "refresh_token"),
644 ("client_id", CLI_CLIENT_ID),
645 ("refresh_token", &refresh_token),
646 ],
647 )
648 .await
649 .map_err(|e| match e {
650 Error::Credentials(message) => {
651 Error::Credentials(format!("renewing the CLI session: {message}"))
652 }
653 other => other,
654 })?;
655 if !granted.refresh_token.is_empty() {
656 state.refresh_token = granted.refresh_token.clone();
657 state.refresh_expiry =
658 Some(SystemTime::now() + seconds(granted.refresh_expires_in));
659 }
660 state.cached = Cached {
661 token: granted.access_token.clone(),
662 expiry: Some(granted.expiry()),
663 };
664 Ok(granted.access_token)
665 })
666 }
667}
668
669#[cfg(not(target_arch = "wasm32"))]
676pub struct InstanceMetadata {
677 endpoint: String,
678 http: Option<reqwest::Client>,
679 state: Mutex<MetadataState>,
680}
681
682#[cfg(not(target_arch = "wasm32"))]
683#[derive(Default)]
684struct MetadataState {
685 session: Cached,
686 cached: Cached,
687}
688
689#[cfg(not(target_arch = "wasm32"))]
691#[derive(Deserialize)]
692struct Issued {
693 access_token: String,
694 expires_at: DateTime<Utc>,
695}
696
697#[cfg(not(target_arch = "wasm32"))]
698impl InstanceMetadata {
699 pub fn new() -> Self {
701 Self {
702 endpoint: METADATA_ENDPOINT.to_owned(),
703 http: None,
704 state: Mutex::default(),
705 }
706 }
707
708 pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
710 self.endpoint = url.into().trim_end_matches('/').to_owned();
711 self
712 }
713
714 pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
719 self.http = Some(http);
720 self
721 }
722
723 fn http(&self) -> Result<&reqwest::Client, Error> {
724 static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
725 if let Some(http) = &self.http {
726 return Ok(http);
727 }
728 CLIENT
729 .get_or_init(|| {
730 reqwest::Client::builder()
731 .no_proxy()
732 .connect_timeout(METADATA_CONNECT_TIMEOUT)
733 .build()
734 .map_err(|e| e.to_string())
735 })
736 .as_ref()
737 .map_err(|e| Error::Credentials(format!("reaching the metadata service: {e}")))
738 }
739
740 async fn open_session(&self) -> Result<String, Error> {
745 let request = self
746 .http()?
747 .put(format!("{}/latest/api/token", self.endpoint))
748 .timeout(METADATA_SESSION_TIMEOUT)
749 .header(
750 METADATA_SESSION_TTL_HEADER,
751 METADATA_SESSION_TTL.as_secs().to_string(),
752 );
753 let (status, body) = send_retrying(request, &METADATA_RETRY_DELAYS)
754 .await
755 .map_err(|_| Error::NoCredentials)?;
756 match status.as_u16() {
757 200 => Ok(String::from_utf8_lossy(&body).trim().to_owned()),
758 403 => Err(refused_through_a_proxy()),
759 503 => Err(Error::Credentials(
760 "the metadata service refused a session (HTTP 503)".to_owned(),
761 )),
762 _ => Err(Error::NoCredentials),
763 }
764 }
765
766 async fn request_credential(&self, session: &str) -> Result<Option<Issued>, Error> {
768 let failed =
769 |e: reqwest::Error| Error::Credentials(format!("reaching the metadata service: {e}"));
770 let request = self
771 .http()?
772 .get(format!(
773 "{}/latest/meta-data/service-account/token",
774 self.endpoint
775 ))
776 .timeout(METADATA_REQUEST_TIMEOUT)
777 .header(METADATA_SESSION_HEADER, session)
778 .header(reqwest::header::ACCEPT, "application/json");
779 let (status, body) = send_retrying(request, &METADATA_RETRY_DELAYS)
780 .await
781 .map_err(failed)?;
782 match status.as_u16() {
783 200 => {}
784 401 => return Ok(None),
785 404 => {
786 return Err(Error::Credentials(
787 "the instance runs as no service account".to_owned(),
788 ));
789 }
790 403 => return Err(refused_through_a_proxy()),
791 status => {
792 return Err(Error::Credentials(format!(
793 "the metadata service answered HTTP {status}"
794 )));
795 }
796 }
797 match serde_json::from_slice::<Issued>(&body) {
798 Ok(issued) if !issued.access_token.is_empty() => Ok(Some(issued)),
799 _ => Err(Error::Credentials(
800 "the metadata service's answer is not a credential".to_owned(),
801 )),
802 }
803 }
804}
805
806#[cfg(not(target_arch = "wasm32"))]
809async fn send_retrying(
810 request: reqwest::RequestBuilder,
811 delays: &[Duration],
812) -> Result<(reqwest::StatusCode, Vec<u8>), reqwest::Error> {
813 let mut delays = delays.iter();
814 loop {
815 let attempt = request
816 .try_clone()
817 .expect("a credential request has no streamed body");
818 let answer = read_bounded(attempt.send().await?).await?;
819 match delays.next() {
820 Some(delay) if answer.0 == reqwest::StatusCode::SERVICE_UNAVAILABLE => {
821 tokio::time::sleep(*delay).await;
822 }
823 _ => return Ok(answer),
824 }
825 }
826}
827
828#[cfg(not(target_arch = "wasm32"))]
829fn refused_through_a_proxy() -> Error {
830 Error::Credentials(
831 "the metadata service refused a request that came through a proxy".to_owned(),
832 )
833}
834
835#[cfg(not(target_arch = "wasm32"))]
836impl Default for InstanceMetadata {
837 fn default() -> Self {
838 Self::new()
839 }
840}
841
842#[cfg(not(target_arch = "wasm32"))]
843impl fmt::Debug for InstanceMetadata {
844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845 f.debug_struct("InstanceMetadata")
846 .field("endpoint", &self.endpoint)
847 .finish_non_exhaustive()
848 }
849}
850
851#[cfg(not(target_arch = "wasm32"))]
852impl Credentials for InstanceMetadata {
853 fn token(&self) -> TokenFuture<'_> {
854 Box::pin(async move {
855 let mut state = self.state.lock().await;
856 if let Some(token) = state.cached.valid_for(METADATA_EXPIRY_MARGIN) {
857 return Ok(token);
858 }
859 for _ in 0..2 {
861 let session = match state.session.valid() {
862 Some(session) => session,
863 None => {
864 let session = self.open_session().await?;
865 state.session = Cached {
866 token: session.clone(),
867 expiry: Some(SystemTime::now() + METADATA_SESSION_TTL),
868 };
869 session
870 }
871 };
872 match self.request_credential(&session).await? {
873 Some(issued) => {
874 state.cached = Cached {
875 token: issued.access_token.clone(),
876 expiry: Some(issued.expires_at.into()),
877 };
878 return Ok(issued.access_token);
879 }
880 None => state.session = Cached::default(),
881 }
882 }
883 Err(Error::Credentials(
884 "the metadata service answered HTTP 401".to_owned(),
885 ))
886 })
887 }
888}
889
890#[cfg(not(target_arch = "wasm32"))]
897pub struct Federated {
898 source: JobToken,
899 endpoint: String,
900 audience: String,
901 http: Option<reqwest::Client>,
902 cache: Mutex<Cached>,
903}
904
905#[cfg(not(target_arch = "wasm32"))]
907enum JobToken {
908 File(PathBuf),
909 Given {
912 token: String,
913 variable: Option<String>,
914 },
915 GitHubActions {
916 request_url: String,
917 request_token: String,
918 },
919}
920
921#[cfg(not(target_arch = "wasm32"))]
923#[derive(Deserialize)]
924struct JobTokenClaims {
925 exp: Option<f64>,
926}
927
928#[cfg(not(target_arch = "wasm32"))]
930#[derive(Deserialize)]
931struct GitHubToken {
932 value: String,
933}
934
935#[cfg(not(target_arch = "wasm32"))]
936impl Federated {
937 pub fn from_file(path: impl Into<PathBuf>) -> Self {
941 Self::with_source(JobToken::File(path.into()))
942 }
943
944 pub fn from_token(token: impl Into<String>) -> Self {
950 Self::with_source(JobToken::Given {
951 token: token.into(),
952 variable: None,
953 })
954 }
955
956 pub fn github_actions(
961 request_url: impl Into<String>,
962 request_token: impl Into<String>,
963 ) -> Self {
964 Self::with_source(JobToken::GitHubActions {
965 request_url: request_url.into(),
966 request_token: request_token.into(),
967 })
968 }
969
970 fn with_source(source: JobToken) -> Self {
971 Self {
972 source,
973 endpoint: STS_ENDPOINT.to_owned(),
974 audience: OIDC_AUDIENCE.to_owned(),
975 http: None,
976 cache: Mutex::default(),
977 }
978 }
979
980 pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
982 self.endpoint = url.into().trim_end_matches('/').to_owned();
983 self
984 }
985
986 pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
990 self.audience = audience.into();
991 self
992 }
993
994 pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
997 self.http = Some(http);
998 self
999 }
1000
1001 fn http(&self) -> Result<&reqwest::Client, Error> {
1002 match &self.http {
1003 Some(http) => Ok(http),
1004 None => default_http_client()
1005 .map_err(|e| Error::Credentials(format!("exchanging the CI job's token: {e}"))),
1006 }
1007 }
1008
1009 async fn job_token(&self, http: &reqwest::Client) -> Result<String, Error> {
1011 match &self.source {
1012 JobToken::File(path) => {
1013 let read = std::fs::read_to_string(path).map_err(|e| {
1014 Error::Credentials(format!(
1015 "reading the OIDC token file {}: {e}",
1016 path.display()
1017 ))
1018 })?;
1019 let token = read.trim();
1020 if token.is_empty() {
1021 return Err(Error::Credentials(format!(
1022 "the OIDC token file {} is empty",
1023 path.display()
1024 )));
1025 }
1026 Ok(token.to_owned())
1027 }
1028 JobToken::Given { token, variable } => {
1029 let token = token.trim();
1030 if token.is_empty() {
1031 return Err(Error::Credentials(format!(
1032 "the CI job's OIDC token{} is empty{}",
1033 in_variable(variable.as_deref()),
1034 if variable.is_some() {
1035 " or not set"
1036 } else {
1037 ""
1038 }
1039 )));
1040 }
1041 if let Some(expiry) = job_token_expiry(token)
1042 && expiry <= SystemTime::now()
1043 {
1044 let expiry = DateTime::<Utc>::from(expiry)
1045 .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
1046 return Err(Error::Credentials(format!(
1047 "the CI job's OIDC token{} expired at {expiry}; a token given as it is \
1048 can't be renewed: ask the CI provider for a longer-lived one, or use \
1049 {ENV_OIDC_TOKEN_FILE}",
1050 in_variable(variable.as_deref())
1051 )));
1052 }
1053 Ok(token.to_owned())
1054 }
1055 JobToken::GitHubActions {
1056 request_url,
1057 request_token,
1058 } => {
1059 let failed = |reason: &dyn fmt::Display| {
1060 Error::Credentials(format!(
1061 "requesting the GitHub Actions job's OIDC token: {reason}; \
1062 the workflow needs `permissions: id-token: write`"
1063 ))
1064 };
1065 let separator = if request_url.contains('?') { '&' } else { '?' };
1066 let audience: String =
1067 url::form_urlencoded::byte_serialize(self.audience.as_bytes()).collect();
1068 let response = http
1069 .get(format!("{request_url}{separator}audience={audience}"))
1070 .timeout(TOKEN_REQUEST_TIMEOUT)
1071 .header(
1072 reqwest::header::AUTHORIZATION,
1073 format!("bearer {request_token}"),
1074 )
1075 .header(reqwest::header::ACCEPT, "application/json")
1076 .send()
1077 .await
1078 .map_err(|e| failed(&e))?;
1079 let (status, body) = read_bounded(response).await.map_err(|e| failed(&e))?;
1080 if status != reqwest::StatusCode::OK {
1081 return Err(failed(&format_args!("HTTP {}", status.as_u16())));
1082 }
1083 match serde_json::from_slice::<GitHubToken>(&body) {
1084 Ok(token) if !token.value.is_empty() => Ok(token.value),
1085 _ => Err(Error::Credentials(
1086 "requesting the GitHub Actions job's OIDC token: the answer holds no token"
1087 .to_owned(),
1088 )),
1089 }
1090 }
1091 }
1092 }
1093
1094 async fn exchange(&self, http: &reqwest::Client, job_token: &str) -> Result<Granted, Error> {
1096 let request = http
1097 .post(format!("{}/v1/token", self.endpoint))
1098 .timeout(TOKEN_REQUEST_TIMEOUT)
1099 .header(reqwest::header::ACCEPT, "application/json")
1100 .form(&[
1101 ("grant_type", TOKEN_EXCHANGE_GRANT),
1102 ("subject_token", job_token),
1103 ("subject_token_type", JWT_TOKEN_TYPE),
1104 ]);
1105 let (status, body) = send_retrying(request, &STS_RETRY_DELAYS)
1106 .await
1107 .map_err(|e| Error::Credentials(format!("exchanging the CI job's token: {e}")))?;
1108 let parsed = serde_json::from_slice::<Granted>(&body);
1109 let granted = parsed.as_ref().ok();
1110 let error = granted.map_or("", |g| g.error.as_str());
1111 match status.as_u16() {
1112 200 => match parsed {
1113 Ok(granted) if !granted.access_token.is_empty() => Ok(granted),
1114 _ => Err(Error::Credentials(
1115 "exchanging the CI job's token: the STS's answer is not a token response"
1116 .to_owned(),
1117 )),
1118 },
1119 503 => Err(Error::Credentials(
1120 "exchanging the CI job's token: the STS can't check it right now \
1121 (HTTP 503, 3 attempts); try again later"
1122 .to_owned(),
1123 )),
1124 _ if error == "invalid_grant" => Err(Error::Credentials(
1125 "the STS refused the CI job's token (invalid_grant): check the federated \
1126 credential's issuer, audience and conditions against the token's claims"
1127 .to_owned(),
1128 )),
1129 status => {
1130 let reason = match granted {
1131 Some(g) if !g.error_description.is_empty() => &g.error_description,
1132 Some(g) if !g.error.is_empty() => &g.error,
1133 _ => "not a token response",
1134 };
1135 Err(Error::Credentials(format!(
1136 "exchanging the CI job's token: the STS answered HTTP {status}: {reason}"
1137 )))
1138 }
1139 }
1140 }
1141}
1142
1143#[cfg(not(target_arch = "wasm32"))]
1144impl fmt::Debug for Federated {
1145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1146 let mut debug = f.debug_struct("Federated");
1147 match &self.source {
1148 JobToken::File(path) => debug.field("token_file", path),
1149 JobToken::Given { .. } => debug.field("source", &"token"),
1150 JobToken::GitHubActions { .. } => debug.field("source", &"GitHub Actions"),
1151 };
1152 debug
1153 .field("endpoint", &self.endpoint)
1154 .field("audience", &self.audience)
1155 .finish_non_exhaustive()
1156 }
1157}
1158
1159#[cfg(not(target_arch = "wasm32"))]
1160impl Credentials for Federated {
1161 fn token(&self) -> TokenFuture<'_> {
1162 Box::pin(async move {
1163 let mut cache = self.cache.lock().await;
1164 if let Some(token) = cache.valid_for(FEDERATED_EXPIRY_MARGIN) {
1165 return Ok(token);
1166 }
1167 let http = self.http()?;
1168 let job_token = self.job_token(http).await?;
1169 let granted = self.exchange(http, &job_token).await?;
1170 *cache = Cached {
1171 token: granted.access_token.clone(),
1172 expiry: Some(granted.expiry()),
1173 };
1174 Ok(granted.access_token)
1175 })
1176 }
1177}
1178
1179#[cfg(not(target_arch = "wasm32"))]
1181fn in_variable(variable: Option<&str>) -> String {
1182 variable.map_or_else(String::new, |name| format!(" in {name}"))
1183}
1184
1185#[cfg(not(target_arch = "wasm32"))]
1189fn job_token_expiry(token: &str) -> Option<SystemTime> {
1190 use base64::Engine as _;
1191 use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
1192
1193 const BASE64URL: GeneralPurpose = GeneralPurpose::new(
1194 &base64::alphabet::URL_SAFE,
1195 GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
1196 );
1197 let payload = token.split('.').nth(1)?;
1198 let claims: JobTokenClaims = serde_json::from_slice(&BASE64URL.decode(payload).ok()?).ok()?;
1199 let exp = claims.exp?;
1200 if !exp.is_finite() || exp < 0.0 {
1201 return None;
1202 }
1203 SystemTime::UNIX_EPOCH.checked_add(Duration::try_from_secs_f64(exp).ok()?)
1204}
1205
1206#[cfg(not(target_arch = "wasm32"))]
1209fn cli_session_path(env: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
1210 let base = match env("XDG_DATA_HOME").filter(|v| !v.is_empty()) {
1211 Some(base) => PathBuf::from(base),
1212 None => home_dir(env)?.join(".local").join("share"),
1213 };
1214 Some(base.join("origincloud").join("session.json"))
1215}
1216
1217#[cfg(not(target_arch = "wasm32"))]
1218fn home_dir(env: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
1219 let name = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
1220 env(name).filter(|v| !v.is_empty()).map(PathBuf::from)
1221}
1222
1223#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1225#[derive(Default)]
1226struct Cached {
1227 token: String,
1228 expiry: Option<SystemTime>,
1229}
1230
1231#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1232impl Cached {
1233 #[cfg(not(target_arch = "wasm32"))]
1234 fn valid(&self) -> Option<String> {
1235 self.valid_for(EXPIRY_MARGIN)
1236 }
1237
1238 fn valid_for(&self, margin: Duration) -> Option<String> {
1240 let expiry = self.expiry?;
1241 (!self.token.is_empty() && now() + margin < expiry).then(|| self.token.clone())
1242 }
1243}
1244
1245#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1247#[derive(Deserialize, Default)]
1248#[serde(default)]
1249struct Granted {
1250 access_token: String,
1251 expires_in: i64,
1252 refresh_token: String,
1253 refresh_expires_in: i64,
1254 error: String,
1255 error_description: String,
1256}
1257
1258#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1259impl Granted {
1260 fn expiry(&self) -> SystemTime {
1261 now() + seconds(self.expires_in)
1262 }
1263}
1264
1265#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1266fn seconds(n: i64) -> Duration {
1267 Duration::from_secs(u64::try_from(n).unwrap_or_default())
1268}
1269
1270#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1273fn default_http_client() -> Result<&'static reqwest::Client, &'static str> {
1274 static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
1275 CLIENT
1276 .get_or_init(|| {
1277 reqwest::Client::builder()
1278 .build()
1279 .map_err(|e| e.to_string())
1280 })
1281 .as_ref()
1282 .map_err(String::as_str)
1283}
1284
1285#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1286async fn request_token(
1287 http: Option<&reqwest::Client>,
1288 url: &str,
1289 form: &[(&str, &str)],
1290) -> Result<Granted, Error> {
1291 let failed = |e: &dyn fmt::Display| Error::Credentials(format!("requesting a token: {e}"));
1292 let http = match http {
1293 Some(http) => http,
1294 None => default_http_client().map_err(|e| failed(&e))?,
1295 };
1296 let response = http
1297 .post(url)
1298 .timeout(TOKEN_REQUEST_TIMEOUT)
1299 .header(reqwest::header::ACCEPT, "application/json")
1300 .form(form)
1301 .send()
1302 .await
1303 .map_err(|e| failed(&e))?;
1304 let (status, body) = read_bounded(response).await.map_err(|e| failed(&e))?;
1305 let granted: Granted = serde_json::from_slice(&body).map_err(|_| {
1306 Error::Credentials(format!(
1307 "requesting a token: HTTP {}, not a token response",
1308 status.as_u16()
1309 ))
1310 })?;
1311 if status != reqwest::StatusCode::OK || granted.access_token.is_empty() {
1312 let reason = if granted.error_description.is_empty() {
1313 &granted.error
1314 } else {
1315 &granted.error_description
1316 };
1317 return Err(Error::Credentials(format!(
1318 "the token request was refused (HTTP {}): {reason}",
1319 status.as_u16()
1320 )));
1321 }
1322 Ok(granted)
1323}
1324
1325#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1328async fn read_bounded(
1329 response: reqwest::Response,
1330) -> Result<(reqwest::StatusCode, Vec<u8>), reqwest::Error> {
1331 let status = response.status();
1332 let (body, _truncated) = read_capped(response, MAX_TOKEN_RESPONSE_BYTES).await?;
1333 Ok((status, body))
1334}
1335
1336#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
1340fn secure_endpoint(endpoint: &str) -> bool {
1341 let Ok(url) = url::Url::parse(endpoint) else {
1342 return false;
1343 };
1344 match (url.scheme(), url.host()) {
1345 ("https", Some(_)) => true,
1346 ("http", Some(url::Host::Domain(host))) => host == "localhost",
1347 ("http", Some(url::Host::Ipv4(ip))) => ip.is_loopback(),
1348 ("http", Some(url::Host::Ipv6(ip))) => ip.is_loopback(),
1349 _ => false,
1350 }
1351}
1352
1353#[cfg(test)]
1354mod tests {
1355 use super::*;
1356 use std::collections::HashMap;
1357
1358 fn env(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
1359 let vars: HashMap<String, String> = vars
1360 .iter()
1361 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1362 .collect();
1363 move |name| vars.get(name).cloned()
1364 }
1365
1366 fn now() -> DateTime<Utc> {
1367 SystemTime::now().into()
1368 }
1369
1370 fn data_home() -> PathBuf {
1371 let dir =
1372 std::env::temp_dir().join(format!("origincloud-sdk-test-{}", uuid::Uuid::new_v4()));
1373 std::fs::create_dir_all(dir.join("origincloud")).unwrap();
1374 dir
1375 }
1376
1377 fn write_session(
1378 dir: &std::path::Path,
1379 expires: DateTime<Utc>,
1380 refresh_expires: DateTime<Utc>,
1381 ) -> PathBuf {
1382 let path = dir.join("origincloud").join("session.json");
1383 let data = serde_json::json!({
1384 "version": 1,
1385 "access_token": "stored-access",
1386 "expires": expires.to_rfc3339(),
1387 "refresh_token": "stored-refresh",
1388 "refresh_expires": refresh_expires.to_rfc3339(),
1389 "token_type": "Bearer",
1390 });
1391 std::fs::write(&path, data.to_string()).unwrap();
1392 path
1393 }
1394
1395 const TEST_KEY: &str = "-----BEGIN PRIVATE KEY-----
1397MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgyHvHtkzp0fjy/hHK
1398/yt/j0yihbwhkfpFzHsrSjh6OqOhRANCAARxfaIx32RdN3JO0GPH8ght/CFjaoE3
1399ao6XiaIxhBdJ6jPPWX/9086Bti4LIfP+qzNTxPn85k7f+yGc6aQoBkr1
1400-----END PRIVATE KEY-----
1401";
1402
1403 fn credentials_file(fields: serde_json::Value) -> serde_json::Value {
1404 let mut file = serde_json::json!({
1405 "type": "service_account_key",
1406 "name": "//iam.origincloudapis.eu/organizations/o/serviceAccounts/s/keys/k",
1407 "service_account": "//iam.origincloudapis.eu/organizations/o/serviceAccounts/s",
1408 "algorithm": "ES256",
1409 "private_key": TEST_KEY,
1410 "sts_endpoint": "https://sts.origincloudapis.eu",
1411 });
1412 for (k, v) in fields.as_object().unwrap() {
1413 file[k] = v.clone();
1414 }
1415 file
1416 }
1417
1418 fn write_credentials_file(file: &serde_json::Value) -> String {
1420 let path = data_home().join("credentials.json");
1421 std::fs::write(&path, file.to_string()).unwrap();
1422 path.to_str().unwrap().to_owned()
1423 }
1424
1425 #[tokio::test]
1426 async fn an_access_token_in_the_environment_comes_first() {
1427 let file = write_credentials_file(&credentials_file(serde_json::json!({})));
1428 let credentials = from_environment(&env(&[
1429 (ENV_ACCESS_TOKEN, "from-env"),
1430 (ENV_CREDENTIALS_FILE, &file),
1431 ]))
1432 .unwrap();
1433 assert_eq!(credentials.token().await.unwrap(), "from-env");
1434 }
1435
1436 #[test]
1437 fn a_credentials_file_comes_before_the_cli_session() {
1438 let dir = data_home();
1439 let hour = chrono::Duration::hours(1);
1440 write_session(&dir, now() + hour, now() + hour);
1441 let file = write_credentials_file(&credentials_file(serde_json::json!({})));
1442 let credentials = from_environment(&env(&[
1443 ("XDG_DATA_HOME", dir.to_str().unwrap()),
1444 (ENV_CREDENTIALS_FILE, &file),
1445 ]))
1446 .unwrap();
1447 assert!(
1448 format!("{credentials:?}").starts_with("ServiceAccount"),
1449 "{credentials:?}"
1450 );
1451 }
1452
1453 const GITHUB: [(&str, &str); 2] = [
1454 (
1455 ENV_GITHUB_REQUEST_URL,
1456 "https://github.invalid/idtoken?api-version=2.0",
1457 ),
1458 (ENV_GITHUB_REQUEST_TOKEN, "github-request-token"),
1459 ];
1460
1461 fn with<'a>(
1462 base: &[(&'a str, &'a str)],
1463 more: &[(&'a str, &'a str)],
1464 ) -> Vec<(&'a str, &'a str)> {
1465 base.iter().chain(more).copied().collect()
1466 }
1467
1468 #[test]
1469 fn a_credentials_file_comes_before_a_ci_job_s_token() {
1470 let file = write_credentials_file(&credentials_file(serde_json::json!({})));
1471 let credentials = from_environment(&env(&with(
1472 &GITHUB,
1473 &[(ENV_OIDC_TOKEN, "job-token"), (ENV_CREDENTIALS_FILE, &file)],
1474 )))
1475 .unwrap();
1476 assert!(
1477 format!("{credentials:?}").starts_with("ServiceAccount"),
1478 "{credentials:?}"
1479 );
1480 }
1481
1482 #[test]
1483 fn a_ci_job_s_token_comes_before_the_cli_session() {
1484 let dir = data_home();
1485 let hour = chrono::Duration::hours(1);
1486 write_session(&dir, now() + hour, now() + hour);
1487 let credentials = from_environment(&env(&with(
1488 &GITHUB,
1489 &[("XDG_DATA_HOME", dir.to_str().unwrap())],
1490 )))
1491 .unwrap();
1492 let debug = format!("{credentials:?}");
1493 assert!(debug.starts_with("Federated"), "{debug}");
1494 assert!(debug.contains("GitHub Actions"), "{debug}");
1495 assert!(debug.contains(&format!("{STS_ENDPOINT:?}")), "{debug}");
1496 assert!(!debug.contains("github-request-token"), "{debug}");
1497 assert!(!debug.contains("github.invalid"), "{debug}");
1498 }
1499
1500 #[test]
1501 fn a_token_file_comes_before_github_actions() {
1502 let credentials = from_environment(&env(&with(
1503 &GITHUB,
1504 &[(ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token")],
1505 )))
1506 .unwrap();
1507 let debug = format!("{credentials:?}");
1508 assert!(
1509 debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1510 "{debug}"
1511 );
1512 }
1513
1514 #[test]
1515 fn a_token_in_the_environment_is_exchanged() {
1516 let credentials = from_environment(&env(&[(ENV_OIDC_TOKEN, "gitlab-job-token")])).unwrap();
1517 let debug = format!("{credentials:?}");
1518 assert!(
1519 debug.starts_with(r#"Federated { source: "token""#),
1520 "{debug}"
1521 );
1522 assert!(!debug.contains("gitlab-job-token"), "{debug}");
1523 }
1524
1525 #[test]
1526 fn a_token_file_comes_before_a_token_in_the_environment() {
1527 let credentials = from_environment(&env(&[
1528 (ENV_OIDC_TOKEN, "gitlab-job-token"),
1529 (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
1530 ]))
1531 .unwrap();
1532 let debug = format!("{credentials:?}");
1533 assert!(
1534 debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1535 "{debug}"
1536 );
1537 }
1538
1539 #[test]
1540 fn a_token_in_the_environment_comes_before_github_actions() {
1541 let credentials = from_environment(&env(&with(
1542 &GITHUB,
1543 &[(ENV_OIDC_TOKEN, "gitlab-job-token")],
1544 )))
1545 .unwrap();
1546 let debug = format!("{credentials:?}");
1547 assert!(
1548 debug.starts_with(r#"Federated { source: "token""#),
1549 "{debug}"
1550 );
1551 }
1552
1553 #[test]
1554 fn a_token_in_the_environment_is_left_out_with_the_federated_step() {
1555 let dir = data_home();
1556 let credentials = from_environment(&env(&[
1557 (ENV_OIDC_TOKEN, "gitlab-job-token"),
1558 (ENV_OIDC_DISABLED, "true"),
1559 ("XDG_DATA_HOME", dir.to_str().unwrap()),
1560 ]))
1561 .unwrap();
1562 assert!(
1563 format!("{credentials:?}").starts_with("InstanceMetadata"),
1564 "{credentials:?}"
1565 );
1566 }
1567
1568 fn jwt(claims: &str) -> String {
1570 use base64::Engine as _;
1571 let encode = |part: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(part);
1572 format!(
1573 "{}.{}.",
1574 encode(r#"{"alg":"none","typ":"JWT"}"#),
1575 encode(claims)
1576 )
1577 }
1578
1579 #[tokio::test]
1580 async fn an_expired_token_in_the_environment_names_the_variable() {
1581 let token = jwt(r#"{"sub":"project_path:group/project","exp":1577836800}"#);
1582 let credentials = from_environment(&env(&[
1583 (ENV_OIDC_TOKEN, &token),
1584 (ENV_STS_ENDPOINT, "http://127.0.0.1:9"),
1585 ]))
1586 .unwrap();
1587 let message = credentials.token().await.unwrap_err().to_string();
1588 assert!(
1589 message.contains(
1590 "the CI job's OIDC token in ORIGINCLOUD_OIDC_TOKEN expired at 2020-01-01T00:00:00Z"
1591 ),
1592 "{message}"
1593 );
1594 assert!(message.contains("ORIGINCLOUD_OIDC_TOKEN_FILE"), "{message}");
1595 assert!(!message.contains(&token), "{message}");
1596 }
1597
1598 async fn exchange_error(vars: &[(&str, &str)]) -> String {
1602 let credentials = from_environment(&env(&with(
1603 vars,
1604 &[(ENV_STS_ENDPOINT, "http://127.0.0.1:9")],
1605 )))
1606 .unwrap();
1607 credentials.token().await.unwrap_err().to_string()
1608 }
1609
1610 fn expired() -> String {
1611 jwt(r#"{"sub":"organization:org:project:p:workspace:w:run_phase:plan","exp":1577836800}"#)
1612 }
1613
1614 #[test]
1615 fn an_hcp_terraform_token_is_exchanged() {
1616 let credentials = from_environment(&env(&[(ENV_TFC_TOKEN, "tfc-token")])).unwrap();
1617 let debug = format!("{credentials:?}");
1618 assert!(
1619 debug.starts_with(r#"Federated { source: "token""#),
1620 "{debug}"
1621 );
1622 assert!(!debug.contains("tfc-token"), "{debug}");
1623 }
1624
1625 #[tokio::test]
1626 async fn an_expired_hcp_terraform_token_names_its_variable() {
1627 let token = expired();
1628 let message = exchange_error(&[(ENV_TFC_TOKEN, &token)]).await;
1629 assert!(
1630 message.contains(
1631 "the CI job's OIDC token in TFC_WORKLOAD_IDENTITY_TOKEN expired at 2020-01-01T00:00:00Z"
1632 ),
1633 "{message}"
1634 );
1635 assert!(!message.contains(&token), "{message}");
1636 }
1637
1638 #[tokio::test]
1639 async fn a_tagged_hcp_terraform_token_is_read_by_its_tag_alone() {
1640 let token = expired();
1641 let message = exchange_error(&[
1642 (ENV_TFC_TAG, " ORIGIN "),
1643 (ENV_TFC_TOKEN, "untagged-token"),
1644 ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", &token),
1645 ("TFC_WORKLOAD_IDENTITY_TOKEN_OTHER", "other-token"),
1646 ])
1647 .await;
1648 assert!(
1649 message.contains("OIDC token in TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN expired"),
1650 "{message}"
1651 );
1652 }
1653
1654 #[tokio::test]
1655 async fn a_tag_without_its_token_fails_naming_the_variable() {
1656 for vars in [
1657 vec![(ENV_TFC_TAG, "ORIGIN"), (ENV_TFC_TOKEN, "untagged-token")],
1658 vec![
1659 (ENV_TFC_TAG, "ORIGIN"),
1660 (ENV_TFC_TOKEN, "untagged-token"),
1661 ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", ""),
1662 ],
1663 ] {
1664 let message = exchange_error(&vars).await;
1665 assert!(
1666 message.contains("in TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN is empty or not set"),
1667 "{message}"
1668 );
1669 assert!(!message.contains("untagged-token"), "{message}");
1670 }
1671 }
1672
1673 #[test]
1674 fn a_tagged_hcp_terraform_token_without_its_tag_is_left_out() {
1675 let dir = data_home();
1676 let credentials = from_environment(&env(&[
1677 ("TFC_WORKLOAD_IDENTITY_TOKEN_ORIGIN", "tagged-token"),
1678 ("XDG_DATA_HOME", dir.to_str().unwrap()),
1679 ]))
1680 .unwrap();
1681 assert!(
1682 format!("{credentials:?}").starts_with("InstanceMetadata"),
1683 "{credentials:?}"
1684 );
1685 }
1686
1687 #[test]
1688 fn an_hcp_terraform_token_is_left_out_with_the_federated_step() {
1689 let dir = data_home();
1690 let credentials = from_environment(&env(&[
1691 (ENV_TFC_TOKEN, "tfc-token"),
1692 (ENV_TFC_TAG, "ORIGIN"),
1693 (ENV_OIDC_DISABLED, "true"),
1694 ("XDG_DATA_HOME", dir.to_str().unwrap()),
1695 ]))
1696 .unwrap();
1697 assert!(
1698 format!("{credentials:?}").starts_with("InstanceMetadata"),
1699 "{credentials:?}"
1700 );
1701 }
1702
1703 #[test]
1704 fn an_hcp_terraform_token_comes_before_github_actions() {
1705 let credentials =
1706 from_environment(&env(&with(&GITHUB, &[(ENV_TFC_TOKEN, "tfc-token")]))).unwrap();
1707 let debug = format!("{credentials:?}");
1708 assert!(
1709 debug.starts_with(r#"Federated { source: "token""#),
1710 "{debug}"
1711 );
1712 }
1713
1714 #[test]
1715 fn an_hcp_terraform_token_comes_after_a_token_file() {
1716 let credentials = from_environment(&env(&[
1717 (ENV_TFC_TOKEN, "tfc-token"),
1718 (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
1719 ]))
1720 .unwrap();
1721 let debug = format!("{credentials:?}");
1722 assert!(
1723 debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
1724 "{debug}"
1725 );
1726 }
1727
1728 #[tokio::test]
1729 async fn an_hcp_terraform_token_comes_after_a_token_in_the_environment() {
1730 let token = expired();
1731 let message =
1732 exchange_error(&[(ENV_OIDC_TOKEN, &token), (ENV_TFC_TOKEN, "tfc-token")]).await;
1733 assert!(
1734 message.contains("in ORIGINCLOUD_OIDC_TOKEN expired"),
1735 "{message}"
1736 );
1737 }
1738
1739 #[test]
1740 fn a_job_token_s_expiry_is_read_from_its_claims() {
1741 let at = |secs| Some(SystemTime::UNIX_EPOCH + Duration::from_secs(secs));
1742 assert_eq!(
1743 job_token_expiry(&jwt(r#"{"exp":1577836800}"#)),
1744 at(1577836800)
1745 );
1746 assert_eq!(
1747 job_token_expiry(&jwt(r#"{"exp":1577836800.5}"#)),
1748 at(1577836800).map(|t| t + Duration::from_millis(500))
1749 );
1750 let padded = {
1752 use base64::Engine as _;
1753 let claims = base64::engine::general_purpose::URL_SAFE.encode(r#"{"exp":12}"#);
1754 assert!(claims.ends_with("=="), "{claims}");
1755 format!("e30.{claims}.")
1756 };
1757 assert_eq!(job_token_expiry(&padded), at(12));
1758 for unreadable in [
1759 jwt(r#"{"sub":"no expiry"}"#),
1760 jwt(r#"{"exp":"tomorrow"}"#),
1761 jwt(r#"{"exp":-1}"#),
1762 jwt("not json"),
1763 "not-a-jwt".to_owned(),
1764 "a.%%%.c".to_owned(),
1765 ] {
1766 assert_eq!(job_token_expiry(&unreadable), None, "{unreadable}");
1767 }
1768 }
1769
1770 #[test]
1771 fn github_actions_needs_both_its_variables() {
1772 let dir = data_home();
1773 for half in GITHUB {
1774 let credentials =
1775 from_environment(&env(&[half, ("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
1776 assert!(
1777 format!("{credentials:?}").starts_with("InstanceMetadata"),
1778 "{credentials:?}"
1779 );
1780 }
1781 }
1782
1783 #[test]
1784 fn the_federated_step_can_be_left_out() {
1785 let dir = data_home();
1786 let credentials = from_environment(&env(&with(
1787 &GITHUB,
1788 &[
1789 (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
1790 (ENV_OIDC_DISABLED, "True"),
1791 ("XDG_DATA_HOME", dir.to_str().unwrap()),
1792 ],
1793 )))
1794 .unwrap();
1795 assert!(
1796 format!("{credentials:?}").starts_with("InstanceMetadata"),
1797 "{credentials:?}"
1798 );
1799 }
1800
1801 #[test]
1802 fn the_sts_and_the_audience_can_be_named() {
1803 let credentials = from_environment(&env(&with(
1804 &GITHUB,
1805 &[
1806 (ENV_STS_ENDPOINT, "http://127.0.0.1:8080/"),
1807 (ENV_OIDC_AUDIENCE, "https://sts.example"),
1808 ],
1809 )))
1810 .unwrap();
1811 let debug = format!("{credentials:?}");
1812 assert!(
1813 debug.contains(r#"endpoint: "http://127.0.0.1:8080", audience: "https://sts.example""#),
1814 "{debug}"
1815 );
1816 }
1817
1818 #[test]
1819 fn a_credentials_file_that_cant_be_read_is_an_error_not_passed_over() {
1820 let missing = data_home().join("missing.json");
1821 let err = from_environment(&env(&with(
1822 &GITHUB,
1823 &[(ENV_CREDENTIALS_FILE, missing.to_str().unwrap())],
1824 )))
1825 .unwrap_err();
1826 assert!(
1827 err.to_string().contains(&format!(
1828 "reading the credentials file {}",
1829 missing.display()
1830 )),
1831 "{err}"
1832 );
1833 }
1834
1835 #[test]
1836 fn a_credentials_file_is_checked_when_it_is_read() {
1837 let refused = |fields: serde_json::Value| {
1838 ServiceAccount::from_json(credentials_file(fields).to_string())
1839 .unwrap_err()
1840 .to_string()
1841 };
1842 let err = refused(serde_json::json!({"type": "authorized_user"}));
1843 assert!(err.contains(r#"its type is "authorized_user""#), "{err}");
1844 let err = refused(serde_json::json!({"algorithm": "RS256"}));
1845 assert!(err.contains(r#"its algorithm is "RS256""#), "{err}");
1846 let err = refused(serde_json::json!({"sts_endpoint": ""}));
1847 assert!(err.contains("it has no sts_endpoint"), "{err}");
1848 let err = refused(serde_json::json!({"sts_endpoint": "http://sts.example.com"}));
1849 assert!(err.contains("is not an https URL"), "{err}");
1850 let err = refused(serde_json::json!({"sts_endpoint": "sts.origincloudapis.eu"}));
1851 assert!(err.contains("is not an https URL"), "{err}");
1852 let err = refused(
1853 serde_json::json!({"private_key": "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n"}),
1854 );
1855 assert!(err.contains("not a PKCS #8 P-256 key"), "{err}");
1856 let err = ServiceAccount::from_json("not json")
1857 .unwrap_err()
1858 .to_string();
1859 assert!(
1860 err.starts_with("origincloud: reading the credentials file: "),
1861 "{err}"
1862 );
1863 }
1864
1865 #[test]
1866 fn a_service_account_s_debug_names_the_key_but_shows_no_private_key() {
1867 let account =
1868 ServiceAccount::from_json(credentials_file(serde_json::json!({})).to_string()).unwrap();
1869 let debug = format!("{account:?}");
1870 assert!(
1871 debug.contains(
1872 r#"key: "//iam.origincloudapis.eu/organizations/o/serviceAccounts/s/keys/k""#
1873 ),
1874 "{debug}"
1875 );
1876 assert!(
1877 !debug.contains("PRIVATE KEY") && !debug.contains("MIGHAgEA"),
1878 "{debug}"
1879 );
1880 }
1881
1882 #[test]
1883 fn without_others_the_metadata_service_comes_last() {
1884 let dir = data_home();
1885 let credentials =
1886 from_environment(&env(&[("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
1887 assert!(
1888 format!("{credentials:?}").starts_with("InstanceMetadata"),
1889 "{credentials:?}"
1890 );
1891 }
1892
1893 #[test]
1894 fn the_metadata_service_s_address_can_be_named() {
1895 let dir = data_home();
1896 let credentials = from_environment(&env(&[
1897 ("XDG_DATA_HOME", dir.to_str().unwrap()),
1898 (ENV_METADATA_ENDPOINT, "http://127.0.0.1:8080/"),
1899 ]))
1900 .unwrap();
1901 assert!(
1902 format!("{credentials:?}").contains(r#"endpoint: "http://127.0.0.1:8080""#),
1903 "{credentials:?}"
1904 );
1905 }
1906
1907 #[test]
1908 fn no_credentials_at_all_without_the_metadata_service() {
1909 let dir = data_home();
1910 let err = from_environment(&env(&[
1911 ("XDG_DATA_HOME", dir.to_str().unwrap()),
1912 (ENV_METADATA_DISABLED, "TRUE"),
1913 ]))
1914 .unwrap_err();
1915 assert!(matches!(err, Error::NoCredentials), "{err}");
1916 }
1917
1918 #[test]
1919 fn the_session_is_found_under_the_home_directory_without_xdg_data_home() {
1920 let path = cli_session_path(&env(&[
1921 ("HOME", "/home/someone"),
1922 ("USERPROFILE", "/home/someone"),
1923 ]))
1924 .unwrap();
1925 assert_eq!(
1926 path,
1927 PathBuf::from("/home/someone/.local/share/origincloud/session.json")
1928 );
1929 }
1930
1931 #[tokio::test]
1932 async fn the_cli_session_is_used_as_stored() {
1933 let dir = data_home();
1934 write_session(
1935 &dir,
1936 now() + chrono::Duration::hours(1),
1937 now() + chrono::Duration::hours(2),
1938 );
1939 let credentials =
1940 from_environment(&env(&[("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
1941 assert_eq!(credentials.token().await.unwrap(), "stored-access");
1942 }
1943
1944 #[tokio::test]
1945 async fn a_cli_session_past_its_refresh_expiry_asks_to_log_in() {
1946 let dir = data_home();
1947 let path = write_session(
1948 &dir,
1949 now() - chrono::Duration::hours(1),
1950 now() - chrono::Duration::minutes(1),
1951 );
1952 let session = CliSession::load_from(path).unwrap().unwrap();
1953 let err = session.token().await.unwrap_err();
1954 assert!(err.to_string().contains("origin id login"), "{err}");
1955 }
1956}