forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

cli.rs400 lines, 14.2 KiBHistoryRawDownload
1//! The `im client` commands: register, list and disable OpenID Connect clients from the operator's
2//! shell.
3//!
4//! The commands open the database and the instance key directly, as the server does at boot, so they
5//! need the data directory. A client secret is printed once, on standard output, and only its SHA-256
6//! is stored. The redirect, logout and back-channel URIs are checked by the same rules the endpoints use.
7
8use std::fmt::Display;
9use std::path::{Path, PathBuf};
10use std::process::ExitCode;
11
12use im_core::config::Config;
13use im_core::names::parse_display_name;
14use im_core::oauth::{
15 SUPPORTED_SCOPES, is_client_family_key, is_supported_scope, is_valid_registered_uri,
16};
17use im_core::store::clients::NewClient;
18use im_core::token::{generate_token, hash_token};
19
20use crate::boot::{KEY_FILE, lock_data_dir, open_state};
21use crate::pages::admin::clients::is_origin;
22use crate::state::AppState;
23
24/// Printed with a usage error.
25const USAGE: &str = "usage:
26 im client add --name <name> [--redirect-uri <uri>]... [--post-logout-uri <uri>]...
27 [--backchannel-uri <uri>] [--family-key <key> --public-url <origin>] [--scopes <scope ...>]
28 im client list
29 im client disable <client_id>";
30
31/// The scopes a client gets when `--scopes` is not given: what a family app signs in with.
32const DEFAULT_SCOPES: &str = "openid profile email";
33
34/// Runs one `im client` command. `words` are the words after `client`.
35pub async fn client(config: &Path, words: &[String]) -> ExitCode {
36 let Some((verb, rest)) = words.split_first() else {
37 return usage();
38 };
39 match verb.as_str() {
40 "add" => match parse_add(rest) {
41 Ok(args) => with_state(config, |state| add(state, args)).await,
42 Err(message) => {
43 eprintln!("im: {message}\n{USAGE}");
44 ExitCode::from(2)
45 }
46 },
47 "list" if rest.is_empty() => with_state(config, list).await,
48 "disable" => match rest {
49 [id] => with_state(config, |state| disable(state, id)).await,
50 _ => usage(),
51 },
52 _ => usage(),
53 }
54}
55
56/// Prints the usage and exits with status 2.
57fn usage() -> ExitCode {
58 eprintln!("im: unknown client command\n{USAGE}");
59 ExitCode::from(2)
60}
61
62/// Prints a failure and exits with status 1.
63fn fail(error: impl Display) -> ExitCode {
64 eprintln!("im: {error}");
65 ExitCode::FAILURE
66}
67
68/// Opens the configuration, the key and the database, runs `action`, and maps its result to an exit
69/// status.
70async fn with_state<F, Fut>(config: &Path, action: F) -> ExitCode
71where
72 F: FnOnce(AppState) -> Fut,
73 Fut: std::future::Future<Output = Result<(), String>>,
74{
75 let outcome = async {
76 let config = Config::load(config).map_err(|e| e.to_string())?;
77 // Held for the whole command: a running server holds the same lock and refuses this one.
78 let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?;
79 let state = open_state(config).await.map_err(|e| e.to_string())?;
80 action(state).await
81 }
82 .await;
83 match outcome {
84 Ok(()) => ExitCode::SUCCESS,
85 Err(message) => fail(message),
86 }
87}
88
89/// The options of `im client add`.
90#[derive(Debug, Default, PartialEq, Eq)]
91struct AddArgs {
92 name: Option<String>,
93 redirect_uris: Vec<String>,
94 post_logout_uris: Vec<String>,
95 backchannel_uri: Option<String>,
96 family_key: Option<String>,
97 public_url: Option<String>,
98 scopes: Option<String>,
99}
100
101/// Reads `--flag value` pairs. Flags that repeat collect; the rest may be given once.
102fn parse_add(words: &[String]) -> std::result::Result<AddArgs, String> {
103 let mut args = AddArgs::default();
104 let mut words = words.iter();
105 while let Some(flag) = words.next() {
106 let value = words
107 .next()
108 .ok_or_else(|| format!("{flag} needs a value"))?
109 .clone();
110 let once = |slot: &mut Option<String>| {
111 if slot.replace(value.clone()).is_some() {
112 Err(format!("{flag} may be given only once"))
113 } else {
114 Ok(())
115 }
116 };
117 match flag.as_str() {
118 "--name" => once(&mut args.name)?,
119 "--redirect-uri" => args.redirect_uris.push(value),
120 "--post-logout-uri" => args.post_logout_uris.push(value),
121 "--backchannel-uri" => once(&mut args.backchannel_uri)?,
122 "--family-key" => once(&mut args.family_key)?,
123 "--public-url" => once(&mut args.public_url)?,
124 "--scopes" => once(&mut args.scopes)?,
125 other => return Err(format!("unknown option {other}")),
126 }
127 }
128 Ok(args)
129}
130
131/// Registers a client and prints its id and its secret. The secret is not shown again.
132async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> {
133 let name = parse_display_name(args.name.as_deref().ok_or("--name is required")?)
134 .map_err(|e| e.to_string())?;
135 for uri in args
136 .redirect_uris
137 .iter()
138 .chain(&args.post_logout_uris)
139 .chain(args.backchannel_uri.iter())
140 {
141 if !is_valid_registered_uri(uri) {
142 return Err(format!(
143 "{uri} is not a valid URI for a client (https, or http on loopback, no fragment or userinfo)"
144 ));
145 }
146 }
147 if let Some(key) = &args.family_key
148 && !is_client_family_key(key)
149 {
150 return Err(format!(
151 "family key {key} must be lowercase letters, digits and hyphens, and not im (the home row)"
152 ));
153 }
154 match (&args.family_key, &args.public_url) {
155 (Some(_), None) => {
156 return Err("a family key needs --public-url, the origin of its service".into());
157 }
158 (None, Some(_)) => return Err("--public-url is only for a family key".into()),
159 (Some(_), Some(url)) if !is_origin(url) => {
160 return Err(format!("{url} is not an origin (scheme and host, no path)"));
161 }
162 _ => {}
163 }
164 let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?;
165
166 let secret = generate_token();
167 let secret_hash = hash_token(&secret);
168 let new = NewClient {
169 name: &name,
170 secret_hash: &secret_hash,
171 redirect_uris: &args.redirect_uris,
172 post_logout_redirect_uris: &args.post_logout_uris,
173 backchannel_logout_uri: args.backchannel_uri.as_deref(),
174 allowed_scopes: &scopes,
175 service_key: args.family_key.as_deref(),
176 };
177 // A family client and its switcher row are written in one transaction, as the admin page does.
178 let client = match (&args.family_key, &args.public_url) {
179 (Some(_), Some(url)) => state.store.create_family_client(&new, &name, url).await,
180 _ => state.store.create_client(&new).await,
181 }
182 .map_err(|e| e.to_string())?;
183 println!("client_id: {}", client.id);
184 println!("client_secret: {secret}");
185 eprintln!("im: the client secret is shown once; store it now");
186 Ok(())
187}
188
189/// The requested scopes, checked and de-duplicated, space separated.
190fn scope_list(requested: &str) -> std::result::Result<String, String> {
191 let mut scopes: Vec<&str> = Vec::new();
192 for word in requested.split_whitespace() {
193 if !is_supported_scope(word) {
194 return Err(format!(
195 "unknown scope {word}; the scopes are {}",
196 SUPPORTED_SCOPES.join(" ")
197 ));
198 }
199 if !scopes.contains(&word) {
200 scopes.push(word);
201 }
202 }
203 if scopes.is_empty() {
204 return Err("--scopes must name at least one scope".into());
205 }
206 Ok(scopes.join(" "))
207}
208
209/// Prints one line per client: id, name, family key, scopes and status. No secret.
210async fn list(state: AppState) -> std::result::Result<(), String> {
211 for client in state
212 .store
213 .list_clients()
214 .await
215 .map_err(|e| e.to_string())?
216 {
217 println!(
218 "{}\t{}\t{}\t{}\t{}",
219 client.id,
220 client.name,
221 client.service_key.as_deref().unwrap_or("-"),
222 client.allowed_scopes,
223 if client.is_disabled() {
224 "disabled"
225 } else {
226 "active"
227 },
228 );
229 }
230 Ok(())
231}
232
233/// Disables a client: it cannot authenticate, so it cannot exchange codes or refresh.
234async fn disable(state: AppState, id: &str) -> std::result::Result<(), String> {
235 if state
236 .store
237 .disable_client(id)
238 .await
239 .map_err(|e| e.to_string())?
240 {
241 println!("disabled {id}");
242 Ok(())
243 } else {
244 Err(format!("no active client {id}"))
245 }
246}
247
248/// Runs `im backup now`: writes a snapshot set now, and waits for it. The outcome is recorded in the
249/// settings, so the health page shows it too.
250pub async fn backup(config: &Path, words: &[String]) -> ExitCode {
251 match words {
252 [verb] if verb == "now" => {
253 with_state(config, |state| async move {
254 let set = crate::backups::run_and_record(&state.config, &state.store, &state.key)
255 .await
256 .map_err(|e| e.to_string())?;
257 println!("im: backup written to {}", set.display());
258 Ok(())
259 })
260 .await
261 }
262 _ => {
263 eprintln!("im: usage: im backup now");
264 ExitCode::from(2)
265 }
266 }
267}
268
269/// Runs `im restore --from <set>`. The set is verified first (every file's hash, and the database's
270/// integrity and schema); a tampered set is refused and nothing is replaced. The current database and
271/// photos move into a `restore-<stamp>` directory inside the data directory. Refused while the server or
272/// another command holds the data directory.
273pub async fn restore(config: &Path, words: &[String]) -> ExitCode {
274 let set = match words {
275 [flag, set] if flag == "--from" => PathBuf::from(set),
276 _ => {
277 eprintln!("im: usage: im restore --from <set>");
278 return ExitCode::from(2);
279 }
280 };
281 let outcome = async {
282 let config = Config::load(config).map_err(|e| e.to_string())?;
283 let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?;
284 // The manifest MAC is keyed with the instance key, so a restore needs the key that made the set. A
285 // missing key is an error: a new key could never verify the set.
286 let key = im_core::secret::read_key(&config.data_dir.join(KEY_FILE))
287 .map_err(|e| e.to_string())?;
288 let stamp = im_core::time::now_stamp().replace([':', '.'], "-");
289 im_core::backup::restore(&config.data_dir, &config.database, &set, &stamp, &key)
290 .await
291 .map_err(|e| e.to_string())
292 }
293 .await;
294 match outcome {
295 Ok(outcome) => {
296 println!(
297 "im: restored {} photo(s); the previous database and photos are in {}",
298 outcome.photos,
299 outcome.previous.display()
300 );
301 ExitCode::SUCCESS
302 }
303 Err(message) => fail(message),
304 }
305}
306
307/// Runs `im fsck`: checks the database's integrity and schema, and that every signing key can be opened
308/// with the instance key. Refused while the server runs.
309pub async fn fsck(config: &Path) -> ExitCode {
310 with_state(config, |state| async move {
311 im_core::backup::check_database(&state.config.database)
312 .await
313 .map_err(|e| e.to_string())?;
314 for key in state
315 .store
316 .signing_keys()
317 .await
318 .map_err(|e| e.to_string())?
319 {
320 // A retired key whose seed was blanked has nothing to open; its public key is all that is kept.
321 if key.retires_at.is_some() && key.private_sealed.is_empty() {
322 continue;
323 }
324 im_core::secret::open(
325 &state.key,
326 im_core::secret::purpose::SIGNING_SEED,
327 &key.private_sealed,
328 )
329 .map_err(|e| format!("signing key {} cannot be opened: {e}", key.kid))?;
330 }
331 println!("im: database and signing keys ok");
332 Ok(())
333 })
334 .await
335}
336
337/// Runs `im keys rotate`: the new key signs from now on, and every other key is withdrawn at once.
338pub async fn keys(config: &Path, words: &[String]) -> ExitCode {
339 match words {
340 [verb] if verb == "rotate" => {
341 with_state(config, |state| async move {
342 let (kid, withdrawn) = crate::oidc::signing::rotate_now(&state.store, &state.key)
343 .await
344 .map_err(|e| e.to_string())?;
345 let data = serde_json::json!({ "withdrawn": withdrawn }).to_string();
346 let entry = im_core::store::audit::NewAudit {
347 actor_id: None,
348 actor_kind: "cli",
349 action: im_core::model::AuditAction::KeyRotated.as_str(),
350 target_kind: Some("signing_key"),
351 target_id: Some(&kid),
352 ip: None,
353 data: Some(&data),
354 };
355 if let Err(error) = state.store.record_audit(&entry).await {
356 eprintln!("im: the audit entry was not written: {error}");
357 }
358 let withdrawn = if withdrawn.is_empty() {
359 "none".to_owned()
360 } else {
361 withdrawn.join(", ")
362 };
363 println!(
364 "im: new signing key {kid} signs from now on; withdrawn at once: {withdrawn}"
365 );
366 Ok(())
367 })
368 .await
369 }
370 _ => {
371 eprintln!("im: usage: im keys rotate");
372 ExitCode::from(2)
373 }
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380
381 fn words(list: &[&str]) -> Vec<String> {
382 list.iter().map(|word| (*word).to_owned()).collect()
383 }
384
385 #[test]
386 fn redirect_uris_repeat_and_a_name_is_given_once() {
387 let args = parse_add(&words(&[
388 "--name",
389 "Files",
390 "--redirect-uri",
391 "https://a/cb",
392 "--redirect-uri",
393 "https://b/cb",
394 ]))
395 .expect("parse");
396 assert_eq!(args.redirect_uris.len(), 2);
397 assert!(parse_add(&words(&["--name", "a", "--name", "b"])).is_err());
398 assert!(parse_add(&words(&["--name"])).is_err());
399 }
400}