aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/party.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-18 12:38:19 +0100
committertv <tv@krebsco.de>2026-11-18 12:38:19 +0100
commit257ad0391ff8eba437108e1885c45314e9fd5833 (patch)
tree3098609e38125c0afb326efeb41a08d0045da3d4 /src/federation/party.rs
parentcfe3dbaff24b5ae433b3203d69c7e9bceb4e1ccc (diff)
parent55f36a960a90aedcb6e899ea963cc642fd630a82 (diff)
Merge branch 'ecdsa'
Diffstat (limited to 'src/federation/party.rs')
-rw-r--r--src/federation/party.rs143
1 files changed, 131 insertions, 12 deletions
diff --git a/src/federation/party.rs b/src/federation/party.rs
index f0ae288..9d9c268 100644
--- a/src/federation/party.rs
+++ b/src/federation/party.rs
@@ -1,5 +1,6 @@
//! `continuum-party`: a party's client of a federation (`docs/federation.md`). It signs its
-//! party's events with one of its keys (an OpenSSH private key file, `--key`), puts them
+//! party's events with one of its keys (`--key`: an OpenSSH private key file, or a public
+//! key the ssh-agent at `SSH_AUTH_SOCK` holds, given itself or in a file), 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. Its options may be set in configuration files as the node's are
@@ -42,6 +43,7 @@ use super::client::{self, Record};
use super::event::{self, Does, Event, Signed};
use super::fold::Federation;
use super::jcs::Json;
+use super::keys::{self, Key};
use super::store::Id;
use super::store::memory::Store;
use super::version::Version;
@@ -282,7 +284,7 @@ pub(crate) async fn main() -> Result<()> {
let keys = strings(sub, "keys")
.iter()
.map(|line| {
- PublicKey::parse(line)
+ Key::parse(line)
.map(|key| key.line())
.map_err(|why| anyhow!("{line:?}: {why}"))
})
@@ -341,25 +343,102 @@ fn strings(matches: &ArgMatches, name: &str) -> Vec<String> {
.collect()
}
-fn signing_key(options: &Options) -> Result<SigningKey> {
- let file = options
+/// What `--key` gives: a private key, from an OpenSSH private key file; or a public key,
+/// given itself (an `authorized_keys` line), or the first of a file of such lines, with
+/// how many more the file holds.
+enum Given {
+ Private(SigningKey),
+ Public(Key, usize),
+}
+
+/// What `given`, `--key`'s value, gives (`Given`).
+fn given_key(given: &str) -> Result<Given> {
+ let itself = match Key::parse(given) {
+ Ok(key) => return Ok(Given::Public(key, 0)),
+ Err(why) => why,
+ };
+ let text = match std::fs::read_to_string(given) {
+ Ok(text) => text,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ bail!("{given}: no file, nor a key ({itself})")
+ }
+ Err(error) => return Err(error).with_context(|| format!("Reading {given}")),
+ };
+ if text.trim_start().starts_with("-----BEGIN") {
+ let key = client::signing_key(&text).map_err(|why| anyhow!("{given}: {why}"))?;
+ return Ok(Given::Private(key));
+ }
+ let mut lines = text
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.is_empty() && !line.starts_with('#'));
+ let first = lines
+ .next()
+ .with_context(|| format!("{given} holds no key"))?;
+ let key = Key::parse(first).map_err(|why| anyhow!("{given}: {why}"))?;
+ Ok(Given::Public(key, lines.count()))
+}
+
+/// The key `--key` gives (`given_key`): a private key, signing here; or a public key,
+/// signing through the ssh-agent at `SSH_AUTH_SOCK`, which must hold it. Of a file of
+/// several public keys, the first, with a warning: another is given as `--key` itself.
+fn signing_key(options: &Options) -> Result<Signing> {
+ let given = 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}"))
+ let key = match given_key(given)? {
+ Given::Private(key) => return Ok(Signing::File(key)),
+ Given::Public(key, 0) => key,
+ Given::Public(key, more) => {
+ eprintln!(
+ "Warning: {given} holds {} keys: signing with the first, {}; to sign with \
+ another, give that key itself as --key",
+ more + 1,
+ key.line()
+ );
+ key
+ }
+ };
+ let socket = std::env::var_os("SSH_AUTH_SOCK").with_context(|| {
+ format!(
+ "{} signs through an ssh-agent: SSH_AUTH_SOCK names none",
+ key.line()
+ )
+ })?;
+ Ok(Signing::Agent(key, PathBuf::from(socket)))
+}
+
+/// What signs: a key at hand, or a key the ssh-agent at a socket holds.
+enum Signing {
+ File(SigningKey),
+ Agent(Key, PathBuf),
}
/// Who signs: the party, with one of its keys.
struct Signer {
- key: SigningKey,
+ key: Signing,
party: String,
}
impl Signer {
- fn sign(&self, deps: &[Id], does: (&str, Json)) -> Vec<u8> {
- let line = PublicKey(self.key.verifying_key().to_bytes()).line();
- event::signed(&self.key, &self.party, &line, deps, does)
+ 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::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
+ // agent may wait for its user (a touch, a confirmation) as long as that
+ // takes, which nothing here should cut short.
+ event::signed_by(&self.party, &key.line(), deps, does, |bytes| {
+ keys::sign_through(socket, key, bytes)
+ })
+ .map_err(|why| anyhow!(why))
+ }
+ }
}
}
@@ -372,7 +451,7 @@ async fn sign(
does: (&str, Json),
) -> Result<()> {
let (_, heads) = node.summary().await?;
- let event = signer.sign(&heads, does);
+ let event = signer.sign(&heads, does)?;
record.signed(&event);
record.save(path).map_err(|why| anyhow!(why))?;
node.put(&event).await
@@ -437,7 +516,7 @@ async fn vote(
.map_err(|why| anyhow!(why))?;
// On the events proposing it: above the heads it names for a checkpoint wherever they
// are, so a version event may be written on it.
- let cast = signer.sign(&proposals, event::vote(current.hash, proposal, yes));
+ let cast = signer.sign(&proposals, event::vote(current.hash, proposal, yes))?;
record.cast(&current, &cast, kept);
record.save(path).map_err(|why| anyhow!(why))?;
node.put(&cast).await
@@ -671,6 +750,46 @@ mod tests {
super::command().debug_assert();
}
+ /// `--key` gives a public key itself, or the first of a file's with how many more it
+ /// holds, or a private key file's key; a file of neither, or none, gives nothing.
+ #[test]
+ fn the_key_given() {
+ use super::{Given, given_key};
+ use crate::federation::vectors::ECDSA_KEY;
+ let ed25519 = crate::federation::harness::key_line(1);
+ let dir = crate::files::scratch_dir("party-key");
+ let file = |name: &str, text: &str| {
+ let path = dir.join(name);
+ std::fs::write(&path, text).unwrap();
+ path.to_str().unwrap().to_owned()
+ };
+ let public = |given: &str| match given_key(given).unwrap() {
+ Given::Public(key, more) => (key.line(), more),
+ Given::Private(_) => panic!("{given}: a private key"),
+ };
+ assert_eq!(public(ECDSA_KEY), (ECDSA_KEY.to_owned(), 0));
+ assert_eq!(
+ public(&format!("{ed25519} tv@laptop")),
+ (ed25519.clone(), 0)
+ );
+ let one = file("phone.pub", &format!("{ECDSA_KEY} tv@phone\n"));
+ assert_eq!(public(&one), (ECDSA_KEY.to_owned(), 0));
+ let two = file(
+ "agent.pub",
+ &format!("{ed25519} tv@laptop\n\n{ECDSA_KEY} tv@phone\n"),
+ );
+ assert_eq!(public(&two), (ed25519, 1));
+ assert!(given_key(&file("rsa.pub", "ssh-rsa AAAAB3NzaC1yc2E tv\n")).is_err());
+ assert!(given_key(&file("empty.pub", "\n")).is_err());
+ assert!(given_key(dir.join("missing").to_str().unwrap()).is_err());
+ let private = file(
+ "tv.key",
+ "-----BEGIN OPENSSH PRIVATE KEY-----\n-----END OPENSSH PRIVATE KEY-----\n",
+ );
+ let why = given_key(&private).err().expect("no key").to_string();
+ assert!(why.contains("OpenSSH private key"), "{why}");
+ }
+
/// Its options come from configuration files as the node's do, arguments winning.
#[test]
fn its_options_come_from_configuration_files_and_arguments() {