use crate::auth::models::Secret;
#[derive(Debug, Clone)]
pub struct ServiceAccountKey {
pub client_email: String,
pub private_key: Secret,
pub token_uri: String,
pub project_id: String,
}
#[derive(Debug, Clone)]
pub struct GoogleCredentials {
pub origin: CredentialOrigin,
pub signer: Signer,
pub impersonate: Option<Impersonation>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CredentialOrigin {
Connection,
Named { path: String },
Gcloud { path: String },
Machine,
}
#[derive(Debug, Clone)]
pub enum Signer {
ServiceAccount(ServiceAccountKey),
User(AuthorizedUser),
Metadata { host: String },
External(Box<ExternalAccount>),
}
#[derive(Debug, Clone)]
pub struct AuthorizedUser {
pub client_id: String,
pub client_secret: Secret,
pub refresh_token: Secret,
pub token_uri: String,
pub quota_project: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Impersonation {
pub account: String,
pub url: String,
pub delegates: Vec<String>,
pub lifetime_secs: u64,
}
#[derive(Debug, Clone)]
pub struct ExternalAccount {
pub audience: String,
pub subject_token_type: String,
pub token_url: String,
pub source: SubjectSource,
pub quota_project: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubjectSource {
File { path: String, field: Option<String> },
Url {
url: String,
headers: Vec<(String, Secret)>,
field: Option<String>,
},
Executable {
command: String,
timeout_ms: u64,
output_file: Option<String>,
},
Aws(AwsSource),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AwsSource {
pub region_url: Option<String>,
pub url: Option<String>,
pub verification_url: String,
pub session_url: Option<String>,
pub region: Option<String>,
pub keys: Option<AwsKeys>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AwsKeys {
pub access_key_id: String,
pub secret_access_key: Secret,
pub session_token: Option<Secret>,
}
impl GoogleCredentials {
pub fn describe(&self) -> String {
let signer = match &self.signer {
Signer::ServiceAccount(key) => {
format!("the service-account key of {}", key.client_email)
}
Signer::User(_) => "a gcloud user login (authorized_user)".to_owned(),
Signer::Metadata { host } => {
format!("the machine's service account, from its metadata server ({host})")
}
Signer::External(account) => {
let source = match &account.source {
SubjectSource::File { path, .. } => format!("the token file {path}"),
SubjectSource::Url { url, .. } => {
let shown = url.split(['?', '#']).next().unwrap_or_default();
format!("a token from {shown}")
}
SubjectSource::Executable { command, .. } => {
let program = command.split_whitespace().next().unwrap_or_default();
format!("a token {program} prints")
}
SubjectSource::Aws(source) => match source.keys {
Some(_) => {
"the AWS keys in AWS_ACCESS_KEY_ID, by a signed GetCallerIdentity"
}
None => "the EC2 instance role's AWS keys, by a signed GetCallerIdentity",
}
.to_owned(),
};
format!(
"workload identity federation with {source}, through provider {}",
account.audience
)
}
};
let origin = match &self.origin {
CredentialOrigin::Connection => " (the connection's service_account_key)".to_owned(),
CredentialOrigin::Named { path } => {
format!(" (GOOGLE_APPLICATION_CREDENTIALS, {path})")
}
CredentialOrigin::Gcloud { path } => {
format!(" (gcloud's application default credentials, {path})")
}
CredentialOrigin::Machine => String::new(),
};
match &self.impersonate {
Some(target) => format!("{signer}{origin}, impersonating {}", target.account),
None => format!("{signer}{origin}"),
}
}
pub fn default_project(&self, environment: Option<String>) -> Option<String> {
match (&self.origin, &self.signer) {
(CredentialOrigin::Connection, Signer::ServiceAccount(key)) => {
Some(key.project_id.clone())
}
_ => environment.or_else(|| self.project()),
}
}
pub fn project(&self) -> Option<String> {
let account_project = |account: &str| {
account
.split_once('@')
.and_then(|(_, domain)| domain.strip_suffix(".iam.gserviceaccount.com"))
.map(str::to_owned)
};
if let Some(target) = &self.impersonate
&& let Some(project) = account_project(&target.account)
{
return Some(project);
}
match &self.signer {
Signer::ServiceAccount(key) => Some(key.project_id.clone()),
Signer::User(user) => user.quota_project.clone(),
Signer::External(account) => account.quota_project.clone(),
Signer::Metadata { .. } => None,
}
}
}