// 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/. //! ```text //! ianitor-control --config run the control plane //! ianitor-control --dev [--edge-bin ] temporary everything on 127.0.0.1 //! ianitor-control token create --name [--expires-days | --never] (--config | --state-dir ) //! ianitor-control token list (--config | --state-dir ) //! ianitor-control token revoke (--config | --state-dir ) //! ianitor-control openapi print the OpenAPI document //! ianitor-control check --config check the config and exit //! ``` //! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), //! the binary answers git's prompt from the push credential file. use std::path::PathBuf; use std::process::ExitCode; use ianitor_control::{Config, logger, tokens::Tokens}; mod dev; fn usage() -> ExitCode { eprintln!( "usage: ianitor-control --config | --dev [--edge-bin ] | \ token create --name [--expires-days | --never] (--config | --state-dir ) | \ token list (...) | token revoke (...) | openapi | check --config " ); ExitCode::from(2) } fn askpass() -> ExitCode { // git asks "Username for 'https://…':" and "Password for 'https://…':". let prompt = std::env::args().nth(1).unwrap_or_default(); if prompt.starts_with("Username") { println!( "{}", std::env::var("IANITOR_ASKPASS_USER").unwrap_or_default() ); return ExitCode::SUCCESS; } // Answer only the password prompt; anything else (a passphrase, a host key question) // gets no answer, so the push fails instead of handing out the token. if !prompt.starts_with("Password for") { eprintln!("ianitor-control askpass: not answering {prompt:?}"); return ExitCode::FAILURE; } let Some(file) = std::env::var_os("IANITOR_ASKPASS_FILE") else { return ExitCode::FAILURE; }; match std::fs::read_to_string(file) { Ok(v) => { println!("{}", v.trim_end_matches(['\r', '\n'])); ExitCode::SUCCESS } Err(_) => ExitCode::FAILURE, } } fn state_dir(args: &[String]) -> Result { let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { "--state-dir" => { return it .next() .map(PathBuf::from) .ok_or("--state-dir needs a path".into()); } "--config" => { let p = it.next().ok_or("--config needs a path")?; return Config::load(&PathBuf::from(p)) .map(|c| c.state_dir) .map_err(|e| e.to_string()); } _ => {} } } Err("give --config or --state-dir ".into()) } /// The token files must stay owned by the user control runs as: refuse to touch them as /// anyone else (typically root), instead of leaving root-owned files control cannot open. #[cfg(unix)] fn same_owner(dir: &std::path::Path) -> Result<(), String> { use std::os::unix::fs::MetadataExt; let existing = dir .ancestors() .find(|p| p.is_dir()) .ok_or_else(|| format!("no part of {} exists", dir.display()))?; let owner = std::fs::metadata(existing) .map_err(|e| format!("cannot read {}: {e}", existing.display()))? .uid(); // Who we are, without libc: the owner of a file we create (in the temp dir, so nothing is // created in the state dir by the wrong user). let probe = std::env::temp_dir().join(format!(".ianitor-owner-probe-{}", std::process::id())); // create_new: never follows or reuses a file someone else put there. let me = std::fs::File::create_new(&probe) .and_then(|f| f.metadata()) .map(|m| m.uid()); if me.is_ok() { let _ = std::fs::remove_file(&probe); } let me = me.map_err(|e| format!("cannot create a probe file to learn who runs this: {e}"))?; if me == 0 && !dir.is_dir() { return Err(format!( "{} does not exist; create it as the user control runs as (or run this as that user), not as root", dir.display() )); } if me != owner { return Err(format!( "{} belongs to uid {owner}, but this runs as uid {me}; run it as that user (e.g. sudo -u ianitor ianitor-control token ...)", existing.display() )); } Ok(()) } #[cfg(not(unix))] fn same_owner(_: &std::path::Path) -> Result<(), String> { Ok(()) } fn token(args: &[String]) -> Result<(), String> { let dir = state_dir(args)?; // Check the owner before creating anything: the nearest existing ancestor must belong to // whoever runs this (so root does not create a state dir control cannot use). same_owner(&dir)?; std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; let tokens = Tokens::new(&dir); match args.first().map(String::as_str) { Some("create") => { let mut name = None; let mut expires = Some(ianitor_control::util::now() + 365 * 86_400); let mut it = args.iter().skip(1); while let Some(a) = it.next() { match a.as_str() { "--name" => name = it.next().cloned(), "--never" => expires = None, "--expires-days" => { let d: u64 = it .next() .and_then(|d| d.parse().ok()) .filter(|d| (1..=3650).contains(d)) .ok_or("--expires-days must be 1 to 3650")?; expires = Some(ianitor_control::util::now() + d * 86_400); } _ => {} } } let name = name.ok_or("--name is required")?; let (rec, value) = tokens.create(&name, expires).map_err(|e| { if e == "token.name" { "the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores" .to_owned() } else { e } })?; eprintln!( "Token {} ({}) created. It is shown once; save it in Custos now:", rec.id, rec.name ); println!("{value}"); Ok(()) } Some("list") => { for t in tokens.list()? { println!( "{} {} created {}{}{}", t.id, t.name, ianitor_control::util::rfc3339(t.created_at), t.expires_at .map(|e| format!(" expires {}", ianitor_control::util::rfc3339(e))) .unwrap_or_default(), t.revoked_at .map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e))) .unwrap_or_default() ); } Ok(()) } Some("revoke") => { let id = args.get(1).ok_or("token revoke ")?; match tokens.revoke(id)? { Some(_) => { eprintln!("Token {id} revoked."); Ok(()) } None => Err(format!("there is no token {id}")), } } _ => Err("token create | list | revoke".into()), } } fn main() -> ExitCode { if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { return askpass(); } logger::init(std::env::var("IANITOR_LOG").ok().as_deref()); let args: Vec = std::env::args().skip(1).collect(); let rt = match tokio::runtime::Builder::new_multi_thread() .enable_all() .build() { Ok(r) => r, Err(e) => { eprintln!("ianitor-control: cannot start: {e}"); return ExitCode::FAILURE; } }; let result = match args.first().map(String::as_str) { Some("token") => token(&args[1..]), Some("openapi") => { println!("{}", ianitor_control::api::openapi_json()); Ok(()) } Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")), Some("--dev") => rt.block_on(dev::run(&args[1..])), Some("--config") => match args.get(1) { Some(p) => match Config::load(&PathBuf::from(p)) { Ok(cfg) => rt.block_on(ianitor_control::serve(cfg, ianitor_control::stop_signal())), Err(e) => Err(e.to_string()), }, None => return usage(), }, Some("--help" | "-h") | None => return usage(), Some(_) => return usage(), }; match result { Ok(()) => ExitCode::SUCCESS, Err(e) => { log::error!(target: "ianitor::control", "{e}"); eprintln!("ianitor-control: {e}"); ExitCode::FAILURE } } }