diff options
| author | tv <tv@krebsco.de> | 2026-11-01 05:32:36 +0100 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-01 05:32:36 +0100 |
| commit | d264f2df01c59bf4627b496290a553aa376369ef (patch) | |
| tree | b0830b6a5b730223f4ef92ad8e4df863e60bc87d /src/swarm | |
| parent | 9f8feeab71ccb864606c336097e20dbb8e1d8c86 (diff) | |
allow creating all key files
Diffstat (limited to 'src/swarm')
| -rw-r--r-- | src/swarm/auth.rs | 30 |
1 files changed, 25 insertions, 5 deletions
diff --git a/src/swarm/auth.rs b/src/swarm/auth.rs index 534a64d..98a004c 100644 --- a/src/swarm/auth.rs +++ b/src/swarm/auth.rs @@ -21,7 +21,7 @@ use std::sync::Mutex; use std::time::{Duration, Instant}; use crate::locks::MutexExt; -use anyhow::{Context, Result, bail}; +use anyhow::{Result, bail}; use sha2::{Digest, Sha256}; const HELLO_LABEL: &[u8] = b"continuum/hello/1"; @@ -46,10 +46,19 @@ const REJECTION_LOG_INTERVAL: Duration = Duration::from_secs(10); impl SwarmKey { /// Reads the key from a file; its bytes are the key, as they are. Generate one with /// e.g. `head -c 32 /dev/urandom > swarm.key`. - pub(crate) fn from_file(path: &Path) -> Result<Self> { - let key = std::fs::read(path) - .with_context(|| format!("Reading the swarm key from {}", path.display()))?; - crate::files::warn_if_readable_by_others(path, "swarm key"); + /// With `create`, a new one (32 random bytes) if there is no file at `path`. + pub(crate) fn from_file(path: &Path, create: bool) -> Result<Self> { + let (key, created) = crate::files::key_file( + path, + "swarm key", + create, + "swarm-key-create", + "on the swarm's first node; the others need a copy of it", + 32, + )?; + if created { + tracing::info!(path = %path.display(), "Created a new swarm key: copy it to the swarm's other nodes"); + } if key.len() < 16 { bail!( "The swarm key in {} has {} bytes; use at least 16 (32 random bytes recommended)", @@ -154,6 +163,17 @@ mod tests { crate::transport::Hex(bytes).to_string() } + /// A swarm key file is made only when asked, then read as any other. + #[test] + fn swarm_key_created_only_when_asked() { + let path = crate::files::scratch_dir("swarm-key-create").join("swarm.key"); + assert!(SwarmKey::from_file(&path, false).is_err()); + assert!(!path.exists()); + let created = SwarmKey::from_file(&path, true).unwrap(); + assert_eq!(created.key.len(), 32); + assert_eq!(SwarmKey::from_file(&path, false).unwrap().key, created.key); + } + #[test] fn hmac_matches_rfc_4231() { // Test case 2. |
