From 9784111bd3b95be5352669b74e174920c101f349 Mon Sep 17 00:00:00 2001 From: tv Date: Thu, 19 Nov 2026 16:18:16 +0000 Subject: continuum-party: a directory for each federation, the only one used unasked A party named its node, key and record on every command, or a file of them with --config; one voting in several federations kept files apart by hand. Without --config, the client now reads a federation's own directory, `continuum/federations/NAME` in $XDG_CONFIG_HOME or ~/.config: its `party.toml` of the client's options, its record (`record`) and, where there, its key (`key`); options on the command line, or `record` and `key` in `party.toml`, win. `--federation NAME` chooses one; where there is only one, it is used without being named; where there are several, the client says which there are and asks for one. `root`, `judge` and `twice`, using no options, read none. `init --federation NAME` begins a federation's directory, only its owner reading it, its `party.toml` holding the options given on the command line with it (`node`, `token`, `key`, the key's path made absolute; the node's default left out), and the record in it. --- src/federation/party.rs | 170 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 168 insertions(+), 2 deletions(-) (limited to 'src/federation') diff --git a/src/federation/party.rs b/src/federation/party.rs index 78c31e2..bacca3d 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -85,6 +85,16 @@ fn command() -> Command { .long_version(crate::release::described()) .about("A party's client of a federation: signs its events, and votes by its record"); config::with_options(command, config::PARTY_OPTIONS) + .arg( + Arg::new("federation") + .long("federation") + .value_name("NAME") + .help( + "The federation to work with, by the name of its directory in \ + ~/.config/continuum/federations: its party.toml, record and key. Where \ + there is one, and no --config, that one", + ), + ) .subcommand_required(true) .subcommand( Command::new("init") @@ -252,12 +262,130 @@ fn changes() -> ArgGroup { .multiple(true) } +/// Where the client keeps a directory for each federation, by its name: `continuum/ +/// federations` in `$XDG_CONFIG_HOME`, else in `~/.config`. +fn federations() -> Option { + let base = std::env::var_os("XDG_CONFIG_HOME") + .filter(|dir| !dir.is_empty()) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?; + Some(base.join("continuum").join("federations")) +} + +/// The directory of the federation the client works with: the one `--federation` names; +/// else, without `--config`, the only one in `all` (`federations`). None where there is +/// none, and an error where there are several. +fn federation(matches: &ArgMatches, all: Option<&Path>) -> Result> { + if let Some(name) = matches.get_one::("federation") { + if name.is_empty() || name.contains('/') || name == "." || name == ".." { + bail!("--federation {name:?}: a federation is named by one segment of a path"); + } + let all = all.context("no directory for federations: set HOME or XDG_CONFIG_HOME")?; + return Ok(Some(all.join(name))); + } + let Some(all) = all else { + return Ok(None); + }; + if matches.get_many::("config").is_some() || !all.is_dir() { + return Ok(None); + } + let mut names: Vec = std::fs::read_dir(all) + .with_context(|| format!("Reading {}", all.display()))? + .filter_map(|entry| entry.ok()) + .filter(|entry| entry.path().is_dir()) + .filter_map(|entry| entry.file_name().into_string().ok()) + .collect(); + names.sort(); + match names.as_slice() { + [] => Ok(None), + [one] => Ok(Some(all.join(one))), + several => bail!( + "{} federations in {} ({}): choose one with --federation", + several.len(), + all.display(), + several.join(", ") + ), + } +} + +/// A federation's directory begun by `init`: made, only its owner reading it, with a +/// `party.toml` holding the options given on the command line, `node`, `token` and `key`, +/// the key's path made absolute. +fn begin_federation(dir: &Path, matches: &ArgMatches) -> Result<()> { + use clap::parser::ValueSource; + use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir) + .with_context(|| format!("Making {}", dir.display()))?; + let mut given = toml::Table::new(); + for name in ["node", "token", "key"] { + if matches.value_source(name) != Some(ValueSource::CommandLine) { + continue; + } + let Some(value) = matches.get_one::(name) else { + continue; + }; + let value = if name == "key" && Path::new(value).exists() { + std::path::absolute(value)?.display().to_string() + } else { + value.clone() + }; + given.insert(name.to_owned(), toml::Value::String(value)); + } + let file = dir.join("party.toml"); + if given.is_empty() || file.exists() { + return Ok(()); + } + let mut out = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&file) + .with_context(|| format!("Writing {}", file.display()))?; + std::io::Write::write_all(&mut out, toml::to_string(&given)?.as_bytes())?; + println!("wrote {}", file.display()); + Ok(()) +} + /// Runs the client, as its arguments say. 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)?; + // Those that use no options read no federation's. + let dir = if matches!(name, "twice" | "root" | "judge") { + None + } else { + federation(&matches, federations().as_deref())? + }; + if let Some(dir) = &dir { + if name == "init" { + begin_federation(dir, &matches)?; + } else if !dir.is_dir() { + bail!( + "no federation {}: {} isn't there; `init` begins one", + dir.file_name().unwrap_or_default().to_string_lossy(), + dir.display() + ); + } + } + let first: Vec = dir + .iter() + .map(|dir| dir.join("party.toml")) + .filter(|file| file.exists()) + .collect(); + let (merged, _) = config::merged_with(&matches, config::PARTY_OPTIONS, &first)?; + let mut options: Options = config::read(&merged)?; + // In a federation's directory, its record and key, where none other is named. + if let Some(dir) = &dir { + if options.record.is_none() { + options.record = Some(dir.join("record").display().to_string()); + } + if options.key.is_none() && dir.join("key").exists() { + options.key = Some(dir.join("key").display().to_string()); + } + } if name == "twice" { let records = sub .get_many::("records") @@ -1298,6 +1426,44 @@ mod tests { assert_eq!(changed_by(Some(&[]), &[], &[], true).unwrap(), list(&[])); } + /// The federation the client works with: the one `--federation` names; else, without + /// `--config`, the only one there is; none where there is none; and an error where + /// there are several. `init` begins one, with the options given on the command line. + #[test] + fn the_federation_is_the_one_there_is_or_the_one_named() { + let all = crate::files::scratch_dir("party-federations"); + let matches = |args: &[&str]| { + super::command() + .try_get_matches_from(["continuum-party"].iter().chain(args).chain(&["proposals"])) + .unwrap() + }; + let chosen = |args: &[&str]| super::federation(&matches(args), Some(&all)); + assert_eq!(chosen(&[]).unwrap(), None); + std::fs::create_dir(all.join("krebs")).unwrap(); + assert_eq!(chosen(&[]).unwrap(), Some(all.join("krebs"))); + assert_eq!(chosen(&["--config", "x.toml"]).unwrap(), None); + std::fs::create_dir(all.join("test")).unwrap(); + let several = chosen(&[]).unwrap_err().to_string(); + assert!(several.contains("krebs, test"), "{several}"); + assert_eq!( + chosen(&["--federation", "test"]).unwrap(), + Some(all.join("test")) + ); + assert!(chosen(&["--federation", "../x"]).is_err()); + assert_eq!(super::federation(&matches(&[]), None).unwrap(), None); + // Begun with the options given on the command line, the default node left out. + let begun = all.join("new"); + super::begin_federation(&begun, &matches(&["--token", "t"])).unwrap(); + let written = std::fs::read_to_string(begun.join("party.toml")).unwrap(); + assert_eq!(written.trim(), r#"token = "t""#); + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(begun.join("party.toml")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + } + /// Votes, proposals, key sets and node lists are signed with a key the current version /// names for their party; another key, or a party the version doesn't have, is refused /// before signing. -- cgit v1.3.1