Diffinery

homeflare/celldpublic

celld/crates/celld/peer_probe.rs
238 lines · 7.8 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3// Peer probing is a real-wire diagnostic outside the Actor execution domain.
4#![allow(clippy::disallowed_types)]
5
6//! Challenge-bound proof that a diagnostic reached the node named by a lease.
7
8use anyhow::{anyhow, Context};
9use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
10use rand::RngCore;
11use serde::{Deserialize, Serialize};
12use std::sync::OnceLock;
13
14const PROBE_DOMAIN: &str = "cells-peer-probe-v1";
15const CHALLENGE_BYTES: usize = 32;
16const MAX_RESPONSE_BYTES: usize = 4096;
17pub(crate) const REEXEC_SIGNER_ENV: &str = "CELLD_REEXEC_PROBE_SIGNING_KEY";
18static INSTALLED_SIGNER: OnceLock<PeerProbeSigner> = OnceLock::new();
19
20pub struct PeerProbeSigner {
21 key: SigningKey,
22}
23
24#[derive(Debug, Deserialize, Serialize)]
25pub struct PeerProbeResponse {
26 version: u8,
27 node: String,
28 advertise: String,
29 challenge: String,
30 signature: String,
31}
32
33impl PeerProbeSigner {
34 fn generate() -> Self {
35 let mut secret = [0_u8; 32];
36 rand::rngs::OsRng.fill_bytes(&mut secret);
37 Self::from_secret(secret)
38 }
39
40 fn from_secret(mut secret: [u8; 32]) -> Self {
41 let key = SigningKey::from_bytes(&secret);
42 secret.fill(0);
43 Self { key }
44 }
45
46 fn public_key_hex(&self) -> String {
47 encode_hex(&self.key.verifying_key().to_bytes())
48 }
49
50 fn respond(
51 &self,
52 node: &str,
53 advertise: &str,
54 challenge: &str,
55 ) -> anyhow::Result<PeerProbeResponse> {
56 validate_challenge(challenge)?;
57 let signature = self
58 .key
59 .sign(probe_payload(node, advertise, challenge).as_bytes());
60 Ok(PeerProbeResponse {
61 version: 1,
62 node: node.to_string(),
63 advertise: advertise.to_string(),
64 challenge: challenge.to_string(),
65 signature: encode_hex(&signature.to_bytes()),
66 })
67 }
68}
69
70pub fn install_signer() -> anyhow::Result<String> {
71 let signer = match std::env::var(REEXEC_SIGNER_ENV) {
72 Ok(encoded) => {
73 // The handoff exists only in the new image's initial environment.
74 // Remove it before any adapter subprocess is launched.
75 std::env::remove_var(REEXEC_SIGNER_ENV);
76 PeerProbeSigner::from_secret(
77 decode_hex(&encoded).context("invalid re-exec peer probe signing key")?,
78 )
79 }
80 Err(std::env::VarError::NotPresent) => PeerProbeSigner::generate(),
81 Err(std::env::VarError::NotUnicode(_)) => {
82 std::env::remove_var(REEXEC_SIGNER_ENV);
83 return Err(anyhow!("re-exec peer probe signing key is not UTF-8"));
84 }
85 };
86 let public_key = signer.public_key_hex();
87 INSTALLED_SIGNER
88 .set(signer)
89 .map_err(|_| anyhow!("peer probe signer is already installed"))?;
90 Ok(public_key)
91}
92
93pub(crate) fn reexec_signer_secret() -> anyhow::Result<String> {
94 let signer = INSTALLED_SIGNER
95 .get()
96 .context("peer probe signer is not installed")?;
97 let mut secret = signer.key.to_bytes();
98 let encoded = encode_hex(&secret);
99 secret.fill(0);
100 Ok(encoded)
101}
102
103pub fn respond(node: &str, advertise: &str, challenge: &str) -> anyhow::Result<PeerProbeResponse> {
104 INSTALLED_SIGNER
105 .get()
106 .context("peer probe signer is not installed")?
107 .respond(node, advertise, challenge)
108}
109
110pub(crate) async fn probe(
111 client: &reqwest::Client,
112 node: &crate::ownership_store::NodeLeaseWire,
113 auth: &crate::peer_auth::PeerAuth,
114) -> anyhow::Result<()> {
115 if node.probe_public_key.is_empty() {
116 return Err(anyhow!(
117 "node {} has no signed-probe key; restart it with a current celld",
118 node.node
119 ));
120 }
121 if node.peer_protocol != crate::peer_auth::PROTOCOL_VERSION {
122 return Err(anyhow!(
123 "node {} speaks incompatible peer protocol {}",
124 node.node,
125 node.peer_protocol,
126 ));
127 }
128 let challenge = random_challenge();
129 let path = "/peer/probe";
130 let request = auth.sign(
131 client.get(format!("http://{}{path}", node.addr)),
132 "GET",
133 path,
134 &[],
135 &node.node,
136 )?;
137 let mut response = request
138 .header("x-cells-probe-challenge", &challenge)
139 .send()
140 .await
141 .with_context(|| format!("connect directly to node {} at {}", node.node, node.addr))?;
142 let status = response.status();
143 if !status.is_success() {
144 return Err(if status.as_u16() == 401 || status.as_u16() == 403 {
145 anyhow!(
146 "node {} rejected the signed probe (HTTP {status})",
147 node.node
148 )
149 } else {
150 anyhow!(
151 "node {} probe failed with HTTP {status}; an intermediary may have answered instead of the node",
152 node.node
153 )
154 });
155 }
156 crate::peer_auth::validate_response(response.headers())?;
157 let mut body = Vec::new();
158 while let Some(chunk) = response.chunk().await.context("read signed peer probe")? {
159 if body.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
160 return Err(anyhow!("node {} returned an oversized probe", node.node));
161 }
162 body.extend_from_slice(&chunk);
163 }
164 let response: PeerProbeResponse =
165 serde_json::from_slice(&body).context("decode signed peer probe")?;
166 verify(node, &challenge, &response)
167}
168
169fn verify(
170 expected: &crate::ownership_store::NodeLeaseWire,
171 challenge: &str,
172 response: &PeerProbeResponse,
173) -> anyhow::Result<()> {
174 if response.version != 1
175 || response.node != expected.node
176 || response.advertise != expected.addr
177 || response.challenge != challenge
178 {
179 return Err(anyhow!("signed peer probe identity or challenge mismatch"));
180 }
181 let public_key = decode_hex::<32>(&expected.probe_public_key)
182 .context("invalid peer probe public key in node lease")?;
183 let signature =
184 decode_hex::<64>(&response.signature).context("invalid peer probe signature encoding")?;
185 let public_key =
186 VerifyingKey::from_bytes(&public_key).context("invalid peer probe public key")?;
187 public_key
188 .verify(
189 probe_payload(&response.node, &response.advertise, &response.challenge).as_bytes(),
190 &Signature::from_bytes(&signature),
191 )
192 .context("peer probe signature verification failed")
193}
194
195fn probe_payload(node: &str, advertise: &str, challenge: &str) -> String {
196 format!("{PROBE_DOMAIN}\n{node}\n{advertise}\n{challenge}")
197}
198
199fn random_challenge() -> String {
200 let mut challenge = [0_u8; CHALLENGE_BYTES];
201 rand::rngs::OsRng.fill_bytes(&mut challenge);
202 encode_hex(&challenge)
203}
204
205fn validate_challenge(challenge: &str) -> anyhow::Result<()> {
206 decode_hex::<CHALLENGE_BYTES>(challenge)
207 .map(|_| ())
208 .context("probe challenge must be 32 lowercase hexadecimal bytes")
209}
210
211fn encode_hex(bytes: &[u8]) -> String {
212 const HEX: &[u8; 16] = b"0123456789abcdef";
213 let mut encoded = String::with_capacity(bytes.len() * 2);
214 for byte in bytes {
215 encoded.push(HEX[(byte >> 4) as usize] as char);
216 encoded.push(HEX[(byte & 0x0f) as usize] as char);
217 }
218 encoded
219}
220
221fn decode_hex<const N: usize>(encoded: &str) -> anyhow::Result<[u8; N]> {
222 if encoded.len() != N * 2 {
223 return Err(anyhow!("incorrect hexadecimal length"));
224 }
225 let mut decoded = [0_u8; N];
226 for (index, pair) in encoded.as_bytes().as_chunks::<2>().0.iter().enumerate() {
227 decoded[index] = (hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?;
228 }
229 Ok(decoded)
230}
231
232fn hex_nibble(value: u8) -> anyhow::Result<u8> {
233 match value {
234 b'0'..=b'9' => Ok(value - b'0'),
235 b'a'..=b'f' => Ok(value - b'a' + 10),
236 _ => Err(anyhow!("hexadecimal must be lowercase ASCII")),
237 }
238}