ssh-cli 0.5.4

Native Rust CLI that gives LLMs (Claude Code, Cursor, Windsurf) the ability to operate remote servers via SSH over stdin/stdout
Documentation
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
// SPDX-License-Identifier: MIT OR Apache-2.0
// G-SECDEV-05: pure module — no `unsafe` permitted (crate root allows only OS FFI / test env).
#![forbid(unsafe_code)]
//! At-rest encryption of secrets in `config.toml` (GAP-009 / R-SECRETS-DEFAULT).
//!
//! Primary-key resolution order (32 bytes), 0.5.1:
//! 1. CLI flags (`--secrets-key-file`, `--use-keyring`, `--allow-plaintext-secrets`)
//! 2. OS keyring when enabled (`service=ssh-cli`, `user=secrets-primary-key`; legacy read alias)
//! 3. XDG `secrets.key` file (next to `config.toml`), auto-created on first write
//!
//! **Env-as-store is forbidden (G-ERR-13 / G-UNSAFE):** if `SSH_CLI_SECRETS_KEY` or
//! `SSH_CLI_SECRETS_KEY_FILE` is present, load **fails closed** with a clear error
//! pointing to XDG `secrets.key` or `--secrets-key-file`.
//!
//! Plaintext at-rest opt-out: **only** CLI `--allow-plaintext-secrets` (no env store).
//!
//! With a key: serialization writes `sshcli-enc:v2:<base64(nonce||ciphertext)>`.
//!
//! # Blob versions (A7)
//!
//! `v1` blobs were sealed **without** associated data, so the AEAD tag only
//! proved "encrypted by this key" and said nothing about *where* the blob
//! belongs. Anyone able to edit `config.toml` could move a `password` blob to
//! another host, or paste it into `su_password`, and decryption would still
//! succeed — context confusion with no detection.
//!
//! `v2` binds the ciphertext to a [`SecretContext`] (host name + field name) via
//! AEAD associated data, so a relocated blob fails tag verification.
//!
//! Compatibility is deliberate and dual-read:
//! - `v1` is still accepted on read (existing configs must keep working).
//! - `v2` is always written.
//! - A `v2` blob sealed under [`SecretContext::unbound`] — the context used by
//!   call sites not yet passing host/field — is accepted under any context. That
//!   keeps the migration monotonic: today's writes are no weaker than `v1`, and
//!   once a call site passes a real context the rewritten blob becomes strictly
//!   bound and can never be relocated afterwards.
//!
//! **Never** log or return the key or plaintext in public errors.

use crate::constants::{
    APP_NAME, ENV_SECRETS_KEY, ENV_SECRETS_KEY_FILE, PRIMARY_KEY_HEX_LEN, PRIMARY_KEY_LEN_BYTES,
    SECRETS_KEY_FILE_NAME,
};
use crate::errors::{SshCliError, SshCliResult};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use zeroize::{Zeroize, Zeroizing};

mod aead;
mod keyring_store;

pub use aead::SecretContext;
use aead::{decrypt_secret, encrypt_secret};
use keyring_store::read_keyring;
pub use keyring_store::write_key_to_keyring;

/// Prefix for legacy encrypted blobs without associated data (read-only).
pub const ENC_PREFIX: &str = "sshcli-enc:v1:";

/// Prefix for context-bound encrypted blobs (written by this version).
pub const ENC_PREFIX_V2: &str = "sshcli-enc:v2:";

/// Primary key material that scrubs itself on drop.
///
/// A8: the bare `[u8; 32]` is `Copy`, so every hand-off between
/// `load_primary_key` → `ensure_key_for_write` → `serialize_secret` left a
/// residual copy on a stack frame that no `.zeroize()` call could reach —
/// zeroizing the last binding cleaned one copy and no more. Wrapping the array
/// makes it move-only in practice: each frame owns exactly one value and drops
/// it scrubbed.
pub type PrimaryKey = Zeroizing<[u8; PRIMARY_KEY_LEN_BYTES]>;

/// File name of the primary key in the config directory (XDG sibling of `config.toml`).
pub const KEY_FILE_NAME: &str = SECRETS_KEY_FILE_NAME;

// Compile-time invariants (const/static rules).
const _: () = assert!(!ENC_PREFIX.is_empty());
const _: () = assert!(!ENC_PREFIX_V2.is_empty());
const _: () = assert!(!KEY_FILE_NAME.is_empty());
const _: () = assert!(PRIMARY_KEY_LEN_BYTES == 32);

