Skip to main content

rings_node/native/
config.rs

1use std::env;
2use std::fs;
3use std::io;
4use std::path::PathBuf;
5
6use rings_gateway::GatewayConfig;
7use rings_gateway::GatewayPlan;
8use serde::Deserialize;
9use serde::Serialize;
10
11use crate::dns_relay::DnsRelayConfig;
12use crate::dns_relay::ServicesConfig;
13use crate::error::Error;
14use crate::error::Result;
15use crate::onion::OnionExitPolicy;
16use crate::onion::OnionServiceName;
17use crate::online::OnlineNodeType;
18use crate::prelude::rings_core::dht::default_storage_virtual_positions_per_owner;
19use crate::prelude::rings_core::dht::DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER;
20#[cfg(test)]
21use crate::prelude::rings_core::ecc::SecretKey;
22use crate::prelude::rings_core::message::OriginQuotaConfig;
23#[cfg(test)]
24use crate::prelude::DelegateeKey;
25use crate::processor::ProcessorConfig;
26use crate::processor::ProcessorConfigSerialized;
27use crate::seed::SeedPeer;
28use crate::util::ensure_parent_dir;
29use crate::util::expand_home;
30
31lazy_static::lazy_static! {
32  static ref DEFAULT_DATA_STORAGE_CONFIG: StorageConfig = StorageConfig {
33    path: get_storage_location(".rings", "data"),
34    capacity: DEFAULT_STORAGE_CAPACITY,
35  };
36  static ref DEFAULT_MEASURE_STORAGE_CONFIG: StorageConfig = StorageConfig {
37    path: get_storage_location(".rings", "measure"),
38    capacity: DEFAULT_STORAGE_CAPACITY,
39  };
40}
41
42/// Default Rings network identifier for native nodes.
43pub const DEFAULT_NETWORK_ID: u32 = 1;
44/// Default internal JSON-RPC API port.
45pub const DEFAULT_INTERNAL_API_PORT: u16 = 50000;
46/// Default external JSON-RPC listener address.
47pub const DEFAULT_EXTERNAL_API_ADDR: &str = "127.0.0.1:50001";
48/// Default internal endpoint URL used by CLI clients.
49pub const DEFAULT_ENDPOINT_URL: &str = "http://127.0.0.1:50000";
50/// Default WebRTC ICE server list.
51pub const DEFAULT_ICE_SERVERS: &str = "stun://stun.l.google.com:19302";
52/// Default Chord stabilization interval in seconds.
53pub const DEFAULT_STABILIZE_INTERVAL: u64 = 15;
54pub use crate::consts::DEFAULT_STORAGE_CAPACITY;
55/// Default interval for refreshing gateway status.
56pub const DEFAULT_GATEWAY_STATUS_REFRESH_SECS: u64 = 2;
57
58/// Native foreground-gateway configuration: the `gateway:` section of the node config file.
59///
60/// `rings init` writes this section in full through [`NativeGatewayConfig::disabled_default`],
61/// so the generated file is the one place an operator edits and `rings run --gateway` works on
62/// it unchanged. Presence of the section is not consent to start a TUN device:
63///
64/// ```text
65/// gateway starts ⟺ section present ∧ (enabled = true ∨ --gateway)
66/// ```
67///
68/// A section that omits `enabled` is inert, and a config without the section loads
69/// with `gateway = None`.
70#[derive(Debug, Clone, Deserialize, Serialize)]
71pub struct NativeGatewayConfig {
72    /// Whether plain `rings run` starts the gateway. Absent means `false`; only an explicit
73    /// `enabled: true` or `rings run --gateway` starts a TUN device.
74    #[serde(default)]
75    pub enabled: bool,
76    /// Platform-neutral routing, TCP, and flow limits.
77    #[serde(flatten)]
78    pub runtime: GatewayConfig,
79    /// Requested Wintun interface name; on Unix the helper's `--interface` is authoritative.
80    #[serde(default)]
81    pub interface_name: Option<String>,
82    /// Durable journal used directly on Windows; on Unix the helper's `--ledger` is authoritative.
83    #[serde(default = "default_gateway_route_ledger_path")]
84    pub route_ledger_path: String,
85    /// Foreground `gateway-config-unix` control socket on Linux and macOS.
86    #[serde(default = "default_gateway_unix_helper_socket")]
87    pub unix_helper_socket: String,
88    /// Optional explicit Wintun DLL path on Windows; overrides `RINGS_GATEWAY_WINTUN_DLL`.
89    #[serde(default)]
90    pub wintun_dll_path: Option<String>,
91    /// Interval for refreshing Onion exit availability in gateway status.
92    #[serde(default = "default_gateway_status_refresh_secs")]
93    pub status_refresh_secs: u64,
94}
95
96impl NativeGatewayConfig {
97    /// The section `rings init` writes: the gateway crate's interface-only plan under its default
98    /// limits, the node's default paths, and `enabled: false`, with every field stated so the
99    /// generated file documents the whole surface. Optional fields are written as `null`.
100    pub fn disabled_default() -> Self {
101        Self {
102            enabled: false,
103            runtime: GatewayConfig::with_default_limits(GatewayPlan::interface_only()),
104            interface_name: None,
105            route_ledger_path: default_gateway_route_ledger_path(),
106            unix_helper_socket: default_gateway_unix_helper_socket(),
107            wintun_dll_path: None,
108            status_refresh_secs: default_gateway_status_refresh_secs(),
109        }
110    }
111
112    /// Render this section as the top-level `gateway:` mapping of a config file, so a message
113    /// telling an operator what to add quotes the shape `rings init` writes rather than a copy.
114    pub fn to_yaml_section(&self) -> Result<String> {
115        serde_saphyr::to_string(&GatewaySection { gateway: self }).map_err(|_| Error::EncodeError)
116    }
117}
118
119/// A config document consisting of the `gateway:` section alone.
120#[derive(Serialize)]
121struct GatewaySection<'a> {
122    gateway: &'a NativeGatewayConfig,
123}
124
125/// Keys of the `gateway:` section: those of [`NativeGatewayConfig`] and of the flattened
126/// [`GatewayConfig`], in the order `rings init` writes them.
127const GATEWAY_KEYS: [&str; 10] = [
128    "enabled",
129    "plan",
130    "max_flows",
131    "flow_idle_timeout",
132    "tcp_buffer_bytes",
133    "interface_name",
134    "route_ledger_path",
135    "unix_helper_socket",
136    "wintun_dll_path",
137    "status_refresh_secs",
138];
139
140/// Deserialize the `gateway:` section, rejecting every key outside [`GATEWAY_KEYS`].
141///
142/// The section flattens [`GatewayConfig`], so serde cannot deny unknown keys there; without this
143/// a misspelt key (say `onion_services`) would silently fall back to its default. The section is
144/// first read as a format-neutral JSON object, so its keys are checked before its fields are.
145fn deserialize_gateway_section<'de, D>(
146    deserializer: D,
147) -> std::result::Result<Option<NativeGatewayConfig>, D::Error>
148where D: serde::Deserializer<'de> {
149    let Some(section) =
150        Option::<serde_json::Map<String, serde_json::Value>>::deserialize(deserializer)?
151    else {
152        return Ok(None);
153    };
154    if let Some(key) = section
155        .keys()
156        .map(String::as_str)
157        .find(|key| !GATEWAY_KEYS.contains(key))
158    {
159        return Err(serde::de::Error::custom(format!(
160            "unknown gateway key {key:?}; expected one of {}",
161            GATEWAY_KEYS.join(", ")
162        )));
163    }
164    serde_json::from_value(serde_json::Value::Object(section))
165        .map(Some)
166        .map_err(serde::de::Error::custom)
167}
168
169const fn default_gateway_status_refresh_secs() -> u64 {
170    DEFAULT_GATEWAY_STATUS_REFRESH_SECS
171}
172
173fn default_gateway_route_ledger_path() -> String {
174    get_storage_location(".rings", "gateway-routes.json")
175}
176
177fn default_gateway_unix_helper_socket() -> String {
178    get_storage_location(".rings", "gateway-helper.sock")
179}
180
181/// Builds the default storage path under the user home directory.
182pub fn get_storage_location<P>(prefix: P, path: P) -> String
183where P: AsRef<std::path::Path> {
184    let home_dir = env::var_os("HOME").map(PathBuf::from);
185    let storage_path = match home_dir {
186        Some(dir) => dir.join(prefix).join(path),
187        None => std::path::Path::new("data").join(prefix).join(path),
188    };
189    storage_path.to_string_lossy().to_string()
190}
191
192/// The `bootstrap` section: targets `rings run` keeps reachable for the life of the process.
193/// `rings init` writes it empty; see [`crate::native::bootstrap`].
194#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
195pub struct BootstrapConfig {
196    /// Managed targets, in the same shape as the entries of a seed document.
197    #[serde(default)]
198    pub peers: Vec<SeedPeer>,
199}
200
201/// Serializable native-node configuration.
202#[derive(Debug, Clone, Deserialize, Serialize)]
203#[serde(deny_unknown_fields)]
204pub struct Config {
205    /// Rings network identifier this node joins.
206    pub network_id: u32,
207    /// Delegation secret key file path.
208    pub delegatee_key: String,
209    /// Optional delegator secret key file path for in-process delegation renewal before the
210    /// signing horizon (#1153); relative paths are resolved next to this config file.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub delegator_key: Option<String>,
213    /// Internal JSON-RPC API port.
214    pub internal_api_port: u16,
215    /// External JSON-RPC listener address.
216    pub external_api_addr: String,
217    /// Internal endpoint URL used by local clients.
218    pub endpoint_url: String,
219    /// Optional HTTP(S) proxy URL used for remote JSON-RPC endpoints (seed and HTTP handshakes).
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub remote_rpc_proxy_url: Option<String>,
222    /// Optional API token file path; relative paths are resolved next to this config file.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub api_token_path: Option<String>,
225    /// Exact browser origins permitted to call the authenticated API.
226    #[serde(default, skip_serializing_if = "Vec::is_empty")]
227    pub api_allowed_origins: Vec<String>,
228    /// Explicitly allow the external API listener to bind a non-loopback address.
229    #[serde(default)]
230    pub allow_remote_external_api: bool,
231    /// WebRTC ICE server list, independent from optional gateway ingress.
232    /// Defaults to empty when `network: { kind, params }` selects the transport explicitly.
233    #[serde(default)]
234    pub ice_servers: String,
235    /// Chord stabilization interval in seconds.
236    pub stabilize_interval: u64,
237    /// Presence descriptor heartbeat interval in seconds.
238    #[serde(default = "crate::registration::default_online_node_heartbeat_interval_secs")]
239    pub online_node_heartbeat_interval_secs: u64,
240    /// Presence descriptor time-to-live in seconds.
241    #[serde(default = "crate::registration::default_online_node_ttl_secs")]
242    pub online_node_ttl_secs: u64,
243    /// Node type advertised in online-node descriptors.
244    #[serde(default = "crate::registration::default_online_node_type")]
245    pub online_node_type: OnlineNodeType,
246    /// Whether this node publishes online-node descriptors.
247    #[serde(default = "crate::registration::default_advertise_presence")]
248    pub advertise_presence: bool,
249    /// Whether this node advertises onion relay capability.
250    #[serde(default = "crate::onion::default_advertise_onion_relay")]
251    pub advertise_onion_relay: bool,
252    /// Whether this node advertises onion exit capability.
253    #[serde(default = "crate::onion::default_advertise_onion_exit")]
254    pub advertise_onion_exit: bool,
255    /// Onion-exit descriptor heartbeat interval in seconds.
256    #[serde(default = "crate::onion::default_onion_exit_heartbeat_interval_secs")]
257    pub onion_exit_heartbeat_interval_secs: u64,
258    /// Onion-exit descriptor time-to-live in seconds.
259    #[serde(default = "crate::onion::default_onion_exit_ttl_secs")]
260    pub onion_exit_ttl_secs: u64,
261    /// Onion-exit services this node can publish.
262    #[serde(default = "crate::onion::default_onion_exit_services")]
263    pub onion_exit_services: Vec<OnionServiceName>,
264    /// Onion-exit target and resource policy.
265    #[serde(default = "crate::onion::default_onion_exit_policy")]
266    pub onion_exit_policy: OnionExitPolicy,
267    /// Optional local HTTP CONNECT proxy listener address.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub onion_http_proxy_addr: Option<String>,
270    /// Timeout for reading HTTP CONNECT headers in seconds.
271    #[serde(default = "crate::onion::proxy::http::default_connect_header_timeout_secs")]
272    pub onion_http_proxy_header_timeout_secs: u64,
273    /// Maximum simultaneous HTTP CONNECT proxy connections.
274    #[serde(default = "crate::onion::proxy::http::default_max_connect_connections")]
275    pub onion_http_proxy_max_connections: usize,
276    /// Native TUN gateway section; `rings init` writes it disabled, and it starts a gateway in
277    /// the same foreground lifecycle only under `enabled: true` or `--gateway`. Older configs
278    /// without the section load as `None`.
279    #[serde(
280        default,
281        deserialize_with = "deserialize_gateway_section",
282        skip_serializing_if = "Option::is_none"
283    )]
284    pub gateway: Option<NativeGatewayConfig>,
285    /// Managed bootstrap targets `rings run` keeps reachable for the life of the process.
286    #[serde(default)]
287    pub bootstrap: BootstrapConfig,
288    /// The services this node serves at `<did>.<zone>` through DNS relays (#1049); absent, it
289    /// announces nothing.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub services: Option<ServicesConfig>,
292    /// The DNS relay this node runs for its zones (#1049), if any.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub dns_relay: Option<DnsRelayConfig>,
295    /// Virtual DHT positions per storage owner.
296    #[serde(default = "default_storage_virtual_positions_per_owner")]
297    pub dht_virtual_nodes: u16,
298    /// Runtime-local final-destination quotas keyed by verified origin and logical lane.
299    #[serde(default)]
300    pub origin_quota: OriginQuotaConfig,
301    /// Optional externally reachable IP address hint.
302    #[serde(skip_serializing_if = "Option::is_none")]
303    pub external_ip: Option<String>,
304    /// Optional lower bound for local UDP port allocation.
305    #[serde(
306        default,
307        alias = "webrtc_udp_port_min",
308        skip_serializing_if = "Option::is_none"
309    )]
310    pub udp_port_min: Option<u16>,
311    /// Optional upper bound for local UDP port allocation.
312    #[serde(
313        default,
314        alias = "webrtc_udp_port_max",
315        skip_serializing_if = "Option::is_none"
316    )]
317    pub udp_port_max: Option<u16>,
318    /// Optional serde-extensible tagged transport configuration (`{ kind, params }`).
319    /// When present, overrides the default `"webrtc"` transport constructed from `ice_servers`,
320    /// `external_ip`, and `udp_port_min` / `udp_port_max`.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub network: Option<crate::processor::NetworkConfigDescriptor>,
323    /// Persistent DHT data storage configuration.
324    pub data_storage: StorageConfig,
325    /// Peer measurement storage configuration.
326    pub measure_storage: StorageConfig,
327}
328
329impl TryFrom<Config> for ProcessorConfigSerialized {
330    type Error = Error;
331    fn try_from(config: Config) -> Result<Self> {
332        let delegatee_key_path = expand_home(&config.delegatee_key)?;
333        let delegatee_key = fs::read_to_string(&delegatee_key_path).map_err(|error| {
334            Error::OpenFileError(format!("{}: {error}", delegatee_key_path.display()))
335        })?;
336
337        let udp_range =
338            crate::processor::parse_udp_port_range(config.udp_port_min, config.udp_port_max)?;
339        if config.network.is_some()
340            && (!config.ice_servers.trim().is_empty()
341                || config.external_ip.is_some()
342                || udp_range.is_some())
343        {
344            return Err(Error::InvalidConfig(
345                "cannot specify both `network` and legacy flat WebRTC fields (`ice_servers`, `external_ip`, `udp_port_min`, `udp_port_max`)"
346                    .to_string(),
347            ));
348        }
349
350        Ok(Self {
351            network_id: config.network_id,
352            ice_servers: config.ice_servers,
353            external_address: config.external_ip,
354            udp_port_min: udp_range.map(|range| range.min()),
355            udp_port_max: udp_range.map(|range| range.max()),
356            network: config.network,
357            delegatee_key,
358            stabilize_interval: config.stabilize_interval,
359            online_node_heartbeat_interval_secs: config.online_node_heartbeat_interval_secs,
360            online_node_ttl_secs: config.online_node_ttl_secs,
361            online_node_type: config.online_node_type,
362            advertise_presence: config.advertise_presence,
363            dht_virtual_nodes: config.dht_virtual_nodes,
364            origin_quota: config.origin_quota,
365            advertise_onion_relay: config.advertise_onion_relay,
366            advertise_onion_exit: config.advertise_onion_exit,
367            onion_exit_heartbeat_interval_secs: config.onion_exit_heartbeat_interval_secs,
368            onion_exit_ttl_secs: config.onion_exit_ttl_secs,
369            onion_exit_services: config.onion_exit_services,
370            onion_exit_policy: config.onion_exit_policy,
371            onion_invoke_offer: None,
372            remote_rpc_proxy_url: config.remote_rpc_proxy_url,
373        })
374    }
375}
376
377impl TryFrom<Config> for ProcessorConfig {
378    type Error = Error;
379    fn try_from(config: Config) -> Result<Self> {
380        ProcessorConfigSerialized::try_from(config).and_then(Self::try_from)
381    }
382}
383
384impl Config {
385    /// Creates a default native-node configuration using the supplied delegatee key path.
386    pub fn new<P>(delegatee_key: P) -> Self
387    where P: AsRef<std::path::Path> {
388        let delegatee_key = delegatee_key.as_ref().to_string_lossy().to_string();
389        Self {
390            network_id: DEFAULT_NETWORK_ID,
391            delegatee_key,
392            delegator_key: None,
393            internal_api_port: DEFAULT_INTERNAL_API_PORT,
394            external_api_addr: DEFAULT_EXTERNAL_API_ADDR.to_string(),
395            endpoint_url: DEFAULT_ENDPOINT_URL.to_string(),
396            remote_rpc_proxy_url: None,
397            api_token_path: None,
398            api_allowed_origins: Vec::new(),
399            allow_remote_external_api: false,
400            ice_servers: DEFAULT_ICE_SERVERS.to_string(),
401            stabilize_interval: DEFAULT_STABILIZE_INTERVAL,
402            online_node_heartbeat_interval_secs:
403                crate::registration::default_online_node_heartbeat_interval_secs(),
404            online_node_ttl_secs: crate::registration::default_online_node_ttl_secs(),
405            online_node_type: crate::registration::default_online_node_type(),
406            advertise_presence: crate::registration::default_advertise_presence(),
407            advertise_onion_relay: crate::onion::default_advertise_onion_relay(),
408            advertise_onion_exit: crate::onion::default_advertise_onion_exit(),
409            onion_exit_heartbeat_interval_secs:
410                crate::onion::default_onion_exit_heartbeat_interval_secs(),
411            onion_exit_ttl_secs: crate::onion::default_onion_exit_ttl_secs(),
412            onion_exit_services: crate::onion::default_onion_exit_services(),
413            onion_exit_policy: crate::onion::default_onion_exit_policy(),
414            onion_http_proxy_addr: None,
415            onion_http_proxy_header_timeout_secs:
416                crate::onion::proxy::http::default_connect_header_timeout_secs(),
417            onion_http_proxy_max_connections:
418                crate::onion::proxy::http::default_max_connect_connections(),
419            gateway: Some(NativeGatewayConfig::disabled_default()),
420            bootstrap: BootstrapConfig::default(),
421            services: None,
422            dns_relay: None,
423            dht_virtual_nodes: DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER,
424            origin_quota: OriginQuotaConfig::default(),
425            external_ip: None,
426            udp_port_min: None,
427            udp_port_max: None,
428            network: None,
429            data_storage: DEFAULT_DATA_STORAGE_CONFIG.clone(),
430            measure_storage: DEFAULT_MEASURE_STORAGE_CONFIG.clone(),
431        }
432    }
433
434    /// The gateway section `rings run` starts a runner from, if any.
435    ///
436    /// Law: `enabled_gateway() = Some(g) ⟺ gateway = Some(g) ∧ g.enabled`. `--gateway` sets
437    /// `enabled` before this is consulted, so the flag and the field select the same runner.
438    pub fn enabled_gateway(&self) -> Option<&NativeGatewayConfig> {
439        self.gateway.as_ref().filter(|gateway| gateway.enabled)
440    }
441
442    /// Writes this configuration to a YAML file and returns the written path.
443    pub fn write_fs<P>(&self, path: P) -> Result<String>
444    where P: AsRef<std::path::Path> {
445        let path = expand_home(path)?;
446        ensure_parent_dir(&path)?;
447        let f =
448            fs::File::create(path.as_path()).map_err(|e| Error::CreateFileError(e.to_string()))?;
449        let mut f_writer = io::BufWriter::new(f);
450        serde_saphyr::to_io_writer(&mut f_writer, self).map_err(|source| {
451            Error::ConfigSerialize {
452                path: path.clone(),
453                source,
454            }
455        })?;
456        io::Write::flush(&mut f_writer).map_err(|e| Error::CreateFileError(e.to_string()))?;
457        let f = f_writer
458            .into_inner()
459            .map_err(|e| Error::CreateFileError(e.into_error().to_string()))?;
460        f.sync_all()
461            .map_err(|e| Error::CreateFileError(e.to_string()))?;
462        path.to_str()
463            .map(str::to_owned)
464            .ok_or_else(|| Error::PathUtf8Error(path.display().to_string()))
465    }
466
467    /// Normalize relative file paths in this configuration (such as `delegator_key`) against the
468    /// parent directory of `config_path`.
469    pub fn resolve_paths_relative_to<P>(&mut self, config_path: P) -> Result<()>
470    where P: AsRef<std::path::Path> {
471        let path = expand_home(config_path)?;
472        if let Some(delegator_key) = self.delegator_key.as_deref() {
473            let expanded = expand_home(delegator_key)?;
474            let resolved = if expanded.is_relative() {
475                match path.parent() {
476                    Some(parent) if !parent.as_os_str().is_empty() => parent.join(expanded),
477                    _ => expanded,
478                }
479            } else {
480                expanded
481            };
482            self.delegator_key = Some(resolved.to_string_lossy().into_owned());
483        }
484        Ok(())
485    }
486
487    /// Reads a native-node configuration from a YAML file.
488    pub fn read_fs<P>(path: P) -> Result<Config>
489    where P: AsRef<std::path::Path> {
490        let path = expand_home(path)?;
491        tracing::debug!("Read config from: {:?}", path);
492        let f = fs::File::open(path.as_path()).map_err(|e| Error::OpenFileError(e.to_string()))?;
493        let f_rdr = io::BufReader::new(f);
494        let mut config: Config =
495            serde_saphyr::from_reader(f_rdr).map_err(|source| Error::ConfigParse {
496                path: path.clone(),
497                source: Box::new(source),
498            })?;
499        config.resolve_paths_relative_to(&path)?;
500        Ok(config)
501    }
502}
503
504/// Configuration for a node storage backend.
505#[derive(Debug, Clone, Deserialize, Serialize)]
506pub struct StorageConfig {
507    /// Storage directory path.
508    pub path: String,
509    /// Storage capacity in bytes.
510    pub capacity: u32,
511}
512
513impl StorageConfig {
514    /// Creates a storage configuration from a path and capacity.
515    pub fn new(path: &str, capacity: u32) -> Self {
516        Self {
517            path: path.to_string(),
518            capacity,
519        }
520    }
521}
522
523#[cfg(test)]
524mod tests;