tsafe-cli 1.0.27

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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! `tsafe ssm-push` — push local vault secrets to AWS SSM Parameter Store.
//!
//! Implements the ADR-030 write contract: upsert semantics, pre-flight diff,
//! confirmation prompt, `--dry-run`, `--delete-missing` (off by default), and
//! audit log entries with no plaintext secret values.
//!
//! ## SSM path reconstruction
//!
//! Local keys use `UPPER_SNAKE_CASE`. Given `--path /myapp/`, the target SSM
//! parameter name is reconstructed as:
//!
//! ```text
//! MYAPP_DB_PASSWORD  →  /myapp/db-password
//! ```
//!
//! The path scope prefix (e.g. `myapp/` from `--path /myapp/`) is stripped
//! from the key before lower-hyphen-casing the remainder, then the full `--path`
//! value is prepended.

use std::collections::HashMap;
use std::io::{IsTerminal, Write as _};

use anyhow::{Context, Result};
use colored::Colorize;
use sha2::{Digest, Sha256};
use crate::tsafe_aws::{
    pull_ssm_parameters, push_ssm_parameter, AwsConfig, AwsCredentials, AwsError, SsmPushOutcome,
};
use tsafe_core::{audit::AuditEntry, events::emit_event};

use crate::helpers::*;

/// Compute a 12-hex-char SHA-256 fingerprint of a secret value.
fn value_fingerprint(value: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(value.as_bytes());
    let result = hasher.finalize();
    result[..6].iter().map(|b| format!("{b:02x}")).collect()
}

/// Normalize an absolute SSM path prefix to the normalized path form used internally.
/// Ensures there is a leading `/` and a trailing `/`.
fn normalize_ssm_path_prefix(path: Option<&str>) -> String {
    match path {
        None | Some("") => "/".to_string(),
        Some(p) => {
            let with_leading = if p.starts_with('/') {
                p.to_string()
            } else {
                format!("/{p}")
            };
            if with_leading.ends_with('/') {
                with_leading
            } else {
                format!("{with_leading}/")
            }
        }
    }
}

/// Derive the SSM parameter name from a local vault key and the `--path` prefix.
///
/// Example: key=`MYAPP_DB_PASSWORD`, path=`/myapp/` →
///   1. The path scope maps to the local prefix `MYAPP_`.
///      Strip `MYAPP_` from local key → `DB_PASSWORD`.
///   2. Lower-hyphen-case: `db-password`.
///   3. Prepend path: `/myapp/db-password`.
///
/// If the key does not have a local equivalent of the path prefix (e.g. path=`/myapp/`
/// but key=`UNRELATED_KEY`), the whole key is lower-hyphen-cased and prepended with
/// the path.
pub fn reconstruct_ssm_name(local_key: &str, ssm_path: &str) -> String {
    // Derive the "local key prefix" equivalent of the ssm_path.
    // /myapp/ → strip leading /, strip trailing /, replace / with _, uppercase → MYAPP_
    let path_as_local_prefix = ssm_path
        .trim_start_matches('/')
        .trim_end_matches('/')
        .replace(['/', '-'], "_")
        .to_uppercase();

    let suffix_local = if !path_as_local_prefix.is_empty() {
        let try_strip = format!("{path_as_local_prefix}_");
        if local_key.to_uppercase().starts_with(&try_strip) {
            // Strip the path-derived prefix from the local key.
            &local_key[try_strip.len()..]
        } else if local_key.to_uppercase() == path_as_local_prefix {
            // The key exactly matches the prefix — use the key as the suffix.
            local_key
        } else {
            // Key does not match the path prefix — use the full key as the suffix.
            local_key
        }
    } else {
        local_key
    };

    // Lower-hyphen-case the suffix.
    let suffix_provider = suffix_local.replace('_', "-").to_lowercase();

    // Ensure ssm_path ends with `/` and concatenate.
    let base = if ssm_path.ends_with('/') {
        ssm_path.to_string()
    } else {
        format!("{ssm_path}/")
    };

    format!("{base}{suffix_provider}")
}