/// Locks a process-global `Mutex`, recovering from poison explicitly.
///
/// Poison means a previous holder panicked; the data is still usable for this
/// one-shot CLI, so we take `into_inner()` rather than silently skipping updates.
/// Recovery is **logged** (Rules Rust: never silence `PoisonError` without log).
///
/// Critical sections using this helper must stay short and **never** hold the
/// guard across `.await` or blocking I/O (clone/copy under lock, then release).
fn lock_global<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    m.lock().unwrap_or_else(|poisoned| {
        tracing::warn!(
            "secrets process-global mutex was poisoned; recovering via into_inner (one-shot CLI)"
        );
        poisoned.into_inner()
    })
}

/// Config directory override (e.g. `--config-dir`) to align `secrets.key`.
///
/// Concurrent access: `std::sync::Mutex` (const ctor) — single composite state
/// (`Option<PathBuf>`); not split into uncoordinated atomics. Poison recovered
/// via [`lock_global`]. Never held across await.
static DIR_CONFIG_OVERRIDE: Mutex<Option<PathBuf>> = Mutex::new(None);

/// CLI runtime overrides (flags). Env remains as deprecated fallback.
#[derive(Debug, Default, Clone)]
struct RuntimeSecretsFlags {
    allow_plaintext: bool,
    secrets_key_file: Option<PathBuf>,
    use_keyring: bool,
}

/// Process-wide secrets CLI flags (set once after parse).
///
/// Single `Mutex` keeps the three fields consistent (Rules: do not protect a
/// multi-field invariant with independent atomics). See [`lock_global`].
static RUNTIME_FLAGS: Mutex<RuntimeSecretsFlags> = Mutex::new(RuntimeSecretsFlags {
    allow_plaintext: false,
    secrets_key_file: None,
    use_keyring: false,
});

/// Set when `secrets.key` is auto-created during this process (GAP-AUD-007).
///
/// Concurrent access: independent status bit; `Ordering::Relaxed` (no dependent
/// data fence — isolated flag, not paired with other memory).
static AUTO_KEY_CREATED: AtomicBool = AtomicBool::new(false);

/// Sets the config directory used to resolve `secrets.key` (one-shot; called from `dispatch`).
pub fn set_config_dir(dir: Option<PathBuf>) {
    *lock_global(&DIR_CONFIG_OVERRIDE) = dir;
}

/// Applies one-shot CLI flags for secrets resolution (GAP-AUD-006).
pub fn set_runtime_flags(
    allow_plaintext: bool,
    secrets_key_file: Option<PathBuf>,
    use_keyring: bool,
) {
    {
        let mut g = lock_global(&RUNTIME_FLAGS);
        g.allow_plaintext = allow_plaintext;
        g.secrets_key_file = secrets_key_file;
        g.use_keyring = use_keyring;
    }
    AUTO_KEY_CREATED.store(false, Ordering::Relaxed);
}

/// Returns true once if a key was auto-created since the last flag reset (consume).
#[must_use]
pub fn take_auto_key_created() -> bool {
    // RMW on an independent flag — Relaxed is enough (no data publish).
    AUTO_KEY_CREATED.swap(false, Ordering::Relaxed)
}

/// Returns true if a key was auto-created (non-consuming).
#[must_use]
pub fn auto_key_created() -> bool {
    AUTO_KEY_CREATED.load(Ordering::Relaxed)
}

/// Primary-key source (without exposing material).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeySource {
    /// No key source available (plaintext at-rest with opt-out or before first write).
    Absent,
    /// Reserved: env key material is **rejected** (fail-closed); never a success source.
    Env,
    /// File from CLI `--secrets-key-file`.
    ConfigFile,
    /// OS keyring.
    Keyring,
    /// XDG / config-dir `secrets.key` file.
    XdgFile,
}

impl KeySource {
    /// Stable name for JSON/doctor.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Absent => "none",
            Self::Env => "env",
            Self::ConfigFile => "file",
            Self::Keyring => "keyring",
            Self::XdgFile => "xdg_file",
        }
    }
}

/// Secrets mode report (no sensitive material).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretsStatus {
    /// Primary-key source.
    pub source: KeySource,
    /// If true, serialization encrypts secrets.
    pub encryption_active: bool,
    /// Path of `secrets.key` (may not exist yet).
    pub key_file_path: PathBuf,
    /// If true, plaintext opt-out is active.
    pub plaintext_opt_out: bool,
}

