Skip to main content

hyprstream_core/cli/
user_handlers.rs

1//! Handlers for `hyprstream user` CLI subcommands.
2// CLI handlers intentionally print to stdout/stderr for user interaction
3#![allow(clippy::print_stdout, clippy::print_stderr)]
4
5use anyhow::{Context, Result};
6use base64::{engine::general_purpose::STANDARD, Engine};
7use ed25519_dalek::{SigningKey, VerifyingKey};
8use std::io::{Read, Write};
9use std::path::Path;
10
11use crate::auth::ProductionUserStore;
12use crate::cli::commands::UserKeysImportFormat;
13use crate::cli::enroll::{enroll_user, EnrollKeySource};
14
15async fn open_store(credentials_dir: &Path) -> Result<ProductionUserStore> {
16    ProductionUserStore::open(credentials_dir)
17        .await
18        .context("Failed to open production credential store")
19}
20
21/// Resolve key material: from -f <path>, -f -, or inline data.
22fn resolve_key_input(file: Option<&str>, data: Option<&str>) -> Result<String> {
23    if let Some(path) = file {
24        if path == "-" {
25            let mut buf = String::new();
26            std::io::stdin().read_to_string(&mut buf)?;
27            return Ok(buf.trim().to_owned());
28        }
29        return std::fs::read_to_string(path)
30            .with_context(|| format!("Failed to read key file: {path}"))
31            .map(|s| s.trim().to_owned());
32    }
33    data.map(|s| s.trim().to_owned())
34        .ok_or_else(|| anyhow::anyhow!("Provide key via -f <path> or inline as the last argument"))
35}
36
37/// Parse an SSH Ed25519 public key line into a VerifyingKey.
38///
39/// Accepts: `ssh-ed25519 <base64> [comment]`
40/// Wire format: u32be(11) "ssh-ed25519" u32be(32) <32-byte-key> = 51 bytes total.
41fn parse_ssh_ed25519(line: &str) -> Result<VerifyingKey> {
42    let line = line.trim();
43    let b64_part = if let Some(rest) = line.strip_prefix("ssh-ed25519 ") {
44        rest.split_whitespace().next().unwrap_or(rest)
45    } else {
46        anyhow::bail!("Not an SSH Ed25519 key line (expected 'ssh-ed25519 AAAA...'). To import a raw key use 'keys import <username> raw'.");
47    };
48
49    let wire = STANDARD
50        .decode(b64_part)
51        .context("Invalid base64 in SSH public key")?;
52
53    if wire.len() != 51 {
54        anyhow::bail!(
55            "SSH Ed25519 wire format must be 51 bytes, got {}. Ensure this is an ssh-ed25519 key (not another type).",
56            wire.len()
57        );
58    }
59
60    // Validate the embedded type string
61    let type_len_bytes: [u8; 4] = wire[0..4]
62        .try_into()
63        .map_err(|_| anyhow::anyhow!("Malformed SSH wire prefix"))?;
64    let type_len = u32::from_be_bytes(type_len_bytes) as usize;
65    if type_len != 11 || &wire[4..15] != b"ssh-ed25519" {
66        anyhow::bail!("Key type mismatch: only Ed25519 keys are supported; got ssh-rsa or similar. Use: ssh-keygen -t ed25519");
67    }
68
69    let key_bytes: [u8; 32] = wire[19..51]
70        .try_into()
71        .map_err(|_| anyhow::anyhow!("Malformed SSH Ed25519 wire payload"))?;
72
73    VerifyingKey::from_bytes(&key_bytes).context("Invalid Ed25519 public key bytes")
74}
75
76/// Handle `user register <username>`
77pub async fn handle_user_register(credentials_dir: &Path, username: &str) -> Result<()> {
78    let store = open_store(credentials_dir).await?;
79    store
80        .register(username)
81        .await
82        .context("Failed to register user")?;
83    println!("Registered user '{username}'");
84    Ok(())
85}
86
87/// Handle `user list`
88pub async fn handle_user_list(credentials_dir: &Path) -> Result<()> {
89    let store = open_store(credentials_dir).await?;
90    let mut users = store.list_users().await?;
91    if users.is_empty() {
92        println!("No users registered.");
93    } else {
94        users.sort();
95        for u in &users {
96            println!("{u}");
97        }
98    }
99    Ok(())
100}
101
102/// Handle `user remove <username> [--force]`
103pub async fn handle_user_remove(credentials_dir: &Path, username: &str, force: bool) -> Result<()> {
104    if !force {
105        print!("Remove user '{username}'? [y/N] ");
106        std::io::stdout().flush()?;
107        let mut input = String::new();
108        std::io::stdin().read_line(&mut input)?;
109        if input.trim().to_lowercase() != "y" {
110            println!("Cancelled.");
111            return Ok(());
112        }
113    }
114    let store = open_store(credentials_dir).await?;
115    let removed = store.remove(username).await?;
116    if removed {
117        println!("Removed user '{username}'");
118    } else {
119        println!("User '{username}' not found");
120    }
121    Ok(())
122}
123
124/// Handle `user keys list <username>`
125pub async fn handle_user_keys_list(credentials_dir: &Path, username: &str) -> Result<()> {
126    let store = open_store(credentials_dir).await?;
127    let pubkeys = store.list_pubkeys(username).await?;
128    if pubkeys.is_empty() {
129        println!("No keys registered for '{username}'");
130    } else {
131        for pk in &pubkeys {
132            let label = pk.label.as_deref().unwrap_or("(no label)");
133            let ts = pk.created_at;
134            println!(
135                "{}  {}  algorithm={}  (added {})",
136                pk.fingerprint,
137                label,
138                pk.algorithm.as_str(),
139                ts
140            );
141        }
142    }
143    Ok(())
144}
145
146/// Handle `user keys import <username> <format>`
147pub async fn handle_user_keys_import(
148    credentials_dir: &Path,
149    username: &str,
150    format: &UserKeysImportFormat,
151) -> Result<()> {
152    let (pubkey, label) = match format {
153        UserKeysImportFormat::SshEd25519 { file, data, label } => {
154            let input = resolve_key_input(file.as_deref(), data.as_deref())?;
155            let vk = parse_ssh_ed25519(&input)?;
156            (vk, label.clone())
157        }
158        UserKeysImportFormat::Raw { file, data, label } => {
159            let input = resolve_key_input(file.as_deref(), data.as_deref())?;
160            let raw = STANDARD
161                .decode(input.trim())
162                .context("Invalid base64 for raw key")?;
163            let bytes: [u8; 32] = raw
164                .try_into()
165                .map_err(|_| anyhow::anyhow!("Raw key must be 32 bytes (Ed25519)"))?;
166            let vk = VerifyingKey::from_bytes(&bytes).context("Invalid Ed25519 public key")?;
167            (vk, label.clone())
168        }
169    };
170
171    let store = open_store(credentials_dir).await?;
172    let fingerprint = store
173        .add_pubkey(username, pubkey, label)
174        .await
175        .context("Failed to add key")?;
176    println!("Added key {fingerprint}");
177    Ok(())
178}
179
180/// Handle `user create <username> [--role] [--generate|--key|--ssh] [--no-role]`.
181///
182/// One-command enrollment (#439): generates (default) or adopts a signing key,
183/// installs it as the client's actual signing key, registers the user record,
184/// binds the derived public key, and grants a role — collapsing the multi-step
185/// dance whose partial failure silently authenticates as `anonymous`.
186pub async fn handle_user_create(
187    credentials_dir: &Path,
188    username: &str,
189    role: &str,
190    no_role: bool,
191    generate: bool,
192    key: Option<&str>,
193    ssh: Option<&str>,
194) -> Result<()> {
195    let store = open_store(credentials_dir).await?;
196    let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()
197        .context("Failed to resolve secrets directory")?;
198
199    let source = resolve_create_key_source(generate, key, ssh)?;
200
201    // Enrollment is a root-of-trust path and uses the same mandatory hybrid
202    // suite as envelope traffic.
203    let policy = hyprstream_rpc::envelope::mandatory_envelope_policy();
204
205    let outcome = enroll_user(&*store, &secrets_dir, username, source, policy)
206        .await
207        .context("Failed to enroll user")?;
208
209    println!("✓ Enrolled user '{}'", outcome.username);
210    if let Some(bak) = &outcome.key_backed_up {
211        println!("  Backed up prior signing key to {}", bak.display());
212    }
213    if let Some(bak) = &outcome.pq_key_backed_up {
214        println!("  Backed up prior post-quantum key to {}", bak.display());
215    }
216    println!("  Signing key installed as the client key — the CLI now signs with this key.");
217    println!(
218        "  Fingerprint: {}  (algorithm={})",
219        outcome.fingerprint,
220        outcome.algorithm.as_str()
221    );
222    for notice in &outcome.notices {
223        println!("  ⚠ {notice}");
224    }
225    println!(
226        "  Verify: `ssh-keygen -l -E sha256` of the key prints {}",
227        outcome.fingerprint
228    );
229
230    if !no_role {
231        // Best-effort role grant via the running PolicyService. Enrollment
232        // already succeeded; a down service (or first-run setup) must not undo
233        // it — point the operator at the manual command instead.
234        match grant_role(username, role).await {
235            Ok(()) => {}
236            Err(e) => {
237                println!(
238                    "  ⚠ Could not grant role '{role}' automatically ({e}).\n    \
239                     Run `hyprstream policy role add {username} {role}` once services are up."
240                );
241            }
242        }
243    }
244
245    Ok(())
246}
247
248/// Resolve the `user create` key source from the `--generate`/`--key`/`--ssh`
249/// flags. `--generate` (or no key flag) → [`EnrollKeySource::Generate`].
250fn resolve_create_key_source(
251    _generate: bool,
252    key: Option<&str>,
253    ssh: Option<&str>,
254) -> Result<EnrollKeySource> {
255    if let Some(path) = ssh {
256        let sk = parse_openssh_ed25519(path)?;
257        return Ok(EnrollKeySource::SigningKey(sk));
258    }
259    if let Some(path) = key {
260        let seed = read_seed_file(path)?;
261        return Ok(EnrollKeySource::RawSeed(seed));
262    }
263    Ok(EnrollKeySource::Generate)
264}
265
266/// Read a raw 32-byte Ed25519 seed from a file (or `-` stdin). Accepts either
267/// raw 32 bytes or standard base64 of 32 bytes.
268fn read_seed_file(path: &str) -> Result<[u8; 32]> {
269    let raw = if path == "-" {
270        let mut buf = Vec::new();
271        std::io::stdin().read_to_end(&mut buf)?;
272        buf
273    } else {
274        std::fs::read(path).with_context(|| format!("Failed to read seed file: {path}"))?
275    };
276
277    let seed: [u8; 32] = if raw.len() == 32 {
278        raw.try_into()
279            .map_err(|_| anyhow::anyhow!("Seed file is not 32 bytes (Ed25519)"))?
280    } else {
281        // Try base64 of 32 bytes.
282        let s = std::str::from_utf8(&raw).map_err(|_| {
283            anyhow::anyhow!("Seed file is neither 32 raw bytes nor base64 of 32 bytes")
284        })?;
285        let decoded = STANDARD.decode(s.trim()).map_err(|_| {
286            anyhow::anyhow!("Seed file is neither 32 raw bytes nor base64 of 32 bytes")
287        })?;
288        decoded
289            .try_into()
290            .map_err(|_| anyhow::anyhow!("Decoded seed is not 32 bytes (Ed25519)"))?
291    };
292    Ok(seed)
293}
294
295/// Parse an OpenSSH Ed25519 private key from `path`, prompting for a passphrase
296/// if the key is encrypted.
297fn parse_openssh_ed25519(path: &str) -> Result<SigningKey> {
298    let pem = std::fs::read_to_string(path)
299        .with_context(|| format!("Failed to read OpenSSH key: {path}"))?;
300    let key = ssh_key::PrivateKey::from_openssh(&pem)
301        .with_context(|| format!("Failed to parse OpenSSH private key: {path}"))?;
302    let key = if key.is_encrypted() {
303        let passphrase = prompt_passphrase()?;
304        key.decrypt(&passphrase)
305            .context("Failed to decrypt OpenSSH key (wrong passphrase?)")?
306    } else {
307        key
308    };
309    match key.key_data() {
310        ssh_key::private::KeypairData::Ed25519(ed) => Ok(SigningKey::from(&ed.private)),
311        _ => anyhow::bail!(
312            "{path} is not an Ed25519 key ({}); only ssh-ed25519 is supported. \
313             Generate one with: ssh-keygen -t ed25519",
314            key.algorithm().as_str()
315        ),
316    }
317}
318
319/// Prompt the terminal for an OpenSSH passphrase without echoing it.
320fn prompt_passphrase() -> Result<String> {
321    inquire::Password::new("Passphrase (OpenSSH key is encrypted): ")
322        .with_display_mode(inquire::PasswordDisplayMode::Hidden)
323        .without_confirmation()
324        .prompt()
325        .map_err(|e| anyhow::anyhow!("failed to read passphrase: {e}"))
326}
327
328/// Grant a role to `username` via the running PolicyService.
329async fn grant_role(username: &str, role: &str) -> Result<()> {
330    let keys_dir = std::path::PathBuf::from("."); // load_or_generate_signing_key resolves via config
331    let signing_key = crate::cli::load_or_generate_signing_key(&keys_dir).await?;
332    crate::cli::handle_policy_role_add(&signing_key, username, role, false).await
333}
334
335/// Handle `user keys remove <username> <fingerprint>`
336pub async fn handle_user_keys_remove(
337    credentials_dir: &Path,
338    username: &str,
339    fingerprint: &str,
340) -> Result<()> {
341    // Normalize: ensure SHA256: prefix is present regardless of whether user included it
342    let owned;
343    let fp = if fingerprint.starts_with("SHA256:") {
344        fingerprint
345    } else {
346        owned = format!("SHA256:{fingerprint}");
347        &owned
348    };
349    let store = open_store(credentials_dir).await?;
350    let removed = store.remove_pubkey(username, fp).await?;
351    if removed {
352        println!("Removed key {fp}");
353    } else {
354        println!("Key {fp} not found for '{username}'");
355    }
356    Ok(())
357}