Skip to main content

kanade_shared/
secrets.rs

1//! Registry-backed secret store for production credentials.
2//!
3//! Windows services run as LocalSystem and inherit Machine-scope env
4//! vars, but those vars are readable by any logged-in user. Storing
5//! the credential under HKLM with a hardened ACL (SYSTEM +
6//! Administrators only) keeps it out of low-privilege reach.
7//!
8//! Layout in use across kanade:
9//!
10//! ```text
11//! HKLM\SOFTWARE\kanade\
12//!   agent\
13//!     NatsToken      — shared NATS bearer token (agent + backend + CLI)
14//!   backend\
15//!     StaticToken    — KANADE_AUTH_STATIC_TOKEN counterpart
16//!     JwtSecret      — KANADE_JWT_SECRET counterpart
17//!     MailPassword   — KANADE_MAIL_PASSWORD counterpart (SMTP AUTH)
18//! ```
19//!
20//! `deploy-agent.ps1` / `deploy-backend.ps1` provision these keys and
21//! apply the ACL. Non-Windows builds get an empty stub so the
22//! workspace still cross-compiles for the CLI's Linux / macOS release
23//! artifacts.
24
25/// Read a `REG_SZ` value from `HKLM\<subkey>` and return it when
26/// non-empty. Returns `None` for missing keys, missing values, empty
27/// strings, or non-Windows targets.
28#[cfg(windows)]
29pub fn read_hklm_value(subkey: &str, value: &str) -> Option<String> {
30    use winreg::RegKey;
31    use winreg::enums::HKEY_LOCAL_MACHINE;
32
33    let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
34    let key = hklm.open_subkey(subkey).ok()?;
35    let s: String = key.get_value(value).ok()?;
36    if s.is_empty() { None } else { Some(s) }
37}
38
39#[cfg(not(windows))]
40pub fn read_hklm_value(_subkey: &str, _value: &str) -> Option<String> {
41    None
42}
43
44/// Like [`read_hklm_value`], but separating **absent** from **unreadable**.
45///
46/// `read_hklm_value` collapses the two into `None`, which is fine for a value
47/// consulted once at startup: either way there is nothing to use. It is not
48/// fine for one re-read on a schedule, where "absent" means *adopt an empty
49/// value* — a transient failure would then replace whatever is loaded with
50/// nothing, on every poll, forever. The command keyring is read that way
51/// (#1165), and there "adopt nothing" silently turns verification off.
52///
53/// `Ok(None)` is reserved for the cases that genuinely mean absent: the subkey
54/// or value does not exist, the value is empty, or this is not Windows and
55/// there is no registry to consult.
56#[cfg(windows)]
57pub fn try_read_hklm_value(subkey: &str, value: &str) -> Result<Option<String>, String> {
58    use std::io::ErrorKind;
59    use winreg::RegKey;
60    use winreg::enums::HKEY_LOCAL_MACHINE;
61
62    let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
63    let key = match hklm.open_subkey(subkey) {
64        Ok(k) => k,
65        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
66        Err(e) => return Err(format!("open HKLM\\{subkey}: {e}")),
67    };
68    match key.get_value::<String, _>(value) {
69        Ok(s) if s.is_empty() => Ok(None),
70        Ok(s) => Ok(Some(s)),
71        Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
72        Err(e) => Err(format!("read HKLM\\{subkey}\\{value}: {e}")),
73    }
74}
75
76#[cfg(not(windows))]
77pub fn try_read_hklm_value(_subkey: &str, _value: &str) -> Result<Option<String>, String> {
78    // Genuinely absent rather than a failure: there is no registry here, so
79    // "nothing is provisioned" is the truthful answer and an agent on this
80    // platform simply holds no keys.
81    Ok(None)
82}
83
84/// Write a `REG_SZ` value into an **existing** `HKLM\<subkey>`.
85///
86/// Deliberately opens rather than creates. Registry ACLs are per-key, and the
87/// deploy scripts are what harden `HKLM\SOFTWARE\kanade\*` to SYSTEM +
88/// Administrators. Creating a missing key here would produce an unhardened one
89/// and leave whatever secret is being written readable by any logged-in user —
90/// the exact thing this module exists to prevent. A missing key means the host
91/// was never deployed properly, which is worth failing loudly over.
92#[cfg(windows)]
93pub fn write_hklm_value(subkey: &str, value: &str, data: &str) -> Result<(), String> {
94    use winreg::RegKey;
95    use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_WRITE};
96
97    let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
98    let key = hklm
99        .open_subkey_with_flags(subkey, KEY_WRITE)
100        .map_err(|e| match e.kind() {
101            // The two failures need opposite responses, so they must not share
102            // a message. Asserting "not present, deploy this host" at an
103            // operator whose real problem is an unelevated shell sends them
104            // re-running a deploy that was already fine.
105            std::io::ErrorKind::NotFound => format!(
106                "HKLM\\{subkey} is not present — refusing to create it. A key created here \
107                 would not carry the SYSTEM+Administrators ACL the deploy scripts apply, \
108                 leaving the value readable by any logged-in user. Deploy this host first."
109            ),
110            std::io::ErrorKind::PermissionDenied => format!(
111                "HKLM\\{subkey} exists but could not be opened for writing: {e}. It is \
112                 restricted to SYSTEM + Administrators — run this elevated."
113            ),
114            _ => format!("HKLM\\{subkey} could not be opened for writing: {e}"),
115        })?;
116    key.set_value(value, &data.to_string())
117        .map_err(|e| format!("writing HKLM\\{subkey}\\{value}: {e}"))
118}
119
120#[cfg(not(windows))]
121pub fn write_hklm_value(_subkey: &str, _value: &str, _data: &str) -> Result<(), String> {
122    Err("registry secrets are Windows-only".to_string())
123}