/// True if plaintext opt-out is active (CLI flag only — G-ERR-13, no env store).
#[must_use]
pub fn plaintext_allowed() -> bool {
    lock_global(&RUNTIME_FLAGS).allow_plaintext
}

/// Config directory used for `secrets.key` (CLI/test override > XDG).
///
/// # Errors
/// [`SshCliError::XdgDirectory`] when XDG cannot be resolved and no override is set.
pub fn secrets_config_dir() -> SshCliResult<PathBuf> {
    if let Some(d) = lock_global(&DIR_CONFIG_OVERRIDE).clone() {
        return Ok(d);
    }
    crate::paths::xdg_config_dir()
}

/// Canonical path of the local primary-key file.
pub fn secrets_key_path() -> SshCliResult<PathBuf> {
    Ok(secrets_config_dir()?.join(KEY_FILE_NAME))
}

/// Resolves primary key and source (does not auto-create).
///
/// # Errors
/// Returns an error if a configured key source exists but cannot be read or parsed.
pub fn load_primary_key() -> SshCliResult<(Option<PrimaryKey>, KeySource)> {
    // CLI flag: --secrets-key-file
    let secrets_key_file = lock_global(&RUNTIME_FLAGS).secrets_key_file.clone();
    if let Some(path) = secrets_key_file {
        let mut text =
            crate::paths::read_text_capped(&path, crate::paths::MAX_SECRETS_KEY_FILE_BYTES)
                .map_err(|e| {
                    SshCliError::InvalidArgument(format!(
                        "failed reading --secrets-key-file {}: {e}",
                        path.display()
                    ))
                })?;
        let key = parse_hex_key(text.trim())
            .map_err(|e| SshCliError::InvalidArgument(format!("invalid --secrets-key-file: {e}")));
        text.zeroize();
        return Ok((Some(key?), KeySource::ConfigFile));
    }

    // G-ERR-13: env-as-store for key material is forbidden (fail closed).
    if std::env::var_os(ENV_SECRETS_KEY).is_some()
        || std::env::var_os(ENV_SECRETS_KEY_FILE).is_some()
    {
        return Err(SshCliError::InvalidArgument(format!(
            "{ENV_SECRETS_KEY} / {ENV_SECRETS_KEY_FILE} are not supported; use XDG `{KEY_FILE_NAME}` \
             (`{APP_NAME} secrets init`) or --secrets-key-file"
        )));
    }

    let use_keyring_flag = lock_global(&RUNTIME_FLAGS).use_keyring;
    if use_keyring_flag {
        match read_keyring() {
            Ok(Some(key)) => return Ok((Some(key), KeySource::Keyring)),
            Ok(None) => {}
            Err(e) => {
                tracing::warn!(err = %e, "keyring unavailable; trying secrets.key");
            }
        }
    }

    let path = secrets_key_path()?;
    if path.is_file() {
        // G-ERR-R01: failing to *read* the key file is I/O, not a data error. The file
        // being unreadable and the file holding garbage are different problems with
        // different fixes, and they shared exit 65.
        let mut text =
            crate::paths::read_text_capped(&path, crate::paths::MAX_SECRETS_KEY_FILE_BYTES)
                .map_err(|e| {
                    tracing::debug!(err = %e, path = %path.display(), "failed reading secrets key");
                    e
                })?;
        let key = parse_hex_key(text.trim())
            .map_err(|e| SshCliError::InvalidArgument(format!("invalid {KEY_FILE_NAME}: {e}")));
        text.zeroize();
        return Ok((Some(key?), KeySource::XdgFile));
    }

    Ok((None, KeySource::Absent))
}

