Skip to main content

tunnet_core/
control.rs

1use anyhow::Context;
2use chrono::Utc;
3use ed25519_dalek::SigningKey;
4use reqwest::{Method, header::HeaderValue};
5use tunnet_common::{
6    EndpointSnapshot, EnrollRequest, EnrollResponse, HDR_ENDPOINT_ID, HDR_SIGNATURE, HDR_TIMESTAMP,
7    PollRequest, RegisterRequest, signing,
8};
9
10pub struct UnauthedClient {
11    base: String,
12    http: reqwest::Client,
13}
14
15impl UnauthedClient {
16    pub fn new(base: String) -> anyhow::Result<Self> {
17        let http = reqwest::Client::builder()
18            .timeout(std::time::Duration::from_secs(15))
19            .build()?;
20        Ok(Self { base, http })
21    }
22
23    pub async fn enroll(&self, req: EnrollRequest) -> anyhow::Result<EnrollResponse> {
24        let url = format!("{}/v1/enroll", self.base);
25        let resp = self
26            .http
27            .post(&url)
28            .json(&req)
29            .send()
30            .await
31            .with_context(|| format!("POST {url}"))?;
32        let status = resp.status();
33        let body = resp.text().await?;
34        if !status.is_success() {
35            anyhow::bail!("enroll failed: {status}: {body}");
36        }
37        Ok(serde_json::from_str(&body)?)
38    }
39
40    pub async fn enroll_status(
41        &self,
42        req: tunnet_common::EnrollStatusRequest,
43    ) -> anyhow::Result<tunnet_common::EnrollStatusResponse> {
44        let url = format!("{}/v1/enroll/status", self.base);
45        let resp = self
46            .http
47            .post(&url)
48            .json(&req)
49            .send()
50            .await
51            .with_context(|| format!("POST {url}"))?;
52        let status = resp.status();
53        let body = resp.text().await?;
54        if !status.is_success() {
55            anyhow::bail!("enroll status failed: {status}: {body}");
56        }
57        Ok(serde_json::from_str(&body)?)
58    }
59}
60
61#[derive(Debug, Clone, serde::Deserialize)]
62#[serde(rename_all = "camelCase")]
63struct SdkRegisterApiResponse {
64    organization_id: String,
65    network_id: uuid::Uuid,
66    network_name: String,
67    #[allow(dead_code)]
68    assigned_ip: String,
69    #[allow(dead_code)]
70    network_cidr: String,
71    snapshot: EndpointSnapshot,
72}
73
74pub struct ManagementClient {
75    base: String,
76    http: reqwest::Client,
77}
78
79impl ManagementClient {
80    pub fn new(base: String) -> anyhow::Result<Self> {
81        let http = reqwest::Client::builder()
82            .timeout(std::time::Duration::from_secs(15))
83            .build()?;
84        Ok(Self { base, http })
85    }
86
87    #[allow(clippy::too_many_arguments)]
88    pub async fn register_sdk_node(
89        &self,
90        api_key: &str,
91        organization_id: &str,
92        network_id: uuid::Uuid,
93        endpoint_id: &str,
94        hostname: &str,
95        metadata: Option<serde_json::Value>,
96        kind: Option<&str>,
97        labels: Option<&std::collections::HashMap<String, String>>,
98        expires_in: Option<&str>,
99        tags: Option<&[String]>,
100    ) -> anyhow::Result<EnrollResponse> {
101        let url = format!(
102            "{}/api/v1/organizations/{organization_id}/networks/{network_id}/sdk-nodes",
103            self.base.trim_end_matches('/')
104        );
105        let mut body = serde_json::json!({
106            "endpointId": endpoint_id,
107            "hostname": hostname,
108        });
109        if let Some(meta) = metadata
110            && let Some(obj) = meta.as_object()
111        {
112            // Nested under metadata key for free-form fields (not top-level merge).
113            body["metadata"] = serde_json::Value::Object(obj.clone());
114        }
115        if let Some(k) = kind {
116            body["kind"] = serde_json::Value::String(k.to_string());
117        }
118        if let Some(labels) = labels {
119            body["labels"] = serde_json::to_value(labels)?;
120        }
121        if let Some(exp) = expires_in {
122            body["expiresIn"] = serde_json::Value::String(exp.to_string());
123        }
124        if let Some(tags) = tags {
125            body["tags"] = serde_json::to_value(tags)?;
126        }
127        let resp = self
128            .http
129            .post(&url)
130            .bearer_auth(api_key)
131            .json(&body)
132            .send()
133            .await
134            .with_context(|| format!("POST {url}"))?;
135        let status = resp.status();
136        let text = resp.text().await?;
137        if !status.is_success() {
138            anyhow::bail!("sdk register failed: {status}: {text}");
139        }
140        let parsed: SdkRegisterApiResponse = serde_json::from_str(&text)?;
141        Ok(EnrollResponse {
142            organization_id: parsed.organization_id,
143            network_id: parsed.network_id,
144            network_name: parsed.network_name,
145            status: "active".into(),
146            snapshot: parsed.snapshot,
147        })
148    }
149
150    pub async fn delete_devices(
151        &self,
152        api_key: &str,
153        organization_id: &str,
154        items: &[(uuid::Uuid, &str)],
155    ) -> anyhow::Result<u32> {
156        let url = format!(
157            "{}/api/v1/organizations/{organization_id}/sdk-nodes",
158            self.base.trim_end_matches('/')
159        );
160        let body = serde_json::json!({
161            "items": items.iter().map(|(network_id, endpoint_id)| {
162                serde_json::json!({
163                    "networkId": network_id,
164                    "endpointId": endpoint_id,
165                })
166            }).collect::<Vec<_>>(),
167        });
168        let resp = self
169            .http
170            .delete(&url)
171            .bearer_auth(api_key)
172            .json(&body)
173            .send()
174            .await
175            .with_context(|| format!("DELETE {url}"))?;
176        let status = resp.status();
177        let text = resp.text().await?;
178        if !status.is_success() {
179            anyhow::bail!("device delete failed: {status}: {text}");
180        }
181        let parsed: serde_json::Value = serde_json::from_str(&text)?;
182        Ok(parsed.get("deleted").and_then(|v| v.as_u64()).unwrap_or(0) as u32)
183    }
184}
185
186pub struct SignedClient {
187    pub base: String,
188    pub http: reqwest::Client,
189    pub endpoint_id: String,
190    pub signing_key: SigningKey,
191}
192
193impl Clone for SignedClient {
194    fn clone(&self) -> Self {
195        Self {
196            base: self.base.clone(),
197            http: self.http.clone(),
198            endpoint_id: self.endpoint_id.clone(),
199            signing_key: self.signing_key.clone(),
200        }
201    }
202}
203
204impl SignedClient {
205    pub fn new(base: String, endpoint_id: String, signing_key: SigningKey) -> anyhow::Result<Self> {
206        let http = reqwest::Client::builder()
207            .timeout(std::time::Duration::from_secs(15))
208            .build()?;
209        Ok(Self {
210            base,
211            http,
212            endpoint_id,
213            signing_key,
214        })
215    }
216
217    fn sign(&self, method: &str, path: &str, body: &[u8]) -> (i64, String) {
218        let ts = Utc::now().timestamp();
219        let sig = signing::sign(&self.signing_key, method, path, ts, body);
220        (ts, sig)
221    }
222
223    async fn do_get<T: serde::de::DeserializeOwned>(&self, path: &str) -> anyhow::Result<T> {
224        let url = format!("{}{}", self.base, path);
225        let (ts, sig) = self.sign("GET", path, b"");
226        let resp = self
227            .http
228            .request(Method::GET, &url)
229            .header(HDR_ENDPOINT_ID, HeaderValue::from_str(&self.endpoint_id)?)
230            .header(HDR_TIMESTAMP, HeaderValue::from_str(&ts.to_string())?)
231            .header(HDR_SIGNATURE, HeaderValue::from_str(&sig)?)
232            .send()
233            .await?;
234        let status = resp.status();
235        let text = resp.text().await?;
236        if !status.is_success() {
237            anyhow::bail!("GET {} => {status}: {text}", path);
238        }
239        Ok(serde_json::from_str(&text)?)
240    }
241
242    async fn do_post<T: serde::de::DeserializeOwned>(
243        &self,
244        path: &str,
245        body: &(impl serde::Serialize + ?Sized),
246    ) -> anyhow::Result<T> {
247        let url = format!("{}{}", self.base, path);
248        let json = serde_json::to_vec(body)?;
249        let (ts, sig) = self.sign("POST", path, &json);
250        let resp = self
251            .http
252            .request(Method::POST, &url)
253            .header(HDR_ENDPOINT_ID, HeaderValue::from_str(&self.endpoint_id)?)
254            .header(HDR_TIMESTAMP, HeaderValue::from_str(&ts.to_string())?)
255            .header(HDR_SIGNATURE, HeaderValue::from_str(&sig)?)
256            .header("content-type", "application/json")
257            .body(json)
258            .send()
259            .await?;
260        let status = resp.status();
261        let text = resp.text().await?;
262        if !status.is_success() {
263            anyhow::bail!("POST {} => {status}: {text}", path);
264        }
265        Ok(serde_json::from_str(&text)?)
266    }
267
268    async fn do_patch<T: serde::de::DeserializeOwned>(
269        &self,
270        path: &str,
271        body: &(impl serde::Serialize + ?Sized),
272    ) -> anyhow::Result<T> {
273        let url = format!("{}{}", self.base, path);
274        let json = serde_json::to_vec(body)?;
275        let (ts, sig) = self.sign("PATCH", path, &json);
276        let resp = self
277            .http
278            .request(Method::PATCH, &url)
279            .header(HDR_ENDPOINT_ID, HeaderValue::from_str(&self.endpoint_id)?)
280            .header(HDR_TIMESTAMP, HeaderValue::from_str(&ts.to_string())?)
281            .header(HDR_SIGNATURE, HeaderValue::from_str(&sig)?)
282            .header("content-type", "application/json")
283            .body(json)
284            .send()
285            .await?;
286        let status = resp.status();
287        let text = resp.text().await?;
288        if !status.is_success() {
289            anyhow::bail!("PATCH {} => {status}: {text}", path);
290        }
291        Ok(serde_json::from_str(&text)?)
292    }
293
294    pub async fn get_device_labels(
295        &self,
296    ) -> anyhow::Result<std::collections::HashMap<String, String>> {
297        self.do_get("/v1/device/labels").await
298    }
299
300    pub async fn patch_device_labels(
301        &self,
302        patch: &std::collections::HashMap<String, Option<String>>,
303    ) -> anyhow::Result<std::collections::HashMap<String, String>> {
304        self.do_patch("/v1/device/labels", patch).await
305    }
306
307    pub async fn patch_device_expiry(&self, expires_in: Option<&str>) -> anyhow::Result<()> {
308        let body = serde_json::json!({ "expires_in": expires_in });
309        let _: serde_json::Value = self.do_patch("/v1/device/expiry", &body).await?;
310        Ok(())
311    }
312
313    pub async fn register(
314        &self,
315        hostname: &str,
316        agent_version: &str,
317        metadata: Option<serde_json::Value>,
318    ) -> anyhow::Result<EndpointSnapshot> {
319        let req = RegisterRequest {
320            endpoint_id: self.endpoint_id.clone(),
321            hostname: hostname.into(),
322            agent_version: agent_version.into(),
323            metadata,
324        };
325        self.do_post("/v1/register", &req).await
326    }
327
328    pub async fn poll(&self, known_version: u64) -> anyhow::Result<EndpointSnapshot> {
329        let req = PollRequest {
330            endpoint_id: self.endpoint_id.clone(),
331            known_version,
332        };
333        self.do_post("/v1/poll", &req).await
334    }
335
336    pub async fn create_tunnel(
337        &self,
338        local_port: u16,
339        protocol: &str,
340        subdomain: Option<&str>,
341        relay: Option<&str>,
342    ) -> anyhow::Result<CreateTunnelResponse> {
343        let body = serde_json::json!({
344            "localPort": local_port,
345            "protocol": protocol,
346            "subdomain": subdomain,
347            "relay": relay,
348        });
349        self.do_post("/v1/tunnels", &body).await
350    }
351
352    pub async fn tunnel_ready(&self, tunnel_id: &str) -> anyhow::Result<()> {
353        let body = serde_json::json!({ "tunnelId": tunnel_id });
354        let _: serde_json::Value = self.do_post("/v1/tunnels/ready", &body).await?;
355        Ok(())
356    }
357
358    pub async fn tunnel_stopped(&self, tunnel_id: &str) -> anyhow::Result<()> {
359        let body = serde_json::json!({ "tunnelId": tunnel_id });
360        let _: serde_json::Value = self.do_post("/v1/tunnels/stopped", &body).await?;
361        Ok(())
362    }
363
364    pub async fn tunnel_failed(&self, tunnel_id: &str, error: &str) -> anyhow::Result<()> {
365        let body = serde_json::json!({ "tunnelId": tunnel_id, "error": error });
366        let _: serde_json::Value = self.do_post("/v1/tunnels/failed", &body).await?;
367        Ok(())
368    }
369
370    pub async fn create_subnet_route(
371        &self,
372        cidr: &str,
373        description: Option<&str>,
374    ) -> anyhow::Result<String> {
375        let body = serde_json::json!({
376            "cidr": cidr,
377            "description": description,
378        });
379        #[derive(serde::Deserialize)]
380        #[serde(rename_all = "camelCase")]
381        struct Resp {
382            cidr: String,
383        }
384        let resp: Resp = self.do_post("/v1/subnet-routes", &body).await?;
385        Ok(resp.cidr)
386    }
387
388    pub async fn upload_ssh_recording(
389        &self,
390        session_id: &str,
391        cast_text: &str,
392        content_sha256: &str,
393    ) -> anyhow::Result<()> {
394        if cast_text.len() > 16 * 1024 * 1024 {
395            anyhow::bail!("recording too large to upload ({} bytes)", cast_text.len());
396        }
397        let body = serde_json::json!({
398            "sessionId": session_id,
399            "castText": cast_text,
400            "contentSha256": content_sha256,
401        });
402        // Large casts need a longer timeout than the default SignedClient.
403        let url = format!("{}/v1/ssh-recordings", self.base);
404        let json = serde_json::to_vec(&body)?;
405        let (ts, sig) = self.sign("POST", "/v1/ssh-recordings", &json);
406        let http = reqwest::Client::builder()
407            .timeout(std::time::Duration::from_secs(120))
408            .build()?;
409        let resp = http
410            .request(Method::POST, &url)
411            .header(HDR_ENDPOINT_ID, HeaderValue::from_str(&self.endpoint_id)?)
412            .header(HDR_TIMESTAMP, HeaderValue::from_str(&ts.to_string())?)
413            .header(HDR_SIGNATURE, HeaderValue::from_str(&sig)?)
414            .header("content-type", "application/json")
415            .body(json)
416            .send()
417            .await?;
418        let status = resp.status();
419        let text = resp.text().await?;
420        if !status.is_success() {
421            anyhow::bail!("POST /v1/ssh-recordings => {status}: {text}");
422        }
423        Ok(())
424    }
425
426    pub async fn list_ssh_sessions(
427        &self,
428        limit: u32,
429        status: Option<&str>,
430    ) -> anyhow::Result<serde_json::Value> {
431        let mut path = format!("/v1/ssh-sessions?limit={limit}");
432        if let Some(s) = status {
433            path.push_str(&format!("&status={s}"));
434        }
435        // Sign without query string (server uses uri.path()).
436        let url = format!("{}{}", self.base, path);
437        let (ts, sig) = self.sign("GET", "/v1/ssh-sessions", b"");
438        let resp = self
439            .http
440            .request(Method::GET, &url)
441            .header(HDR_ENDPOINT_ID, HeaderValue::from_str(&self.endpoint_id)?)
442            .header(HDR_TIMESTAMP, HeaderValue::from_str(&ts.to_string())?)
443            .header(HDR_SIGNATURE, HeaderValue::from_str(&sig)?)
444            .send()
445            .await?;
446        let status_code = resp.status();
447        let text = resp.text().await?;
448        if !status_code.is_success() {
449            anyhow::bail!("GET /v1/ssh-sessions => {status_code}: {text}");
450        }
451        Ok(serde_json::from_str(&text)?)
452    }
453
454    pub async fn list_ssh_recordings(&self, limit: u32) -> anyhow::Result<serde_json::Value> {
455        let url = format!("{}/v1/ssh-recordings/list?limit={limit}", self.base);
456        let (ts, sig) = self.sign("GET", "/v1/ssh-recordings/list", b"");
457        let resp = self
458            .http
459            .request(Method::GET, &url)
460            .header(HDR_ENDPOINT_ID, HeaderValue::from_str(&self.endpoint_id)?)
461            .header(HDR_TIMESTAMP, HeaderValue::from_str(&ts.to_string())?)
462            .header(HDR_SIGNATURE, HeaderValue::from_str(&sig)?)
463            .send()
464            .await?;
465        let status = resp.status();
466        let text = resp.text().await?;
467        if !status.is_success() {
468            anyhow::bail!("GET /v1/ssh-recordings/list => {status}: {text}");
469        }
470        Ok(serde_json::from_str(&text)?)
471    }
472
473    pub async fn get_ssh_recording_cast(
474        &self,
475        session_id: &str,
476    ) -> anyhow::Result<serde_json::Value> {
477        let path = format!("/v1/ssh-recordings/{session_id}/cast");
478        self.do_get(&path).await
479    }
480
481    pub async fn evaluate_ssh_auth(
482        &self,
483        peer_endpoint_id: &str,
484        check_period_secs: u64,
485    ) -> anyhow::Result<serde_json::Value> {
486        let body = serde_json::json!({
487            "peerEndpointId": peer_endpoint_id,
488            "checkPeriodSecs": check_period_secs,
489        });
490        self.do_post("/v1/ssh/auth/evaluate", &body).await
491    }
492
493    pub async fn poll_ssh_auth(&self, challenge_token: &str) -> anyhow::Result<serde_json::Value> {
494        let body = serde_json::json!({ "challengeToken": challenge_token });
495        self.do_post("/v1/ssh/auth/poll", &body).await
496    }
497
498    pub async fn verify_ssh_auth(
499        &self,
500        peer_endpoint_id: &str,
501        check_period_secs: u64,
502        auth_token: Option<&str>,
503    ) -> anyhow::Result<serde_json::Value> {
504        let body = serde_json::json!({
505            "peerEndpointId": peer_endpoint_id,
506            "checkPeriodSecs": check_period_secs,
507            "authToken": auth_token,
508        });
509        self.do_post("/v1/ssh/auth/verify", &body).await
510    }
511}
512
513#[derive(Debug, Clone, serde::Deserialize)]
514#[serde(rename_all = "camelCase")]
515pub struct CreateTunnelResponse {
516    pub tunnel_id: String,
517    pub subdomain: String,
518    pub public_hostname: String,
519    pub protocol: String,
520    pub local_port: u16,
521    pub relay_endpoint_id: String,
522    pub relay_domain: String,
523    pub auth_token: String,
524    #[serde(default)]
525    pub redirect_rules: Vec<tunnet_common::RedirectRule>,
526}
527
528pub fn basic_metadata(hostname: &str, agent_version: &str, kind: &str) -> serde_json::Value {
529    serde_json::json!({
530        "hostname": hostname,
531        "agentVersion": agent_version,
532        "os": std::env::consts::OS,
533        "arch": std::env::consts::ARCH,
534        "family": std::env::consts::FAMILY,
535        "kind": kind, // "agent" | "sdk"
536        "reportedAt": chrono::Utc::now().to_rfc3339(),
537    })
538}