tsafe-cli 1.0.26

Secrets runtime for developers — inject credentials into processes via exec, never into shell history or .env files
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! `tsafe push` — run all push sources from `.tsafe.yml` / `.tsafe.json`.
//!
//! # ADR-030: Execution Policy
//!
//! Sources are executed **sequentially** in manifest order.  Parallel execution
//! is explicitly foreclosed — this mirrors the sequential-pull policy in ADR-012
//! and the write-contract sequential requirement in ADR-030.
//!
//! Rationale:
//! - Write ordering must be deterministic to make `--on-error fail-all` unambiguous.
//! - Provider rate limits are unpredictable; sequential writes avoid compounding backoff.
//! - The `--on-error` handling logic is clear under sequential execution and
//!   becomes ambiguous if sources run concurrently.
//!
//! Do not introduce `tokio::spawn`, `rayon`, or any concurrent executor without
//! first revising ADR-030 and ADR-012.

use anyhow::Result;
use colored::Colorize;
use tsafe_core::pushconfig::{self, PushSource};

#[cfg(feature = "akv-pull")]
use crate::cmd_kv_push::cmd_kv_push;
use crate::cli::PushOnError;

/// Return a display label for a source: `[name]` if declared, else `[<index>/<total>]`.
fn source_display_label(source: &PushSource, index: usize, total: usize) -> String {
    match source.name() {
        Some(n) => format!("[{n}]"),
        None => format!("[{}/{}]", index + 1, total),
    }
}

/// Return the name of an unsupported source, or `None` if it is supported.
fn unsupported_source_name(source: &PushSource) -> Option<&'static str> {
    match source {
        PushSource::Kv { .. } => {
            if cfg!(feature = "akv-pull") {
                None
            } else {
                Some("Azure Key Vault")
            }
        }
        PushSource::Aws { .. } => Some("AWS Secrets Manager (aws-push not yet compiled)"),
        PushSource::Ssm { .. } => Some("AWS SSM Parameter Store (ssm-push not yet compiled)"),
        PushSource::Gcp { .. } => Some("GCP Secret Manager (gcp-push not yet compiled)"),
    }
}

fn unsupported_source_error(source: &PushSource) -> anyhow::Error {
    let source_name = unsupported_source_name(source).unwrap_or("unknown source");
    anyhow::anyhow!(
        "{source_name} is not available in this tsafe build\n\
         \n  This build supports Azure Key Vault push via `tsafe kv-push`.\n\
         \n  Fix: remove this source from the push config or install a build with the required push feature.\n\
         \n  Check compiled capabilities: tsafe build-info"
    )
}

/// Dry-run preview: print the sources that would be invoked without making any live API calls.
///
/// ADR-030: dry-run is manifest-inspection only.  No live API calls, no pre-flight diff
/// (diff requires fetching remote state, which is a live call).
fn print_dry_run(cfg_path: &std::path::Path, sources: &[&PushSource]) {
    println!("Dry run — no live API calls will be made, no secrets will be written.");
    println!("Config: {}", cfg_path.display());
    println!();
    if sources.is_empty() {
        println!("  (no sources match the current filter)");
        return;
    }
    println!("Sources that would be invoked (in manifest order):");
    for (i, source) in sources.iter().enumerate() {
        let label = match source.name() {
            Some(n) => format!("name={n}"),
            None => format!("index={}", i + 1),
        };
        let delete_note = if source.delete_missing() {
            " [delete-missing]"
        } else {
            ""
        };
        match source {
            PushSource::Kv {
                vault_url, prefix, ..
            } => {
                let prefix_note = prefix
                    .as_deref()
                    .map(|p| format!(" prefix={p}"))
                    .unwrap_or_default();
                println!("  {i}. [{label}] akv: {vault_url}{prefix_note}{delete_note}");
            }
            PushSource::Aws { region, prefix, .. } => {
                let region_str = region.as_deref().unwrap_or("(from env)");
                let prefix_note = prefix
                    .as_deref()
                    .map(|p| format!(" prefix={p}"))
                    .unwrap_or_default();
                println!("  {i}. [{label}] aws: region={region_str}{prefix_note}{delete_note}");
            }
            PushSource::Ssm { region, path, .. } => {
                let region_str = region.as_deref().unwrap_or("(from env)");
                let path_str = path.as_deref().unwrap_or("/");
                println!("  {i}. [{label}] ssm: region={region_str} path={path_str}{delete_note}");
            }
            PushSource::Gcp {
                project, prefix, ..
            } => {
                let project_str = project.as_deref().unwrap_or("(from env)");
                let prefix_note = prefix
                    .as_deref()
                    .map(|p| format!(" prefix={p}"))
                    .unwrap_or_default();
                println!("  {i}. [{label}] gcp: project={project_str}{prefix_note}{delete_note}");
            }
        }
    }
    println!();
    println!(
        "Note: pre-flight diff requires a live run. Run without --dry-run to see what would change."
    );
}