/// Ensures a key for **write**: loads existing or auto-creates `secrets.key`
/// (unless plaintext opt-out).
///
/// # Errors
/// Returns an error if auto-creating `secrets.key` fails when encryption is required.
pub fn ensure_key_for_write() -> SshCliResult<(Option<PrimaryKey>, KeySource)> {
    let (existing, source) = load_primary_key()?;
    if existing.is_some() {
        return Ok((existing, source));
    }
    if plaintext_allowed() {
        return Ok((None, KeySource::Absent));
    }
    let path = secrets_key_path()?;
    let mut hex = generate_hex_key()?;
    write_key_file(&path, &hex, false)?;
    AUTO_KEY_CREATED.store(true, Ordering::Relaxed);
    tracing::info!(
        path = %path.display(),
        "secrets.key auto-created (event secrets-key-auto-created)"
    );
    // G-ERR-R01: this key was produced by `generate_hex_key` three lines up, so failing
    // to parse it back is an internal contradiction, not bad user input. Exit 65 told
    // the caller to fix data they never supplied.
    let key = parse_hex_key(&hex).map_err(|e| {
        tracing::error!(err = %e, "generated key failed round-trip parse");
        SshCliError::software("key_encoding")
    });
    hex.zeroize();
    Ok((Some(key?), KeySource::XdgFile))
}

/// Current status (without loading material into logs).
pub fn secrets_status() -> SshCliResult<SecretsStatus> {
    let key_file_path = secrets_key_path()?;
    let (key, source) = load_primary_key()?;
    let encryption_active = key.is_some();
    // A8: dropping the `Zeroizing` scrubs the material; no manual call needed.
    drop(key);
    Ok(SecretsStatus {
        source,
        encryption_active,
        key_file_path,
        plaintext_opt_out: plaintext_allowed(),
    })
}

/// True if the string is already an encrypted blob (any supported version).
#[must_use]
pub fn is_encrypted_blob(value: &str) -> bool {
    value.starts_with(ENC_PREFIX) || value.starts_with(ENC_PREFIX_V2)
}

/// Serializes a secret for TOML: encrypts if a key exists (or is auto-created); otherwise plaintext.
///
/// Empty secret never becomes a blob `sshcli-enc` (GAP-SSH-EXP-001): export redacted zera
/// passwords and must store readable `""`, not ciphertext of empty string (which fools import
/// on another machine without the primary-key and fakes "secret present").
///
/// # Errors
/// Returns an error if key resolution, RNG, or AEAD encryption fails.
pub fn serialize_secret(plaintext: &str) -> SshCliResult<String> {
    serialize_secret_in_context(SecretContext::unbound(), plaintext)
}

/// Serializes a secret bound to `ctx` (A7): writes a `v2` blob sealed with AAD.
///
/// # Errors
/// Returns an error if key resolution, RNG, or AEAD encryption fails.
pub fn serialize_secret_in_context(
    ctx: SecretContext<'_>,
    plaintext: &str,
) -> SshCliResult<String> {
    if plaintext.is_empty() {
        return Ok(String::new());
    }
    let (key, _) = ensure_key_for_write()?;
    match key {
        None => Ok(plaintext.to_string()),
        // `key` is dropped scrubbed at the end of this arm (A8).
        Some(key) => encrypt_secret(&key, plaintext, ctx),
    }
}

/// Deserializes from TOML: decrypts `sshcli-enc:` blobs; otherwise returns as-is.
///
/// Uses [`SecretContext::unbound`], so it accepts `v1` blobs and `v2` blobs that
/// were themselves sealed unbound, but rejects a `v2` blob bound to a concrete
/// host/field. Call sites that know the owner must use
/// [`deserialize_secret_in_context`] to get the relocation check.
pub fn deserialize_secret(stored: &str) -> SshCliResult<String> {
    deserialize_secret_in_context(SecretContext::unbound(), stored)
}

/// Deserializes a secret expected to belong to `ctx`.
///
/// Fails when a `v2` blob was sealed for a different host or a different field:
/// the AEAD tag no longer verifies, which is the whole point of A7.
///
/// # Errors
/// Missing primary key, malformed blob, or AEAD verification failure.
pub fn deserialize_secret_in_context(ctx: SecretContext<'_>, stored: &str) -> SshCliResult<String> {
    if !is_encrypted_blob(stored) {
        return Ok(stored.to_string());
    }
    let (key, _) = load_primary_key()?;
    let key = key.ok_or_else(|| {
        SshCliError::InvalidArgument(format!(
            "config contains encrypted secrets; run `{APP_NAME} secrets init` (XDG `{KEY_FILE_NAME}`) or pass `--secrets-key-file PATH` / `--use-keyring` (env key material is not supported)"
        ))
    })?;
    decrypt_secret(&key, stored, ctx)
}

