tsafe-cli 1.0.21

tsafe CLI — local secret and credential manager (replaces .env files)
Documentation
//! Non-core `tsafe aws-pull` handler — import secrets from AWS Secrets Manager.

use anyhow::{Context as _, Result};
use colored::Colorize;
use tsafe_cli::tsafe_aws::{pull_secrets, AwsConfig, AwsCredentials, AwsError};
use tsafe_core::{audit::AuditEntry, events::emit_event};

use crate::helpers::*;
use tsafe_cli::cli::PullOnError;

pub(crate) fn cmd_aws_pull(
    profile: &str,
    region: Option<&str>,
    prefix: Option<&str>,
    overwrite: bool,
    on_error: PullOnError,
) -> Result<()> {
    cmd_aws_pull_ns(profile, region, prefix, overwrite, on_error, None)
}

/// Inner implementation that supports an optional namespace prefix (ADR-012).
///
/// When `ns` is `Some("staging")`, every key name returned from Secrets Manager
/// is stored as `staging.KEY_NAME` in the local vault.
pub(crate) fn cmd_aws_pull_ns(
    profile: &str,
    region: Option<&str>,
    prefix: Option<&str>,
    overwrite: bool,
    on_error: PullOnError,
    ns: Option<&str>,
) -> Result<()> {
    let cfg = match region {
        Some(r) => {
            let endpoint = format!("https://secretsmanager.{r}.amazonaws.com");
            AwsConfig::with_endpoint(r, endpoint)
        }
        None => AwsConfig::from_env().with_context(|| {
            "AWS region is not configured\n\
             \n  Fix:  export AWS_DEFAULT_REGION=us-east-1  (or pass --region)\
             \n  Help: tsafe explain pull-auth"
        })?,
    };

    let secrets = match pull_secrets(
        &cfg,
        &|| AwsCredentials::from_env_or_imds().map_err(|e| AwsError::Auth(format!("{e}"))),
        prefix,
    )
    .with_context(|| {
        "failed to pull secrets from AWS Secrets Manager\n\
         \n  Credential setup: tsafe explain pull-auth\
         \n  Required env:    AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY + AWS_DEFAULT_REGION"
    }) {
        Ok(secrets) => secrets,
        Err(err) => match on_error {
            PullOnError::FailAll => return Err(err),
            PullOnError::SkipFailed | PullOnError::WarnOnly => {
                eprintln!("{} AWS pull failed: {err}", "!".yellow());
                return Ok(());
            }
        },
    };

    if secrets.is_empty() {
        println!(
            "{} No secrets found in Secrets 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 {
        // ADR-012: apply per-source namespace prefix when declared in the manifest.
        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, "aws-pull", None))
        .ok();
    emit_event(profile, "aws-pull", None);
    println!(
        "{} Imported {imported} secret(s) from AWS Secrets Manager (region: {}){}",
        "".green(),
        cfg.region,
        if skipped > 0 {
            format!(" ({skipped} skipped — use --overwrite to replace)")
        } else {
            String::new()
        }
    );
    Ok(())
}