1use std::fs;
34use std::path::Path;
35
36use ed25519_dalek::pkcs8::{DecodePrivateKey, DecodePublicKey};
37#[cfg(test)]
38use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey};
39use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
40
41use crate::config::{AuthMode, GossipConfig};
42
43pub const SIGNED_TAG: u8 = 0x01;
46const SIG_LEN: usize = 64;
47
48#[derive(Debug)]
50pub enum GossipCryptoError {
51 Io(std::io::Error),
52 Decode(String),
53 Config(String),
57}
58
59impl std::fmt::Display for GossipCryptoError {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 match self {
62 GossipCryptoError::Io(e) => write!(f, "gossip key I/O: {e}"),
63 GossipCryptoError::Decode(m) => write!(f, "gossip key decode: {m}"),
64 GossipCryptoError::Config(m) => write!(f, "gossip authentication config: {m}"),
65 }
66 }
67}
68
69impl std::error::Error for GossipCryptoError {}
70
71impl From<std::io::Error> for GossipCryptoError {
72 fn from(e: std::io::Error) -> Self {
73 GossipCryptoError::Io(e)
74 }
75}
76
77pub fn load_signing_key(path: &Path) -> Result<SigningKey, GossipCryptoError> {
80 let bytes = fs::read(path)?;
81 if let Ok(text) = std::str::from_utf8(&bytes) {
82 if text.contains("-----BEGIN") {
83 return SigningKey::from_pkcs8_pem(text)
84 .map_err(|e| GossipCryptoError::Decode(format!("PKCS#8 PEM: {e}")));
85 }
86 }
87 SigningKey::from_pkcs8_der(&bytes)
88 .map_err(|e| GossipCryptoError::Decode(format!("PKCS#8 DER: {e}")))
89}
90
91pub fn load_verifying_key(path: &Path) -> Result<VerifyingKey, GossipCryptoError> {
94 let bytes = fs::read(path)?;
95 if let Ok(text) = std::str::from_utf8(&bytes) {
96 if text.contains("-----BEGIN") {
97 return VerifyingKey::from_public_key_pem(text)
98 .map_err(|e| GossipCryptoError::Decode(format!("SPKI PEM: {e}")));
99 }
100 }
101 VerifyingKey::from_public_key_der(&bytes)
102 .map_err(|e| GossipCryptoError::Decode(format!("SPKI DER: {e}")))
103}
104
105pub struct GossipSigner {
107 key: SigningKey,
108}
109
110impl GossipSigner {
111 pub fn new(key: SigningKey) -> Self {
112 Self { key }
113 }
114
115 pub fn verifying_key(&self) -> VerifyingKey {
118 self.key.verifying_key()
119 }
120
121 pub fn frame(&self, payload: &[u8]) -> Vec<u8> {
123 let sig = self.key.sign(payload);
124 let mut out = Vec::with_capacity(1 + SIG_LEN + payload.len());
125 out.push(SIGNED_TAG);
126 out.extend_from_slice(&sig.to_bytes());
127 out.extend_from_slice(payload);
128 out
129 }
130}
131
132pub enum VerifyOutcome<'a> {
134 Accept(&'a [u8]),
137 Reject(&'static str),
139}
140
141pub struct GossipVerifier {
144 trusted: Vec<VerifyingKey>,
145 mode: AuthMode,
146 identities: Vec<(String, VerifyingKey)>,
147}
148
149impl GossipVerifier {
150 #[cfg(test)]
151 pub(crate) fn new(trusted: Vec<VerifyingKey>, mode: AuthMode) -> Self {
152 Self {
153 trusted,
154 mode,
155 identities: Vec::new(),
156 }
157 }
158
159 pub fn for_identities(identities: Vec<(String, VerifyingKey)>, mode: AuthMode) -> Self {
161 Self {
162 trusted: identities.iter().map(|(_, key)| *key).collect(),
163 mode,
164 identities,
165 }
166 }
167
168 pub fn auth_mode(&self) -> AuthMode {
170 self.mode
171 }
172
173 pub fn check<'a>(&self, data: &'a [u8]) -> VerifyOutcome<'a> {
178 match data.first() {
179 Some(&SIGNED_TAG) => {
180 if data.len() < 1 + SIG_LEN {
181 return VerifyOutcome::Reject("truncated signed frame");
182 }
183 let sig_arr: [u8; SIG_LEN] = match data[1..1 + SIG_LEN].try_into() {
184 Ok(a) => a,
185 Err(_) => return VerifyOutcome::Reject("bad signature length"),
186 };
187 let sig = Signature::from_bytes(&sig_arr);
188 let payload = &data[1 + SIG_LEN..];
189 let ok = self.trusted.iter().any(|k| k.verify(payload, &sig).is_ok());
190 if ok {
191 if !self.identities.is_empty() {
192 let Ok(msg) =
193 serde_json::from_slice::<crate::broadcast::GossipMessage>(payload)
194 else {
195 return VerifyOutcome::Reject("invalid signed message");
196 };
197 if !self.identities.iter().any(|(name, key)| {
198 name == msg.origin_node() && key.verify_strict(payload, &sig).is_ok()
199 }) {
200 return VerifyOutcome::Reject("signing key not authorized for origin");
201 }
202 }
203 VerifyOutcome::Accept(payload)
204 } else {
205 VerifyOutcome::Reject("no trusted key verified signature")
206 }
207 }
208 _ => match self.mode {
210 AuthMode::Permissive => VerifyOutcome::Accept(data),
211 AuthMode::Required => {
212 VerifyOutcome::Reject("unsigned message under required-auth policy")
213 }
214 },
215 }
216 }
217}
218
219pub fn load_authentication(
239 config: &GossipConfig,
240) -> Result<(Option<GossipSigner>, GossipVerifier), GossipCryptoError> {
241 if !config.peer_keys.is_empty() {
242 return Err(GossipCryptoError::Config(
243 "gossip.peer_keys is no longer safe: migrate to gossip.peer_identities \
244 (node name -> public key path)"
245 .into(),
246 ));
247 }
248
249 let signer = match &config.identity_key {
250 Some(path) => {
251 let key = load_signing_key(path).map_err(|e| {
252 GossipCryptoError::Config(format!("gossip.identity_key {}: {e}", path.display()))
253 })?;
254 Some(GossipSigner::new(key))
255 }
256 None => None,
257 };
258
259 if config.auth_mode == AuthMode::Required && signer.is_none() {
260 return Err(GossipCryptoError::Config(format!(
261 "gossip auth_mode \"required\" needs gossip.identity_key for node '{}'",
262 config.node_name
263 )));
264 }
265
266 let mut identities: Vec<(String, VerifyingKey)> = Vec::new();
267 for (name, path) in &config.peer_identities {
268 if name.is_empty() || name.len() > 256 {
269 return Err(GossipCryptoError::Config(
270 "gossip peer identity names must contain 1..=256 bytes".into(),
271 ));
272 }
273 let key = load_verifying_key(path).map_err(|e| {
274 GossipCryptoError::Config(format!(
275 "gossip.peer_identities '{name}' ({}): {e}",
276 path.display()
277 ))
278 })?;
279 if name == &config.node_name {
283 match &signer {
284 Some(s) if s.verifying_key() != key => {
285 return Err(GossipCryptoError::Config(format!(
286 "gossip.peer_identities maps local node '{}' to a different key than \
287 gossip.identity_key",
288 config.node_name
289 )));
290 }
291 _ => {}
292 }
293 }
294 identities.push((name.clone(), key));
295 }
296 if let Some(s) = &signer {
301 if !identities
302 .iter()
303 .any(|(name, key)| name == &config.node_name && *key == s.verifying_key())
304 {
305 identities.push((config.node_name.clone(), s.verifying_key()));
306 }
307 }
308
309 Ok((
310 signer,
311 GossipVerifier::for_identities(identities, config.auth_mode),
312 ))
313}
314
315#[cfg(test)]
318pub(crate) fn write_test_identity(
319 dir: &std::path::Path,
320 name: &str,
321 seed: u8,
322) -> (SigningKey, std::path::PathBuf, std::path::PathBuf) {
323 let key = SigningKey::from_bytes(&[seed; 32]);
324 let priv_path = dir.join(format!("{name}.ed25519.p8"));
325 let priv_pem = key.to_pkcs8_pem(Default::default()).unwrap();
326 fs::write(&priv_path, priv_pem.as_str()).unwrap();
327 let pub_path = dir.join(format!("{name}.ed25519.pub.pem"));
328 let pub_pem = key
329 .verifying_key()
330 .to_public_key_pem(Default::default())
331 .unwrap();
332 fs::write(&pub_path, pub_pem).unwrap();
333 (key, priv_path, pub_path)
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339 use crate::config::{AuthMode, GossipConfig};
340 use ed25519_dalek::SigningKey;
341
342 fn test_key(seed: u8) -> SigningKey {
343 SigningKey::from_bytes(&[seed; 32])
344 }
345
346 fn auth_config(
349 node_name: &str,
350 mode: AuthMode,
351 identity: Option<&std::path::Path>,
352 peers: &[(&str, &std::path::Path)],
353 ) -> GossipConfig {
354 GossipConfig {
355 enabled: true,
356 bind: "127.0.0.1:0".into(),
357 seeds: vec![],
358 node_name: node_name.into(),
359 auth_mode: mode,
360 identity_key: identity.map(std::path::Path::to_path_buf),
361 peer_keys: vec![],
362 peer_identities: peers
363 .iter()
364 .map(|(name, path)| ((*name).to_string(), path.to_path_buf()))
365 .collect(),
366 }
367 }
368
369 fn broadcast(origin: &str) -> Vec<u8> {
371 serde_json::to_vec(&crate::broadcast::GossipMessage::UrgentRevocation {
372 producer_id: "producer".into(),
373 issuer_key_hash: vec![1; 32],
374 epoch: 1,
375 origin_node: origin.into(),
376 })
377 .unwrap()
378 }
379
380 #[test]
381 fn authenticated_peer_cannot_claim_another_origin() {
382 let signer = GossipSigner::new(test_key(1));
383 let verifier = GossipVerifier::for_identities(
384 vec![("node-a".into(), signer.verifying_key())],
385 AuthMode::Required,
386 );
387 let message = |origin: &str| {
388 serde_json::to_vec(&crate::broadcast::GossipMessage::UrgentRevocation {
389 producer_id: "p".into(),
390 issuer_key_hash: vec![1; 32],
391 epoch: 1,
392 origin_node: origin.into(),
393 })
394 .unwrap()
395 };
396 assert!(matches!(
397 verifier.check(&signer.frame(&message("node-a"))),
398 VerifyOutcome::Accept(_)
399 ));
400 for origin in ["node-b", ""] {
401 assert!(matches!(
402 verifier.check(&signer.frame(&message(origin))),
403 VerifyOutcome::Reject(_)
404 ));
405 }
406 }
407
408 #[test]
409 fn signed_frame_round_trips_and_verifies() {
410 let signer = GossipSigner::new(test_key(1));
411 let verifier = GossipVerifier::new(vec![signer.verifying_key()], AuthMode::Required);
412
413 let payload = br#"{"GenerationAnnouncement":{"epoch":7}}"#;
414 let framed = signer.frame(payload);
415 assert_eq!(framed[0], SIGNED_TAG);
416
417 match verifier.check(&framed) {
418 VerifyOutcome::Accept(p) => assert_eq!(p, payload),
419 VerifyOutcome::Reject(r) => panic!("expected accept, got reject: {r}"),
420 }
421 }
422
423 #[test]
424 fn required_policy_drops_forged_signature() {
425 let attacker = GossipSigner::new(test_key(9));
427 let trusted = GossipVerifier::new(vec![test_key(1).verifying_key()], AuthMode::Required);
428 let framed = attacker.frame(br#"{"UrgentRevocation":{"epoch":1}}"#);
429 assert!(matches!(
430 trusted.check(&framed),
431 VerifyOutcome::Reject("no trusted key verified signature")
432 ));
433 }
434
435 #[test]
436 fn required_policy_drops_tampered_payload() {
437 let signer = GossipSigner::new(test_key(1));
438 let verifier = GossipVerifier::new(vec![signer.verifying_key()], AuthMode::Required);
439 let mut framed = signer.frame(br#"{"epoch":1}"#);
440 let last = framed.len() - 1;
442 framed[last] ^= 0xFF;
443 assert!(matches!(verifier.check(&framed), VerifyOutcome::Reject(_)));
444 }
445
446 #[test]
447 fn required_policy_drops_unsigned_legacy() {
448 let verifier = GossipVerifier::new(vec![test_key(1).verifying_key()], AuthMode::Required);
449 let legacy = br#"{"GenerationAnnouncement":{"epoch":7}}"#;
450 assert!(matches!(
451 verifier.check(legacy),
452 VerifyOutcome::Reject("unsigned message under required-auth policy")
453 ));
454 }
455
456 #[test]
457 fn permissive_policy_accepts_unsigned_legacy() {
458 let verifier = GossipVerifier::new(vec![], AuthMode::Permissive);
460 let legacy = br#"{"GenerationAnnouncement":{"epoch":7}}"#;
461 match verifier.check(legacy) {
462 VerifyOutcome::Accept(p) => assert_eq!(p, legacy),
463 VerifyOutcome::Reject(r) => panic!("permissive must accept legacy: {r}"),
464 }
465 }
466
467 #[test]
468 fn permissive_policy_still_drops_forged_signed() {
469 let attacker = GossipSigner::new(test_key(9));
472 let verifier = GossipVerifier::new(vec![test_key(1).verifying_key()], AuthMode::Permissive);
473 let framed = attacker.frame(br#"{"epoch":1}"#);
474 assert!(matches!(verifier.check(&framed), VerifyOutcome::Reject(_)));
475 }
476
477 #[test]
478 fn truncated_signed_frame_rejected() {
479 let verifier = GossipVerifier::new(vec![], AuthMode::Permissive);
480 let truncated = [SIGNED_TAG, 0x00, 0x01, 0x02];
482 assert!(matches!(
483 verifier.check(&truncated),
484 VerifyOutcome::Reject("truncated signed frame")
485 ));
486 }
487
488 #[test]
494 fn permissive_accepts_known_signed_and_unsigned_peers() {
495 let dir = tempfile::tempdir().unwrap();
496 let (_key_a, _, pub_a) = write_test_identity(dir.path(), "a", 1);
497 let (_key_b, priv_b, pub_b) = write_test_identity(dir.path(), "b", 2);
498 let (key_c, _, _) = write_test_identity(dir.path(), "c", 3);
499
500 let config = auth_config(
502 "node-b",
503 AuthMode::Permissive,
504 Some(&priv_b),
505 &[("node-a", &pub_a), ("node-b", &pub_b)],
506 );
507 let (signer, permissive) = load_authentication(&config).unwrap();
508 let signer_b = signer.expect("permissive node keeps its outbound signer");
509
510 let unsigned = broadcast("node-a");
511 let b_signed = signer_b.frame(&broadcast("node-b"));
512 let c_signed = GossipSigner::new(key_c).frame(&broadcast("node-c"));
513
514 assert!(matches!(
515 permissive.check(&b_signed),
516 VerifyOutcome::Accept(_)
517 ));
518 assert!(matches!(
519 permissive.check(&unsigned),
520 VerifyOutcome::Accept(_)
521 ));
522 assert!(matches!(
523 permissive.check(&c_signed),
524 VerifyOutcome::Reject(_)
525 ));
526 }
527
528 #[test]
532 fn permissive_rejects_unknown_and_forged_signed_frames() {
533 let dir = tempfile::tempdir().unwrap();
534 let (key_a, _, pub_a) = write_test_identity(dir.path(), "a", 1);
535 let (_key_b, _, pub_b) = write_test_identity(dir.path(), "b", 2);
536 let (key_c, _, _) = write_test_identity(dir.path(), "c", 3);
537
538 let config = auth_config(
539 "node-b",
540 AuthMode::Permissive,
541 None,
542 &[("node-a", &pub_a), ("node-b", &pub_b)],
543 );
544 let (signer, permissive) = load_authentication(&config).unwrap();
545 assert!(signer.is_none(), "no identity_key configured");
546
547 let c_signer = GossipSigner::new(key_c);
548 let unknown = c_signer.frame(&broadcast("node-c"));
551 let forged = c_signer.frame(&broadcast("node-b"));
553 assert!(matches!(
554 permissive.check(&unknown),
555 VerifyOutcome::Reject(_)
556 ));
557 assert!(matches!(
558 permissive.check(&forged),
559 VerifyOutcome::Reject(_)
560 ));
561
562 let a_signer = GossipSigner::new(key_a);
564 let known = a_signer.frame(&broadcast("node-a"));
565 assert!(matches!(permissive.check(&known), VerifyOutcome::Accept(_)));
566
567 let empty = auth_config("node-b", AuthMode::Permissive, None, &[]);
570 let (_, empty_verifier) = load_authentication(&empty).unwrap();
571 assert!(matches!(
572 empty_verifier.check(&unknown),
573 VerifyOutcome::Reject(_)
574 ));
575 assert!(matches!(
576 empty_verifier.check(&forged),
577 VerifyOutcome::Reject(_)
578 ));
579 }
580
581 #[test]
585 fn required_rejects_unsigned_and_missing_identity() {
586 let dir = tempfile::tempdir().unwrap();
587 let (_key_a, priv_a, pub_a) = write_test_identity(dir.path(), "a", 1);
588
589 let config = auth_config(
590 "node-a",
591 AuthMode::Required,
592 Some(&priv_a),
593 &[("node-a", &pub_a)],
594 );
595 let (signer, required) = load_authentication(&config).unwrap();
596 assert!(signer.is_some(), "single-node required trusts its own key");
597
598 let unsigned = broadcast("node-a");
599 assert!(matches!(
600 required.check(&unsigned),
601 VerifyOutcome::Reject(_)
602 ));
603
604 let missing = auth_config("node-a", AuthMode::Required, None, &[]);
605 assert!(matches!(
606 load_authentication(&missing),
607 Err(GossipCryptoError::Config(_))
608 ));
609 }
610
611 #[test]
614 fn local_identity_conflict_rejects() {
615 let dir = tempfile::tempdir().unwrap();
616 let (_key_a, _, pub_a) = write_test_identity(dir.path(), "a", 1);
617 let (_key_b, priv_b, pub_b) = write_test_identity(dir.path(), "b", 2);
618
619 let conflicting = auth_config(
620 "node-b",
621 AuthMode::Permissive,
622 Some(&priv_b),
623 &[("node-b", &pub_a)],
624 );
625 assert!(matches!(
626 load_authentication(&conflicting),
627 Err(GossipCryptoError::Config(_))
628 ));
629
630 let consistent = auth_config(
632 "node-b",
633 AuthMode::Required,
634 Some(&priv_b),
635 &[("node-b", &pub_b), ("node-a", &pub_a)],
636 );
637 assert!(load_authentication(&consistent).is_ok());
638 }
639}