/// Generates [`PRIMARY_KEY_LEN_BYTES`] random bytes as [`PRIMARY_KEY_HEX_LEN`] hex chars.
pub fn generate_hex_key() -> SshCliResult<String> {
    let mut bytes = [0u8; PRIMARY_KEY_LEN_BYTES];
    // G-ERR-R01: a CSPRNG that cannot produce bytes is a broken host, not malformed
    // input. Reporting it as exit 65 told an agent to "fix the data" for a condition
    // no input change can resolve.
    getrandom::fill(&mut bytes).map_err(|_| SshCliError::software("rng"))?;
    let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
    bytes.zeroize();
    Ok(hex)
}

/// Writes hex key to file with 0o600 (when supported).
///
/// # Errors
/// Returns an error if the key is invalid, the file exists without force, or I/O fails.
pub fn write_key_file(path: &Path, hex64: &str, force: bool) -> SshCliResult<()> {
    let _ = parse_hex_key(hex64)
        .map_err(|e| SshCliError::InvalidArgument(format!("invalid key: {e}")))?;
    if path.exists() && !force {
        return Err(SshCliError::InvalidArgument(format!(
            "{} already exists; use --force to overwrite",
            path.display()
        )));
    }
    // GAP-AUD-SEC-001: backup previous key before force-overwrite.
    if path.exists() && force {
        let bak = path.with_file_name(format!(
            "{}.bak",
            path.file_name()
                .and_then(|s| s.to_str())
                .unwrap_or(KEY_FILE_NAME)
        ));
        if let Err(e) = std::fs::copy(path, &bak) {
            tracing::warn!(
                err = %e,
                path = %bak.display(),
                "failed to backup secrets key before --force"
            );
        }
    }
    if let Some(parent_dir) = path.parent() {
        std::fs::create_dir_all(parent_dir)?;
    }
    let parent_dir = path.parent().unwrap_or_else(|| Path::new("."));
    // G-ERR-R01: a full disk, a read-only mount or a missing XDG directory is I/O
    // (exit 74), not malformed data (exit 65). Every step below used to collapse into
    // `Config`, so `secrets init` on a read-only home reported "configuration error"
    // and an agent had no way to tell it apart from a corrupt registry file.
    let mut tmp = tempfile::NamedTempFile::new_in(parent_dir).map_err(SshCliError::Io)?;
    use std::io::Write;
    tmp.write_all(hex64.trim().as_bytes())
        .map_err(SshCliError::Io)?;
    tmp.write_all(b"\n").map_err(SshCliError::Io)?;
    tmp.as_file().sync_all().map_err(SshCliError::Io)?;
    crate::fs_perm::set_secret_file_mode(tmp.path())?;
    // `PersistError` wraps the underlying `io::Error`; unwrapping it keeps the real
    // cause instead of flattening "permission denied" into a formatted string.
    tmp.persist(path).map_err(|e| SshCliError::Io(e.error))?;
    // Best-effort re-apply after rename (matches prior ignore-on-error chmod).
    let _ = crate::fs_perm::set_secret_file_mode(path);
    Ok(())
}

/// Initializes primary-key in XDG file or keyring. **Never** prints the key.
///
/// # Errors
/// Returns an error if the key already exists without `--force`, RNG fails, or keyring/file I/O fails.
pub fn init_primary_key(use_keyring: bool, force: bool) -> SshCliResult<SecretsStatus> {
    let mut hex = generate_hex_key()?;
    if use_keyring {
        if !force {
            match read_keyring() {
                Ok(Some(_)) => {
                    hex.zeroize();
                    return Err(SshCliError::InvalidArgument(
                        "keyring already has a primary-key; use --force".to_string(),
                    ));
                }
                Ok(None) => {}
                Err(e) => {
                    hex.zeroize();
                    return Err(e);
                }
            }
        }
        let result = write_key_to_keyring(&hex);
        hex.zeroize();
        result?;
        return secrets_status();
    }
    let path = secrets_key_path()?;
    let result = write_key_file(&path, &hex, force);
    hex.zeroize();
    result?;
    secrets_status()
}

