| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | // Authentication entropy and signature timestamps belong to the real peer wire. |
| 4 | #![allow(clippy::disallowed_methods, clippy::disallowed_types)] |
| 5 | |
| 6 | use crate::bucket::Bucket; |
| 7 | use anyhow::{anyhow, Context}; |
| 8 | use hmac::{Hmac, Mac}; |
| 9 | use rand::RngCore; |
| 10 | use serde::{Deserialize, Serialize}; |
| 11 | use sha2::{Digest, Sha256}; |
| 12 | use std::collections::HashMap; |
| 13 | use std::sync::Mutex; |
| 14 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 15 | |
| 16 | pub const PROTOCOL_VERSION: u16 = 5; |
| 17 | pub const PROTOCOL_VERSION_TEXT: &str = "5"; |
| 18 | pub const RESPONSE_VERSION_HEADER: &str = "x-cells-peer-version"; |
| 19 | |
| 20 | const SECRET_KEY: &str = "fleet/peer-auth.json"; |
| 21 | const SECRET_VERSION: u8 = 1; |
| 22 | const DOMAIN: &str = "cells-peer-request-v1"; |
| 23 | const CLOCK_WINDOW_MS: u64 = 30_000; |
| 24 | const REPLAY_RETENTION_MS: u64 = CLOCK_WINDOW_MS * 2; |
| 25 | // A nonce must be retained at least as long as its signature stays acceptable, |
| 26 | // or the replay cache forgets it while a replay is still in-window. Pinned at |
| 27 | // compile time (see celld_logic::peer::replay_entry_expired). |
| 28 | const _: () = assert!(REPLAY_RETENTION_MS >= CLOCK_WINDOW_MS); |
| 29 | const MAX_REPLAY_ENTRIES: usize = 1_000_000; |
| 30 | |
| 31 | const HEADER_SOURCE: &str = "x-cells-peer-source"; |
| 32 | const HEADER_TARGET: &str = "x-cells-peer-target"; |
| 33 | const HEADER_TIMESTAMP: &str = "x-cells-peer-timestamp"; |
| 34 | const HEADER_NONCE: &str = "x-cells-peer-nonce"; |
| 35 | const HEADER_BODY_SHA256: &str = "x-cells-peer-body-sha256"; |
| 36 | const HEADER_SIGNATURE: &str = "x-cells-peer-signature"; |
| 37 | |
| 38 | #[derive(Deserialize, Serialize)] |
| 39 | #[serde(deny_unknown_fields)] |
| 40 | struct StoredSecret { |
| 41 | version: u8, |
| 42 | key: String, |
| 43 | } |
| 44 | |
| 45 | struct ReplayCache { |
| 46 | entries: HashMap<[u8; 16], u64>, |
| 47 | checks: u64, |
| 48 | } |
| 49 | |
| 50 | struct CanonicalRequest<'a> { |
| 51 | method: &'a str, |
| 52 | path_and_query: &'a str, |
| 53 | body_hash: &'a str, |
| 54 | source: &'a str, |
| 55 | target: &'a str, |
| 56 | timestamp: u64, |
| 57 | nonce: &'a str, |
| 58 | } |
| 59 | |
| 60 | pub struct PeerAuth { |
| 61 | key: [u8; 32], |
| 62 | source: String, |
| 63 | replay: Mutex<ReplayCache>, |
| 64 | } |
| 65 | |
| 66 | #[derive(Debug)] |
| 67 | pub enum VerifyError { |
| 68 | Unauthorized, |
| 69 | WrongTarget, |
| 70 | IncompatibleVersion, |
| 71 | Replay, |
| 72 | ReplayCapacity, |
| 73 | } |
| 74 | |
| 75 | impl VerifyError { |
| 76 | pub fn status(&self) -> axum::http::StatusCode { |
| 77 | match self { |
| 78 | Self::Unauthorized => axum::http::StatusCode::UNAUTHORIZED, |
| 79 | Self::WrongTarget => axum::http::StatusCode::CONFLICT, |
| 80 | Self::IncompatibleVersion => axum::http::StatusCode::UPGRADE_REQUIRED, |
| 81 | Self::Replay => axum::http::StatusCode::CONFLICT, |
| 82 | Self::ReplayCapacity => axum::http::StatusCode::SERVICE_UNAVAILABLE, |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | pub fn message(&self) -> &'static str { |
| 87 | match self { |
| 88 | Self::Unauthorized => "peer authentication failed", |
| 89 | Self::WrongTarget => "peer request targets a different node session", |
| 90 | Self::IncompatibleVersion => "peer protocol version is incompatible", |
| 91 | Self::Replay => "peer request replay rejected", |
| 92 | Self::ReplayCapacity => "peer replay cache is full", |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | impl PeerAuth { |
| 98 | pub fn new(key: [u8; 32], source: impl Into<String>) -> anyhow::Result<Self> { |
| 99 | let source = source.into(); |
| 100 | crate::machine::validate_node_name(&source) |
| 101 | .context("invalid peer authentication source")?; |
| 102 | Ok(Self { |
| 103 | key, |
| 104 | source, |
| 105 | replay: Mutex::new(ReplayCache { |
| 106 | entries: HashMap::new(), |
| 107 | checks: 0, |
| 108 | }), |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | pub fn source(&self) -> &str { |
| 113 | &self.source |
| 114 | } |
| 115 | |
| 116 | pub fn sign( |
| 117 | &self, |
| 118 | request: reqwest::RequestBuilder, |
| 119 | method: &str, |
| 120 | path_and_query: &str, |
| 121 | body: &[u8], |
| 122 | target: &str, |
| 123 | ) -> anyhow::Result<reqwest::RequestBuilder> { |
| 124 | Ok(request.headers(self.signed_headers(method, path_and_query, body, target)?)) |
| 125 | } |
| 126 | |
| 127 | pub fn signed_headers( |
| 128 | &self, |
| 129 | method: &str, |
| 130 | path_and_query: &str, |
| 131 | body: &[u8], |
| 132 | target: &str, |
| 133 | ) -> anyhow::Result<axum::http::HeaderMap> { |
| 134 | self.signed_headers_parts(method, path_and_query, &[body], target) |
| 135 | } |
| 136 | |
| 137 | fn signed_headers_parts( |
| 138 | &self, |
| 139 | method: &str, |
| 140 | path_and_query: &str, |
| 141 | body: &[&[u8]], |
| 142 | target: &str, |
| 143 | ) -> anyhow::Result<axum::http::HeaderMap> { |
| 144 | crate::machine::validate_node_name(target).context("invalid peer authentication target")?; |
| 145 | let timestamp = now_ms()?; |
| 146 | let mut nonce = [0_u8; 16]; |
| 147 | rand::rngs::OsRng.fill_bytes(&mut nonce); |
| 148 | let nonce = encode_hex(&nonce); |
| 149 | let body_hash = sha256_hex_parts(body); |
| 150 | let canonical = CanonicalRequest { |
| 151 | method, |
| 152 | path_and_query, |
| 153 | body_hash: &body_hash, |
| 154 | source: &self.source, |
| 155 | target, |
| 156 | timestamp, |
| 157 | nonce: &nonce, |
| 158 | }; |
| 159 | let signature = self.signature(&canonical); |
| 160 | let mut headers = axum::http::HeaderMap::new(); |
| 161 | for (name, value) in [ |
| 162 | (RESPONSE_VERSION_HEADER, PROTOCOL_VERSION_TEXT.to_string()), |
| 163 | (HEADER_SOURCE, self.source.clone()), |
| 164 | (HEADER_TARGET, target.to_string()), |
| 165 | (HEADER_TIMESTAMP, timestamp.to_string()), |
| 166 | (HEADER_NONCE, nonce), |
| 167 | (HEADER_BODY_SHA256, body_hash), |
| 168 | (HEADER_SIGNATURE, signature), |
| 169 | ] { |
| 170 | headers.insert( |
| 171 | axum::http::HeaderName::from_static(name), |
| 172 | axum::http::HeaderValue::from_str(&value) |
| 173 | .with_context(|| format!("encode peer header {name}"))?, |
| 174 | ); |
| 175 | } |
| 176 | Ok(headers) |
| 177 | } |
| 178 | |
| 179 | pub fn verify( |
| 180 | &self, |
| 181 | method: &axum::http::Method, |
| 182 | path_and_query: &str, |
| 183 | headers: &axum::http::HeaderMap, |
| 184 | body: &[u8], |
| 185 | expected_target: &str, |
| 186 | ) -> Result<(), VerifyError> { |
| 187 | match header(headers, RESPONSE_VERSION_HEADER) { |
| 188 | Some(PROTOCOL_VERSION_TEXT) => {} |
| 189 | Some(_) => return Err(VerifyError::IncompatibleVersion), |
| 190 | None => return Err(VerifyError::Unauthorized), |
| 191 | } |
| 192 | let source = header(headers, HEADER_SOURCE).ok_or(VerifyError::Unauthorized)?; |
| 193 | let target = header(headers, HEADER_TARGET).ok_or(VerifyError::Unauthorized)?; |
| 194 | if crate::machine::validate_node_name(source).is_err() |
| 195 | || crate::machine::validate_node_name(target).is_err() |
| 196 | { |
| 197 | return Err(VerifyError::Unauthorized); |
| 198 | } |
| 199 | let timestamp = header(headers, HEADER_TIMESTAMP) |
| 200 | .and_then(|value| value.parse::<u64>().ok()) |
| 201 | .ok_or(VerifyError::Unauthorized)?; |
| 202 | let now = now_ms().map_err(|_| VerifyError::Unauthorized)?; |
| 203 | if !celld_logic::peer::within_clock_window(now, timestamp, CLOCK_WINDOW_MS) { |
| 204 | return Err(VerifyError::Unauthorized); |
| 205 | } |
| 206 | let nonce_text = header(headers, HEADER_NONCE).ok_or(VerifyError::Unauthorized)?; |
| 207 | let nonce = decode_hex::<16>(nonce_text).map_err(|_| VerifyError::Unauthorized)?; |
| 208 | let claimed_body_hash = |
| 209 | header(headers, HEADER_BODY_SHA256).ok_or(VerifyError::Unauthorized)?; |
| 210 | let body_hash = sha256_hex(body); |
| 211 | if claimed_body_hash != body_hash { |
| 212 | return Err(VerifyError::Unauthorized); |
| 213 | } |
| 214 | let signature = header(headers, HEADER_SIGNATURE) |
| 215 | .and_then(|value| decode_hex::<32>(value).ok()) |
| 216 | .ok_or(VerifyError::Unauthorized)?; |
| 217 | let canonical = CanonicalRequest { |
| 218 | method: method.as_str(), |
| 219 | path_and_query, |
| 220 | body_hash: &body_hash, |
| 221 | source, |
| 222 | target, |
| 223 | timestamp, |
| 224 | nonce: nonce_text, |
| 225 | }; |
| 226 | let mac = self.mac(&canonical); |
| 227 | mac.verify_slice(&signature) |
| 228 | .map_err(|_| VerifyError::Unauthorized)?; |
| 229 | if target != expected_target { |
| 230 | return Err(VerifyError::WrongTarget); |
| 231 | } |
| 232 | |
| 233 | let mut replay = self.replay.lock().unwrap(); |
| 234 | replay.checks = replay.checks.saturating_add(1); |
| 235 | if replay.checks.is_multiple_of(1024) || replay.entries.len() >= MAX_REPLAY_ENTRIES { |
| 236 | replay.entries.retain(|_, seen_ms| { |
| 237 | !celld_logic::peer::replay_entry_expired(now, *seen_ms, REPLAY_RETENTION_MS) |
| 238 | }); |
| 239 | } |
| 240 | if replay.entries.contains_key(&nonce) { |
| 241 | return Err(VerifyError::Replay); |
| 242 | } |
| 243 | if replay.entries.len() >= MAX_REPLAY_ENTRIES { |
| 244 | return Err(VerifyError::ReplayCapacity); |
| 245 | } |
| 246 | replay.entries.insert(nonce, now); |
| 247 | Ok(()) |
| 248 | } |
| 249 | |
| 250 | fn signature(&self, request: &CanonicalRequest<'_>) -> String { |
| 251 | encode_hex(&self.mac(request).finalize().into_bytes()) |
| 252 | } |
| 253 | |
| 254 | fn mac(&self, request: &CanonicalRequest<'_>) -> Hmac<Sha256> { |
| 255 | let CanonicalRequest { |
| 256 | method, |
| 257 | path_and_query, |
| 258 | body_hash, |
| 259 | source, |
| 260 | target, |
| 261 | timestamp, |
| 262 | nonce, |
| 263 | } = request; |
| 264 | let canonical = format!( |
| 265 | "{DOMAIN}\n{PROTOCOL_VERSION}\n{method}\n{path_and_query}\n{body_hash}\n\ |
| 266 | {source}\n{target}\n{timestamp}\n{nonce}" |
| 267 | ); |
| 268 | let mut mac = |
| 269 | <Hmac<Sha256> as Mac>::new_from_slice(&self.key).expect("HMAC accepts a 32-byte key"); |
| 270 | mac.update(canonical.as_bytes()); |
| 271 | mac |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | pub async fn load_or_create(bucket: &Bucket) -> anyhow::Result<[u8; 32]> { |
| 276 | if let Some(key) = load(bucket).await? { |
| 277 | return Ok(key); |
| 278 | } |
| 279 | let mut key = [0_u8; 32]; |
| 280 | rand::rngs::OsRng.fill_bytes(&mut key); |
| 281 | let stored = StoredSecret { |
| 282 | version: SECRET_VERSION, |
| 283 | key: encode_hex(&key), |
| 284 | }; |
| 285 | match bucket |
| 286 | .put_cas(SECRET_KEY, serde_json::to_vec(&stored)?, None) |
| 287 | .await |
| 288 | { |
| 289 | Ok(Some(_)) => Ok(key), |
| 290 | Ok(None) => load(bucket) |
| 291 | .await? |
| 292 | .context("peer authentication secret disappeared after create race"), |
| 293 | Err(error) => Err(error.context("create fleet peer authentication secret")), |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | pub async fn load_existing(bucket: &Bucket) -> anyhow::Result<[u8; 32]> { |
| 298 | load(bucket) |
| 299 | .await? |
| 300 | .context("fleet has no peer authentication secret; start a current celld node first") |
| 301 | } |
| 302 | |
| 303 | async fn load(bucket: &Bucket) -> anyhow::Result<Option<[u8; 32]>> { |
| 304 | let Some((bytes, _)) = bucket |
| 305 | .get(SECRET_KEY) |
| 306 | .await |
| 307 | .context("read fleet peer authentication secret")? |
| 308 | else { |
| 309 | return Ok(None); |
| 310 | }; |
| 311 | let stored: StoredSecret = |
| 312 | serde_json::from_slice(&bytes).context("decode fleet peer authentication secret")?; |
| 313 | if stored.version != SECRET_VERSION { |
| 314 | return Err(anyhow!( |
| 315 | "unsupported fleet peer authentication secret version {}", |
| 316 | stored.version |
| 317 | )); |
| 318 | } |
| 319 | decode_hex::<32>(&stored.key) |
| 320 | .context("invalid fleet peer authentication secret") |
| 321 | .map(Some) |
| 322 | } |
| 323 | |
| 324 | pub fn validate_response(headers: &axum::http::HeaderMap) -> anyhow::Result<()> { |
| 325 | match headers |
| 326 | .get(RESPONSE_VERSION_HEADER) |
| 327 | .and_then(|value| value.to_str().ok()) |
| 328 | { |
| 329 | Some(PROTOCOL_VERSION_TEXT) => Ok(()), |
| 330 | Some(version) => Err(anyhow!( |
| 331 | "peer responded with incompatible protocol version {version:?}" |
| 332 | )), |
| 333 | None => Err(anyhow!("peer response has no protocol version")), |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | fn header<'a>(headers: &'a axum::http::HeaderMap, name: &str) -> Option<&'a str> { |
| 338 | headers.get(name)?.to_str().ok() |
| 339 | } |
| 340 | |
| 341 | fn now_ms() -> anyhow::Result<u64> { |
| 342 | Ok(SystemTime::now() |
| 343 | .duration_since(UNIX_EPOCH) |
| 344 | .context("system clock is before the Unix epoch")? |
| 345 | .as_millis() as u64) |
| 346 | } |
| 347 | |
| 348 | fn sha256_hex(body: &[u8]) -> String { |
| 349 | encode_hex(&Sha256::digest(body)) |
| 350 | } |
| 351 | |
| 352 | fn sha256_hex_parts(parts: &[&[u8]]) -> String { |
| 353 | let mut digest = Sha256::new(); |
| 354 | for part in parts { |
| 355 | digest.update(part); |
| 356 | } |
| 357 | encode_hex(&digest.finalize()) |
| 358 | } |
| 359 | |
| 360 | fn encode_hex(bytes: &[u8]) -> String { |
| 361 | const HEX: &[u8; 16] = b"0123456789abcdef"; |
| 362 | let mut encoded = String::with_capacity(bytes.len() * 2); |
| 363 | for byte in bytes { |
| 364 | encoded.push(HEX[(byte >> 4) as usize] as char); |
| 365 | encoded.push(HEX[(byte & 0x0f) as usize] as char); |
| 366 | } |
| 367 | encoded |
| 368 | } |
| 369 | |
| 370 | fn decode_hex<const N: usize>(encoded: &str) -> anyhow::Result<[u8; N]> { |
| 371 | if encoded.len() != N * 2 { |
| 372 | return Err(anyhow!("incorrect hexadecimal length")); |
| 373 | } |
| 374 | let mut decoded = [0_u8; N]; |
| 375 | for (index, pair) in encoded.as_bytes().chunks_exact(2).enumerate() { |
| 376 | decoded[index] = (hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?; |
| 377 | } |
| 378 | Ok(decoded) |
| 379 | } |
| 380 | |
| 381 | fn hex_nibble(value: u8) -> anyhow::Result<u8> { |
| 382 | match value { |
| 383 | b'0'..=b'9' => Ok(value - b'0'), |
| 384 | b'a'..=b'f' => Ok(value - b'a' + 10), |
| 385 | _ => Err(anyhow!("hexadecimal must be lowercase ASCII")), |
| 386 | } |
| 387 | } |