fabrica

hanna/fabrica

8135 bytes
Raw
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `fabrica key` — register and manage SSH and GPG public keys.
6
7use std::io::Read as _;
8use std::path::Path;
9use std::process::ExitCode;
10
11use clap::Subcommand;
12use model::{Key, KeyKind};
13use store::{NewKey, Store};
14
15use crate::context::{block_on, open_store};
16use crate::prompt::confirm;
17
18/// Actions under `fabrica key`.
19#[derive(Debug, Subcommand)]
20pub(crate) enum KeyCommand {
21 /// Register a public key for a user. The key material may be given literally,
22 /// as `@path` to read a file, or `-` to read stdin. It is parsed and
23 /// fingerprinted before storage; a duplicate fingerprint is rejected.
24 Add {
25 /// SSH or GPG.
26 #[arg(long = "type", value_parser = parse_kind)]
27 r#type: KeyKind,
28 /// The user to register the key for.
29 user: String,
30 /// Key material: a literal key, `@path`, or `-` for stdin.
31 key: String,
32 /// Optional label (defaults to the key's own comment for SSH keys).
33 #[arg(long)]
34 name: Option<String>,
35 },
36 /// Remove a key by its 1-based index (as shown by `key list`). Indices are
37 /// stable — removing one never renumbers the others.
38 Del {
39 /// The key's owner.
40 user: String,
41 /// The 1-based index from `key list`.
42 index: i64,
43 /// Skip the confirmation prompt (required when stdin is not a terminal).
44 #[arg(long)]
45 yes: bool,
46 },
47 /// List a user's keys.
48 List {
49 /// The user whose keys to list.
50 user: String,
51 },
52}
53
54/// Parse the `--type` value into a [`KeyKind`].
55fn parse_kind(s: &str) -> Result<KeyKind, String> {
56 KeyKind::from_token(s).ok_or_else(|| format!("unknown key type {s:?} (expected ssh or gpg)"))
57}
58
59/// Dispatch a `key` subcommand.
60pub(crate) fn run(
61 command: &KeyCommand,
62 config_path: Option<&Path>,
63 json: bool,
64) -> anyhow::Result<ExitCode> {
65 match command {
66 KeyCommand::Add {
67 r#type,
68 user,
69 key,
70 name,
71 } => block_on(add(config_path, *r#type, user, key, name.clone())),
72 KeyCommand::Del { user, index, yes } => block_on(del(config_path, user, *index, *yes)),
73 KeyCommand::List { user } => block_on(list(config_path, user, json)),
74 }
75}
76
77/// Read key material from a literal string, `@path`, or `-` (stdin).
78fn read_material(arg: &str) -> anyhow::Result<String> {
79 if arg == "-" {
80 let mut buf = String::new();
81 std::io::stdin().read_to_string(&mut buf)?;
82 Ok(buf)
83 } else if let Some(path) = arg.strip_prefix('@') {
84 Ok(std::fs::read_to_string(path)?)
85 } else {
86 Ok(arg.to_string())
87 }
88}
89
90/// Look up a user by name, or error cleanly.
91async fn require_user_id(store: &Store, name: &str) -> anyhow::Result<String> {
92 store
93 .user_by_username(name)
94 .await?
95 .map(|u| u.id)
96 .ok_or_else(|| anyhow::anyhow!("no such user {name:?}"))
97}
98
99async fn add(
100 config_path: Option<&Path>,
101 kind: KeyKind,
102 user: &str,
103 key: &str,
104 name: Option<String>,
105) -> anyhow::Result<ExitCode> {
106 let (_config, store) = open_store(config_path).await?;
107 let user_id = require_user_id(&store, user).await?;
108
109 let material = read_material(key)?;
110 let parsed = git::parse_public_key(kind, &material)?;
111
112 // Reject a duplicate fingerprint, naming the existing owner.
113 if let Some(existing) = store.key_by_fingerprint(kind, &parsed.fingerprint).await? {
114 let owner = store
115 .user_by_id(&existing.user_id)
116 .await?
117 .map_or_else(|| existing.user_id.clone(), |u| u.username);
118 anyhow::bail!(
119 "that {kind} key is already registered (fingerprint {}) to {owner}",
120 parsed.fingerprint
121 );
122 }
123
124 let stored = store
125 .create_key(NewKey {
126 user_id,
127 kind,
128 name: name.or(parsed.label),
129 fingerprint: parsed.fingerprint.clone(),
130 public_key: parsed.public_key,
131 })
132 .await?;
133 println!(
134 "added {kind} key #{} for {user}: {}",
135 stored.ordinal, stored.fingerprint
136 );
137 Ok(ExitCode::SUCCESS)
138}
139
140async fn del(
141 config_path: Option<&Path>,
142 user: &str,
143 index: i64,
144 yes: bool,
145) -> anyhow::Result<ExitCode> {
146 let (_config, store) = open_store(config_path).await?;
147 let user_id = require_user_id(&store, user).await?;
148 let key = store
149 .key_by_ordinal(&user_id, index)
150 .await?
151 .ok_or_else(|| anyhow::anyhow!("{user} has no key #{index}"))?;
152
153 if !confirm(
154 &format!("Delete {} key #{index} ({})?", key.kind, key.fingerprint),
155 yes,
156 )? {
157 println!("aborted");
158 return Ok(ExitCode::SUCCESS);
159 }
160 store.delete_key(&key.id).await?;
161 println!("deleted {} key #{index} for {user}", key.kind);
162 Ok(ExitCode::SUCCESS)
163}
164
165async fn list(config_path: Option<&Path>, user: &str, json: bool) -> anyhow::Result<ExitCode> {
166 let (_config, store) = open_store(config_path).await?;
167 let user_id = require_user_id(&store, user).await?;
168 let keys = store.keys_by_user(&user_id).await?;
169
170 if json {
171 let view: Vec<_> = keys.iter().map(key_json).collect();
172 println!("{}", serde_json::to_string_pretty(&view)?);
173 return Ok(ExitCode::SUCCESS);
174 }
175 if keys.is_empty() {
176 println!("{user} has no keys");
177 return Ok(ExitCode::SUCCESS);
178 }
179 println!("{:>3} {:<4} {:<12} FINGERPRINT", "IDX", "TYPE", "NAME");
180 for key in &keys {
181 println!(
182 "{:>3} {:<4} {:<12} {}",
183 key.ordinal,
184 key.kind,
185 key.name.as_deref().unwrap_or("-"),
186 key.fingerprint
187 );
188 }
189 Ok(ExitCode::SUCCESS)
190}
191
192/// Render a key for `--json` (never includes secret material — public keys are
193/// public, but the shape mirrors the other list commands).
194fn key_json(key: &Key) -> serde_json::Value {
195 serde_json::json!({
196 "index": key.ordinal,
197 "type": key.kind.as_str(),
198 "name": key.name,
199 "fingerprint": key.fingerprint,
200 "created_at": key.created_at,
201 "last_used_at": key.last_used_at,
202 })
203}
204
205#[cfg(test)]
206mod tests {
207 #![allow(clippy::unwrap_used)]
208
209 use super::*;
210 use crate::testutil::env;
211
212 const SSH_KEY: &str = "ssh-ed25519 \
213AAAAC3NzaC1lZDI1NTE5AAAAIJqq6nD0E4SlM+xw1UVOompehxQE8sUYCVoyV+NBjfKU cli-test@fabrica";
214
215 #[test]
216 fn add_list_and_del_ssh_key() {
217 let env = env();
218 block_on(async { anyhow::Ok(env.make_user("ada").await) }).unwrap();
219
220 block_on(add(env.path(), KeyKind::Ssh, "ada", SSH_KEY, None)).unwrap();
221
222 let keys = block_on(async {
223 let store = env.store().await;
224 let id = require_user_id(&store, "ada").await?;
225 anyhow::Ok(store.keys_by_user(&id).await?)
226 })
227 .unwrap();
228 assert_eq!(keys.len(), 1);
229 assert_eq!(keys[0].ordinal, 1);
230 assert_eq!(keys[0].name.as_deref(), Some("cli-test@fabrica"));
231 assert!(keys[0].fingerprint.starts_with("SHA256:"));
232
233 // A duplicate is rejected.
234 let dup = block_on(add(env.path(), KeyKind::Ssh, "ada", SSH_KEY, None));
235 assert!(dup.is_err(), "duplicate fingerprint should be rejected");
236
237 // Delete by its ordinal.
238 block_on(del(env.path(), "ada", 1, true)).unwrap();
239 let after = block_on(async {
240 let store = env.store().await;
241 let id = require_user_id(&store, "ada").await?;
242 anyhow::Ok(store.keys_by_user(&id).await?)
243 })
244 .unwrap();
245 assert!(after.is_empty());
246 }
247
248 #[test]
249 fn rejects_bad_key_material() {
250 let env = env();
251 block_on(async { anyhow::Ok(env.make_user("bob").await) }).unwrap();
252 let err = block_on(add(env.path(), KeyKind::Ssh, "bob", "not a key", None));
253 assert!(err.is_err());
254 }
255}