diff options
| author | tv <tv@krebsco.de> | 2026-11-17 16:18:58 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-17 17:36:10 +0100 |
| commit | 7fc844ff0167fb0943e3fa85af671d8f3bbf005d (patch) | |
| tree | ea7a759bfdfbd1705b64f6a1083ae42d9c84515c /src | |
| parent | e9b1ea18694c88abe1e31f8236f8d8beb6362be9 (diff) | |
continuum-party: options from configuration files, as the node's
`continuum-party` takes its options (`node`, `token`, `key`, `record`:
`config::PARTY_OPTIONS`) on the command line and in configuration files of the node's
format: `--config`, repeatable, arguments winning, `--unset`, includes and imports. The
configuration's loader takes the options it reads as a table (`config::with_options`,
`config::merged`, `file::load_with`), the node's or the client's, and a key naming
none of them is an error in either; `node` and `token` are secrets, never logged.
Diffstat (limited to 'src')
| -rw-r--r-- | src/config/file.rs | 23 | ||||
| -rw-r--r-- | src/config/mod.rs | 124 | ||||
| -rw-r--r-- | src/federation/party.rs | 114 |
3 files changed, 192 insertions, 69 deletions
diff --git a/src/config/file.rs b/src/config/file.rs index bd6a3d5..ee71133 100644 --- a/src/config/file.rs +++ b/src/config/file.rs @@ -17,18 +17,29 @@ use serde_json::{Map as JsonMap, Value as JsonValue}; use tracing::debug; use super::import; -use super::{Entry, Layer, Overlay, Provenance, UNSET, overlay, spec, unset_entry}; +use super::{Entry, Layer, OptionSpec, Overlay, Provenance, UNSET, overlay, spec_in, unset_entry}; const INCLUDE: &str = "include"; /// Gone: optional includes are entries of `include`, so the order is the list's. const INCLUDE_OPTIONAL: &str = "include-optional"; /// The settings `path` makes, its includes resolved. +#[cfg(test)] pub(super) fn load(path: &Path) -> Result<Layer> { - load_inner(path, &mut Vec::new()) + load_with(path, super::OPTIONS) +} + +/// The settings `path` makes of `options`, its includes resolved: a key naming none of +/// them is an error. +pub(super) fn load_with(path: &Path, options: &'static [OptionSpec]) -> Result<Layer> { + load_inner(path, options, &mut Vec::new()) } -fn load_inner(path: &Path, loading: &mut Vec<PathBuf>) -> Result<Layer> { +fn load_inner( + path: &Path, + options: &'static [OptionSpec], + loading: &mut Vec<PathBuf>, +) -> Result<Layer> { let canonical = path .canonicalize() .with_context(|| format!("configuration file {}", path.display()))?; @@ -58,7 +69,7 @@ fn load_inner(path: &Path, loading: &mut Vec<PathBuf>) -> Result<Layer> { debug!(file = %include.display(), "Optional configuration file is missing; skipped"); continue; } - let included = load_inner(&include, loading) + let included = load_inner(&include, options, loading) .with_context(|| format!("included from {}", canonical.display()))?; for (name, entry) in included { overlay(&mut layer, name, entry, Overlay::IncludeOverInclude); @@ -67,7 +78,7 @@ fn load_inner(path: &Path, loading: &mut Vec<PathBuf>) -> Result<Layer> { loading.pop(); for name in unsets { - if spec(&name).is_none() { + if spec_in(options, &name).is_none() { bail!( "unknown option {name:?} in unset, in {}", canonical.display() @@ -80,7 +91,7 @@ fn load_inner(path: &Path, loading: &mut Vec<PathBuf>) -> Result<Layer> { let mut own = Vec::new(); flatten(&root, "", &dir, &mut own).with_context(|| format!("in {}", canonical.display()))?; for (name, value) in own { - let spec = spec(&name) + let spec = spec_in(options, &name) .ok_or_else(|| anyhow!("unknown option {name:?} in {}", canonical.display()))?; let (value, sources) = super::resolve_file_value(spec, value, &dir) .with_context(|| format!("option {name} in {}", canonical.display()))?; diff --git a/src/config/mod.rs b/src/config/mod.rs index 142dc01..533b44c 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -65,7 +65,7 @@ impl OptionSpec { } } -const fn option( +pub(crate) const fn option( name: &'static str, kind: Kind, value_name: &'static str, @@ -718,7 +718,59 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[ ]; pub(crate) fn spec(name: &str) -> Option<&'static OptionSpec> { - OPTIONS.iter().find(|spec| spec.name == name) + spec_in(OPTIONS, name) +} + +/// The option of `options` named `name`. +pub(super) fn spec_in(options: &'static [OptionSpec], name: &str) -> Option<&'static OptionSpec> { + options.iter().find(|spec| spec.name == name) +} + +/// The options of a party's client (`continuum-party`), set as the node's are: on the +/// command line, or in configuration files of the same format (`with_options`, +/// `merged`). +#[cfg(feature = "federation")] +pub(crate) const PARTY_OPTIONS: &[OptionSpec] = &[ + option( + "node", + Kind::Text, + "URL", + Some("http://localhost:3000"), + "The node whose API it puts events through; its user and password in the URL", + ) + .secret(), + option( + "token", + Kind::Text, + "TOKEN", + None, + "A token the node issued, instead of a password", + ) + .secret(), + option( + "key", + Kind::Text, + "PATH", + None, + "The party's key it signs with: an OpenSSH private key file, unencrypted", + ), + option( + "record", + Kind::Text, + "PATH", + None, + "The party's record of its votes, written before each vote is sent", + ), +]; +#[cfg(not(feature = "federation"))] +const PARTY_OPTIONS: &[OptionSpec] = &[]; + +/// Whether `option`, the node's or a party's client's, is never shown. +fn secret(option: &str) -> bool { + OPTIONS + .iter() + .chain(PARTY_OPTIONS) + .any(|spec| spec.name == option && spec.secret) } /// The effective configuration. @@ -1511,7 +1563,7 @@ impl Entry { pub(crate) fn shown(&self, option: &str) -> String { if self.origin.unset { "<default>".to_owned() - } else if spec(option).is_some_and(|spec| spec.secret) { + } else if secret(option) { "<secret>".to_owned() } else if self.origin.is_imported() { "<imported>".to_owned() @@ -1798,9 +1850,22 @@ const PRINT_CONFIG: &str = "print-config"; pub(super) const UNSET: &str = "unset"; fn command() -> Command { - let mut command = Command::new("continuum") + let command = Command::new("continuum") .version(env!("CARGO_PKG_VERSION")) .about("continuum: a replicated Automerge document over Mycelium, libp2p or Tor") + .arg( + Arg::new(PRINT_CONFIG) + .long(PRINT_CONFIG) + .action(ArgAction::SetTrue) + .help("Print the effective configuration as JSON (with each value's source) and exit."), + ); + with_options(command, OPTIONS) +} + +/// `command` taking `options` as arguments, and configuration files for them +/// (`--config`) and unsets of what those set (`--unset`). +pub(crate) fn with_options(command: Command, options: &'static [OptionSpec]) -> Command { + let mut command = command .after_help( "Every option can also be set in a configuration file (--config); arguments win.\n\ A value can be imported instead of written out: env:NAME, file:PATH or cmd:COMMAND \ @@ -1820,14 +1885,8 @@ fn command() -> Command { .value_name("OPTION") .action(ArgAction::Append) .help("Unset an option set by a configuration file (back to its default); repeatable."), - ) - .arg( - Arg::new(PRINT_CONFIG) - .long(PRINT_CONFIG) - .action(ArgAction::SetTrue) - .help("Print the effective configuration as JSON (with each value's source) and exit."), ); - for spec in OPTIONS { + for spec in options { let help = match spec.default { Some(default) => format!("{} [default: {default}]", spec.help), None => spec.help.to_owned(), @@ -1848,15 +1907,21 @@ fn command() -> Command { } /// The values given as arguments (unsets first, so a value given too wins). +#[cfg(test)] fn arguments(matches: &ArgMatches) -> Result<Layer> { + arguments_with(matches, OPTIONS) +} + +/// The values of `options` given as arguments (unsets first, so a value given too wins). +fn arguments_with(matches: &ArgMatches, options: &'static [OptionSpec]) -> Result<Layer> { let mut layer = Layer::new(); for name in matches.get_many::<String>(UNSET).into_iter().flatten() { - if spec(name).is_none() { + if spec_in(options, name).is_none() { bail!("--unset {name}: no such option"); } layer.insert(name.clone(), unset_entry(Provenance::Argument)); } - for spec in OPTIONS { + for spec in options { if matches.value_source(spec.name) != Some(ValueSource::CommandLine) { continue; } @@ -2047,25 +2112,46 @@ pub(crate) fn load() -> Result<Loaded> { // Logs go to stdout too; the report says where each value came from anyway. let _ = crate::logging::set_filter("off"); } + let (merged, files) = merged(&matches, OPTIONS)?; + let mut loaded = resolve(merged, files)?; + loaded.print_only = print_only; + Ok(loaded) +} + +/// The values of `options`: from the configuration files `matches` names (`--config`), in +/// order, then from its arguments; and those files. +pub(crate) fn merged( + matches: &ArgMatches, + options: &'static [OptionSpec], +) -> Result<(Layer, Vec<PathBuf>)> { let files: Vec<PathBuf> = matches .get_many::<String>(CONFIG) .into_iter() .flatten() .map(PathBuf::from) .collect(); - let mut merged = Layer::new(); for path in &files { - for (name, entry) in file::load(path)? { + for (name, entry) in file::load_with(path, options)? { overlay(&mut merged, name, entry, Overlay::FileOverFile); } } - for (name, entry) in arguments(&matches)? { + for (name, entry) in arguments_with(matches, options)? { overlay(&mut merged, name, entry, Overlay::ArgumentOverFile); } - let mut loaded = resolve(merged, files)?; - loaded.print_only = print_only; - Ok(loaded) + Ok((merged, files)) +} + +/// `T` read from the values `merged` sets, each option's by its name: those unset take +/// `T`'s defaults. +#[cfg(feature = "federation")] +pub(crate) fn read<T: serde::de::DeserializeOwned>(merged: &Layer) -> Result<T> { + let object: serde_json::Map<String, JsonValue> = merged + .iter() + .filter(|(_, entry)| !entry.value.is_null()) + .map(|(name, entry)| (name.clone(), entry.value.clone())) + .collect(); + serde_json::from_value(JsonValue::Object(object)).map_err(|error| anyhow!("{error}")) } /// HyParView's active view, where `neighbours` isn't set: the paper's, for swarms of up diff --git a/src/federation/party.rs b/src/federation/party.rs index aaa983f..f0ae288 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -2,7 +2,8 @@ //! party's events with one of its keys (an OpenSSH private key file, `--key`), puts them //! through a node's API (`--node`, its user and password in the URL, or `--token`), and //! keeps its party's record (`--record`, `client::Record`), by which it votes, written -//! before a vote is sent. +//! before a vote is sent. Its options may be set in configuration files as the node's are +//! (`--config`, `config::PARTY_OPTIONS`): the same format, imports and all. //! //! * `init PARTY`: begins a record of `PARTY`, on the version current now; with `--root //! FILE`, from the file the store's swarm starts from, for a party that never voted in @@ -34,6 +35,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result, anyhow, bail}; use clap::{Arg, ArgAction, ArgMatches, Command}; use ed25519_dalek::SigningKey; +use serde::Deserialize; use serde_json::Value as JsonValue; use super::client::{self, Record}; @@ -44,38 +46,29 @@ use super::store::Id; use super::store::memory::Store; use super::version::Version; use crate::access::sshsig::PublicKey; +use crate::config; + +/// The client's options (`config::PARTY_OPTIONS`), as the command line and configuration +/// files set them. +#[derive(Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct Options { + #[serde(default = "default_node")] + node: String, + token: Option<String>, + key: Option<String>, + record: Option<String>, +} + +fn default_node() -> String { + "http://localhost:3000".to_owned() +} fn command() -> Command { let id = |name: &'static str| Arg::new(name).required(true); - Command::new("continuum-party") - .about("A party's client of a federation: signs its events, and votes by its record") - .arg( - Arg::new("node") - .long("node") - .value_name("URL") - .default_value("http://localhost:3000") - .help( - "The node whose API it puts events through; its user and password in the URL", - ), - ) - .arg( - Arg::new("token") - .long("token") - .value_name("TOKEN") - .help("A token the node issued, instead of a password"), - ) - .arg( - Arg::new("key") - .long("key") - .value_name("FILE") - .help("The party's key it signs with: an OpenSSH private key file, unencrypted"), - ) - .arg( - Arg::new("record") - .long("record") - .value_name("FILE") - .help("The party's record of its votes, written before each vote is sent"), - ) + let command = Command::new("continuum-party") + .about("A party's client of a federation: signs its events, and votes by its record"); + config::with_options(command, config::PARTY_OPTIONS) .subcommand_required(true) .subcommand( Command::new("init") @@ -158,6 +151,8 @@ fn command() -> Command { pub(crate) async fn main() -> Result<()> { let matches = command().get_matches(); let (name, sub) = matches.subcommand().expect("a subcommand is required"); + let (merged, _) = config::merged(&matches, config::PARTY_OPTIONS)?; + let options: Options = config::read(&merged)?; if name == "twice" { let records = sub .get_many::<String>("records") @@ -184,7 +179,7 @@ pub(crate) async fn main() -> Result<()> { } return out(&super::fork::root_file(&root, &[])); } - let node = Node::new(&matches)?; + let node = Node::new(&options)?; if name == "proposals" { return proposals(&node).await; } @@ -232,8 +227,9 @@ pub(crate) async fn main() -> Result<()> { return Ok(()); } let path = PathBuf::from( - matches - .get_one::<String>("record") + options + .record + .as_ref() .context("--record names the party's record")?, ); if name == "init" { @@ -260,7 +256,7 @@ pub(crate) async fn main() -> Result<()> { return Ok(()); } let mut record = Record::load(&path).map_err(|why| anyhow!(why))?; - let key = signing_key(&matches)?; + let key = signing_key(&options)?; let signer = Signer { key, party: record.party.clone(), @@ -345,9 +341,10 @@ fn strings(matches: &ArgMatches, name: &str) -> Vec<String> { .collect() } -fn signing_key(matches: &ArgMatches) -> Result<SigningKey> { - let file = matches - .get_one::<String>("key") +fn signing_key(options: &Options) -> Result<SigningKey> { + let file = options + .key + .as_ref() .context("--key names the party's key")?; let text = std::fs::read_to_string(file).with_context(|| format!("Reading {file}"))?; client::signing_key(&text).map_err(|why| anyhow!("{file}: {why}")) @@ -544,13 +541,9 @@ struct Node { } impl Node { - fn new(matches: &ArgMatches) -> Result<Self> { + fn new(options: &Options) -> Result<Self> { let _ = rustls::crypto::ring::default_provider().install_default(); - let mut url: reqwest::Url = matches - .get_one::<String>("node") - .expect("defaulted") - .parse() - .context("--node isn't a URL")?; + let mut url: reqwest::Url = options.node.parse().context("--node isn't a URL")?; let password = (!url.username().is_empty()) .then(|| (url.username().to_owned(), url.password().map(str::to_owned))); let _ = url.set_username(""); @@ -559,7 +552,7 @@ impl Node { url, http: reqwest::Client::new(), password, - token: matches.get_one::<String>("token").cloned(), + token: options.token.clone(), }) } @@ -677,4 +670,37 @@ mod tests { fn its_arguments_are_well_formed() { super::command().debug_assert(); } + + /// Its options come from configuration files as the node's do, arguments winning. + #[test] + fn its_options_come_from_configuration_files_and_arguments() { + use crate::config; + let dir = crate::files::scratch_dir("party-config"); + let file = dir.join("party.toml"); + std::fs::write( + &file, + "node = \"http://tv:secret@localhost:3001\"\nkey = \"tv.key\"\nrecord = \"tv.record\"\n", + ) + .unwrap(); + let path = file.to_str().unwrap(); + let matches = super::command() + .try_get_matches_from([ + "continuum-party", + "--config", + path, + "--key", + "laptop.key", + "proposals", + ]) + .unwrap(); + let (merged, _) = config::merged(&matches, config::PARTY_OPTIONS).unwrap(); + let options: super::Options = config::read(&merged).unwrap(); + assert_eq!(options.node, "http://tv:secret@localhost:3001"); + assert_eq!(options.key.as_deref(), Some("laptop.key")); + assert_eq!(options.record.as_deref(), Some("tv.record")); + assert_eq!(options.token, None); + // A key naming none of the client's options is an error, as in the node's files. + std::fs::write(&file, "bind-addr = \"127.0.0.1:3000\"\n").unwrap(); + assert!(config::merged(&matches, config::PARTY_OPTIONS).is_err()); + } } |