#[tracing::instrument(skip_all, fields(provider = "aws-ssm", dry_run))]
pub(crate) fn cmd_ssm_push(
    profile: &str,
    region: Option<&str>,
    path: Option<&str>,
    dry_run: bool,
    yes: bool,
    delete_missing: bool,
) -> Result<()> {
    tracing::Span::current().record("dry_run", dry_run);

    let mut cfg = match region {
        Some(r) => {
            let endpoint = format!("https://ssm.{r}.amazonaws.com");
            AwsConfig::with_endpoint(r, endpoint)
        }
        None => {
            let mut c = 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"
            })?;
            c.endpoint = format!("https://ssm.{}.amazonaws.com", c.region);
            c
        }
    };

    // Always point at SSM.
    if !cfg.endpoint.contains("/ssm.") && !cfg.endpoint.contains("://ssm.") {
        cfg.endpoint = format!("https://ssm.{}.amazonaws.com", cfg.region);
    }

    let ssm_path = normalize_ssm_path_prefix(path);
    let get_creds = || -> Result<AwsCredentials, AwsError> {
        AwsCredentials::from_env_or_imds().map_err(|e| AwsError::Auth(format!("{e}")))
    };

    // ── 1. Fetch remote parameters (list) ─────────────────────────────────────
    // pull_ssm_parameters returns (UPPER_SNAKE_normalized, value).
    // We need to re-map them to their original SSM names for upsert comparison.
    // Since pull_ssm_parameters normalises names, we need the raw parameter names
    // for the write path. We store remote by the SSM path directly.
    let remote_raw = pull_ssm_parameters(&cfg, &get_creds, Some(&ssm_path)).with_context(|| {
        "failed to fetch parameters from AWS SSM Parameter Store\n\
             \n  Credential setup: tsafe explain pull-auth\
             \n  Required policy:  ssm:GetParametersByPath + kms:Decrypt"
    })?;

    // Build remote lookup by reconstructed SSM path → value.
    // pull_ssm_parameters normalizes names, so we need to reconstruct the SSM path
    // from the normalized key for comparison. We'll index by the reconstructed SSM name.
    // Actually — pull_ssm_parameters returns (UPPER_SNAKE, value). We invert: compute
    // the expected SSM name from the local key form, then look up by the local upper key.
    // Build a map: upper_snake_key → value (as returned by pull)
    let remote_by_upper: HashMap<String, String> = remote_raw.into_iter().collect();

    // ── 2. Fetch local vault secrets ──────────────────────────────────────────
    let vault = open_vault(profile)?;
    // Derive the local key prefix equivalent of the SSM path so we can filter.
    // /myapp/ → MYAPP_  (used to filter local keys that belong under this path)
    let path_as_local_prefix: String = {
        let stripped = ssm_path.trim_start_matches('/').trim_end_matches('/');
        if stripped.is_empty() {
            String::new()
        } else {
            format!("{}_", stripped.replace(['/', '-'], "_").to_uppercase())
        }
    };

    let all_keys: Vec<String> = vault
        .list()
        .iter()
        .map(|k| k.to_string())
        .filter(|k| {
            if path_as_local_prefix.is_empty() {
                true
            } else {
                k.to_uppercase().starts_with(&path_as_local_prefix)
                    || k.to_uppercase() == path_as_local_prefix.trim_end_matches('_')
            }
        })
        .collect();

    // ── 3. Collision detection (pre-flight) ───────────────────────────────────
    // Two local keys that reconstruct to the same SSM path → abort.
    let mut ssm_name_map: HashMap<String, Vec<String>> = HashMap::new();
    for local_key in &all_keys {
        let ssm_name = reconstruct_ssm_name(local_key, &ssm_path);
        ssm_name_map
            .entry(ssm_name)
            .or_default()
            .push(local_key.clone());
    }
    let mut collisions: Vec<(String, Vec<String>)> = ssm_name_map
        .into_iter()
        .filter(|(_, locals)| locals.len() > 1)
        .collect();
    collisions.sort_by(|(a, _), (b, _)| a.cmp(b));
    if !collisions.is_empty() {
        let msg = collisions
            .iter()
            .map(|(ssm_name, locals)| {
                format!(
                    "  SSM parameter '{}' claimed by: {}",
                    ssm_name,
                    locals.join(", ")
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
        anyhow::bail!(
            "reverse-normalization collision detected — two local keys map to the same \
             SSM parameter name:\n{msg}\n\
             Rename one of the colliding local keys before pushing."
        );
    }

    // ── 4. Compute diff ───────────────────────────────────────────────────────
    // For comparison we need the remote value. pull_ssm_parameters returns keys as
    // UPPER_SNAKE. The SSM name /myapp/db-password → MYAPP_DB_PASSWORD. So we can
    // look up the remote value by reconstructing the expected upper key from the
    // local key's SSM name.
    let mut to_create: Vec<(String, String, String)> = Vec::new(); // (local, ssm_name, hash)
    let mut to_update: Vec<(String, String, String, String)> = Vec::new(); // (local, ssm_name, old, new)
    let mut unchanged = 0usize;

    for local_key in &all_keys {
        let ssm_name = reconstruct_ssm_name(local_key, &ssm_path);
        let local_value = vault.get(local_key).map_err(|e| anyhow::anyhow!("{e}"))?;
        let local_hash = value_fingerprint(local_value.as_str());

        // The upper_snake equivalent of the ssm_name for remote lookup.
        let ssm_upper_key = ssm_name
            .trim_start_matches('/')
            .replace(['/', '-'], "_")
            .to_uppercase();

        match remote_by_upper.get(&ssm_upper_key) {
            None => {
                to_create.push((local_key.clone(), ssm_name, local_hash));
            }
            Some(remote_value) => {
                let remote_hash = value_fingerprint(remote_value);
                if remote_hash == local_hash {
                    unchanged += 1;
                } else {
                    to_update.push((local_key.clone(), ssm_name, remote_hash, local_hash));
                }
            }
        }
    }

    // Deletions: remote parameters not present in local selection.
    let mut to_delete: Vec<String> = Vec::new();
    if delete_missing {
        let local_ssm_names: std::collections::HashSet<String> = all_keys
            .iter()
            .map(|k| reconstruct_ssm_name(k, &ssm_path))
            .collect();
        for upper_key in remote_by_upper.keys() {
            // Reconstruct the SSM name from the upper key returned by pull.
            let ssm_name = format!(
                "{}{}",
                ssm_path,
                upper_key
                    .trim_start_matches(&path_as_local_prefix)
                    .replace('_', "-")
                    .to_lowercase()
            );
            if !local_ssm_names.contains(&ssm_name) {
                to_delete.push(ssm_name);
            }
        }
        to_delete.sort();
    }

    // ── 5. Print pre-flight diff ──────────────────────────────────────────────
    let total_changes = to_create.len() + to_update.len() + to_delete.len();

    if total_changes == 0 && unchanged == 0 {
        println!(
            "{} No parameters to push — local vault is empty for the given path filter.",
            "i".blue()
        );
        return Ok(());
    }

    println!(
        "{} Pre-flight diff for AWS SSM Parameter Store (region: {}, path: {}):",
        "".cyan().bold(),
        cfg.region,
        ssm_path
    );
    for (local_key, ssm_name, hash) in &to_create {
        println!(
            "  {}  {}  {} (local: {})",
            "create".green().bold(),
            ssm_name,
            format!("(sha256: {hash})").dimmed(),
            local_key
        );
    }
    for (local_key, ssm_name, old_hash, new_hash) in &to_update {
        println!(
            "  {}  {}  {} (local: {})",
            "update".yellow().bold(),
            ssm_name,
            format!("(sha256: {old_hash}{new_hash})").dimmed(),
            local_key
        );
    }
    for ssm_name in &to_delete {
        println!(
            "  {}  {}  {}",
            "delete".red().bold(),
            ssm_name,
            "(--delete-missing)".dimmed()
        );
    }

    let delete_note = if !to_delete.is_empty() {
        format!(", {} delete(s)", to_delete.len())
    } else {
        String::new()
    };
    println!(
        "  {} {} create(s), {} update(s){delete_note}, {} unchanged",
        "---".dimmed(),
        to_create.len(),
        to_update.len(),
        unchanged
    );

    // ── 6. Dry-run exit ───────────────────────────────────────────────────────
    if dry_run {
        println!("{} Dry-run complete — no writes made.", "".green());
        return Ok(());
    }

    if total_changes == 0 {
        println!(
            "{} Nothing to push — all parameters are up to date.",
            "".green()
        );
        return Ok(());
    }

    // ── 7. Confirmation prompt ────────────────────────────────────────────────
    if !yes {
        if std::io::stdin().is_terminal() {
            let delete_prompt = if !to_delete.is_empty() {
                format!(", {} delete(s)", to_delete.len())
            } else {
                String::new()
            };
            eprint!(
                "Push {} create(s), {} update(s){delete_prompt} to SSM Parameter Store? [y/N] ",
                to_create.len(),
                to_update.len()
            );
            std::io::stderr().flush().ok();

            let mut response = String::new();
            std::io::stdin()
                .read_line(&mut response)
                .context("failed to read confirmation")?;
            if !response.trim().eq_ignore_ascii_case("y") {
                println!("{} Push aborted.", "i".blue());
                return Ok(());
            }
        } else {
            anyhow::bail!(
                "non-interactive stdin and --yes not passed — refusing to push without confirmation.\n\
                 Add --yes to push from CI or non-interactive contexts:\n  tsafe ssm-push --yes"
            );
        }
    }

    // ── 8. Execute writes sequentially ───────────────────────────────────────
    let mut created = 0usize;
    let mut updated = 0usize;
    let deleted = 0usize;
    let mut errors: Vec<String> = Vec::new();

    for (local_key, ssm_name, _hash) in &to_create {
        let value = vault.get(local_key).map_err(|e| anyhow::anyhow!("{e}"))?;
        match push_ssm_parameter(&cfg, &get_creds, ssm_name, value.as_str(), false) {
            Ok(SsmPushOutcome::Created | SsmPushOutcome::Updated) => {
                tracing::debug!(ssm_name = %ssm_name, local_key = %local_key, "created SSM parameter");
                created += 1;
            }
            Ok(SsmPushOutcome::Unchanged) => {}
            Ok(SsmPushOutcome::Deleted) => {}
            Err(e) => {
                errors.push(format!("failed to create '{ssm_name}': {e}"));
            }
        }
    }

    for (local_key, ssm_name, _old_hash, _new_hash) in &to_update {
        let value = vault.get(local_key).map_err(|e| anyhow::anyhow!("{e}"))?;
        match push_ssm_parameter(&cfg, &get_creds, ssm_name, value.as_str(), true) {
            Ok(SsmPushOutcome::Updated | SsmPushOutcome::Created | SsmPushOutcome::Unchanged) => {
                tracing::debug!(ssm_name = %ssm_name, local_key = %local_key, "updated SSM parameter");
                updated += 1;
            }
            Ok(SsmPushOutcome::Deleted) => {}
            Err(e) => {
                errors.push(format!("failed to update '{ssm_name}': {e}"));
            }
        }
    }

    // Deletion: DeleteParameter is not yet implemented; emit an error per skipped deletion.
    for ssm_name in &to_delete {
        tracing::warn!(ssm_name = %ssm_name, "ssm-push: --delete-missing delete skipped — DeleteParameter not yet implemented");
        errors.push(format!(
            "delete '{ssm_name}' skipped — ssm-push --delete-missing delete is not yet implemented; \
             remove the parameter manually in the AWS Console or CLI"
        ));
    }

    // ── 9. Audit log entry (no plaintext values) ──────────────────────────────
    let audit_context =
        format!("created={created} updated={updated} unchanged={unchanged} deleted={deleted}");
    audit(profile)
        .append(&AuditEntry::success(
            profile,
            "ssm-push",
            Some(&audit_context),
        ))
        .ok();
    emit_event(profile, "ssm-push", Some(&audit_context));

    // ── 10. Summary ───────────────────────────────────────────────────────────
    if errors.is_empty() {
        println!(
            "{} Pushed to SSM Parameter Store (region: {}, path: {}): {created} created, {updated} updated, {unchanged} unchanged.",
            "".green(),
            cfg.region,
            ssm_path
        );
    } else {
        println!(
            "{} Partial push to SSM (region: {}, path: {}): {created} created, {updated} updated, {unchanged} unchanged.",
            "!".yellow(),
            cfg.region,
            ssm_path
        );
        for error in &errors {
            eprintln!("{} {error}", "error:".red().bold());
        }
        anyhow::bail!("{} parameter(s) failed to push", errors.len());
    }

    Ok(())
}

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

    #[test]
    fn reconstruct_ssm_name_strips_path_prefix_from_local_key() {
        // /myapp/ → strip MYAPP_ from MYAPP_DB_PASSWORD → db-password → /myapp/db-password
        assert_eq!(
            reconstruct_ssm_name("MYAPP_DB_PASSWORD", "/myapp/"),
            "/myapp/db-password"
        );
    }

    #[test]
    fn reconstruct_ssm_name_full_key_when_no_prefix_match() {
        // Key doesn't start with MYAPP_ — use full key lower-hyphenated.
        assert_eq!(reconstruct_ssm_name("DB_URL", "/myapp/"), "/myapp/db-url");
    }

    #[test]
    fn reconstruct_ssm_name_root_path() {
        // Root path /: full key lower-hyphenated.
        assert_eq!(reconstruct_ssm_name("MY_KEY", "/"), "/my-key");
    }

    #[test]
    fn reconstruct_ssm_name_nested_path() {
        // /prod/myapp/ → strip PROD_MYAPP_ from PROD_MYAPP_API_KEY → api-key
        assert_eq!(
            reconstruct_ssm_name("PROD_MYAPP_API_KEY", "/prod/myapp/"),
            "/prod/myapp/api-key"
        );
    }

    #[test]
    fn normalize_ssm_path_prefix_adds_slashes() {
        assert_eq!(normalize_ssm_path_prefix(Some("myapp")), "/myapp/");
        assert_eq!(normalize_ssm_path_prefix(Some("/myapp")), "/myapp/");
        assert_eq!(normalize_ssm_path_prefix(Some("/myapp/")), "/myapp/");
        assert_eq!(normalize_ssm_path_prefix(None), "/");
        assert_eq!(normalize_ssm_path_prefix(Some("")), "/");
    }
}