aboutsummaryrefslogtreecommitdiffstats
path: root/src/swarm/auth.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-01 05:32:36 +0100
committertv <tv@krebsco.de>2026-11-01 05:43:56 +0100
commitac81f5a68bf3259d1e0c49c93b2f84635b873824 (patch)
treef239d0a5d2f153ec4618b6413b9e5b735cb743eb /src/swarm/auth.rs
parentb644b4a8084a1060c9bc27566dfac8470e1090b5 (diff)
allow creating all key files
Diffstat (limited to 'src/swarm/auth.rs')
-rw-r--r--src/swarm/auth.rs30
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.