pub mod duration;
pub mod ipv6;
pub mod policy;
pub mod recording;
pub mod relay;
pub mod send;
pub mod signing;
pub mod ws;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::{Ipv4Addr, Ipv6Addr};
use uuid::Uuid;
pub type EndpointIdHex = String;
pub const TUNNEL_ALPN: &[u8] = b"tunnet/tunnel/1";
pub const RELAY_ALPN: &[u8] = b"tunnet/relay/1";
pub use recording::RECORDING_ALPN;
pub use send::SEND_ALPN;
pub const HDR_ENDPOINT_ID: &str = "x-endpoint-id";
pub const HDR_TIMESTAMP: &str = "x-timestamp";
pub const HDR_SIGNATURE: &str = "x-endpoint-signature";
pub const HDR_TRACE_ID: &str = "x-trace-id";
pub const MAX_SKEW_SECS: i64 = 60;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnrollRequest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enrollment_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub organization_slug: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub network_id: Option<Uuid>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub network_name: Option<String>,
pub endpoint_id: EndpointIdHex,
pub hostname: String,
pub os: String,
pub agent_version: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub labels: Option<HashMap<String, String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_in: Option<String>,
}
fn default_enroll_status() -> String {
"active".into()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnrollResponse {
pub organization_id: String,
pub network_id: Uuid,
pub network_name: String,
#[serde(default = "default_enroll_status")]
pub status: String,
pub snapshot: EndpointSnapshot,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnrollStatusRequest {
pub endpoint_id: EndpointIdHex,
pub network_id: Uuid,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "lowercase")]
pub enum EnrollStatusResponse {
Pending {
organization_id: String,
network_id: Uuid,
network_name: String,
},
Active {
organization_id: String,
network_id: Uuid,
network_name: String,
snapshot: Box<EndpointSnapshot>,
},
Rejected,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterRequest {
pub endpoint_id: EndpointIdHex,
pub hostname: String,
pub agent_version: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PollRequest {
pub endpoint_id: EndpointIdHex,
pub known_version: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerEntry {
pub ip: Ipv4Addr,
pub endpoint_id: EndpointIdHex,
pub hostname: String,
pub tags: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ssh_host_key: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubnetRoute {
pub cidr: ipnet::Ipv4Net,
pub via_endpoint_id: EndpointIdHex,
pub via_ip: Ipv4Addr,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostnameRoute {
pub hostname: String,
pub via_endpoint_id: EndpointIdHex,
pub via_ip: Ipv4Addr,
#[serde(default)]
pub is_wildcard: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_ip: Option<Ipv4Addr>,
}
fn default_magic_ip() -> Ipv4Addr {
Ipv4Addr::new(100, 100, 100, 53)
}
fn default_synthetic_base() -> Ipv4Addr {
Ipv4Addr::new(100, 100, 0, 1)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DnsConfig {
pub suffix: String,
#[serde(default)]
pub upstream: Vec<std::net::IpAddr>,
#[serde(default = "default_synthetic_base")]
pub synthetic_base: Ipv4Addr,
#[serde(default = "default_magic_ip")]
pub magic_ip: Ipv4Addr,
}
impl Default for DnsConfig {
fn default() -> Self {
Self {
suffix: "tunnet".into(),
upstream: vec![
std::net::IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
std::net::IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)),
],
synthetic_base: default_synthetic_base(),
magic_ip: default_magic_ip(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExitNodeInfo {
pub endpoint_id: EndpointIdHex,
pub via_ip: Ipv4Addr,
pub allowed_cidrs: Vec<ipnet::Ipv4Net>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum SplitTunnelMode {
Include,
#[default]
Exclude,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DeviceProfile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exit_node_endpoint_id: Option<EndpointIdHex>,
#[serde(default)]
pub split_tunnel_mode: SplitTunnelMode,
#[serde(default)]
pub split_tunnel_cidrs: Vec<ipnet::Ipv4Net>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Ipv6PeerEntry {
pub ip: Ipv6Addr,
pub endpoint_id: EndpointIdHex,
pub hostname: String,
pub tags: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActiveServe {
pub id: String,
pub endpoint_id: EndpointIdHex,
pub hostname: String,
pub port: u16,
pub protocol: String,
pub internal_hostname: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TunnelConfig {
pub id: String,
pub local_port: u16,
pub protocol: String,
pub subdomain: String,
pub public_hostname: String,
pub relay_addr: String,
pub relay_auth_token: String,
pub status: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RedirectRule {
pub path_pattern: String,
pub target_port: u16,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_ipv4: Option<Ipv4Addr>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PortMapping {
pub external_port: u16,
pub target_port: u16,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_ipv4: Option<Ipv4Addr>,
}
pub fn path_matches(pattern: &str, path: &str) -> bool {
if let Some(prefix) = pattern.strip_suffix('*') {
path.starts_with(prefix)
} else {
path == pattern
}
}
pub fn match_redirect_port(rules: &[RedirectRule], path: &str) -> Option<u16> {
match_redirect(rules, path).map(|r| r.target_port)
}
pub fn match_redirect<'a>(rules: &'a [RedirectRule], path: &str) -> Option<&'a RedirectRule> {
rules.iter().find(|r| path_matches(&r.path_pattern, path))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkMembershipSnapshot {
pub network_id: Uuid,
pub network_name: String,
pub assigned_ipv4: Ipv4Addr,
pub prefix: u8,
pub mtu: u16,
pub ipv4_peers: Vec<PeerEntry>,
#[serde(default)]
pub subnet_routes: Vec<SubnetRoute>,
#[serde(default)]
pub hostname_routes: Vec<HostnameRoute>,
#[serde(default)]
pub dns: DnsConfig,
#[serde(default)]
pub exit_nodes: Vec<ExitNodeInfo>,
#[serde(default)]
pub device_profile: DeviceProfile,
#[serde(default)]
pub active_serves: Vec<ActiveServe>,
#[serde(default)]
pub tunnel_config: Vec<TunnelConfig>,
#[serde(default)]
pub self_tags: Vec<String>,
#[serde(default)]
pub self_hostname: String,
pub policy: policy::PolicyBundle,
pub gossip_bootstrap: Vec<EndpointIdHex>,
pub gossip_topic_hex: String,
pub version: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EndpointSnapshot {
pub ipv6_enabled: bool,
pub tenant_ipv6: Option<Ipv6Addr>,
pub memberships: Vec<NetworkMembershipSnapshot>,
pub ipv6_peers: Vec<Ipv6PeerEntry>,
pub org_policy: policy::PolicyBundle,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub org_ca_pem: Option<String>,
#[serde(default)]
pub labels: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
pub version: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotDelta {
pub added: Vec<PeerEntry>,
pub removed: Vec<EndpointIdHex>,
pub version: u64,
}
#[derive(Debug, thiserror::Error)]
pub enum ProtocolError {
#[error("invalid endpoint id: {0}")]
InvalidEndpointId(String),
#[error("network is full")]
NetworkFull,
#[error("unauthorized")]
Unauthorized,
#[error("signature invalid")]
BadSignature,
#[error("stale timestamp")]
StaleTimestamp,
}
pub fn validate_endpoint_id(s: &str) -> Result<(), ProtocolError> {
if s.len() != 64 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(ProtocolError::InvalidEndpointId(s.to_string()));
}
Ok(())
}
pub fn validate_network_name(s: &str) -> bool {
let len_ok = (3..=32).contains(&s.len());
let chars_ok = s
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
len_ok && chars_ok
}
pub fn network_topic_hex(id: &uuid::Uuid) -> String {
hex::encode(blake3::hash(id.as_bytes()).as_bytes())
}
pub fn mdns_relay_topic_hex(id: &uuid::Uuid) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(id.as_bytes());
hasher.update(b"mdns-relay");
hex::encode(hasher.finalize().as_bytes())
}