//! The `im client` commands: register, list and disable OpenID Connect clients from the operator's //! shell. //! //! The commands open the database and the instance key directly, as the server does at boot, so they //! need the data directory. A client secret is printed once, on standard output, and only its SHA-256 //! is stored. The redirect, logout and back-channel URIs are checked by the same rules the endpoints use. use std::fmt::Display; use std::path::{Path, PathBuf}; use std::process::ExitCode; use im_core::config::Config; use im_core::names::parse_display_name; use im_core::oauth::{ SUPPORTED_SCOPES, is_client_family_key, is_supported_scope, is_valid_registered_uri, }; use im_core::store::clients::NewClient; use im_core::token::{generate_token, hash_token}; use crate::boot::{KEY_FILE, lock_data_dir, open_state}; use crate::pages::admin::clients::is_origin; use crate::state::AppState; /// Printed with a usage error. const USAGE: &str = "usage: im client add --name [--redirect-uri ]... [--post-logout-uri ]... [--backchannel-uri ] [--family-key --public-url ] [--scopes ] im client list im client disable "; /// The scopes a client gets when `--scopes` is not given: what a family app signs in with. const DEFAULT_SCOPES: &str = "openid profile email"; /// Runs one `im client` command. `words` are the words after `client`. pub async fn client(config: &Path, words: &[String]) -> ExitCode { let Some((verb, rest)) = words.split_first() else { return usage(); }; match verb.as_str() { "add" => match parse_add(rest) { Ok(args) => with_state(config, |state| add(state, args)).await, Err(message) => { eprintln!("im: {message}\n{USAGE}"); ExitCode::from(2) } }, "list" if rest.is_empty() => with_state(config, list).await, "disable" => match rest { [id] => with_state(config, |state| disable(state, id)).await, _ => usage(), }, _ => usage(), } } /// Prints the usage and exits with status 2. fn usage() -> ExitCode { eprintln!("im: unknown client command\n{USAGE}"); ExitCode::from(2) } /// Prints a failure and exits with status 1. fn fail(error: impl Display) -> ExitCode { eprintln!("im: {error}"); ExitCode::FAILURE } /// Opens the configuration, the key and the database, runs `action`, and maps its result to an exit /// status. async fn with_state(config: &Path, action: F) -> ExitCode where F: FnOnce(AppState) -> Fut, Fut: std::future::Future>, { let outcome = async { let config = Config::load(config).map_err(|e| e.to_string())?; // Held for the whole command: a running server holds the same lock and refuses this one. let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?; let state = open_state(config).await.map_err(|e| e.to_string())?; action(state).await } .await; match outcome { Ok(()) => ExitCode::SUCCESS, Err(message) => fail(message), } } /// The options of `im client add`. #[derive(Debug, Default, PartialEq, Eq)] struct AddArgs { name: Option, redirect_uris: Vec, post_logout_uris: Vec, backchannel_uri: Option, family_key: Option, public_url: Option, scopes: Option, } /// Reads `--flag value` pairs. Flags that repeat collect; the rest may be given once. fn parse_add(words: &[String]) -> std::result::Result { let mut args = AddArgs::default(); let mut words = words.iter(); while let Some(flag) = words.next() { let value = words .next() .ok_or_else(|| format!("{flag} needs a value"))? .clone(); let once = |slot: &mut Option| { if slot.replace(value.clone()).is_some() { Err(format!("{flag} may be given only once")) } else { Ok(()) } }; match flag.as_str() { "--name" => once(&mut args.name)?, "--redirect-uri" => args.redirect_uris.push(value), "--post-logout-uri" => args.post_logout_uris.push(value), "--backchannel-uri" => once(&mut args.backchannel_uri)?, "--family-key" => once(&mut args.family_key)?, "--public-url" => once(&mut args.public_url)?, "--scopes" => once(&mut args.scopes)?, other => return Err(format!("unknown option {other}")), } } Ok(args) } /// Registers a client and prints its id and its secret. The secret is not shown again. async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> { let name = parse_display_name(args.name.as_deref().ok_or("--name is required")?) .map_err(|e| e.to_string())?; for uri in args .redirect_uris .iter() .chain(&args.post_logout_uris) .chain(args.backchannel_uri.iter()) { if !is_valid_registered_uri(uri) { return Err(format!( "{uri} is not a valid URI for a client (https, or http on loopback, no fragment or userinfo)" )); } } if let Some(key) = &args.family_key && !is_client_family_key(key) { return Err(format!( "family key {key} must be lowercase letters, digits and hyphens, and not im (the home row)" )); } match (&args.family_key, &args.public_url) { (Some(_), None) => { return Err("a family key needs --public-url, the origin of its service".into()); } (None, Some(_)) => return Err("--public-url is only for a family key".into()), (Some(_), Some(url)) if !is_origin(url) => { return Err(format!("{url} is not an origin (scheme and host, no path)")); } _ => {} } let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?; let secret = generate_token(); let secret_hash = hash_token(&secret); let new = NewClient { name: &name, secret_hash: &secret_hash, redirect_uris: &args.redirect_uris, post_logout_redirect_uris: &args.post_logout_uris, backchannel_logout_uri: args.backchannel_uri.as_deref(), allowed_scopes: &scopes, service_key: args.family_key.as_deref(), }; // A family client and its switcher row are written in one transaction, as the admin page does. let client = match (&args.family_key, &args.public_url) { (Some(_), Some(url)) => state.store.create_family_client(&new, &name, url).await, _ => state.store.create_client(&new).await, } .map_err(|e| e.to_string())?; println!("client_id: {}", client.id); println!("client_secret: {secret}"); eprintln!("im: the client secret is shown once; store it now"); Ok(()) } /// The requested scopes, checked and de-duplicated, space separated. fn scope_list(requested: &str) -> std::result::Result { let mut scopes: Vec<&str> = Vec::new(); for word in requested.split_whitespace() { if !is_supported_scope(word) { return Err(format!( "unknown scope {word}; the scopes are {}", SUPPORTED_SCOPES.join(" ") )); } if !scopes.contains(&word) { scopes.push(word); } } if scopes.is_empty() { return Err("--scopes must name at least one scope".into()); } Ok(scopes.join(" ")) } /// Prints one line per client: id, name, family key, scopes and status. No secret. async fn list(state: AppState) -> std::result::Result<(), String> { for client in state .store .list_clients() .await .map_err(|e| e.to_string())? { println!( "{}\t{}\t{}\t{}\t{}", client.id, client.name, client.service_key.as_deref().unwrap_or("-"), client.allowed_scopes, if client.is_disabled() { "disabled" } else { "active" }, ); } Ok(()) } /// Disables a client: it cannot authenticate, so it cannot exchange codes or refresh. async fn disable(state: AppState, id: &str) -> std::result::Result<(), String> { if state .store .disable_client(id) .await .map_err(|e| e.to_string())? { println!("disabled {id}"); Ok(()) } else { Err(format!("no active client {id}")) } } /// Runs `im backup now`: writes a snapshot set now, and waits for it. The outcome is recorded in the /// settings, so the health page shows it too. pub async fn backup(config: &Path, words: &[String]) -> ExitCode { match words { [verb] if verb == "now" => { with_state(config, |state| async move { let set = crate::backups::run_and_record(&state.config, &state.store, &state.key) .await .map_err(|e| e.to_string())?; println!("im: backup written to {}", set.display()); Ok(()) }) .await } _ => { eprintln!("im: usage: im backup now"); ExitCode::from(2) } } } /// Runs `im restore --from `. The set is verified first (every file's hash, and the database's /// integrity and schema); a tampered set is refused and nothing is replaced. The current database and /// photos move into a `restore-` directory inside the data directory. Refused while the server or /// another command holds the data directory. pub async fn restore(config: &Path, words: &[String]) -> ExitCode { let set = match words { [flag, set] if flag == "--from" => PathBuf::from(set), _ => { eprintln!("im: usage: im restore --from "); return ExitCode::from(2); } }; let outcome = async { let config = Config::load(config).map_err(|e| e.to_string())?; let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?; // The manifest MAC is keyed with the instance key, so a restore needs the key that made the set. A // missing key is an error: a new key could never verify the set. let key = im_core::secret::read_key(&config.data_dir.join(KEY_FILE)) .map_err(|e| e.to_string())?; let stamp = im_core::time::now_stamp().replace([':', '.'], "-"); im_core::backup::restore(&config.data_dir, &config.database, &set, &stamp, &key) .await .map_err(|e| e.to_string()) } .await; match outcome { Ok(outcome) => { println!( "im: restored {} photo(s); the previous database and photos are in {}", outcome.photos, outcome.previous.display() ); ExitCode::SUCCESS } Err(message) => fail(message), } } /// Runs `im fsck`: checks the database's integrity and schema, and that every signing key can be opened /// with the instance key. Refused while the server runs. pub async fn fsck(config: &Path) -> ExitCode { with_state(config, |state| async move { im_core::backup::check_database(&state.config.database) .await .map_err(|e| e.to_string())?; for key in state .store .signing_keys() .await .map_err(|e| e.to_string())? { // A retired key whose seed was blanked has nothing to open; its public key is all that is kept. if key.retires_at.is_some() && key.private_sealed.is_empty() { continue; } im_core::secret::open( &state.key, im_core::secret::purpose::SIGNING_SEED, &key.private_sealed, ) .map_err(|e| format!("signing key {} cannot be opened: {e}", key.kid))?; } println!("im: database and signing keys ok"); Ok(()) }) .await } /// Runs `im keys rotate`: the new key signs from now on, and every other key is withdrawn at once. pub async fn keys(config: &Path, words: &[String]) -> ExitCode { match words { [verb] if verb == "rotate" => { with_state(config, |state| async move { let (kid, withdrawn) = crate::oidc::signing::rotate_now(&state.store, &state.key) .await .map_err(|e| e.to_string())?; let data = serde_json::json!({ "withdrawn": withdrawn }).to_string(); let entry = im_core::store::audit::NewAudit { actor_id: None, actor_kind: "cli", action: im_core::model::AuditAction::KeyRotated.as_str(), target_kind: Some("signing_key"), target_id: Some(&kid), ip: None, data: Some(&data), }; if let Err(error) = state.store.record_audit(&entry).await { eprintln!("im: the audit entry was not written: {error}"); } let withdrawn = if withdrawn.is_empty() { "none".to_owned() } else { withdrawn.join(", ") }; println!( "im: new signing key {kid} signs from now on; withdrawn at once: {withdrawn}" ); Ok(()) }) .await } _ => { eprintln!("im: usage: im keys rotate"); ExitCode::from(2) } } } #[cfg(test)] mod tests { use super::*; fn words(list: &[&str]) -> Vec { list.iter().map(|word| (*word).to_owned()).collect() } #[test] fn redirect_uris_repeat_and_a_name_is_given_once() { let args = parse_add(&words(&[ "--name", "Files", "--redirect-uri", "https://a/cb", "--redirect-uri", "https://b/cb", ])) .expect("parse"); assert_eq!(args.redirect_uris.len(), 2); assert!(parse_add(&words(&["--name", "a", "--name", "b"])).is_err()); assert!(parse_add(&words(&["--name"])).is_err()); } }