// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! `fabrica key` — register and manage SSH and GPG public keys. use std::io::Read as _; use std::path::Path; use std::process::ExitCode; use clap::Subcommand; use model::{Key, KeyKind}; use store::{NewKey, Store}; use crate::context::{block_on, open_store}; use crate::prompt::confirm; /// Actions under `fabrica key`. #[derive(Debug, Subcommand)] pub(crate) enum KeyCommand { /// Register a public key for a user. The key material may be given literally, /// as `@path` to read a file, or `-` to read stdin. It is parsed and /// fingerprinted before storage; a duplicate fingerprint is rejected. Add { /// SSH or GPG. #[arg(long = "type", value_parser = parse_kind)] r#type: KeyKind, /// The user to register the key for. user: String, /// Key material: a literal key, `@path`, or `-` for stdin. key: String, /// Optional label (defaults to the key's own comment for SSH keys). #[arg(long)] name: Option, }, /// Remove a key by its 1-based index (as shown by `key list`). Indices are /// stable — removing one never renumbers the others. Del { /// The key's owner. user: String, /// The 1-based index from `key list`. index: i64, /// Skip the confirmation prompt (required when stdin is not a terminal). #[arg(long)] yes: bool, }, /// List a user's keys. List { /// The user whose keys to list. user: String, }, } /// Parse the `--type` value into a [`KeyKind`]. fn parse_kind(s: &str) -> Result { KeyKind::from_token(s).ok_or_else(|| format!("unknown key type {s:?} (expected ssh or gpg)")) } /// Dispatch a `key` subcommand. pub(crate) fn run( command: &KeyCommand, config_path: Option<&Path>, json: bool, ) -> anyhow::Result { match command { KeyCommand::Add { r#type, user, key, name, } => block_on(add(config_path, *r#type, user, key, name.clone())), KeyCommand::Del { user, index, yes } => block_on(del(config_path, user, *index, *yes)), KeyCommand::List { user } => block_on(list(config_path, user, json)), } } /// Read key material from a literal string, `@path`, or `-` (stdin). fn read_material(arg: &str) -> anyhow::Result { if arg == "-" { let mut buf = String::new(); std::io::stdin().read_to_string(&mut buf)?; Ok(buf) } else if let Some(path) = arg.strip_prefix('@') { Ok(std::fs::read_to_string(path)?) } else { Ok(arg.to_string()) } } /// Look up a user by name, or error cleanly. async fn require_user_id(store: &Store, name: &str) -> anyhow::Result { store .user_by_username(name) .await? .map(|u| u.id) .ok_or_else(|| anyhow::anyhow!("no such user {name:?}")) } async fn add( config_path: Option<&Path>, kind: KeyKind, user: &str, key: &str, name: Option, ) -> anyhow::Result { let (_config, store) = open_store(config_path).await?; let user_id = require_user_id(&store, user).await?; let material = read_material(key)?; let parsed = git::parse_public_key(kind, &material)?; // Reject a duplicate fingerprint, naming the existing owner. if let Some(existing) = store.key_by_fingerprint(kind, &parsed.fingerprint).await? { let owner = store .user_by_id(&existing.user_id) .await? .map_or_else(|| existing.user_id.clone(), |u| u.username); anyhow::bail!( "that {kind} key is already registered (fingerprint {}) to {owner}", parsed.fingerprint ); } let stored = store .create_key(NewKey { user_id, kind, name: name.or(parsed.label), fingerprint: parsed.fingerprint.clone(), public_key: parsed.public_key, }) .await?; println!( "added {kind} key #{} for {user}: {}", stored.ordinal, stored.fingerprint ); Ok(ExitCode::SUCCESS) } async fn del( config_path: Option<&Path>, user: &str, index: i64, yes: bool, ) -> anyhow::Result { let (_config, store) = open_store(config_path).await?; let user_id = require_user_id(&store, user).await?; let key = store .key_by_ordinal(&user_id, index) .await? .ok_or_else(|| anyhow::anyhow!("{user} has no key #{index}"))?; if !confirm( &format!("Delete {} key #{index} ({})?", key.kind, key.fingerprint), yes, )? { println!("aborted"); return Ok(ExitCode::SUCCESS); } store.delete_key(&key.id).await?; println!("deleted {} key #{index} for {user}", key.kind); Ok(ExitCode::SUCCESS) } async fn list(config_path: Option<&Path>, user: &str, json: bool) -> anyhow::Result { let (_config, store) = open_store(config_path).await?; let user_id = require_user_id(&store, user).await?; let keys = store.keys_by_user(&user_id).await?; if json { let view: Vec<_> = keys.iter().map(key_json).collect(); println!("{}", serde_json::to_string_pretty(&view)?); return Ok(ExitCode::SUCCESS); } if keys.is_empty() { println!("{user} has no keys"); return Ok(ExitCode::SUCCESS); } println!("{:>3} {:<4} {:<12} FINGERPRINT", "IDX", "TYPE", "NAME"); for key in &keys { println!( "{:>3} {:<4} {:<12} {}", key.ordinal, key.kind, key.name.as_deref().unwrap_or("-"), key.fingerprint ); } Ok(ExitCode::SUCCESS) } /// Render a key for `--json` (never includes secret material — public keys are /// public, but the shape mirrors the other list commands). fn key_json(key: &Key) -> serde_json::Value { serde_json::json!({ "index": key.ordinal, "type": key.kind.as_str(), "name": key.name, "fingerprint": key.fingerprint, "created_at": key.created_at, "last_used_at": key.last_used_at, }) } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; use crate::testutil::env; const SSH_KEY: &str = "ssh-ed25519 \ AAAAC3NzaC1lZDI1NTE5AAAAIJqq6nD0E4SlM+xw1UVOompehxQE8sUYCVoyV+NBjfKU cli-test@fabrica"; #[test] fn add_list_and_del_ssh_key() { let env = env(); block_on(async { anyhow::Ok(env.make_user("ada").await) }).unwrap(); block_on(add(env.path(), KeyKind::Ssh, "ada", SSH_KEY, None)).unwrap(); let keys = block_on(async { let store = env.store().await; let id = require_user_id(&store, "ada").await?; anyhow::Ok(store.keys_by_user(&id).await?) }) .unwrap(); assert_eq!(keys.len(), 1); assert_eq!(keys[0].ordinal, 1); assert_eq!(keys[0].name.as_deref(), Some("cli-test@fabrica")); assert!(keys[0].fingerprint.starts_with("SHA256:")); // A duplicate is rejected. let dup = block_on(add(env.path(), KeyKind::Ssh, "ada", SSH_KEY, None)); assert!(dup.is_err(), "duplicate fingerprint should be rejected"); // Delete by its ordinal. block_on(del(env.path(), "ada", 1, true)).unwrap(); let after = block_on(async { let store = env.store().await; let id = require_user_id(&store, "ada").await?; anyhow::Ok(store.keys_by_user(&id).await?) }) .unwrap(); assert!(after.is_empty()); } #[test] fn rejects_bad_key_material() { let env = env(); block_on(async { anyhow::Ok(env.make_user("bob").await) }).unwrap(); let err = block_on(add(env.path(), KeyKind::Ssh, "bob", "not a key", None)); assert!(err.is_err()); } }