aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/federation/party.rs216
1 files changed, 198 insertions, 18 deletions
diff --git a/src/federation/party.rs b/src/federation/party.rs
index 43b2cba..d302612 100644
--- a/src/federation/party.rs
+++ b/src/federation/party.rs
@@ -11,7 +11,10 @@
//! it: the record casts on every version, the first too;
//! * `write PATH VALUE`: writes `VALUE` (JSON) at `PATH`;
//! * `keys KEY...`, `nodes NODE...`: writes the party's key set (`authorized_keys` lines,
-//! each one argument, their comments left out) or node list (node IDs);
+//! each one argument, their comments left out) or node list (node IDs); with `--add` and
+//! `--remove`, the set or list as it counts at the node, changed. Signed with a key the
+//! current version names for the party, which the client checks first: where its key
+//! isn't one, only a version naming the party's keys or list anew changes them;
//! * `next`: the version after the current one, to change and propose: the current one
//! numbered on, naming its hash, without its checkpoint (JSON), to standard output;
//! * `propose FILE`: proposes the version `FILE` holds (JSON), where it changes the
@@ -95,13 +98,24 @@ fn command() -> Command {
)
.subcommand(
Command::new("keys")
- .about("Writes the party's key set")
- .arg(Arg::new("keys").num_args(1..).required(true)),
+ .about("Writes the party's key set: these keys, or the set as it counts, changed")
+ .arg(
+ Arg::new("keys")
+ .num_args(1..)
+ .required_unless_present_any(["add", "remove"])
+ .conflicts_with_all(["add", "remove"]),
+ )
+ .args(changing("KEY", "keys")),
)
.subcommand(
Command::new("nodes")
- .about("Writes the party's node list")
- .arg(Arg::new("nodes").num_args(0..)),
+ .about("Writes the party's node list: these nodes, or the list as it counts, changed")
+ .arg(
+ Arg::new("nodes")
+ .num_args(0..)
+ .conflicts_with_all(["add", "remove"]),
+ )
+ .args(changing("NODE", "nodes")),
)
.subcommand(Command::new("next").about(
"The version after the current one, to change and propose: numbered on, naming the \
@@ -163,6 +177,29 @@ fn command() -> Command {
)
}
+/// `--add` and `--remove`, of the party's key set or node list as it counts: `what`, of
+/// values named `value`.
+fn changing(value: &'static str, what: &str) -> [Arg; 2] {
+ [
+ Arg::new("add")
+ .long("add")
+ .value_name(value)
+ .num_args(1..)
+ .action(ArgAction::Append)
+ .help(format!(
+ "Adds these {what} to the party's, as they count at the node"
+ )),
+ Arg::new("remove")
+ .long("remove")
+ .value_name(value)
+ .num_args(1..)
+ .action(ArgAction::Append)
+ .help(format!(
+ "Takes these {what} off the party's, as they count at the node"
+ )),
+ ]
+}
+
/// Runs the client, as its arguments say.
pub(crate) async fn main() -> Result<()> {
let matches = command().get_matches();
@@ -300,18 +337,44 @@ pub(crate) async fn main() -> Result<()> {
}
("keys", sub) => {
// As the federation spells a key: without the line's comment.
- let keys = strings(sub, "keys")
- .iter()
- .map(|line| {
- Key::parse(line)
- .map(|key| key.line())
- .map_err(|why| anyhow!("{line:?}: {why}"))
- })
- .collect::<Result<Vec<String>>>()?;
+ let spelled = |name: &str| {
+ strings(sub, name)
+ .iter()
+ .map(|line| {
+ Key::parse(line)
+ .map(|key| key.line())
+ .map_err(|why| anyhow!("{line:?}: {why}"))
+ })
+ .collect::<Result<Vec<String>>>()
+ };
+ let counts = node.counts().await?;
+ signer.named_by(&current(&counts)?)?;
+ let keys = changed(
+ listed(&counts, &signer.party, "keys"),
+ spelled("keys")?,
+ spelled("add")?,
+ spelled("remove")?,
+ &format!("{}'s key set", signer.party),
+ )?;
sign(&node, &signer, &mut record, &path, event::keys(&keys)).await
}
("nodes", sub) => {
- let nodes: Vec<String> = strings(sub, "nodes");
+ let given = |name: &str| -> Result<Vec<String>> {
+ let nodes = strings(sub, name);
+ match nodes.iter().find(|id| !keys::node_id(id)) {
+ Some(none) => bail!("{none:?} isn't a node ID"),
+ None => Ok(nodes),
+ }
+ };
+ let counts = node.counts().await?;
+ signer.named_by(&current(&counts)?)?;
+ let nodes = changed(
+ listed(&counts, &signer.party, "nodes"),
+ given("nodes")?,
+ given("add")?,
+ given("remove")?,
+ &format!("{}'s node list", signer.party),
+ )?;
sign(&node, &signer, &mut record, &path, event::nodes(&nodes)).await
}
("propose", sub) => {
@@ -347,6 +410,52 @@ pub(crate) async fn main() -> Result<()> {
}
}
+/// The party's keys or nodes (`what`) as they count, as `counts` names them.
+fn listed(counts: &JsonValue, party: &str, what: &str) -> Vec<String> {
+ counts["parties"][party][what]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|value| value.as_str().map(str::to_owned))
+ .collect()
+}
+
+/// The key set or node list to write: `given` where neither `add` nor `remove` names any,
+/// else `now`, as it counts, with `add` added and `remove` taken off, each of which must
+/// change it (`what` names it in the error otherwise). Said where it is changed, before it
+/// is signed.
+fn changed(
+ now: Vec<String>,
+ given: Vec<String>,
+ add: Vec<String>,
+ remove: Vec<String>,
+ what: &str,
+) -> Result<Vec<String>> {
+ if add.is_empty() && remove.is_empty() {
+ return Ok(given);
+ }
+ let mut list = now;
+ for item in add {
+ if list.contains(&item) {
+ bail!("{what} holds {item} already");
+ }
+ list.push(item);
+ }
+ for item in remove {
+ let Some(at) = list.iter().position(|held| *held == item) else {
+ bail!("{what} doesn't hold {item}");
+ };
+ list.remove(at);
+ }
+ let shown = if list.is_empty() {
+ "none".to_owned()
+ } else {
+ list.join(" ")
+ };
+ println!("{what}: {shown}");
+ Ok(list)
+}
+
/// The version the file `file` holds, as JSON the federation takes.
fn version_in(file: &str) -> Result<Json> {
let text = std::fs::read_to_string(file).with_context(|| format!("Reading {file}"))?;
@@ -452,12 +561,39 @@ struct Signer {
}
impl Signer {
+ /// The key it signs with, as the federation spells it.
+ fn line(&self) -> String {
+ match &self.key {
+ Signing::File(key) => PublicKey(key.verifying_key().to_bytes()).line(),
+ Signing::Agent(key, _) => key.line(),
+ }
+ }
+
+ /// Refuses where `current` doesn't name the key it signs with for its party: only those
+ /// sign the party's key set and node list, and otherwise only a version naming the
+ /// party's keys or list anew, by the parties' votes, changes them.
+ fn named_by(&self, current: &Version) -> Result<()> {
+ let (party, number) = (&self.party, current.number);
+ let Some(given) = current.parties.get(party) else {
+ bail!(
+ "{party} is no party of version {number}: only a version letting it in names its \
+ keys and node list, which a party of it proposes and the parties pass"
+ );
+ };
+ if !given.keys.contains(&self.line()) {
+ bail!(
+ "version {number} doesn't name the key --key gives for {party}: only the keys it \
+ names sign {party}'s key set and node list. A version naming its keys or its \
+ list anew changes them: a party proposes it (continuum-party next, then \
+ propose), and the parties pass it"
+ );
+ }
+ Ok(())
+ }
+
fn sign(&self, deps: &[Id], does: (&str, Json)) -> Result<Vec<u8>> {
match &self.key {
- Signing::File(key) => {
- let line = PublicKey(key.verifying_key().to_bytes()).line();
- Ok(event::signed(key, &self.party, &line, deps, does))
- }
+ Signing::File(key) => Ok(event::signed(key, &self.party, &self.line(), deps, does)),
Signing::Agent(key, socket) => {
// The agent's answer is waited for blocking the thread, in async code: the
// client signs one event at a time and does nothing else meanwhile, and an
@@ -834,6 +970,50 @@ mod tests {
assert!(why.contains("OpenSSH private key"), "{why}");
}
+ /// A key set or node list changed as it counts: each name added absent, each taken off
+ /// held; named whole, it is as named.
+ #[test]
+ fn a_list_changed_as_it_counts() {
+ use super::changed;
+ let list = |items: &[&str]| -> Vec<String> {
+ items.iter().map(|item| (*item).to_owned()).collect()
+ };
+ let now = list(&["a", "b"]);
+ let changed_by = |given: &[&str], add: &[&str], remove: &[&str]| {
+ changed(
+ now.clone(),
+ list(given),
+ list(add),
+ list(remove),
+ "tv's list",
+ )
+ };
+ assert_eq!(changed_by(&["c"], &[], &[]).unwrap(), list(&["c"]));
+ assert_eq!(changed_by(&[], &["c"], &["a"]).unwrap(), list(&["b", "c"]));
+ assert_eq!(changed_by(&[], &[], &["a", "b"]).unwrap(), list(&[]));
+ assert!(changed_by(&[], &["a"], &[]).is_err());
+ assert!(changed_by(&[], &[], &["c"]).is_err());
+ }
+
+ /// A key set or node list is signed with a key the current version names for its
+ /// party; another key, or a party the version doesn't have, is refused before signing.
+ #[test]
+ fn a_key_set_or_node_list_is_signed_with_a_key_the_version_names() {
+ use super::{Signer, Signing};
+ use crate::federation::harness::{Party, Spec};
+ use crate::federation::version::Version;
+ let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2));
+ let current = Version::read(&Spec::first(&[&tv, &lass], &[]).json()).unwrap();
+ let signer = |key: &Party, party: &str| Signer {
+ key: Signing::File(key.key.clone()),
+ party: party.to_owned(),
+ };
+ assert!(signer(&tv, "tv").named_by(&current).is_ok());
+ assert!(signer(&lass, "tv").named_by(&current).is_err());
+ let makefu = Party::new("makefu", 3);
+ assert!(signer(&makefu, "makefu").named_by(&current).is_err());
+ }
+
/// The next version is the current one numbered on, naming its hash, without its
/// checkpoint: a version changing it, as its parties may pass.
#[test]