Skip to main content

tunnet_common/
lib.rs

1pub mod duration;
2pub mod ipv6;
3pub mod policy;
4pub mod recording;
5pub mod relay;
6pub mod send;
7pub mod signing;
8pub mod ws;
9
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use std::net::{Ipv4Addr, Ipv6Addr};
13use uuid::Uuid;
14
15pub type EndpointIdHex = String;
16
17/// ALPN identifier for our tunnel protocol (mesh datagrams).
18pub const TUNNEL_ALPN: &[u8] = b"tunnet/tunnel/1";
19
20/// ALPN for agent ↔ public relay reverse tunnels.
21pub const RELAY_ALPN: &[u8] = b"tunnet/relay/1";
22
23/// ALPN for SSH session recording streams.
24pub use recording::RECORDING_ALPN;
25
26/// ALPN for file-transfer offer streams.
27pub use send::SEND_ALPN;
28
29/// Header the agent sends with every authenticated request.
30pub const HDR_ENDPOINT_ID: &str = "x-endpoint-id";
31pub const HDR_TIMESTAMP: &str = "x-timestamp";
32pub const HDR_SIGNATURE: &str = "x-endpoint-signature";
33pub const HDR_TRACE_ID: &str = "x-trace-id";
34
35/// Maximum allowed clock skew for signature validation.
36pub const MAX_SKEW_SECS: i64 = 60;
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct EnrollRequest {
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub enrollment_token: Option<String>,
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub organization_slug: Option<String>,
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub network_id: Option<Uuid>,
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub network_name: Option<String>,
48    pub endpoint_id: EndpointIdHex,
49    pub hostname: String,
50    pub os: String,
51    pub agent_version: String,
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub metadata: Option<serde_json::Value>,
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub labels: Option<HashMap<String, String>>,
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub expires_in: Option<String>,
58}
59
60fn default_enroll_status() -> String {
61    "active".into()
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct EnrollResponse {
66    pub organization_id: String,
67    pub network_id: Uuid,
68    pub network_name: String,
69    /// `"pending"` for quick enroll awaiting approval; `"active"` otherwise.
70    #[serde(default = "default_enroll_status")]
71    pub status: String,
72    pub snapshot: EndpointSnapshot,
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct EnrollStatusRequest {
77    pub endpoint_id: EndpointIdHex,
78    pub network_id: Uuid,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
82#[serde(tag = "status", rename_all = "lowercase")]
83pub enum EnrollStatusResponse {
84    Pending {
85        organization_id: String,
86        network_id: Uuid,
87        network_name: String,
88    },
89    Active {
90        organization_id: String,
91        network_id: Uuid,
92        network_name: String,
93        snapshot: Box<EndpointSnapshot>,
94    },
95    Rejected,
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct RegisterRequest {
100    pub endpoint_id: EndpointIdHex,
101    pub hostname: String,
102    pub agent_version: String,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub metadata: Option<serde_json::Value>,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct PollRequest {
109    pub endpoint_id: EndpointIdHex,
110    pub known_version: u64,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct PeerEntry {
115    pub ip: Ipv4Addr,
116    pub endpoint_id: EndpointIdHex,
117    pub hostname: String,
118    pub tags: Vec<String>,
119    /// OpenSSH public host key line (`ssh-ed25519 AAAA...`), when advertised.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub ssh_host_key: Option<String>,
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct SubnetRoute {
126    pub cidr: ipnet::Ipv4Net,
127    pub via_endpoint_id: EndpointIdHex,
128    pub via_ip: Ipv4Addr,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct HostnameRoute {
133    pub hostname: String,
134    pub via_endpoint_id: EndpointIdHex,
135    pub via_ip: Ipv4Addr,
136    #[serde(default)]
137    pub is_wildcard: bool,
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub target_ip: Option<Ipv4Addr>,
140}
141
142fn default_magic_ip() -> Ipv4Addr {
143    Ipv4Addr::new(100, 100, 100, 53)
144}
145
146fn default_synthetic_base() -> Ipv4Addr {
147    Ipv4Addr::new(100, 100, 0, 1)
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct DnsConfig {
152    pub suffix: String,
153    #[serde(default)]
154    pub upstream: Vec<std::net::IpAddr>,
155    #[serde(default = "default_synthetic_base")]
156    pub synthetic_base: Ipv4Addr,
157    #[serde(default = "default_magic_ip")]
158    pub magic_ip: Ipv4Addr,
159}
160
161impl Default for DnsConfig {
162    fn default() -> Self {
163        Self {
164            suffix: "tunnet".into(),
165            upstream: vec![
166                std::net::IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
167                std::net::IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)),
168            ],
169            // CGNAT-style pool reserved for PeerDNS hostname routes.
170            synthetic_base: default_synthetic_base(),
171            magic_ip: default_magic_ip(),
172        }
173    }
174}
175
176/// Exit node advertisement in the snapshot.
177#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct ExitNodeInfo {
179    pub endpoint_id: EndpointIdHex,
180    pub via_ip: Ipv4Addr,
181    pub allowed_cidrs: Vec<ipnet::Ipv4Net>,
182}
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
185#[serde(rename_all = "lowercase")]
186pub enum SplitTunnelMode {
187    Include,
188    #[default]
189    Exclude,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize, Default)]
193pub struct DeviceProfile {
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub exit_node_endpoint_id: Option<EndpointIdHex>,
196    #[serde(default)]
197    pub split_tunnel_mode: SplitTunnelMode,
198    #[serde(default)]
199    pub split_tunnel_cidrs: Vec<ipnet::Ipv4Net>,
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct Ipv6PeerEntry {
204    pub ip: Ipv6Addr,
205    pub endpoint_id: EndpointIdHex,
206    pub hostname: String,
207    pub tags: Vec<String>,
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct ActiveServe {
212    pub id: String,
213    pub endpoint_id: EndpointIdHex,
214    pub hostname: String,
215    pub port: u16,
216    pub protocol: String,
217    pub internal_hostname: String,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
221pub struct TunnelConfig {
222    pub id: String,
223    pub local_port: u16,
224    pub protocol: String,
225    pub subdomain: String,
226    pub public_hostname: String,
227    pub relay_addr: String,
228    pub relay_auth_token: String,
229    pub status: String,
230}
231
232/// Path-based redirect on the agent (multi-port / mesh HTTPS).
233#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
234#[serde(rename_all = "camelCase")]
235pub struct RedirectRule {
236    pub path_pattern: String,
237    pub target_port: u16,
238    /// When set, agent dials this mesh IP instead of localhost.
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub target_ipv4: Option<Ipv4Addr>,
241}
242
243/// Public TCP port mapping on the relay edge.
244#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
245#[serde(rename_all = "camelCase")]
246pub struct PortMapping {
247    pub external_port: u16,
248    pub target_port: u16,
249    /// When set, agent dials this mesh IP instead of localhost.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub target_ipv4: Option<Ipv4Addr>,
252}
253
254/// Match an HTTP path against a redirect pattern (`/api/*` or exact).
255pub fn path_matches(pattern: &str, path: &str) -> bool {
256    if let Some(prefix) = pattern.strip_suffix('*') {
257        path.starts_with(prefix)
258    } else {
259        path == pattern
260    }
261}
262
263/// Pick the first matching redirect rule (caller should sort by priority desc).
264pub fn match_redirect_port(rules: &[RedirectRule], path: &str) -> Option<u16> {
265    match_redirect(rules, path).map(|r| r.target_port)
266}
267
268/// Pick the first matching redirect rule with optional mesh target IP.
269pub fn match_redirect<'a>(rules: &'a [RedirectRule], path: &str) -> Option<&'a RedirectRule> {
270    rules.iter().find(|r| path_matches(&r.path_pattern, path))
271}
272
273#[derive(Debug, Clone, Serialize, Deserialize)]
274pub struct NetworkMembershipSnapshot {
275    pub network_id: Uuid,
276    pub network_name: String,
277    pub assigned_ipv4: Ipv4Addr,
278    pub prefix: u8,
279    pub mtu: u16,
280    pub ipv4_peers: Vec<PeerEntry>,
281    /// Subnet routes visible to this peer (enabled routes in the network).
282    #[serde(default)]
283    pub subnet_routes: Vec<SubnetRoute>,
284    /// Hostname routes visible to this peer.
285    #[serde(default)]
286    pub hostname_routes: Vec<HostnameRoute>,
287    #[serde(default)]
288    pub dns: DnsConfig,
289    /// Exit nodes available in this network.
290    #[serde(default)]
291    pub exit_nodes: Vec<ExitNodeInfo>,
292    /// This device's profile (exit selection + split tunnel).
293    #[serde(default)]
294    pub device_profile: DeviceProfile,
295    /// Serves active in this network (discoverability for peers).
296    #[serde(default)]
297    pub active_serves: Vec<ActiveServe>,
298    /// Tunnel configs for *this* endpoint (agent opens reverse tunnels).
299    #[serde(default)]
300    pub tunnel_config: Vec<TunnelConfig>,
301    /// Tags assigned to *this* endpoint (needed for dst tag ACL / SSH policy).
302    #[serde(default)]
303    pub self_tags: Vec<String>,
304    /// This endpoint's hostname (for PeerDNS self-resolution; peers list excludes self).
305    #[serde(default)]
306    pub self_hostname: String,
307    pub policy: policy::PolicyBundle,
308    pub gossip_bootstrap: Vec<EndpointIdHex>,
309    pub gossip_topic_hex: String,
310    pub version: u64,
311}
312
313#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct EndpointSnapshot {
315    pub ipv6_enabled: bool,
316    pub tenant_ipv6: Option<Ipv6Addr>,
317    pub memberships: Vec<NetworkMembershipSnapshot>,
318    pub ipv6_peers: Vec<Ipv6PeerEntry>,
319    pub org_policy: policy::PolicyBundle,
320    /// Org internal CA root cert (PEM) so agents can verify peer Serve TLS.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub org_ca_pem: Option<String>,
323    /// User-defined key-value labels on this machine.
324    #[serde(default)]
325    pub labels: HashMap<String, String>,
326    /// When this machine is deleted if it stays inactive (RFC3339).
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub expires_at: Option<String>,
329    pub version: u64,
330}
331
332#[derive(Debug, Clone, Serialize, Deserialize)]
333pub struct SnapshotDelta {
334    pub added: Vec<PeerEntry>,
335    pub removed: Vec<EndpointIdHex>,
336    pub version: u64,
337}
338
339#[derive(Debug, thiserror::Error)]
340pub enum ProtocolError {
341    #[error("invalid endpoint id: {0}")]
342    InvalidEndpointId(String),
343    #[error("network is full")]
344    NetworkFull,
345    #[error("unauthorized")]
346    Unauthorized,
347    #[error("signature invalid")]
348    BadSignature,
349    #[error("stale timestamp")]
350    StaleTimestamp,
351}
352
353pub fn validate_endpoint_id(s: &str) -> Result<(), ProtocolError> {
354    if s.len() != 64 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
355        return Err(ProtocolError::InvalidEndpointId(s.to_string()));
356    }
357    Ok(())
358}
359
360pub fn validate_network_name(s: &str) -> bool {
361    let len_ok = (3..=32).contains(&s.len());
362    let chars_ok = s
363        .chars()
364        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
365    len_ok && chars_ok
366}
367
368pub fn network_topic_hex(id: &uuid::Uuid) -> String {
369    hex::encode(blake3::hash(id.as_bytes()).as_bytes())
370}
371
372/// Gossip topic for mDNS/DNS-SD service relay records on a network.
373pub fn mdns_relay_topic_hex(id: &uuid::Uuid) -> String {
374    let mut hasher = blake3::Hasher::new();
375    hasher.update(id.as_bytes());
376    hasher.update(b"mdns-relay");
377    hex::encode(hasher.finalize().as_bytes())
378}