diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index 9a676fab..d0df524b 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -358,11 +358,17 @@ contact the network. IMDSv2 region fallback requires explicit opt-in and applies a deadline to the complete metadata-token and region exchange. Exposed endpoint settings remain the caller's responsibility to interpret. +Google's well-known ADC provider honors the `CLOUDSDK_CONFIG` directory from +`Context`. A missing file yields no credential. Other read or parsing errors +are returned to direct callers. The Google default provider chain logs provider +errors and proceeds to the next slot. + Google ADC impersonation files use the canonical OAuth token endpoint for authorized-user and service-account source exchanges. The trusted credential file supplies the target IAM Credentials URL. An external-account source uses -its configured endpoints and subject token source, including the requirement -to set `GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES=1` in the `Context` environment +its configured endpoints and subject token source. OAuth client authentication +from the file is sent to its configured STS endpoint. Executable sources +require `GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES=1` in the `Context` environment before reading an executable's cached output or running the command. GitHub credential discovery reads `GH_TOKEN` before `GITHUB_TOKEN`. When the diff --git a/services/google/README.md b/services/google/README.md index 0a369d07..2607d2c0 100644 --- a/services/google/README.md +++ b/services/google/README.md @@ -98,12 +98,32 @@ the context, then the credential's quota project metadata. Credential files can also supply `universe_domain` metadata. VM universe discovery is opt-in through `VmMetadataCredentialProvider::with_universe_domain_discovery`. +## ADC discovery and federation + +`WellKnownCredentialProvider` looks for `application_default_credentials.json` +in the directory named by a nonempty `CLOUDSDK_CONFIG`. Otherwise it uses the +`gcloud` subdirectory of the first directory set by `APPDATA`, +`XDG_CONFIG_HOME`, or `HOME` (under `.config`). Direct calls return `Ok(None)` +when the path is unavailable or the file reader reports `NotFound`. Other +read, parsing, and exchange errors are returned to the caller. The default +chain logs provider errors and continues to the next source. + +For a workforce pool `external_account` file, `workforce_pool_user_project` +sets `userProject` in the STS `options` field. The workforce principal needs +`serviceusage.services.use` on the project. When the file supplies an OAuth +`client_id`, Reqsign uses HTTP Basic with that ID and the optional +`client_secret`, and STS determines the project from the client ID. Use trusted +external-account files, which select the STS endpoint and subject token source. +[Google's workforce token exchange guide](https://cloud.google.com/iam/docs/workforce-obtaining-short-lived-credentials) + ## ADC service-account impersonation An `impersonated_service_account` credential file accepts `authorized_user`, `service_account`, or `external_account` in `source_credentials`. Legacy `authorized_user` sources may omit `type`. List intermediate service accounts -in order in `delegates`. A nested `impersonated_service_account` source is rejected. +in order in `delegates`. An `external_account` file with its own +`service_account_impersonation_url` can also set top-level `delegates` for that +IAM request. A nested `impersonated_service_account` source is rejected. Service-account and external-account source tokens use the IAM scope. Authorized-user sources use their existing refresh grant. The configured OAuth diff --git a/services/google/src/credential.rs b/services/google/src/credential.rs index 57ef3541..b0e88b4b 100644 --- a/services/google/src/credential.rs +++ b/services/google/src/credential.rs @@ -131,7 +131,7 @@ impl Debug for ImpersonatedServiceAccount { pub(crate) enum ImpersonationSource { AuthorizedUser(OAuth2Credentials), ServiceAccount(ServiceAccount), - ExternalAccount(ExternalAccount), + ExternalAccount(Box), ImpersonatedServiceAccount, } @@ -246,6 +246,11 @@ pub struct ExternalAccount { pub service_account_impersonation_url: Option, /// Optional service account impersonation options. pub service_account_impersonation: Option, + /// Optional delegation chain for the impersonation request. + pub(crate) delegates: Option>, + pub(crate) workforce_pool_user_project: Option, + pub(crate) client_id: Option, + pub(crate) client_secret: Option, #[serde(flatten)] pub(crate) metadata: CredentialMetadata, } diff --git a/services/google/src/provide_credential/default.rs b/services/google/src/provide_credential/default.rs index 33b20af8..bfe77459 100644 --- a/services/google/src/provide_credential/default.rs +++ b/services/google/src/provide_credential/default.rs @@ -15,6 +15,10 @@ // specific language governing permissions and limitations // under the License. +use std::error::Error as _; +use std::io; +use std::path::PathBuf; + use log::debug; use reqsign_core::{Context, ProvideCredential, ProvideCredentialChain, Result}; @@ -28,7 +32,7 @@ use super::{parse::parse_credential_bytes, vm_metadata::VmMetadataCredentialProv /// /// Resolution order follows ADC (Application Default Credentials): /// 1. Env var `GOOGLE_APPLICATION_CREDENTIALS` -/// 2. Well-known location (`~/.config/gcloud/application_default_credentials.json`) +/// 2. [Well-known gcloud credentials file](WellKnownCredentialProvider) /// 3. VM metadata service (GCE / Cloud Functions / App Engine) #[derive(Debug)] pub struct DefaultCredentialProvider { @@ -108,6 +112,16 @@ impl ProvideCredential for EnvCredentialProvider { } } +/// Loads the gcloud Application Default Credentials file. +/// +/// A nonempty `CLOUDSDK_CONFIG` selects the directory that contains +/// `application_default_credentials.json`. Otherwise, the file is under +/// `gcloud` in the first available directory among `APPDATA`, `XDG_CONFIG_HOME`, +/// and `$HOME/.config`. +/// +/// This provider returns no credential when it has no path or the file reader +/// reports an I/O `NotFound` error. Other read, parsing, and exchange errors are +/// returned to direct callers. [DefaultCredentialProvider] continues on errors. #[derive(Default, Clone, Debug)] pub struct WellKnownCredentialProvider { scope: Option, @@ -129,31 +143,41 @@ impl ProvideCredential for WellKnownCredentialProvider { type Credential = Credential; async fn provide_credential(&self, ctx: &Context) -> Result> { - let config_dir = if let Some(v) = ctx.env_var("APPDATA") { - v - } else if let Some(v) = ctx.env_var("XDG_CONFIG_HOME") { - v - } else if let Some(v) = ctx.env_var("HOME") { - format!("{v}/.config") - } else { + let env_directory = |name| { + ctx.env_var(name) + .filter(|dir| !dir.is_empty()) + .map(PathBuf::from) + }; + let Some(config_dir) = env_directory("CLOUDSDK_CONFIG").or_else(|| { + env_directory("APPDATA") + .or_else(|| env_directory("XDG_CONFIG_HOME")) + .or_else(|| env_directory("HOME").map(|home| home.join(".config"))) + .map(|root| root.join("gcloud")) + }) else { return Ok(None); }; - - let path = format!("{config_dir}/gcloud/application_default_credentials.json"); + let path = config_dir.join("application_default_credentials.json"); + let path = path.to_string_lossy(); debug!("trying to load credential from well-known location: {path}"); let content = match ctx.file_read(&path).await { - Ok(v) => v, - Err(_) => return Ok(None), + Ok(content) => content, + Err(err) if is_missing_adc_file(&err) => return Ok(None), + Err(err) => return Err(err.with_context(format!("ADC file: {path}"))), }; - match parse_credential_bytes(ctx, &content, self.scope.clone()).await { - Ok(v) => Ok(v), - Err(_) => Ok(None), - } + parse_credential_bytes(ctx, &content, self.scope.clone()) + .await + .map_err(|err| err.with_context(format!("ADC file: {path}"))) } } +fn is_missing_adc_file(err: &reqsign_core::Error) -> bool { + std::iter::successors(err.source(), |&cause| cause.source()) + .filter_map(|cause| cause.downcast_ref::()) + .any(|cause| cause.kind() == io::ErrorKind::NotFound) +} + /// Builder for `DefaultCredentialProvider`. pub struct DefaultCredentialProviderBuilder { env: Option, @@ -237,9 +261,10 @@ impl DefaultCredentialProviderBuilder { mod tests { use super::*; use bytes::Bytes; - use reqsign_core::{FileRead, HttpSend, StaticEnv}; + use reqsign_core::{Error, ErrorKind, FileRead, HttpSend, StaticEnv}; use std::collections::HashMap; use std::env; + use std::path::Path; use std::sync::{Arc, Mutex}; #[derive(Clone, Debug, Default)] @@ -281,7 +306,8 @@ mod tests { async fn file_read(&self, path: &str) -> Result> { self.paths.lock().unwrap().push(path.to_string()); self.files.get(path).cloned().ok_or_else(|| { - reqsign_core::Error::config_invalid(format!("file not found: {path}")) + Error::unexpected("failed to read test file") + .with_source(io::Error::from(io::ErrorKind::NotFound)) }) } } @@ -424,6 +450,161 @@ mod tests { let _ = provider.provide_credential(&ctx).await; } + const ADC_FILENAME: &str = "application_default_credentials.json"; + const SERVICE_ACCOUNT_JSON: &[u8] = br#"{ + "type":"service_account", "client_email":"local@example.test", "private_key":"test-key" + }"#; + + #[tokio::test] + async fn adc_prefers_env_and_config_directories_in_order() -> Result<()> { + let candidates = [ + ( + GOOGLE_APPLICATION_CREDENTIALS, + "/custom.json", + PathBuf::from("/custom.json"), + ), + ( + "CLOUDSDK_CONFIG", + "/sdk/", + Path::new("/sdk/").join(ADC_FILENAME), + ), + ( + "APPDATA", + "/appdata", + Path::new("/appdata").join("gcloud").join(ADC_FILENAME), + ), + ( + "XDG_CONFIG_HOME", + "/xdg", + Path::new("/xdg").join("gcloud").join(ADC_FILENAME), + ), + ( + "HOME", + "/home", + Path::new("/home") + .join(".config") + .join("gcloud") + .join(ADC_FILENAME), + ), + ]; + for (index, (_, _, path)) in candidates.iter().enumerate() { + let expected_path = path.to_str().unwrap(); + let mut envs = candidates[index..] + .iter() + .map(|(key, value, _)| (key.to_string(), value.to_string())) + .collect::>(); + for (key, _, _) in &candidates[..index] { + envs.insert(key.to_string(), String::new()); + } + let file_read = MockFileRead::new(HashMap::from([( + expected_path.to_string(), + SERVICE_ACCOUNT_JSON.to_vec(), + )])); + let ctx = Context::new() + .with_file_read(file_read.clone()) + .with_env(StaticEnv { + home_dir: None, + envs, + }); + let credential = DefaultCredentialProvider::new() + .provide_credential(&ctx) + .await? + .expect("credential at the selected ADC path"); + assert_eq!( + credential.service_account().unwrap().client_email(), + "local@example.test" + ); + assert_eq!(file_read.paths.lock().unwrap().as_slice(), [expected_path]); + } + Ok(()) + } + + #[tokio::test] + async fn well_known_adc_distinguishes_missing_and_malformed_files() -> Result<()> { + let sdk_path = Path::new("/sdk").join(ADC_FILENAME).display().to_string(); + let home_path = Path::new("/home") + .join(".config") + .join("gcloud") + .join(ADC_FILENAME); + for malformed in [false, true] { + let mut files = HashMap::from([( + home_path.display().to_string(), + SERVICE_ACCOUNT_JSON.to_vec(), + )]); + if malformed { + files.insert( + sdk_path.clone(), + br#"{"private_key":"test-key", "type": "#.to_vec(), + ); + } + let file_read = MockFileRead::new(files); + let http = MockHttpSend::default(); + let ctx = Context::new() + .with_file_read(file_read.clone()) + .with_http_send(http.clone()) + .with_env(StaticEnv { + home_dir: None, + envs: HashMap::from([ + ("CLOUDSDK_CONFIG".into(), "/sdk".into()), + ("HOME".into(), "/home".into()), + ]), + }); + + let result = WellKnownCredentialProvider::new() + .provide_credential(&ctx) + .await; + if malformed { + let error = result.expect_err("existing malformed ADC must report its error"); + assert_eq!(error.kind(), ErrorKind::Unexpected); + assert!( + error + .to_string() + .contains("failed to parse credential file") + ); + assert!(!format!("{error:?}").contains("test-key")); + } else { + assert!(result?.is_none()); + } + assert!(http.uris.lock().unwrap().is_empty()); + + let credential = DefaultCredentialProvider::new() + .provide_credential(&ctx) + .await? + .expect("default chain must fall through to VM metadata"); + assert!(credential.has_token()); + assert_eq!( + file_read.paths.lock().unwrap().as_slice(), + [sdk_path.as_str(), sdk_path.as_str()] + ); + assert_eq!(http.uris.lock().unwrap().len(), 1); + } + Ok(()) + } + + #[tokio::test] + async fn well_known_adc_propagates_non_missing_read_errors() { + #[derive(Debug)] + struct UnreadableAdc; + + impl FileRead for UnreadableAdc { + async fn file_read(&self, _path: &str) -> Result> { + Err(io::Error::from(io::ErrorKind::PermissionDenied).into()) + } + } + + let ctx = Context::new() + .with_file_read(UnreadableAdc) + .with_env(StaticEnv { + home_dir: None, + envs: HashMap::from([("HOME".into(), "/home".into())]), + }); + let error = WellKnownCredentialProvider::new() + .provide_credential(&ctx) + .await + .expect_err("permission errors must be returned"); + assert_eq!(error.kind(), ErrorKind::PermissionDenied); + } + #[tokio::test] async fn test_default_provider_no_env_removes_provider() -> Result<()> { let env_path = "/tmp/google-env-adc.json"; diff --git a/services/google/src/provide_credential/external_account.rs b/services/google/src/provide_credential/external_account.rs index e53e2e64..2e28f535 100644 --- a/services/google/src/provide_credential/external_account.rs +++ b/services/google/src/provide_credential/external_account.rs @@ -21,7 +21,7 @@ use std::time::Duration; use form_urlencoded::Serializer; use http::Method; -use http::header::{ACCEPT, CONTENT_LENGTH, CONTENT_TYPE}; +use http::header::{ACCEPT, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE}; use log::{debug, error}; use reqsign_aws_v4::{ Credential as AwsCredential, EnvCredentialProvider as AwsEnvCredentialProvider, @@ -35,6 +35,7 @@ use crate::credential::{ parse_service_account_impersonation_url, }; use crate::service_account_impersonation::generate_access_token; +use reqsign_core::hash::base64_encode; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, ProvideCredential, Result, SignRequest}; @@ -129,6 +130,10 @@ pub struct ExternalAccountConfig { token_url: String, service_account_impersonation_url: Option, service_account_impersonation_lifetime: Option, + delegates: Option>, + workforce_pool_user_project: Option, + client_id: Option, + client_secret: Option, } impl Debug for ExternalAccountConfig { @@ -151,6 +156,10 @@ impl ExternalAccountConfig { token_url: token_url.into(), service_account_impersonation_url: None, service_account_impersonation_lifetime: None, + delegates: None, + workforce_pool_user_project: None, + client_id: None, + client_secret: None, } } @@ -179,6 +188,10 @@ impl ExternalAccountConfig { .as_ref() .and_then(|options| options.token_lifetime_seconds) .map(|seconds| Duration::from_secs(seconds as u64)), + delegates: external_account.delegates.clone(), + workforce_pool_user_project: external_account.workforce_pool_user_project.clone(), + client_id: external_account.client_id.clone(), + client_secret: external_account.client_secret.clone(), } } } @@ -908,13 +921,35 @@ impl ExternalAccountCredentialProvider { Ok(subject.token) } - async fn exchange_sts_token(&self, ctx: &Context, oidc_token: &str) -> Result { - debug!("exchanging OIDC token for STS access token"); + async fn exchange_sts_token(&self, ctx: &Context) -> Result { + let audience = resolve_template(ctx, &self.config.audience)?; + let workforce_user_project = self + .config + .workforce_pool_user_project + .as_deref() + .filter(|project| !project.is_empty()); + if workforce_user_project.is_some() && !is_workforce_pool_audience(&audience) { + return Err(Error::config_invalid( + "workforce_pool_user_project requires a workforce pool audience", + )); + } + + let subject_token = self.load_subject_token(ctx).await?; + debug!("exchanging external subject token for STS access token"); let scope = self.resolve_sts_scope(ctx); let token_url = resolve_template(ctx, &self.config.token_url)?; - let audience = resolve_template(ctx, &self.config.audience)?; let subject_token_type = resolve_template(ctx, &self.config.subject_token_type)?; + let client_id = self.config.client_id.as_deref().filter(|id| !id.is_empty()); + // Client authentication already identifies the user project to STS. + let options = workforce_user_project + .filter(|_| client_id.is_none()) + .map(|project| { + ( + "options", + serde_json::json!({"userProject": project}).to_string(), + ) + }); let body = Serializer::new(String::new()) .append_pair( @@ -927,19 +962,29 @@ impl ExternalAccountCredentialProvider { ) .append_pair("audience", &audience) .append_pair("scope", &scope) - .append_pair("subject_token", oidc_token) + .append_pair("subject_token", &subject_token.token) .append_pair("subject_token_type", &subject_token_type) + .extend_pairs(options) .finish(); - let req = http::Request::builder() + let mut req = http::Request::builder() .method(http::Method::POST) .uri(token_url) .header(ACCEPT, "application/json") - .header(CONTENT_TYPE, "application/x-www-form-urlencoded") - .body(body.into_bytes().into()) - .map_err(|e| { - reqsign_core::Error::unexpected("failed to build HTTP request").with_source(e) - })?; + .header(CONTENT_TYPE, "application/x-www-form-urlencoded"); + if let Some(client_id) = client_id { + let client_secret = self.config.client_secret.as_deref().unwrap_or_default(); + let encoded = base64_encode(format!("{client_id}:{client_secret}").as_bytes()); + let mut authorization = http::HeaderValue::from_str(&format!("Basic {encoded}")) + .map_err(|_| { + Error::config_invalid("invalid Google STS client authentication header") + })?; + authorization.set_sensitive(true); + req = req.header(AUTHORIZATION, authorization); + } + let req = req.body(body.into_bytes().into()).map_err(|e| { + reqsign_core::Error::unexpected("failed to build HTTP request").with_source(e) + })?; let resp = ctx.http_send(req).await.map_err(|err| { Error::new(err.kind(), "Google STS token exchange request failed") @@ -990,9 +1035,16 @@ impl ExternalAccountCredentialProvider { lifetime.min(MAX_LIFETIME) }; - generate_access_token(ctx, url, access_token, &[scope], None, Some(lifetime)) - .await - .map(Some) + generate_access_token( + ctx, + url, + access_token, + &[scope], + self.config.delegates.as_deref(), + Some(lifetime), + ) + .await + .map(Some) } } impl ProvideCredential for ExternalAccountCredentialProvider { @@ -1005,11 +1057,7 @@ impl ProvideCredential for ExternalAccountCredentialProvider { .as_deref() .and_then(|url| parse_service_account_impersonation_url(url).ok()); - // Load the explicitly configured subject token. - let subject_token = self.load_subject_token(ctx).await?; - - // Exchange for STS token - let sts_token = self.exchange_sts_token(ctx, &subject_token.token).await?; + let sts_token = self.exchange_sts_token(ctx).await?; // Try to impersonate service account if configured let final_token = if let Some(token) = self @@ -1029,6 +1077,21 @@ impl ProvideCredential for ExternalAccountCredentialProvider { } } +fn is_workforce_pool_audience(audience: &str) -> bool { + let Some((location, rest)) = audience + .strip_prefix("//iam.googleapis.com/locations/") + .and_then(|path| path.split_once("/workforcePools/")) + else { + return false; + }; + let Some((pool, provider)) = rest.split_once("/providers/") else { + return false; + }; + [location, pool, provider] + .into_iter() + .all(|segment| !segment.is_empty() && !segment.contains('/')) +} + fn resolve_template(ctx: &Context, input: &str) -> Result { // Google external account credentials commonly contain `${VAR}` placeholders that must be // substituted using process environment variables (e.g. GitHub Actions OIDC). @@ -1610,6 +1673,10 @@ mod tests { }), service_account_impersonation_url: None, service_account_impersonation: None, + delegates: None, + workforce_pool_user_project: None, + client_id: None, + client_secret: None, metadata: CredentialMetadata::default(), }; @@ -1723,6 +1790,10 @@ mod tests { }), service_account_impersonation_url: Some(impersonation_url.to_string()), service_account_impersonation: None, + delegates: None, + workforce_pool_user_project: None, + client_id: None, + client_secret: None, metadata: CredentialMetadata::default(), }; @@ -1772,6 +1843,10 @@ mod tests { }), service_account_impersonation_url: None, service_account_impersonation: None, + delegates: None, + workforce_pool_user_project: None, + client_id: None, + client_secret: None, metadata: CredentialMetadata::default(), }; @@ -1824,6 +1899,10 @@ mod tests { credential_source: external_account::Source::Aws(source), service_account_impersonation_url: None, service_account_impersonation: None, + delegates: None, + workforce_pool_user_project: None, + client_id: None, + client_secret: None, metadata: CredentialMetadata::default(), } } @@ -1980,6 +2059,10 @@ mod tests { .to_string(), ), service_account_impersonation: None, + delegates: None, + workforce_pool_user_project: None, + client_id: None, + client_secret: None, metadata: CredentialMetadata::default(), } } diff --git a/services/google/src/provide_credential/impersonated_service_account.rs b/services/google/src/provide_credential/impersonated_service_account.rs index b1559922..9a370ad7 100644 --- a/services/google/src/provide_credential/impersonated_service_account.rs +++ b/services/google/src/provide_credential/impersonated_service_account.rs @@ -67,7 +67,7 @@ impl ImpersonatedServiceAccountCredentialProvider { .await } ImpersonationSource::ExternalAccount(source) => { - ExternalAccountCredentialProvider::new(source.clone()) + ExternalAccountCredentialProvider::new(source.as_ref().clone()) .with_scope(IAM_SCOPE) .provide_credential(ctx) .await diff --git a/services/google/tests/credential_kinds.rs b/services/google/tests/credential_kinds.rs index 4fdf22f9..e9508782 100644 --- a/services/google/tests/credential_kinds.rs +++ b/services/google/tests/credential_kinds.rs @@ -765,6 +765,130 @@ async fn adc_metadata_survives_discovery_and_oauth_exchange() -> Result<()> { Ok(()) } +#[tokio::test] +async fn workforce_adc_sends_the_sts_project_or_client_authentication() -> Result<()> { + const STS_URL: &str = "https://sts.example.test/v1/token"; + const WORKFORCE_AUDIENCE: &str = + "//iam.googleapis.com/locations/global/workforcePools/pool/providers/oidc"; + const SUBJECT_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt"; + const SCOPE: &str = "https://www.googleapis.com/auth/devstorage.read_only"; + + for (client_id, client_secret, expected_authorization) in [ + (None, None, None), + ( + Some("invented-client"), + Some("invented-secret"), + Some("Basic aW52ZW50ZWQtY2xpZW50OmludmVudGVkLXNlY3JldA=="), + ), + ( + Some("invented-client"), + None, + Some("Basic aW52ZW50ZWQtY2xpZW50Og=="), + ), + ] { + let input = json!({ + "type": "external_account", + "audience": "${WORKFORCE_AUDIENCE}", + "subject_token_type": SUBJECT_TYPE, + "token_url": STS_URL, + "credential_source": {"file": "/invented-subject-token"}, + "workforce_pool_user_project": "workforce-billing", + "client_id": client_id, + "client_secret": client_secret, + "quota_project_id": "adc-quota", + "universe_domain": "universe.example.test", + }); + let http = MockHttp::new([json_response( + json!({"access_token": "workforce-token", "expires_in": 3600}), + )]); + let ctx = Context::new() + .with_file_read(SubjectTokenFile) + .with_http_send(http.clone()) + .with_env(StaticEnv { + home_dir: None, + envs: HashMap::from([ + ("WORKFORCE_AUDIENCE".into(), WORKFORCE_AUDIENCE.into()), + ("GOOGLE_SCOPE".into(), SCOPE.into()), + ]), + }); + let credential = StaticCredentialProvider::new(input.to_string()) + .provide_credential(&ctx) + .await? + .expect("workforce credential"); + assert_eq!( + credential.token().unwrap().access_token(), + "workforce-token" + ); + assert_eq!(credential.quota_project_id(), Some("adc-quota")); + assert_eq!(credential.universe_domain(), "universe.example.test"); + + let requests = http.requests.lock().unwrap(); + let [request] = requests.as_slice() else { + panic!("expected a single STS request"); + }; + assert_eq!(request.method(), Method::POST); + assert_eq!(request.uri(), STS_URL); + assert_eq!( + request.headers()[header::CONTENT_TYPE], + "application/x-www-form-urlencoded" + ); + assert!(!request.headers().contains_key("x-goog-user-project")); + let authorization = request.headers().get(header::AUTHORIZATION); + assert_eq!( + authorization.map(|value| value.to_str().unwrap()), + expected_authorization + ); + if let Some(authorization) = authorization { + assert!(authorization.is_sensitive()); + } + + let form: HashMap<_, _> = form_urlencoded::parse(request.body()).collect(); + let mut expected = HashMap::from([ + ( + "grant_type".into(), + "urn:ietf:params:oauth:grant-type:token-exchange".into(), + ), + ( + "requested_token_type".into(), + "urn:ietf:params:oauth:token-type:access_token".into(), + ), + ("audience".into(), WORKFORCE_AUDIENCE.into()), + ("subject_token_type".into(), SUBJECT_TYPE.into()), + ("subject_token".into(), "invented-subject-token".into()), + ("scope".into(), SCOPE.into()), + ]); + if expected_authorization.is_none() { + expected.insert( + "options".into(), + r#"{"userProject":"workforce-billing"}"#.into(), + ); + } + assert_eq!(form, expected); + } + Ok(()) +} + +#[tokio::test] +async fn workforce_adc_rejects_a_workload_pool_before_loading_the_subject_token() { + let input = json!({ + "type": "external_account", + "audience": "//iam.googleapis.com/projects/1/locations/global/workloadIdentityPools/pool/providers/oidc", + "subject_token_type": "urn:ietf:params:oauth:token-type:jwt", + "token_url": "https://sts.example.test/v1/token", + "credential_source": {"file": "/unexpected-workload-subject-token"}, + "workforce_pool_user_project": "workforce-billing", + }); + let ctx = Context::new() + .with_file_read(SubjectTokenFile) + .with_http_send(MockHttp::default()); + let error = StaticCredentialProvider::new(input.to_string()) + .provide_credential(&ctx) + .await + .expect_err("workload pools cannot use a workforce user project"); + assert_eq!(error.kind(), ErrorKind::ConfigInvalid); + assert!(error.to_string().contains("workforce_pool_user_project")); +} + const VM_TOKEN_PATH: &str = "/computeMetadata/v1/instance/service-accounts/default/token"; const VM_EMAIL_PATH: &str = "/computeMetadata/v1/instance/service-accounts/default/email"; const SIGNED_URL_LIFETIME: Option = Some(Duration::from_secs(3600)); diff --git a/services/google/tests/impersonated_service_account.rs b/services/google/tests/impersonated_service_account.rs index b60c0feb..c8b5e45d 100644 --- a/services/google/tests/impersonated_service_account.rs +++ b/services/google/tests/impersonated_service_account.rs @@ -47,6 +47,13 @@ const DELEGATES: [&str; 2] = [ ]; const AUDIENCE: &str = "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/pool/providers/oidc"; +const WORKFORCE_AUDIENCE: &str = + "//iam.googleapis.com/locations/global/workforcePools/pool/providers/oidc"; +const WORKFORCE_PROJECT: &str = "workforce-billing"; +const SOURCE_DELEGATES: [&str; 2] = [ + "projects/-/serviceAccounts/z-source-delegate@example.test", + "projects/-/serviceAccounts/a-source-delegate@example.test", +]; const SUBJECT_TYPE: &str = "urn:ietf:params:oauth:token-type:id_token"; #[derive(Debug)] @@ -184,6 +191,7 @@ async fn load_target(ctx: &Context, provider: FileCredentialProvider) -> Result< fn assert_iam_request(request: &Request, uri: &str, bearer: &str, body: Value) { assert_eq!(request.method(), Method::POST); assert_eq!(request.uri(), uri); + assert_eq!(request.headers()[header::CONTENT_TYPE], "application/json"); let authorization = &request.headers()[header::AUTHORIZATION]; assert_eq!(authorization, &format!("Bearer {bearer}")); assert!(authorization.is_sensitive()); @@ -202,18 +210,33 @@ fn assert_target_request(request: &Request, bearer: &str) { ); } -fn assert_sts_request(request: &Request, subject_token: &str) { +fn assert_sts_request(request: &Request, subject_token: &str, workforce: bool) { assert_eq!(request.method(), Method::POST); assert_eq!(request.uri(), STS_URL); + assert_eq!( + request.headers()[header::CONTENT_TYPE], + "application/x-www-form-urlencoded" + ); + assert!(!request.headers().contains_key(header::AUTHORIZATION)); let form: HashMap<_, _> = form_urlencoded::parse(request.body()).collect(); assert_eq!( form["grant_type"], "urn:ietf:params:oauth:grant-type:token-exchange" ); + assert_eq!( + form["requested_token_type"], + "urn:ietf:params:oauth:token-type:access_token" + ); assert_eq!(form["scope"], SOURCE_SCOPE); - assert_eq!(form["audience"], AUDIENCE); assert_eq!(form["subject_token"], subject_token); assert_eq!(form["subject_token_type"], SUBJECT_TYPE); + if workforce { + assert_eq!(form["audience"], WORKFORCE_AUDIENCE); + assert_eq!(form["options"], r#"{"userProject":"workforce-billing"}"#); + } else { + assert_eq!(form["audience"], AUDIENCE); + assert!(!form.contains_key("options")); + } } #[tokio::test] @@ -292,8 +315,11 @@ async fn exchanges_external_account_file_sources_with_iam_scope() -> Result<()> for impersonate_source in [false, true] { let mut source = external_source(json!({"file": SUBJECT_PATH})); if impersonate_source { + source["audience"] = WORKFORCE_AUDIENCE.into(); + source["workforce_pool_user_project"] = WORKFORCE_PROJECT.into(); source["service_account_impersonation_url"] = SOURCE_IAM_URL.into(); source["service_account_impersonation"] = json!({"token_lifetime_seconds": 600}); + source["delegates"] = json!(SOURCE_DELEGATES); } let io = MockIo::new(source); load_target( @@ -314,7 +340,7 @@ async fn exchanges_external_account_file_sources_with_iam_scope() -> Result<()> }; assert_eq!(adc, ADC_PATH); assert_eq!(subject, SUBJECT_PATH); - assert_sts_request(sts, "subject-from-file"); + assert_sts_request(sts, "subject-from-file", impersonate_source); match (impersonate_source, iam) { (false, [Call::Http(target)]) => assert_target_request(target, "sts-token"), (true, [Call::Http(source), Call::Http(target)]) => { @@ -322,7 +348,7 @@ async fn exchanges_external_account_file_sources_with_iam_scope() -> Result<()> source, SOURCE_IAM_URL, "sts-token", - json!({"scope": [SOURCE_SCOPE], "lifetime": "600s"}), + json!({"scope": [SOURCE_SCOPE], "lifetime": "600s", "delegates": SOURCE_DELEGATES}), ); assert_target_request(target, "source-token"); } @@ -386,7 +412,7 @@ async fn requires_explicit_opt_in_for_executable_external_account_sources() -> R assert_eq!(adc, ADC_PATH); assert_eq!(cache, EXECUTABLE_OUTPUT_PATH); assert!(command.ends_with("fetch-test-subject")); - assert_sts_request(sts, "subject-from-command"); + assert_sts_request(sts, "subject-from-command", false); assert_target_request(target, "sts-token"); Ok(()) }