Skip to main content

krot_server/
config.rs

1//! Server configuration.
2
3use std::net::{IpAddr, Ipv4Addr, SocketAddr};
4use std::ops::RangeInclusive;
5use std::path::PathBuf;
6
7use krot_proto::consts::DEFAULT_UDP_PORT;
8
9/// Source of the apex-domain TLS certificate (DomainMode only).
10#[derive(Debug, Clone)]
11pub enum DomainTls {
12    /// Read a PEM-encoded cert chain and PKCS#8 key from disk.
13    PemFile { cert: PathBuf, key: PathBuf },
14    /// Obtain a certificate via ACME HTTP-01.
15    ///
16    /// `contact` is passed to the ACME account (`mailto:...`).
17    /// `directory` selects the ACME server; `None` means Let's Encrypt
18    /// **staging** (safer default while iterating).
19    Acme {
20        contact: String,
21        directory: Option<String>,
22    },
23}
24
25impl DomainTls {
26    /// Let's Encrypt production directory URL.
27    pub const LETSENCRYPT_PRODUCTION: &'static str =
28        "https://acme-v02.api.letsencrypt.org/directory";
29    /// Let's Encrypt staging directory URL (default).
30    pub const LETSENCRYPT_STAGING: &'static str =
31        "https://acme-staging-v02.api.letsencrypt.org/directory";
32}
33
34/// Deployment mode (§15).
35#[derive(Debug, Clone)]
36pub enum Mode {
37    /// No domain configured — TCP-only tunnels on a port pool.
38    Ip {
39        /// Public IP or DNS name to embed in the tunnels' `public_url`.
40        public_host: String,
41        port_pool: RangeInclusive<u16>,
42    },
43    /// Apex domain configured — full L7 routing.
44    Domain {
45        apex: String,
46        tls: DomainTls,
47        /// TCP address to bind the plain HTTP router on (Host-header
48        /// routing plus `/.well-known/acme-challenge/`).
49        http_bind: SocketAddr,
50        /// TCP address to bind the HTTPS SNI-passthrough router on.
51        https_bind: SocketAddr,
52        /// Port pool reserved for TCP tunnels registered in DomainMode.
53        tcp_port_pool: RangeInclusive<u16>,
54    },
55}
56
57impl Default for Mode {
58    fn default() -> Self {
59        Self::Ip {
60            public_host: Ipv4Addr::LOCALHOST.to_string(),
61            port_pool: 10_000..=19_999,
62        }
63    }
64}
65
66impl Mode {
67    #[must_use]
68    pub fn tcp_port_pool(&self) -> RangeInclusive<u16> {
69        match self {
70            Self::Ip { port_pool, .. }
71            | Self::Domain {
72                tcp_port_pool: port_pool,
73                ..
74            } => port_pool.clone(),
75        }
76    }
77}
78
79/// Everything the server needs at startup.
80#[derive(Debug, Clone)]
81pub struct ServerConfig {
82    /// UDP address to bind the QUIC endpoint on.
83    pub bind: SocketAddr,
84    /// Directory used for persistent state (identity cert, admin_token hash).
85    pub data_dir: PathBuf,
86    /// Path to the `authorized_keys` file.
87    pub authorized_keys_path: PathBuf,
88    /// Deployment mode.
89    pub mode: Mode,
90    /// If true, always print a fresh admin token at startup.
91    pub issue_admin_token: bool,
92    /// §16.4: TCP bind for the structured admin API. `None` disables
93    /// the endpoint. Default is loopback-only (`127.0.0.1:9700`);
94    /// operators exposing it publicly are expected to front it with a
95    /// TLS reverse-proxy.
96    pub admin_bind: Option<SocketAddr>,
97    /// §16.4: TTL of admin API session tokens minted from the
98    /// enrollment `admin_token`.
99    pub admin_session_ttl: std::time::Duration,
100    /// §16.3.2: on-disk static peer list. Missing file = empty list
101    /// (no federated peers). Hot-reloaded on file change.
102    pub peer_list_path: PathBuf,
103    /// §16.1.4: optional TCP+TLS bind for the `krot-tcp/1` fallback
104    /// transport. `None` disables the fallback listener; clients
105    /// with UDP blocked will simply not be able to connect. Default
106    /// is `None` — operators opt in.
107    pub tcp_fallback_bind: Option<SocketAddr>,
108    /// §9.2 per-core rate-limit partitions. Should match the actual
109    /// worker count (1 for `Server::run`, `cores` for
110    /// `Server::run_multicore`). Each identity's `bw=` cap is
111    /// divided evenly across this many buckets so cores don't
112    /// contend on a single `governor` bucket. Default 1.
113    pub bw_partitions: usize,
114    /// §7.3 session-resume grace period. When a client disconnects
115    /// abruptly (no ServerBye), its tunnels stay in `Dangling` state
116    /// for this long so a reconnecting client can pick up the same
117    /// public URLs. `None` = protocol default (30s). Local dev may
118    /// want a shorter value so `Ctrl+C` → immediate re-run works.
119    pub resume_grace: Option<std::time::Duration>,
120}
121
122impl ServerConfig {
123    /// A local IpMode config with fresh state in `data_dir`. Useful for tests.
124    #[must_use]
125    pub fn local_in(data_dir: PathBuf) -> Self {
126        Self {
127            bind: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
128            authorized_keys_path: data_dir.join("authorized_keys"),
129            peer_list_path: data_dir.join("peers.txt"),
130            data_dir,
131            mode: Mode::default(),
132            issue_admin_token: false,
133            // Tests bind the admin API on an ephemeral loopback port so
134            // they can drive it without colliding on 9700 across parallel
135            // runs.
136            admin_bind: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)),
137            admin_session_ttl: crate::admin_api::DEFAULT_SESSION_TTL,
138            tcp_fallback_bind: None,
139            bw_partitions: 1,
140            resume_grace: None,
141        }
142    }
143
144    #[must_use]
145    pub fn with_bind(mut self, bind: SocketAddr) -> Self {
146        self.bind = bind;
147        self
148    }
149
150    #[must_use]
151    pub fn with_mode(mut self, mode: Mode) -> Self {
152        self.mode = mode;
153        self
154    }
155
156    #[must_use]
157    pub fn with_issue_admin_token(mut self, issue: bool) -> Self {
158        self.issue_admin_token = issue;
159        self
160    }
161
162    #[must_use]
163    pub fn with_tcp_fallback_bind(mut self, addr: SocketAddr) -> Self {
164        self.tcp_fallback_bind = Some(addr);
165        self
166    }
167
168    #[must_use]
169    pub fn with_bw_partitions(mut self, n: usize) -> Self {
170        self.bw_partitions = n.max(1);
171        self
172    }
173}
174
175/// Default `bind` for CLI construction: wildcard IPv4 on [`DEFAULT_UDP_PORT`].
176#[must_use]
177pub fn default_bind() -> SocketAddr {
178    SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), DEFAULT_UDP_PORT)
179}