Skip to main content

orch/store/cluster/
network.rs

1//! Raft RPCs and forwarded writes between nodes, JSON over HTTP like `../agents-coordination`.
2//! Every request carries the cluster secret, so reaching the port is not enough to join
3
4use std::error;
5use std::fmt::Write as _;
6use std::sync::{Arc, LazyLock};
7use std::time::Duration;
8
9use axum::extract::State;
10use axum::http::{HeaderMap, StatusCode};
11use axum::response::{IntoResponse, Response};
12use axum::routing::{get, post};
13use axum::{Json, Router};
14use hmac::Hmac;
15use hmac::Mac;
16use openraft::BasicNode;
17use openraft::error::ClientWriteError;
18use openraft::error::{
19    InstallSnapshotError, NetworkError, RPCError, RaftError, RemoteError, Unreachable,
20};
21use openraft::network::{RPCOption, RaftNetwork, RaftNetworkFactory};
22use openraft::raft::{
23    AppendEntriesRequest, AppendEntriesResponse, InstallSnapshotRequest, InstallSnapshotResponse,
24    VoteRequest, VoteResponse,
25};
26use reqwest::header::HeaderValue;
27use serde::Serialize;
28use serde::de::DeserializeOwned;
29use subtle::ConstantTimeEq;
30
31use super::version::{Version, Versions};
32use super::{NodeId, Raft, Reply, Request, TypeConfig};
33
34const SECRET_HEADER: &str = "x-orch-cluster-secret";
35const NONCE_HEADER: &str = "x-orch-nonce";
36const PROOF_HEADER: &str = "x-orch-proof";
37/// The sender's orch version on every Raft RPC, so each node learns what its peers run
38const VERSION_HEADER: &str = "x-orch-version";
39
40static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
41    reqwest::Client::builder()
42        .timeout(Duration::from_secs(30))
43        .build()
44        .unwrap_or_default()
45});
46
47#[derive(Clone)]
48struct App {
49    raft: Raft,
50    secret: Arc<str>,
51    me: Arc<Hello>,
52    /// The address peers dial, bound into every proof so a proof relayed through another host fails
53    addr: Arc<str>,
54    versions: Arc<Versions>,
55}
56
57/// What a node says about itself to a peer that found it on the tailnet
58#[derive(Debug, Clone, PartialEq, Serialize, serde::Deserialize)]
59pub struct Hello {
60    pub name: String,
61    pub id: NodeId,
62    pub witness: bool,
63    #[serde(default)]
64    pub leader: Option<NodeId>,
65    #[serde(default)]
66    pub term: u64,
67    /// HMAC of the prober's nonce and this name, so the prober knows the peer holds the secret
68    #[serde(default)]
69    pub proof: String,
70    /// None from a node older than version reports
71    #[serde(default)]
72    pub version: Option<Version>,
73    /// The version the node needs before it applies again
74    #[serde(default)]
75    pub needs_upgrade: Option<Version>,
76    /// The node upgrades itself, so a lower node waits its turn behind it
77    #[serde(default)]
78    pub auto_upgrade: bool,
79    /// Why the node's last upgrade failed
80    #[serde(default)]
81    pub upgrade_error: Option<String>,
82}
83
84/// HMAC-SHA256 under the cluster secret, in hex. Proves the secret without sending it
85fn mac(secret: &str, parts: &[&str]) -> String {
86    let mut m =
87        Hmac::<sha2::Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes any key");
88    for part in parts {
89        m.update(part.as_bytes());
90        m.update(b"\0");
91    }
92
93    let bytes = m.finalize().into_bytes();
94    let mut out = String::with_capacity(bytes.len() * 2);
95    for b in bytes {
96        let _ = write!(out, "{b:02x}");
97    }
98    out
99}
100
101/// A node asking the leader to add it as a learner
102#[derive(Debug, Clone, Serialize, serde::Deserialize)]
103pub struct Join {
104    pub id: NodeId,
105    pub addr: String,
106}
107
108fn authorized(app: &App, headers: &HeaderMap) -> bool {
109    let given = headers
110        .get(SECRET_HEADER)
111        .map(HeaderValue::as_bytes)
112        .unwrap_or_default();
113    let ok: bool = given.ct_eq(app.secret.as_bytes()).into();
114    if ok
115        && let Some(v) = headers
116            .get(VERSION_HEADER)
117            .and_then(|v| v.to_str().ok())
118            .and_then(|v| v.parse().ok())
119    {
120        app.versions.saw_peer(v);
121    }
122
123    ok
124}
125
126pub(crate) fn router(
127    raft: Raft,
128    secret: Arc<str>,
129    me: Hello,
130    addr: String,
131    versions: Arc<Versions>,
132) -> Router {
133    Router::new()
134        .route("/raft/append", post(append))
135        .route("/raft/snapshot", post(snapshot))
136        .route("/raft/vote", post(vote))
137        .route("/cluster/write", post(write))
138        .route("/cluster/hello", get(hello))
139        .route("/cluster/join", post(join))
140        .with_state(App {
141            raft,
142            secret,
143            me: Arc::new(me),
144            addr: Arc::from(addr),
145            versions,
146        })
147}
148
149/// Answers only a prober that proves the secret, and proves it back, so neither side sends it
150async fn hello(State(a): State<App>, headers: HeaderMap) -> Response {
151    let header = |name: &str| {
152        headers
153            .get(name)
154            .and_then(|v| v.to_str().ok())
155            .unwrap_or_default()
156            .to_string()
157    };
158    let nonce = header(NONCE_HEADER);
159    let expected = mac(&a.secret, &["probe", &nonce, &a.addr]);
160    let proven: bool = header(PROOF_HEADER)
161        .as_bytes()
162        .ct_eq(expected.as_bytes())
163        .into();
164    if nonce.len() < 16 || !proven {
165        return StatusCode::UNAUTHORIZED.into_response();
166    }
167
168    let m = a.raft.metrics().borrow().clone();
169    Json(Hello {
170        leader: m.current_leader,
171        term: m.current_term,
172        proof: mac(&a.secret, &["hello", &nonce, &a.me.name, &a.addr]),
173        needs_upgrade: a.versions.needs_upgrade(),
174        upgrade_error: a.versions.upgrade_error(),
175        ..(*a.me).clone()
176    })
177    .into_response()
178}
179
180/// Adds the caller as a learner on the leader, or sends it on to the leader
181async fn join(State(a): State<App>, headers: HeaderMap, Json(req): Json<Join>) -> Response {
182    if !authorized(&a, &headers) {
183        return StatusCode::UNAUTHORIZED.into_response();
184    }
185
186    let node = BasicNode::new(&req.addr);
187    match a.raft.add_learner(req.id, node, false).await {
188        Ok(_) => StatusCode::OK.into_response(),
189        Err(RaftError::APIError(ClientWriteError::ForwardToLeader(f))) => match f.leader_node {
190            Some(leader) => match send_join(&leader.addr, &a.secret, &req).await {
191                Ok(()) => StatusCode::OK.into_response(),
192                Err(e) => (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
193            },
194            None => (StatusCode::SERVICE_UNAVAILABLE, "no leader yet").into_response(),
195        },
196        Err(e) => (StatusCode::SERVICE_UNAVAILABLE, e.to_string()).into_response(),
197    }
198}
199
200pub async fn send_join(addr: &str, secret: &str, req: &Join) -> anyhow::Result<()> {
201    let res = CLIENT
202        .post(format!("http://{addr}/cluster/join"))
203        .header(SECRET_HEADER, secret)
204        .json(req)
205        .send()
206        .await?;
207    anyhow::ensure!(
208        res.status().is_success(),
209        "join refused by {addr} ({}): {}",
210        res.status(),
211        res.text().await?
212    );
213    Ok(())
214}
215
216/// Ask a host found on the tailnet who it is. The secret never leaves this node. Both proofs cover
217/// the address dialed, and the answer must carry the name Tailscale gives that address, so a host
218/// that relays a real member's answer is rejected
219pub async fn probe(addr: &str, secret: &str, expect_name: Option<&str>) -> Option<Hello> {
220    let nonce = uuid::Uuid::new_v4().simple().to_string();
221    let res = CLIENT
222        .get(format!("http://{addr}/cluster/hello"))
223        .header(NONCE_HEADER, &nonce)
224        .header(PROOF_HEADER, mac(secret, &["probe", &nonce, addr]))
225        .timeout(Duration::from_secs(1))
226        .send()
227        .await
228        .ok()?;
229    let hello: Hello = res.error_for_status().ok()?.json().await.ok()?;
230    if expect_name.is_some_and(|name| name != hello.name) {
231        return None;
232    }
233
234    let expected = mac(secret, &["hello", &nonce, &hello.name, addr]);
235    let proven: bool = hello.proof.as_bytes().ct_eq(expected.as_bytes()).into();
236    proven.then_some(hello)
237}
238
239async fn append(
240    State(a): State<App>,
241    headers: HeaderMap,
242    Json(req): Json<AppendEntriesRequest<TypeConfig>>,
243) -> Response {
244    if !authorized(&a, &headers) {
245        return StatusCode::UNAUTHORIZED.into_response();
246    }
247
248    Json(a.raft.append_entries(req).await).into_response()
249}
250
251async fn snapshot(
252    State(a): State<App>,
253    headers: HeaderMap,
254    Json(req): Json<InstallSnapshotRequest<TypeConfig>>,
255) -> Response {
256    if !authorized(&a, &headers) {
257        return StatusCode::UNAUTHORIZED.into_response();
258    }
259
260    Json(a.raft.install_snapshot(req).await).into_response()
261}
262
263async fn vote(
264    State(a): State<App>,
265    headers: HeaderMap,
266    Json(req): Json<VoteRequest<NodeId>>,
267) -> Response {
268    if !authorized(&a, &headers) {
269        return StatusCode::UNAUTHORIZED.into_response();
270    }
271
272    Json(a.raft.vote(req).await).into_response()
273}
274
275/// A write a follower forwarded. It is proposed here and never forwarded again, so writes cannot loop
276async fn write(State(a): State<App>, headers: HeaderMap, Json(req): Json<Request>) -> Response {
277    if !authorized(&a, &headers) {
278        return StatusCode::UNAUTHORIZED.into_response();
279    }
280
281    if let Err(e) = req.cmd.check_replicable() {
282        return (StatusCode::BAD_REQUEST, e.to_string()).into_response();
283    }
284
285    if let Some(v) = req.version {
286        a.versions.saw_peer(v);
287        // It could not apply the entry, so it stops here and lets a node that can lead
288        if a.versions.mine().is_some_and(|mine| v > mine) {
289            a.versions.hold(v);
290        }
291    }
292
293    // A node that stopped applying steps aside, so the sender waits for the next leader
294    if let Some(needed) = a.versions.needs_upgrade() {
295        return (
296            StatusCode::MISDIRECTED_REQUEST,
297            format!("this node needs orch {needed} and steps aside as leader"),
298        )
299            .into_response();
300    }
301
302    match a.raft.client_write(req).await {
303        Ok(r) => Json(r.data).into_response(),
304        // Refused before anything was proposed, so the sender may safely try another node
305        Err(e @ RaftError::APIError(ClientWriteError::ForwardToLeader(_))) => {
306            (StatusCode::MISDIRECTED_REQUEST, e.to_string()).into_response()
307        }
308        Err(e) => (StatusCode::SERVICE_UNAVAILABLE, e.to_string()).into_response(),
309    }
310}
311
312/// Why a forwarded write failed. Only `NotApplied` is safe to send again
313#[derive(Debug)]
314pub(crate) enum ForwardError {
315    /// The connection was refused, or the node said it is not the leader
316    NotApplied(String),
317    /// It may or may not have been applied, so it must not be sent again
318    Unknown(anyhow::Error),
319}
320
321pub(crate) async fn forward(
322    addr: &str,
323    secret: &str,
324    req: &Request,
325) -> Result<Reply, ForwardError> {
326    let res = CLIENT
327        .post(format!("http://{addr}/cluster/write"))
328        .header(SECRET_HEADER, secret)
329        .json(req)
330        .send()
331        .await
332        .map_err(|e| {
333            if e.is_connect() {
334                ForwardError::NotApplied(e.to_string())
335            } else {
336                ForwardError::Unknown(e.into())
337            }
338        })?;
339    let status = res.status();
340    if status == StatusCode::MISDIRECTED_REQUEST {
341        let body = res.text().await.unwrap_or_default();
342        return Err(ForwardError::NotApplied(format!(
343            "{addr} is not the leader: {body}"
344        )));
345    }
346
347    if !status.is_success() {
348        let body = res.text().await.unwrap_or_default();
349        return Err(ForwardError::Unknown(anyhow::anyhow!(
350            "leader at {addr} refused the write ({status}): {body}"
351        )));
352    }
353
354    res.json()
355        .await
356        .map_err(|e| ForwardError::Unknown(e.into()))
357}
358
359pub(crate) struct HttpNetwork {
360    pub secret: Arc<str>,
361    pub version: Version,
362}
363
364impl RaftNetworkFactory<TypeConfig> for HttpNetwork {
365    type Network = Peer;
366
367    async fn new_client(&mut self, target: NodeId, node: &BasicNode) -> Peer {
368        Peer {
369            target,
370            addr: node.addr.clone(),
371            secret: Arc::clone(&self.secret),
372            version: self.version.to_string(),
373        }
374    }
375}
376
377pub(crate) struct Peer {
378    target: NodeId,
379    addr: String,
380    secret: Arc<str>,
381    version: String,
382}
383
384impl Peer {
385    async fn send<Req, Resp, E>(
386        &self,
387        path: &str,
388        req: Req,
389        option: &RPCOption,
390    ) -> Result<Resp, RPCError<NodeId, BasicNode, RaftError<NodeId, E>>>
391    where
392        Req: Serialize,
393        Resp: DeserializeOwned,
394        E: error::Error + DeserializeOwned,
395    {
396        let res = CLIENT
397            .post(format!("http://{}/raft/{path}", self.addr))
398            .header(SECRET_HEADER, &*self.secret)
399            .header(VERSION_HEADER, &self.version)
400            .timeout(option.hard_ttl())
401            .json(&req)
402            .send()
403            .await
404            .map_err(|e| {
405                if e.is_connect() {
406                    RPCError::Unreachable(Unreachable::new(&e))
407                } else {
408                    RPCError::Network(NetworkError::new(&e))
409                }
410            })?;
411        let res = res
412            .error_for_status()
413            .map_err(|e| RPCError::Network(NetworkError::new(&e)))?;
414        let body: Result<Resp, RaftError<NodeId, E>> = res
415            .json()
416            .await
417            .map_err(|e| RPCError::Network(NetworkError::new(&e)))?;
418        body.map_err(|e| RPCError::RemoteError(RemoteError::new(self.target, e)))
419    }
420}
421
422impl RaftNetwork<TypeConfig> for Peer {
423    async fn append_entries(
424        &mut self,
425        req: AppendEntriesRequest<TypeConfig>,
426        option: RPCOption,
427    ) -> Result<AppendEntriesResponse<NodeId>, RPCError<NodeId, BasicNode, RaftError<NodeId>>> {
428        self.send("append", req, &option).await
429    }
430
431    async fn install_snapshot(
432        &mut self,
433        req: InstallSnapshotRequest<TypeConfig>,
434        option: RPCOption,
435    ) -> Result<
436        InstallSnapshotResponse<NodeId>,
437        RPCError<NodeId, BasicNode, RaftError<NodeId, InstallSnapshotError>>,
438    > {
439        self.send("snapshot", req, &option).await
440    }
441
442    async fn vote(
443        &mut self,
444        req: VoteRequest<NodeId>,
445        option: RPCOption,
446    ) -> Result<VoteResponse<NodeId>, RPCError<NodeId, BasicNode, RaftError<NodeId>>> {
447        self.send("vote", req, &option).await
448    }
449}