Skip to main content

ssh_cli/vps/
secrets_cmd.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// G-COMP: secrets command dispatcher extracted from vps/mod (SRP; line budget).
3#![forbid(unsafe_code)]
4//! One-shot `secrets status|init|reencrypt` local crypto workload.
5
6use super::config_io::{load, resolve_config_path, save};
7use crate::cli::{OutputFormat, SecretsAction};
8use crate::errors::SshCliError;
9use anyhow::Result;
10use std::path::{Path, PathBuf};
11
12/// Dispatcher one-shot de `secrets status|init|reencrypt`.
13/// Secrets primary-key status/init/reencrypt.
14///
15/// Workload: **local crypto + disk** (not multi-host SSH). Sequential justified:
16/// single key file / single config rewrite; Mutex in secrets layer.
17pub async fn run_secrets_command(
18    action: SecretsAction,
19    config_override: Option<PathBuf>,
20    format: OutputFormat,
21) -> Result<()> {
22    // Keep secrets.key aligned with --config-dir (owned copy for process static).
23    crate::secrets::set_config_dir(config_override.clone());
24    match action {
25        SecretsAction::Status { json } => {
26            let seg = crate::secrets::secrets_status()?;
27            let use_json = json || format == OutputFormat::Json;
28            if use_json {
29                let v = serde_json::json!({
30                    "encryption_active": seg.encryption_active,
31                    "key_source": seg.source.as_str(),
32                    "key_file": seg.key_file_path.display().to_string(),
33                    "plaintext_opt_out": seg.plaintext_opt_out,
34                    "at_rest": if seg.encryption_active { "encrypted" } else { "plaintext" },
35                });
36                crate::output::print_json_value(&v)?;
37            } else {
38                let at_rest = if seg.encryption_active {
39                    "encrypted"
40                } else {
41                    "plaintext"
42                };
43                crate::output::print_success_fmt(format_args!(
44                    "at-rest: {at_rest} | source: {} | key_file: {} | plaintext_opt_out: {}",
45                    seg.source.as_str(),
46                    seg.key_file_path.display(),
47                    seg.plaintext_opt_out
48                ));
49            }
50            Ok(())
51        }
52        SecretsAction::Init {
53            keyring,
54            force,
55            json,
56        } => {
57            // GAP-AUD-SEC-001: rotating the primary key without re-encrypting hosts
58            // permanently loses at-rest secrets. Load/decrypt BEFORE overwriting the key,
59            // then save under the new key after rotation.
60            let path = resolve_config_path(config_override.as_deref())?;
61            let hosts_to_reencrypt = if force && path.is_file() {
62                Some(load(&path)?)
63            } else {
64                None
65            };
66
67            let seg = crate::secrets::init_primary_key(keyring, force)?;
68            let mut reencrypted_hosts = 0usize;
69
70            if let Some(file) = hosts_to_reencrypt {
71                reencrypted_hosts = file.hosts.len();
72                save(&path, &file).map_err(|e| {
73                    SshCliError::Config(format!(
74                        "primary key was rotated but re-encrypting config failed: {e}; \
75                         restore secrets.key.bak if present and re-run `secrets reencrypt`"
76                    ))
77                })?;
78            }
79
80            let use_json = json || format == OutputFormat::Json;
81            crate::output::emit_success(
82                "secrets-init",
83                serde_json::json!({
84                    "key_source": seg.source.as_str(),
85                    "key_file": seg.key_file_path.display().to_string(),
86                    "reencrypted_hosts": reencrypted_hosts,
87                    "force": force,
88                }),
89                &crate::i18n::t(crate::i18n::Message::PrimaryKeyReady {
90                    source: seg.source.as_str().to_string(),
91                    key_file: seg.key_file_path.display().to_string(),
92                }),
93                use_json,
94            )?;
95            Ok(())
96        }
97        SecretsAction::Reencrypt { json } => {
98            let path = resolve_config_path(config_override.as_deref())?;
99            run_reencrypt(&path, json || format == OutputFormat::Json)?;
100            Ok(())
101        }
102    }
103}
104
105/// Reloads and rewrites config, re-encrypting secrets with the current key.
106/// Re-encrypt all secrets in `config.toml` with the current primary key.
107///
108/// Workload: **local AEAD** over one file. Sequential justified: single atomic
109/// save; host count is small vs coordination overhead.
110fn run_reencrypt(path: &Path, json: bool) -> Result<()> {
111    let (key, _source) = crate::secrets::ensure_key_for_write()?;
112    if key.is_none() {
113        return Err(SshCliError::InvalidArgument(
114            "no primary-key; run `ssh-cli secrets init` or pass --allow-plaintext-secrets"
115                .to_string(),
116        )
117        .into());
118    }
119    if let Some(mut k) = key {
120        use zeroize::Zeroize;
121        k.zeroize();
122    }
123    let file = load(path)?;
124    let hosts = file.hosts.len();
125    save(path, &file)?;
126    crate::output::emit_success(
127        "secrets-reencrypt",
128        serde_json::json!({ "hosts": hosts }),
129        &crate::i18n::t(crate::i18n::Message::ReencryptCompleted { hosts }),
130        json,
131    )?;
132    Ok(())
133}
134
135/// Side-effect metadata when `secrets.key` was auto-created in this process.
136///
137/// G-E2E-04: callers **fold** this into the primary success event (one JSON
138/// document per one-shot). Do **not** emit a second stdout root.
139#[derive(Debug, Clone)]
140pub(crate) struct AutoKeyMeta {
141    /// Absolute path to the primary-key file.
142    pub key_file: String,
143    /// Always `xdg_file` for auto-create.
144    pub key_source: &'static str,
145}
146
147/// Consumes the auto-key-created flag without writing to stdout (G-E2E-04).
148#[must_use]
149pub(crate) fn take_auto_key_meta() -> Option<AutoKeyMeta> {
150    if crate::secrets::take_auto_key_created() {
151        let path = crate::secrets::secrets_key_path().unwrap_or_default();
152        Some(AutoKeyMeta {
153            key_file: path.display().to_string(),
154            key_source: "xdg_file",
155        })
156    } else {
157        None
158    }
159}
160