fn parse_hex_key(hex: &str) -> Result<PrimaryKey, String> {
    let h = hex.trim();
    // A6: `len()` counts BYTES while `&h[i*2..i*2+2]` requires a char boundary. A key
    // file holding multi-byte UTF-8 that happens to total 64 bytes would slice mid-character
    // and panic instead of returning a typed error. Rejecting non-ASCII first makes byte
    // offsets and character boundaries the same thing, so the loop below cannot panic.
    if !h.is_ascii() || h.len() != PRIMARY_KEY_HEX_LEN {
        return Err(format!(
            "expected {PRIMARY_KEY_HEX_LEN} hex characters ({PRIMARY_KEY_LEN_BYTES} bytes)"
        ));
    }
    // A8: fill the protected buffer directly so no bare `[u8; 32]` copy is left
    // behind on this frame.
    let mut out: PrimaryKey = Zeroizing::new([0u8; PRIMARY_KEY_LEN_BYTES]);
    for i in 0..PRIMARY_KEY_LEN_BYTES {
        let byte =
            u8::from_str_radix(&h[i * 2..i * 2 + 2], 16).map_err(|_| "invalid hex".to_string())?;
        out[i] = byte;
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    // Crypto types live in `secrets::aead` now; the legacy-v1 fixture below still
    // needs to seal a blob by hand, so it imports them locally instead of forcing
    // the production module to keep an import it no longer uses.
    use crate::constants::AEAD_NONCE_LEN_BYTES;
    use chacha20poly1305::aead::{Aead, KeyInit};
    use chacha20poly1305::{ChaCha20Poly1305, Nonce};
    use serial_test::serial;
    use tempfile::TempDir;

    fn clear_key_env() {
        // Fail-closed path reads these keys; clear so serial tests start clean.
        crate::test_util::env::remove_var(ENV_SECRETS_KEY);
        crate::test_util::env::remove_var(ENV_SECRETS_KEY_FILE);
        crate::test_util::env::remove_var(crate::constants::ENV_USE_KEYRING);
        set_runtime_flags(false, None, false);
        set_config_dir(None);
    }

    /// Isolates tests from real XDG (never pollute user config).
    fn sandbox() -> TempDir {
        clear_key_env();
        let tmp = TempDir::new().unwrap();
        set_config_dir(Some(tmp.path().to_path_buf()));
        tmp
    }

    #[test]
    #[serial]
    fn roundtrip_with_xdg_key() {
        let _tmp = sandbox();
        init_primary_key(false, false).expect("init key");
        let plain = "fake-test-password-not-real";
        let enc = serialize_secret(plain).unwrap();
        assert!(is_encrypted_blob(&enc));
        assert!(!enc.contains(plain));
        let back = deserialize_secret(&enc).unwrap();
        assert_eq!(back, plain);
        clear_key_env();
    }

    #[test]
    #[serial]
    fn opt_out_keeps_plaintext() {
        let _tmp = sandbox();
        set_runtime_flags(true, None, false);
        let plain = "fake-plaintext-only-for-unit-test";
        let out = serialize_secret(plain).unwrap();
        assert_eq!(out, plain);
        assert!(!is_encrypted_blob(&out));
        clear_key_env();
    }

    #[test]
    #[serial]
    fn default_auto_creates_secrets_key() {
        let tmp = sandbox();
        let plain = "fake-auto-enc-password";
        let enc = serialize_secret(plain).unwrap();
        assert!(is_encrypted_blob(&enc));
        assert!(!enc.contains(plain));
        assert!(tmp.path().join(KEY_FILE_NAME).is_file());
        let back = deserialize_secret(&enc).unwrap();
        assert_eq!(back, plain);
        clear_key_env();
    }

    #[test]
    #[serial]
    fn blob_without_key_fails() {
        let tmp = sandbox();
        init_primary_key(false, false).expect("init");
        let enc = serialize_secret("fake-secret").unwrap();
        // Drop key material from sandbox; allow plaintext so deserialize path
        // still requires a key for encrypted blobs.
        clear_key_env();
        set_config_dir(Some(tmp.path().to_path_buf()));
        let _ = std::fs::remove_file(tmp.path().join(KEY_FILE_NAME));
        set_runtime_flags(true, None, false);
        let err = deserialize_secret(&enc).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("encrypted") || msg.contains("secrets") || msg.contains("key"),
            "msg={msg}"
        );
        clear_key_env();
    }

    #[test]
    #[serial]
    fn empty_secret_never_encrypted_blob() {
        // GAP-SSH-EXP-001
        let _tmp = sandbox();
        init_primary_key(false, false).expect("init");
        let out = serialize_secret("").unwrap();
        assert_eq!(out, "");
        assert!(!is_encrypted_blob(&out));
        clear_key_env();
    }

    #[test]
    #[serial]
    fn v2_blob_rejects_foreign_host_and_field() {
        // A7: an operator editing config.toml must not be able to move a blob
        // between hosts or between fields and still have it decrypt.
        let _tmp = sandbox();
        init_primary_key(false, false).expect("init key");
        let plain = "fake-bound-secret";
        let host_a = SecretContext::new("host-a", "password");
        let enc = serialize_secret_in_context(host_a, plain).unwrap();
        assert!(enc.starts_with(ENC_PREFIX_V2), "v2 must be written");

        assert_eq!(deserialize_secret_in_context(host_a, &enc).unwrap(), plain);

        let other_host = SecretContext::new("host-b", "password");
        assert!(
            deserialize_secret_in_context(other_host, &enc).is_err(),
            "blob bound to host-a must not open as host-b"
        );

        let other_field = SecretContext::new("host-a", "su_password");
        assert!(
            deserialize_secret_in_context(other_field, &enc).is_err(),
            "blob bound to password must not open as su_password"
        );
        clear_key_env();
    }

    #[test]
    #[serial]
    fn unbound_blob_stays_readable_under_any_context() {
        // Migration: call sites not yet passing host/field write unbound blobs;
        // wiring a context later must not lock the user out of their config.
        let _tmp = sandbox();
        init_primary_key(false, false).expect("init key");
        let plain = "fake-unbound-secret";
        let enc = serialize_secret(plain).unwrap();
        assert!(enc.starts_with(ENC_PREFIX_V2));
        let bound = SecretContext::new("host-a", "password");
        assert_eq!(deserialize_secret_in_context(bound, &enc).unwrap(), plain);
        clear_key_env();
    }

    #[test]
    #[serial]
    fn legacy_v1_blob_still_decrypts() {
        // Existing configs hold v1 blobs sealed without associated data.
        let _tmp = sandbox();
        init_primary_key(false, false).expect("init key");
        let (key, _) = load_primary_key().unwrap();
        let key = key.expect("key present");
        let plain = "fake-legacy-v1-secret";

        // Rebuild a v1 blob exactly as the previous version wrote it.
        let cipher = ChaCha20Poly1305::new_from_slice(key.as_slice()).unwrap();
        let mut nonce_bytes = [0u8; AEAD_NONCE_LEN_BYTES];
        getrandom::fill(&mut nonce_bytes).unwrap();
        let ct = cipher
            .encrypt(&Nonce::from(nonce_bytes), plain.as_bytes())
            .unwrap();
        let mut packed = nonce_bytes.to_vec();
        packed.extend_from_slice(&ct);
        let blob = format!(
            "{ENC_PREFIX}{}",
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &packed)
        );

        assert!(is_encrypted_blob(&blob));
        assert_eq!(deserialize_secret(&blob).unwrap(), plain);
        assert_eq!(
            deserialize_secret_in_context(SecretContext::new("host-a", "password"), &blob).unwrap(),
            plain
        );
        clear_key_env();
    }

    #[test]
    fn aad_encoding_is_unambiguous() {
        // A host literally named "a:b" must not collide with the pair (a, b).
        assert_ne!(
            SecretContext::new("a:b", "password").aad(),
            SecretContext::new("a", "b:password").aad()
        );
        assert!(SecretContext::unbound().is_unbound());
        assert!(!SecretContext::new("host-a", "password").is_unbound());
    }

    #[test]
    fn parse_hex_tamanho() {
        assert!(parse_hex_key("aa").is_err());
        assert!(
            parse_hex_key("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff")
                .is_ok()
        );
    }

    #[test]
    #[serial]
    fn init_creates_file() {
        clear_key_env();
        let tmp = TempDir::new().unwrap();
        set_config_dir(Some(tmp.path().to_path_buf()));
        let st = init_primary_key(false, false).unwrap();
        assert!(st.encryption_active);
        assert_eq!(st.source, KeySource::XdgFile);
        assert!(st.key_file_path.is_file());
        clear_key_env();
    }

    #[test]
    fn lock_global_recovers_from_poison_with_usable_data() {
        let m = Mutex::new(42_u32);
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _g = m.lock().unwrap();
            panic!("intentional poison for lock_global test");
        }));
        assert!(m.is_poisoned());
        let g = lock_global(&m);
        assert_eq!(*g, 42);
    }
}