Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 21 additions & 1 deletion services/google/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion services/google/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl Debug for ImpersonatedServiceAccount {
pub(crate) enum ImpersonationSource {
AuthorizedUser(OAuth2Credentials),
ServiceAccount(ServiceAccount),
ExternalAccount(ExternalAccount),
ExternalAccount(Box<ExternalAccount>),
ImpersonatedServiceAccount,
}

Expand Down Expand Up @@ -246,6 +246,11 @@ pub struct ExternalAccount {
pub service_account_impersonation_url: Option<String>,
/// Optional service account impersonation options.
pub service_account_impersonation: Option<external_account::ImpersonationOptions>,
/// Optional delegation chain for the impersonation request.
pub(crate) delegates: Option<Vec<String>>,
pub(crate) workforce_pool_user_project: Option<String>,
pub(crate) client_id: Option<String>,
pub(crate) client_secret: Option<String>,
#[serde(flatten)]
pub(crate) metadata: CredentialMetadata,
}
Expand Down
217 changes: 199 additions & 18 deletions services/google/src/provide_credential/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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 {
Expand Down Expand Up @@ -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<String>,
Expand All @@ -129,31 +143,41 @@ impl ProvideCredential for WellKnownCredentialProvider {
type Credential = Credential;

async fn provide_credential(&self, ctx: &Context) -> Result<Option<Self::Credential>> {
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::<io::Error>())
.any(|cause| cause.kind() == io::ErrorKind::NotFound)
}

/// Builder for `DefaultCredentialProvider`.
pub struct DefaultCredentialProviderBuilder {
env: Option<EnvCredentialProvider>,
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -281,7 +306,8 @@ mod tests {
async fn file_read(&self, path: &str) -> Result<Vec<u8>> {
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))
})
}
}
Expand Down Expand Up @@ -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::<HashMap<_, _>>();
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<Vec<u8>> {
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";
Expand Down
Loading
Loading