#[tracing::instrument(skip_all, fields(source_count, dry_run))]
pub(crate) fn cmd_push(
    profile: &str,
    config_path: Option<&std::path::Path>,
    source_filter: &[String],
    dry_run: bool,
    yes: bool,
    global_delete_missing: bool,
    on_error: PushOnError,
) -> Result<()> {
    let cfg_path = match config_path {
        Some(p) => p.to_path_buf(),
        None => {
            let cwd = std::env::current_dir()?;
            pushconfig::find_config(&cwd).ok_or_else(|| {
                anyhow::anyhow!(
                    "no .tsafe.yml / .tsafe.json found (searched upward from {})\n\
                     \n  Fix: create a .tsafe.yml with a `pushes:` section in your project root.\n\
                     \n  Example:\n    pushes:\n      - source: akv\n        vault_url: https://myvault.vault.azure.net",
                    cwd.display()
                )
            })?
        }
    };

    let cfg = pushconfig::load(&cfg_path).map_err(|e| {
        // Provide a clearer message when `pushes:` is absent.
        let msg = e.to_string();
        if msg.contains("missing field `pushes`") || msg.contains("pushes") {
            anyhow::anyhow!(
                "no `pushes:` key found in {} — add a `pushes:` section.\n\
                 \n  Example:\n    pushes:\n      - source: akv\n        vault_url: https://myvault.vault.azure.net\n\
                 \n  Original error: {msg}",
                cfg_path.display()
            )
        } else {
            anyhow::anyhow!("{msg}")
        }
    })?;

    // Source filtering — by `name` label, not by provider type.
    // When --source flags are given, only sources with matching `name` labels
    // are included.  Sources without a `name` field are skipped when any filter
    // is active.
    let filtered_sources: Vec<&PushSource> = if source_filter.is_empty() {
        cfg.pushes.iter().collect()
    } else {
        cfg.pushes
            .iter()
            .filter(|s| {
                s.name()
                    .map(|n| source_filter.iter().any(|f| f == n))
                    .unwrap_or(false)
            })
            .collect()
    };

    tracing::Span::current().record("source_count", filtered_sources.len());
    tracing::Span::current().record("dry_run", dry_run);

    // ADR-030 / ADR-012: dry-run — manifest preview only, no live API calls.
    if dry_run {
        print_dry_run(&cfg_path, &filtered_sources);
        return Ok(());
    }

    println!("Using config: {}", cfg_path.display());
    if !source_filter.is_empty() {
        println!("Source filter active: {}", source_filter.join(", "));
    }

    let total_sources = filtered_sources.len();
    let mut successes = 0usize;
    let mut failures = 0usize;

    // ADR-030 / ADR-012: sequential, manifest-ordered execution.
    //
    // Do NOT change this loop to use tokio::spawn, rayon, or any other
    // concurrent executor.  Sequential execution is a hard policy decision:
    // - write ordering must be deterministic for fail-all/skip-failed semantics
    // - provider rate-limit back-pressure is less likely to compound sequentially
    for (i, source) in filtered_sources.iter().enumerate() {
        let source_label = source_display_label(source, i, total_sources);

        if unsupported_source_name(source).is_some() {
            let err = unsupported_source_error(source);
            failures += 1;
            match on_error {
                PushOnError::FailAll => return Err(err),
                PushOnError::SkipFailed => {
                    eprintln!("{} Source {source_label} skipped: {err}", "!".yellow());
                    continue;
                }
            }
        }

        // Per-source delete_missing: global flag overrides to true if set;
        // per-source flag in the manifest is the baseline.
        let effective_delete_missing = global_delete_missing || source.delete_missing();

        let run_result: Result<()> = match source {
            #[cfg(feature = "akv-pull")]
            PushSource::Kv {
                vault_url, prefix, ..
            } => {
                println!("\n{source_label} Azure Key Vault: {vault_url}");
                std::env::set_var("TSAFE_AKV_URL", vault_url);
                cmd_kv_push(
                    profile,
                    prefix.as_deref(),
                    None,  // ns not supported in orchestrated push (not in PushSource)
                    false, // dry_run: already handled above
                    yes,
                    effective_delete_missing,
                )
            }
            #[allow(unreachable_patterns)]
            _ => Err(unsupported_source_error(source)),
        };

        if let Err(err) = run_result {
            failures += 1;
            match on_error {
                PushOnError::FailAll => return Err(err),
                PushOnError::SkipFailed => {
                    eprintln!("{} Source {source_label} failed: {err}", "!".yellow());
                }
            }
        } else {
            successes += 1;
            println!("{} Source {source_label} succeeded", "".green());
        }
    }

    println!(
        "\n{} Push complete ({} sources)",
        "".green(),
        total_sources
    );
    println!(
        "{} source summary: {} succeeded, {} failed",
        "".cyan(),
        successes,
        failures
    );
    if failures > 0 {
        eprintln!(
            "{} {} source(s) failed (mode: {:?})",
            "!".yellow(),
            failures,
            on_error
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unsupported_source_returns_none_for_akv_when_feature_is_on() {
        let source = PushSource::Kv {
            name: None,
            vault_url: "https://example.vault.azure.net".into(),
            prefix: None,
            delete_missing: false,
        };
        // akv-pull is on in default builds; if compiled without it, this is Some.
        let result = unsupported_source_name(&source);
        if cfg!(feature = "akv-pull") {
            assert_eq!(result, None);
        } else {
            assert!(result.is_some());
        }
    }

    #[test]
    fn unsupported_source_returns_some_for_aws_ssm_gcp() {
        let cases = [
            PushSource::Aws {
                name: None,
                region: Some("us-east-1".into()),
                prefix: None,
                delete_missing: false,
            },
            PushSource::Ssm {
                name: None,
                region: Some("us-east-1".into()),
                path: Some("/".into()),
                delete_missing: false,
            },
            PushSource::Gcp {
                name: None,
                project: Some("demo".into()),
                prefix: None,
                delete_missing: false,
            },
        ];
        for source in &cases {
            assert!(
                unsupported_source_name(source).is_some(),
                "expected unsupported for {:?}",
                source.provider_type()
            );
        }
    }

    /// Source filtering: when filter is active, only named+matching sources included.
    #[test]
    fn source_filter_selects_named_sources_only() {
        let sources = [
            PushSource::Kv {
                name: Some("prod-akv".into()),
                vault_url: "https://prod.vault.azure.net".into(),
                prefix: None,
                delete_missing: false,
            },
            PushSource::Kv {
                name: Some("staging-akv".into()),
                vault_url: "https://staging.vault.azure.net".into(),
                prefix: None,
                delete_missing: false,
            },
            PushSource::Kv {
                name: None,
                vault_url: "https://anon.vault.azure.net".into(),
                prefix: None,
                delete_missing: false,
            },
        ];

        let filter = ["prod-akv".to_string()];
        let filtered: Vec<&PushSource> = sources
            .iter()
            .filter(|s| {
                s.name()
                    .map(|n| filter.iter().any(|f| f == n))
                    .unwrap_or(false)
            })
            .collect();

        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].name(), Some("prod-akv"));
    }

    /// Sequential execution order is preserved in manifest order.
    #[test]
    fn sequential_execution_order_is_preserved() {
        let sources = [
            PushSource::Kv {
                name: Some("first".into()),
                vault_url: "https://first.vault.azure.net".into(),
                prefix: None,
                delete_missing: false,
            },
            PushSource::Kv {
                name: Some("second".into()),
                vault_url: "https://second.vault.azure.net".into(),
                prefix: None,
                delete_missing: false,
            },
            PushSource::Kv {
                name: Some("third".into()),
                vault_url: "https://third.vault.azure.net".into(),
                prefix: None,
                delete_missing: false,
            },
        ];

        let filtered: Vec<&PushSource> = sources.iter().collect();
        assert_eq!(filtered.len(), 3);

        let names: Vec<Option<&str>> = filtered.iter().map(|s| s.name()).collect();
        assert_eq!(names, vec![Some("first"), Some("second"), Some("third")]);

        let labels: Vec<String> = filtered
            .iter()
            .enumerate()
            .map(|(i, s)| source_display_label(s, i, filtered.len()))
            .collect();
        assert_eq!(labels, vec!["[first]", "[second]", "[third]"]);
    }

    /// Empty filter includes all sources.
    #[test]
    fn empty_source_filter_includes_all_sources() {
        let sources = [
            PushSource::Kv {
                name: Some("a".into()),
                vault_url: "https://a.vault.azure.net".into(),
                prefix: None,
                delete_missing: false,
            },
            PushSource::Kv {
                name: None,
                vault_url: "https://b.vault.azure.net".into(),
                prefix: None,
                delete_missing: false,
            },
        ];

        let filter: Vec<String> = Vec::new();
        let filtered: Vec<&PushSource> = if filter.is_empty() {
            sources.iter().collect()
        } else {
            sources
                .iter()
                .filter(|s| {
                    s.name()
                        .map(|n| filter.iter().any(|f| f == n))
                        .unwrap_or(false)
                })
                .collect()
        };

        assert_eq!(filtered.len(), 2);
    }
}