use anyhow::{Context as _, Result};
use colored::Colorize;
use crate::tsafe_gcp::{acquire_token, pull_secrets, GcpConfig, GcpError};
use tsafe_core::{audit::AuditEntry, events::emit_event};
use crate::helpers::*;
use crate::cli::PullOnError;
pub(crate) fn cmd_gcp_pull(
profile: &str,
project: Option<&str>,
prefix: Option<&str>,
overwrite: bool,
on_error: PullOnError,
) -> Result<()> {
cmd_gcp_pull_ns(profile, project, prefix, overwrite, on_error, None)
}
pub(crate) fn cmd_gcp_pull_ns(
profile: &str,
project: Option<&str>,
prefix: Option<&str>,
overwrite: bool,
on_error: PullOnError,
ns: Option<&str>,
) -> Result<()> {
let cfg = match project {
Some(p) => GcpConfig::with_endpoint(p, "https://secretmanager.googleapis.com/v1"),
None => GcpConfig::from_env().with_context(|| {
"GCP project is not configured\n\
\n Fix: export GOOGLE_CLOUD_PROJECT=my-project (or pass --project)\
\n Help: tsafe explain pull-auth"
})?,
};
let secrets = match pull_secrets(
&cfg,
&|| acquire_token().map_err(|e| GcpError::Auth(format!("{e}"))),
prefix,
)
.with_context(|| {
"failed to pull secrets from GCP Secret Manager\n\
\n Credential setup: tsafe explain pull-auth\
\n Local dev: gcloud auth application-default login\
\n CI: export GOOGLE_OAUTH_TOKEN=$(gcloud auth print-access-token)"
}) {
Ok(secrets) => secrets,
Err(err) => match on_error {
PullOnError::FailAll => return Err(err),
PullOnError::SkipFailed | PullOnError::WarnOnly => {
eprintln!("{} GCP pull failed: {err}", "!".yellow());
return Ok(());
}
},
};
if secrets.is_empty() {
println!(
"{} No secrets found in Secret Manager matching the filter",
"i".blue()
);
return Ok(());
}
let mut vault = open_vault(profile)?;
let mut imported = 0usize;
let mut skipped = 0usize;
for (raw_key, value) in &secrets {
let key = match ns {
Some(prefix) => format!("{prefix}.{raw_key}"),
None => raw_key.clone(),
};
let exists = vault.list().contains(&key.as_str());
if exists && !overwrite {
skipped += 1;
continue;
}
vault.set(&key, value, std::collections::HashMap::new())?;
imported += 1;
}
audit(profile)
.append(&AuditEntry::success(profile, "gcp-pull", None))
.ok();
emit_event(profile, "gcp-pull", None);
println!(
"{} Imported {imported} secret(s) from GCP Secret Manager (project: {}){}",
"✓".green(),
cfg.project_id,
if skipped > 0 {
format!(" ({skipped} skipped — use --overwrite to replace)")
} else {
String::new()
}
);
Ok(())
}