Skip to main content

fips_core/config/
mod.rs

1//! FIPS Configuration System
2//!
3//! Loads configuration from YAML files with a cascading priority system:
4//! 1. `./fips.yaml` (current directory - highest priority)
5//! 2. `~/.config/fips/fips.yaml` (user config directory)
6//! 3. `/etc/fips/fips.yaml` (system - lowest priority)
7//!
8//! Values from higher priority files override those from lower priority files.
9//!
10//! # YAML Structure
11//!
12//! The YAML structure mirrors the sysctl-style paths in the architecture docs.
13//! For example, `node.identity.nsec` in the docs corresponds to:
14//!
15//! ```yaml
16//! node:
17//!   identity:
18//!     nsec: "nsec1..."
19//! ```
20
21#[cfg(target_os = "linux")]
22mod gateway;
23mod node;
24mod peer;
25mod transport;
26
27use crate::upper::config::{DnsConfig, TunConfig};
28use crate::{Identity, IdentityError};
29use serde::{Deserialize, Serialize};
30use std::path::{Path, PathBuf};
31use thiserror::Error;
32
33#[cfg(target_os = "linux")]
34pub use gateway::{ConntrackConfig, GatewayConfig, GatewayDnsConfig, PortForward, Proto};
35pub use node::{
36    BloomConfig, BuffersConfig, CacheConfig, ControlConfig, DiscoveryConfig, LimitsConfig,
37    NodeConfig, NostrDiscoveryConfig, NostrDiscoveryPolicy, RateLimitConfig, RekeyConfig,
38    RetryConfig, RoutingConfig, RoutingMode, SessionConfig, SessionMmpConfig, TreeConfig,
39};
40pub use peer::{ConnectPolicy, PeerAddress, PeerConfig};
41#[cfg(feature = "sim-transport")]
42pub use transport::SimTransportConfig;
43pub use transport::{
44    BleConfig, DirectoryServiceConfig, EthernetConfig, TcpConfig, TorConfig, TransportInstances,
45    TransportsConfig, UdpConfig,
46};
47
48/// Default config filename.
49const CONFIG_FILENAME: &str = "fips.yaml";
50
51/// Default key filename, placed alongside the config file.
52const KEY_FILENAME: &str = "fips.key";
53
54/// Default public key filename, placed alongside the key file.
55const PUB_FILENAME: &str = "fips.pub";
56
57/// Returns true if the textual `host:port` form refers to a loopback host.
58/// Recognizes IPv4 `127.x.x.x`, IPv6 `::1` (with or without brackets), and
59/// the literal string `localhost`. Hostnames are conservatively assumed to
60/// be non-loopback. Used by `Config::validate()` to reject misconfigured
61/// loopback UDP binds combined with non-loopback peer addresses (see
62/// ISSUE-2026-0005).
63fn is_loopback_addr_str(addr: &str) -> bool {
64    // Bracketed IPv6: `[::1]:port`
65    if let Some(rest) = addr.strip_prefix('[')
66        && let Some(end) = rest.find(']')
67    {
68        let host = &rest[..end];
69        return host == "::1";
70    }
71    // Plain `host:port` — split on the rightmost ':'.
72    let host = match addr.rsplit_once(':') {
73        Some((h, _)) => h,
74        None => addr,
75    };
76    host == "localhost" || host == "::1" || host == "0:0:0:0:0:0:0:1" || host.starts_with("127.")
77}
78
79/// Derive the key file path from a config file path.
80pub fn key_file_path(config_path: &Path) -> PathBuf {
81    config_path
82        .parent()
83        .unwrap_or(Path::new("."))
84        .join(KEY_FILENAME)
85}
86
87/// Derive the public key file path from a config file path.
88pub fn pub_file_path(config_path: &Path) -> PathBuf {
89    config_path
90        .parent()
91        .unwrap_or(Path::new("."))
92        .join(PUB_FILENAME)
93}
94
95/// Resolve a default Unix-socket path under the canonical order:
96/// `/run/fips/<filename>` -> `$XDG_RUNTIME_DIR/fips/<filename>` -> `/tmp/fips-<filename>`.
97///
98/// `/run/fips` is the packaged convention. The resolver selects it whenever
99/// the directory exists so daemon and client defaults stay aligned. The daemon
100/// bind path creates missing parent directories; packaged installs create
101/// `/run/fips` via tmpfiles before service start.
102#[cfg(unix)]
103pub(crate) fn resolve_default_socket(filename: &str) -> String {
104    if Path::new("/run/fips").is_dir() {
105        return format!("/run/fips/{filename}");
106    }
107
108    if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR")
109        && Path::new(&xdg).is_dir()
110    {
111        return format!("{xdg}/fips/{filename}");
112    }
113
114    format!("/tmp/fips-{filename}")
115}
116
117/// Default control socket path for fipsctl / fipstop.
118///
119/// On Unix, checks the system-wide path first (used when the daemon runs as
120/// a systemd service), then falls back to the user's XDG runtime directory.
121/// On Windows, returns the default TCP port ("21210").
122pub fn default_control_path() -> PathBuf {
123    #[cfg(unix)]
124    {
125        PathBuf::from(resolve_default_socket("control.sock"))
126    }
127    #[cfg(windows)]
128    {
129        PathBuf::from("21210")
130    }
131}
132
133/// Default gateway control socket path.
134///
135/// On Unix, follows the same pattern as the main control socket.
136/// On Windows, returns a placeholder TCP port ("21211").
137pub fn default_gateway_path() -> PathBuf {
138    #[cfg(unix)]
139    {
140        PathBuf::from(resolve_default_socket("gateway.sock"))
141    }
142    #[cfg(windows)]
143    {
144        PathBuf::from("21211")
145    }
146}
147
148/// Read a bare bech32 nsec from a key file.
149pub fn read_key_file(path: &Path) -> Result<String, ConfigError> {
150    let contents = std::fs::read_to_string(path).map_err(|e| ConfigError::ReadFile {
151        path: path.to_path_buf(),
152        source: e,
153    })?;
154    let nsec = contents.trim().to_string();
155    if nsec.is_empty() {
156        return Err(ConfigError::EmptyKeyFile {
157            path: path.to_path_buf(),
158        });
159    }
160    Ok(nsec)
161}
162
163/// Write a bare bech32 nsec to a key file with restricted permissions.
164///
165/// On Unix, the file is created with mode 0600 (owner read/write only).
166/// On Windows, the file inherits default ACLs from the parent directory.
167pub fn write_key_file(path: &Path, nsec: &str) -> Result<(), ConfigError> {
168    use std::io::Write;
169
170    let mut opts = std::fs::OpenOptions::new();
171    opts.write(true).create(true).truncate(true);
172
173    #[cfg(unix)]
174    {
175        use std::os::unix::fs::OpenOptionsExt;
176        opts.mode(0o600);
177    }
178
179    let mut file = opts.open(path).map_err(|e| ConfigError::WriteKeyFile {
180        path: path.to_path_buf(),
181        source: e,
182    })?;
183
184    #[cfg(unix)]
185    {
186        use std::os::unix::fs::PermissionsExt;
187        file.set_permissions(std::fs::Permissions::from_mode(0o600))
188            .map_err(|e| ConfigError::WriteKeyFile {
189                path: path.to_path_buf(),
190                source: e,
191            })?;
192    }
193
194    file.write_all(nsec.as_bytes())
195        .map_err(|e| ConfigError::WriteKeyFile {
196            path: path.to_path_buf(),
197            source: e,
198        })?;
199    file.write_all(b"\n")
200        .map_err(|e| ConfigError::WriteKeyFile {
201            path: path.to_path_buf(),
202            source: e,
203        })?;
204    Ok(())
205}
206
207/// Write a bare bech32 npub to a public key file.
208///
209/// On Unix, the file is created with mode 0644 (owner read/write, others read).
210/// On Windows, the file inherits default ACLs from the parent directory.
211pub fn write_pub_file(path: &Path, npub: &str) -> Result<(), ConfigError> {
212    use std::io::Write;
213
214    let mut opts = std::fs::OpenOptions::new();
215    opts.write(true).create(true).truncate(true);
216
217    #[cfg(unix)]
218    {
219        use std::os::unix::fs::OpenOptionsExt;
220        opts.mode(0o644);
221    }
222
223    let mut file = opts.open(path).map_err(|e| ConfigError::WriteKeyFile {
224        path: path.to_path_buf(),
225        source: e,
226    })?;
227
228    file.write_all(npub.as_bytes())
229        .map_err(|e| ConfigError::WriteKeyFile {
230            path: path.to_path_buf(),
231            source: e,
232        })?;
233    file.write_all(b"\n")
234        .map_err(|e| ConfigError::WriteKeyFile {
235            path: path.to_path_buf(),
236            source: e,
237        })?;
238    Ok(())
239}
240
241/// Resolve identity from config and key file.
242///
243/// Behavior depends on `node.identity.persistent`:
244///
245/// - **`persistent: false`** (default): generate a fresh ephemeral keypair
246///   every start. Key files are written for operator visibility but overwritten
247///   on each restart.
248///
249/// - **`persistent: true`**: use three-tier resolution:
250///   1. Explicit nsec in config — highest priority
251///   2. Persistent key file (`fips.key`) — reused across restarts
252///   3. Generate new — creates keypair, writes `fips.key` and `fips.pub`
253///
254/// - **`nsec` set explicitly**: always uses that, regardless of `persistent`.
255///
256/// Returns the nsec string (bech32 or hex) to be used for identity creation.
257pub fn resolve_identity(
258    config: &Config,
259    loaded_paths: &[PathBuf],
260) -> Result<ResolvedIdentity, ConfigError> {
261    use crate::encode_nsec;
262
263    // Explicit nsec in config always wins
264    if let Some(nsec) = &config.node.identity.nsec {
265        return Ok(ResolvedIdentity {
266            nsec: nsec.clone(),
267            source: IdentitySource::Config,
268        });
269    }
270
271    // Determine key file directory from loaded config paths
272    let config_ref = if let Some(path) = loaded_paths.last() {
273        path.clone()
274    } else {
275        Config::search_paths()
276            .first()
277            .cloned()
278            .unwrap_or_else(|| PathBuf::from("./fips.yaml"))
279    };
280    let key_path = key_file_path(&config_ref);
281    let pub_path = pub_file_path(&config_ref);
282
283    if config.node.identity.persistent {
284        // Persistent mode: load existing key file or generate-and-persist
285        if key_path.exists() {
286            let nsec = read_key_file(&key_path)?;
287            let identity = Identity::from_secret_str(&nsec)?;
288            let _ = write_pub_file(&pub_path, &identity.npub());
289            return Ok(ResolvedIdentity {
290                nsec,
291                source: IdentitySource::KeyFile(key_path),
292            });
293        }
294
295        // No key file yet — generate and persist
296        let identity = Identity::generate();
297        let nsec = encode_nsec(&identity.keypair().secret_key());
298        let npub = identity.npub();
299
300        if let Some(parent) = key_path.parent() {
301            let _ = std::fs::create_dir_all(parent);
302        }
303
304        match write_key_file(&key_path, &nsec) {
305            Ok(()) => {
306                let _ = write_pub_file(&pub_path, &npub);
307                Ok(ResolvedIdentity {
308                    nsec,
309                    source: IdentitySource::Generated(key_path),
310                })
311            }
312            Err(_) => Ok(ResolvedIdentity {
313                nsec,
314                source: IdentitySource::Ephemeral,
315            }),
316        }
317    } else {
318        // Ephemeral mode (default): fresh keypair every start, write key files
319        // for operator visibility
320        let identity = Identity::generate();
321        let nsec = encode_nsec(&identity.keypair().secret_key());
322        let npub = identity.npub();
323
324        if let Some(parent) = key_path.parent() {
325            let _ = std::fs::create_dir_all(parent);
326        }
327
328        let _ = write_key_file(&key_path, &nsec);
329        let _ = write_pub_file(&pub_path, &npub);
330
331        Ok(ResolvedIdentity {
332            nsec,
333            source: IdentitySource::Ephemeral,
334        })
335    }
336}
337
338/// Result of identity resolution.
339pub struct ResolvedIdentity {
340    /// The nsec string (bech32 or hex) for creating an Identity.
341    pub nsec: String,
342    /// Where the identity came from.
343    pub source: IdentitySource,
344}
345
346/// Where a resolved identity originated.
347pub enum IdentitySource {
348    /// From explicit nsec in config file.
349    Config,
350    /// Loaded from a persistent key file.
351    KeyFile(PathBuf),
352    /// Generated and saved to a new key file.
353    Generated(PathBuf),
354    /// Generated but could not be persisted.
355    Ephemeral,
356}
357
358/// Errors that can occur during configuration loading.
359#[derive(Debug, Error)]
360pub enum ConfigError {
361    #[error("failed to read config file {path}: {source}")]
362    ReadFile {
363        path: PathBuf,
364        source: std::io::Error,
365    },
366
367    #[error("failed to parse config file {path}: {source}")]
368    ParseYaml {
369        path: PathBuf,
370        source: serde_yaml::Error,
371    },
372
373    #[error("key file is empty: {path}")]
374    EmptyKeyFile { path: PathBuf },
375
376    #[error("failed to write key file {path}: {source}")]
377    WriteKeyFile {
378        path: PathBuf,
379        source: std::io::Error,
380    },
381
382    #[error("identity error: {0}")]
383    Identity(#[from] IdentityError),
384
385    #[error("invalid configuration: {0}")]
386    Validation(String),
387}
388
389/// Identity configuration (`node.identity.*`).
390#[derive(Debug, Clone, Default, Serialize, Deserialize)]
391pub struct IdentityConfig {
392    /// Secret key in nsec (bech32) or hex format (`node.identity.nsec`).
393    /// If not specified, a new keypair will be generated.
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub nsec: Option<String>,
396
397    /// Whether to persist the identity across restarts (`node.identity.persistent`).
398    /// When false (default), a fresh ephemeral keypair is generated each start.
399    /// When true, the key file is reused across restarts.
400    #[serde(default)]
401    pub persistent: bool,
402}
403
404/// Root configuration structure.
405#[derive(Debug, Clone, Default, Serialize, Deserialize)]
406pub struct Config {
407    /// Node configuration (`node.*`).
408    #[serde(default)]
409    pub node: NodeConfig,
410
411    /// TUN interface configuration (`tun.*`).
412    #[serde(default)]
413    pub tun: TunConfig,
414
415    /// DNS responder configuration (`dns.*`).
416    #[serde(default)]
417    pub dns: DnsConfig,
418
419    /// Transport instances (`transports.*`).
420    #[serde(default, skip_serializing_if = "TransportsConfig::is_empty")]
421    pub transports: TransportsConfig,
422
423    /// Static peers to connect to (`peers`).
424    #[serde(default, skip_serializing_if = "Vec::is_empty")]
425    pub peers: Vec<PeerConfig>,
426
427    /// Gateway configuration (`gateway`).
428    #[cfg(target_os = "linux")]
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub gateway: Option<GatewayConfig>,
431}
432
433impl Config {
434    /// Create a new empty configuration.
435    pub fn new() -> Self {
436        Self::default()
437    }
438
439    /// Load configuration from the standard search paths.
440    ///
441    /// Files are loaded in reverse priority order and merged:
442    /// 1. `/etc/fips/fips.yaml` (loaded first, lowest priority)
443    /// 2. `~/.config/fips/fips.yaml` (user config)
444    /// 3. `./fips.yaml` (loaded last, highest priority)
445    ///
446    /// Returns a tuple of (config, paths_loaded) where paths_loaded contains
447    /// the paths that were successfully loaded.
448    pub fn load() -> Result<(Self, Vec<PathBuf>), ConfigError> {
449        let search_paths = Self::search_paths();
450        Self::load_from_paths(&search_paths)
451    }
452
453    /// Load configuration from specific paths.
454    ///
455    /// Paths are processed in order, with later paths overriding earlier ones.
456    pub fn load_from_paths(paths: &[PathBuf]) -> Result<(Self, Vec<PathBuf>), ConfigError> {
457        let mut config = Config::default();
458        let mut loaded_paths = Vec::new();
459
460        for path in paths {
461            if path.exists() {
462                let file_config = Self::load_file(path)?;
463                config.merge(file_config);
464                loaded_paths.push(path.clone());
465            }
466        }
467
468        Ok((config, loaded_paths))
469    }
470
471    /// Load configuration from a single file.
472    pub fn load_file(path: &Path) -> Result<Self, ConfigError> {
473        let contents = std::fs::read_to_string(path).map_err(|e| ConfigError::ReadFile {
474            path: path.to_path_buf(),
475            source: e,
476        })?;
477
478        serde_yaml::from_str(&contents).map_err(|e| ConfigError::ParseYaml {
479            path: path.to_path_buf(),
480            source: e,
481        })
482    }
483
484    /// Get the standard search paths in priority order (lowest to highest).
485    pub fn search_paths() -> Vec<PathBuf> {
486        let mut paths = Vec::new();
487
488        // System config (lowest priority)
489        paths.push(PathBuf::from("/etc/fips").join(CONFIG_FILENAME));
490
491        // User config directory
492        if let Some(config_dir) = dirs::config_dir() {
493            paths.push(config_dir.join("fips").join(CONFIG_FILENAME));
494        }
495
496        // Home directory (legacy location)
497        if let Some(home_dir) = dirs::home_dir() {
498            paths.push(home_dir.join(".fips.yaml"));
499        }
500
501        // Current directory (highest priority)
502        paths.push(PathBuf::from(".").join(CONFIG_FILENAME));
503
504        paths
505    }
506
507    /// Merge another configuration into this one.
508    ///
509    /// Values from `other` override values in `self` when present.
510    pub fn merge(&mut self, other: Config) {
511        // Merge node.identity section
512        if other.node.identity.nsec.is_some() {
513            self.node.identity.nsec = other.node.identity.nsec;
514        }
515        if other.node.identity.persistent {
516            self.node.identity.persistent = true;
517        }
518        // Merge node.leaf_only
519        if other.node.leaf_only {
520            self.node.leaf_only = true;
521        }
522        // Merge tun section
523        if other.tun.enabled {
524            self.tun.enabled = true;
525        }
526        if other.tun.name.is_some() {
527            self.tun.name = other.tun.name;
528        }
529        if other.tun.mtu.is_some() {
530            self.tun.mtu = other.tun.mtu;
531        }
532        // Merge dns section — higher-priority config always wins for enabled
533        self.dns.enabled = other.dns.enabled;
534        if other.dns.bind_addr.is_some() {
535            self.dns.bind_addr = other.dns.bind_addr;
536        }
537        if other.dns.port.is_some() {
538            self.dns.port = other.dns.port;
539        }
540        if other.dns.ttl.is_some() {
541            self.dns.ttl = other.dns.ttl;
542        }
543        // Merge transports section
544        self.transports.merge(other.transports);
545        // Merge peers (replace if non-empty)
546        if !other.peers.is_empty() {
547            self.peers = other.peers;
548        }
549        // Merge gateway section — higher-priority config replaces entirely
550        #[cfg(target_os = "linux")]
551        if other.gateway.is_some() {
552            self.gateway = other.gateway;
553        }
554    }
555
556    /// Create an Identity from this configuration.
557    ///
558    /// If an nsec is configured, uses that to create the identity.
559    /// Otherwise, generates a new random identity.
560    pub fn create_identity(&self) -> Result<Identity, ConfigError> {
561        match &self.node.identity.nsec {
562            Some(nsec) => Ok(Identity::from_secret_str(nsec)?),
563            None => Ok(Identity::generate()),
564        }
565    }
566
567    /// Check if an identity is configured (vs. will be generated).
568    pub fn has_identity(&self) -> bool {
569        self.node.identity.nsec.is_some()
570    }
571
572    /// Check if leaf-only mode is configured.
573    pub fn is_leaf_only(&self) -> bool {
574        self.node.leaf_only
575    }
576
577    /// Get the configured peers.
578    pub fn peers(&self) -> &[PeerConfig] {
579        &self.peers
580    }
581
582    /// Get peers that should auto-connect on startup.
583    pub fn auto_connect_peers(&self) -> impl Iterator<Item = &PeerConfig> {
584        self.peers.iter().filter(|p| p.is_auto_connect())
585    }
586
587    /// Validate cross-field configuration invariants.
588    pub fn validate(&self) -> Result<(), ConfigError> {
589        let nostr = &self.node.discovery.nostr;
590
591        let any_transport_advertises_on_nostr = self
592            .transports
593            .udp
594            .iter()
595            .any(|(_, cfg)| cfg.advertise_on_nostr())
596            || self
597                .transports
598                .tcp
599                .iter()
600                .any(|(_, cfg)| cfg.advertise_on_nostr())
601            || self
602                .transports
603                .tor
604                .iter()
605                .any(|(_, cfg)| cfg.advertise_on_nostr());
606
607        if any_transport_advertises_on_nostr && !nostr.enabled {
608            return Err(ConfigError::Validation(
609                "at least one transport has `advertise_on_nostr = true`, but `node.discovery.nostr.enabled` is false".to_string(),
610            ));
611        }
612
613        for (i, peer) in self.peers.iter().enumerate() {
614            if peer.addresses.is_empty() && !nostr.enabled {
615                return Err(ConfigError::Validation(format!(
616                    "peers[{i}] ({}): must specify at least one address, or enable `node.discovery.nostr` to resolve endpoints from Nostr adverts",
617                    peer.npub
618                )));
619            }
620        }
621
622        let has_nat_udp_advert = self
623            .transports
624            .udp
625            .iter()
626            .any(|(_, cfg)| cfg.advertise_on_nostr() && !cfg.is_public());
627
628        if nostr.enabled && has_nat_udp_advert {
629            if nostr.dm_relays.is_empty() {
630                return Err(ConfigError::Validation(
631                    "NAT UDP advert publishing requires `node.discovery.nostr.dm_relays` to be non-empty".to_string(),
632                ));
633            }
634            if nostr.stun_servers.is_empty() {
635                return Err(ConfigError::Validation(
636                    "NAT UDP advert publishing requires `node.discovery.nostr.stun_servers` to be non-empty".to_string(),
637                ));
638            }
639        }
640
641        // Reject loopback UDP bind combined with non-loopback peer addresses.
642        // Linux pins the source IP to a loopback-bound socket, so packets
643        // sent from such a socket to external peers are dropped at the
644        // routing layer with no clear error in the daemon log. See
645        // ISSUE-2026-0005. Outbound-only mode is exempt because it
646        // overrides bind_addr to 0.0.0.0:0 (kernel-picked source).
647        for (name, cfg) in self.transports.udp.iter() {
648            if cfg.outbound_only() {
649                continue;
650            }
651            if is_loopback_addr_str(cfg.bind_addr()) {
652                let any_external_peer = self.peers.iter().any(|peer| {
653                    peer.addresses
654                        .iter()
655                        .any(|a| a.transport == "udp" && !is_loopback_addr_str(&a.addr))
656                });
657                if any_external_peer {
658                    let label = name.unwrap_or("(unnamed)");
659                    return Err(ConfigError::Validation(format!(
660                        "transports.udp[{label}].bind_addr is loopback ({}) but at least one peer has a non-loopback UDP address; \
661                         fips cannot reach external peers from a loopback-bound socket. \
662                         Use bind_addr: \"0.0.0.0:2121\" (with kernel-firewall hardening if exposure is a concern), or set outbound_only: true.",
663                        cfg.bind_addr()
664                    )));
665                }
666            }
667        }
668
669        Ok(())
670    }
671
672    /// Serialize this configuration to YAML.
673    pub fn to_yaml(&self) -> Result<String, serde_yaml::Error> {
674        serde_yaml::to_string(self)
675    }
676}
677
678#[cfg(test)]
679mod tests {
680    use super::*;
681    use std::collections::HashMap;
682    use std::fs;
683    use tempfile::TempDir;
684
685    #[cfg(unix)]
686    static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
687
688    #[test]
689    fn test_empty_config() {
690        let config = Config::new();
691        assert!(config.node.identity.nsec.is_none());
692        assert!(!config.has_identity());
693    }
694
695    #[test]
696    fn test_parse_yaml_with_nsec() {
697        let yaml = r#"
698node:
699  identity:
700    nsec: nsec1qyqsqypqxqszqg9qyqsqypqxqszqg9qyqsqypqxqszqg9qyqsqypqxfnm5g9
701"#;
702        let config: Config = serde_yaml::from_str(yaml).unwrap();
703        assert!(config.node.identity.nsec.is_some());
704        assert!(config.has_identity());
705    }
706
707    #[test]
708    fn test_parse_yaml_with_hex() {
709        let yaml = r#"
710node:
711  identity:
712    nsec: "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20"
713"#;
714        let config: Config = serde_yaml::from_str(yaml).unwrap();
715        assert!(config.node.identity.nsec.is_some());
716
717        let identity = config.create_identity().unwrap();
718        assert!(!identity.npub().is_empty());
719    }
720
721    #[test]
722    fn test_parse_yaml_empty() {
723        let yaml = "";
724        let config: Config = serde_yaml::from_str(yaml).unwrap();
725        assert!(config.node.identity.nsec.is_none());
726    }
727
728    #[test]
729    fn test_parse_yaml_partial() {
730        let yaml = r#"
731node:
732  identity: {}
733"#;
734        let config: Config = serde_yaml::from_str(yaml).unwrap();
735        assert!(config.node.identity.nsec.is_none());
736    }
737
738    #[test]
739    fn test_merge_configs() {
740        let mut base = Config::new();
741        base.node.identity.nsec = Some("base_nsec".to_string());
742
743        let mut override_config = Config::new();
744        override_config.node.identity.nsec = Some("override_nsec".to_string());
745
746        base.merge(override_config);
747        assert_eq!(base.node.identity.nsec, Some("override_nsec".to_string()));
748    }
749
750    #[test]
751    fn test_merge_preserves_base_when_override_empty() {
752        let mut base = Config::new();
753        base.node.identity.nsec = Some("base_nsec".to_string());
754
755        let override_config = Config::new();
756
757        base.merge(override_config);
758        assert_eq!(base.node.identity.nsec, Some("base_nsec".to_string()));
759    }
760
761    #[test]
762    fn test_create_identity_from_nsec() {
763        let mut config = Config::new();
764        config.node.identity.nsec =
765            Some("0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20".to_string());
766
767        let identity = config.create_identity().unwrap();
768        assert!(!identity.npub().is_empty());
769    }
770
771    #[test]
772    fn test_create_identity_generates_new() {
773        let config = Config::new();
774        let identity = config.create_identity().unwrap();
775        assert!(!identity.npub().is_empty());
776    }
777
778    #[test]
779    fn test_load_from_file() {
780        let temp_dir = TempDir::new().unwrap();
781        let config_path = temp_dir.path().join("fips.yaml");
782
783        let yaml = r#"
784node:
785  identity:
786    nsec: "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20"
787"#;
788        fs::write(&config_path, yaml).unwrap();
789
790        let config = Config::load_file(&config_path).unwrap();
791        assert!(config.node.identity.nsec.is_some());
792    }
793
794    #[test]
795    fn test_load_from_paths_merges() {
796        let temp_dir = TempDir::new().unwrap();
797
798        // Create two config files
799        let low_priority = temp_dir.path().join("low.yaml");
800        let high_priority = temp_dir.path().join("high.yaml");
801
802        fs::write(
803            &low_priority,
804            r#"
805node:
806  identity:
807    nsec: "low_priority_nsec"
808"#,
809        )
810        .unwrap();
811
812        fs::write(
813            &high_priority,
814            r#"
815node:
816  identity:
817    nsec: "high_priority_nsec"
818"#,
819        )
820        .unwrap();
821
822        let paths = vec![low_priority.clone(), high_priority.clone()];
823        let (config, loaded) = Config::load_from_paths(&paths).unwrap();
824
825        assert_eq!(loaded.len(), 2);
826        assert_eq!(
827            config.node.identity.nsec,
828            Some("high_priority_nsec".to_string())
829        );
830    }
831
832    #[test]
833    fn test_load_skips_missing_files() {
834        let temp_dir = TempDir::new().unwrap();
835        let existing = temp_dir.path().join("exists.yaml");
836        let missing = temp_dir.path().join("missing.yaml");
837
838        fs::write(
839            &existing,
840            r#"
841node:
842  identity:
843    nsec: "existing_nsec"
844"#,
845        )
846        .unwrap();
847
848        let paths = vec![missing, existing.clone()];
849        let (config, loaded) = Config::load_from_paths(&paths).unwrap();
850
851        assert_eq!(loaded.len(), 1);
852        assert_eq!(loaded[0], existing);
853        assert_eq!(config.node.identity.nsec, Some("existing_nsec".to_string()));
854    }
855
856    #[test]
857    fn test_search_paths_includes_expected() {
858        let paths = Config::search_paths();
859
860        // Should include current directory
861        assert!(paths.iter().any(|p| p.ends_with("fips.yaml")));
862
863        // Should include /etc/fips on Unix
864        #[cfg(unix)]
865        assert!(
866            paths
867                .iter()
868                .any(|p| p.starts_with("/etc/fips") && p.ends_with("fips.yaml"))
869        );
870    }
871
872    #[test]
873    fn test_to_yaml() {
874        let mut config = Config::new();
875        config.node.identity.nsec = Some("test_nsec".to_string());
876
877        let yaml = config.to_yaml().unwrap();
878        assert!(yaml.contains("node:"));
879        assert!(yaml.contains("identity:"));
880        assert!(yaml.contains("nsec:"));
881        assert!(yaml.contains("test_nsec"));
882    }
883
884    #[test]
885    fn test_key_file_write_read_roundtrip() {
886        let temp_dir = TempDir::new().unwrap();
887        let key_path = temp_dir.path().join("fips.key");
888
889        let identity = crate::Identity::generate();
890        let nsec = crate::encode_nsec(&identity.keypair().secret_key());
891
892        write_key_file(&key_path, &nsec).unwrap();
893
894        let loaded_nsec = read_key_file(&key_path).unwrap();
895        assert_eq!(loaded_nsec, nsec);
896
897        // Verify the loaded nsec produces the same identity
898        let loaded_identity = crate::Identity::from_secret_str(&loaded_nsec).unwrap();
899        assert_eq!(loaded_identity.npub(), identity.npub());
900    }
901
902    #[cfg(unix)]
903    #[test]
904    fn test_key_file_permissions() {
905        use std::os::unix::fs::MetadataExt;
906
907        let temp_dir = TempDir::new().unwrap();
908        let key_path = temp_dir.path().join("fips.key");
909
910        write_key_file(&key_path, "nsec1test").unwrap();
911
912        let metadata = fs::metadata(&key_path).unwrap();
913        assert_eq!(metadata.mode() & 0o777, 0o600);
914    }
915
916    #[cfg(unix)]
917    #[test]
918    fn test_key_file_permissions_are_tightened_on_overwrite() {
919        use std::os::unix::fs::{MetadataExt, PermissionsExt};
920
921        let temp_dir = TempDir::new().unwrap();
922        let key_path = temp_dir.path().join("fips.key");
923        fs::write(&key_path, "old\n").unwrap();
924        fs::set_permissions(&key_path, fs::Permissions::from_mode(0o644)).unwrap();
925
926        write_key_file(&key_path, "nsec1test").unwrap();
927
928        let metadata = fs::metadata(&key_path).unwrap();
929        assert_eq!(metadata.mode() & 0o777, 0o600);
930        assert_eq!(read_key_file(&key_path).unwrap(), "nsec1test");
931    }
932
933    #[cfg(unix)]
934    #[test]
935    fn test_pub_file_permissions() {
936        use std::os::unix::fs::MetadataExt;
937
938        let temp_dir = TempDir::new().unwrap();
939        let pub_path = temp_dir.path().join("fips.pub");
940
941        write_pub_file(&pub_path, "npub1test").unwrap();
942
943        let metadata = fs::metadata(&pub_path).unwrap();
944        assert_eq!(metadata.mode() & 0o777, 0o644);
945    }
946
947    #[test]
948    fn test_key_file_empty_error() {
949        let temp_dir = TempDir::new().unwrap();
950        let key_path = temp_dir.path().join("fips.key");
951
952        fs::write(&key_path, "").unwrap();
953
954        let result = read_key_file(&key_path);
955        assert!(result.is_err());
956        assert!(result.unwrap_err().to_string().contains("empty"));
957    }
958
959    #[test]
960    fn test_key_file_whitespace_trimmed() {
961        let temp_dir = TempDir::new().unwrap();
962        let key_path = temp_dir.path().join("fips.key");
963
964        fs::write(&key_path, "  nsec1test  \n").unwrap();
965
966        let nsec = read_key_file(&key_path).unwrap();
967        assert_eq!(nsec, "nsec1test");
968    }
969
970    #[test]
971    fn test_key_file_path_derivation() {
972        let config_path = PathBuf::from("/etc/fips/fips.yaml");
973        assert_eq!(
974            key_file_path(&config_path),
975            PathBuf::from("/etc/fips/fips.key")
976        );
977        assert_eq!(
978            pub_file_path(&config_path),
979            PathBuf::from("/etc/fips/fips.pub")
980        );
981    }
982
983    #[cfg(windows)]
984    #[test]
985    fn test_key_file_write_read_roundtrip_windows() {
986        let temp_dir = TempDir::new().unwrap();
987        let key_path = temp_dir.path().join("fips.key");
988
989        let identity = crate::Identity::generate();
990        let nsec = crate::encode_nsec(&identity.keypair().secret_key());
991
992        write_key_file(&key_path, &nsec).unwrap();
993
994        // Verify file was created and can be read back
995        let loaded_nsec = read_key_file(&key_path).unwrap();
996        assert_eq!(loaded_nsec, nsec);
997
998        // Verify the loaded nsec produces the same identity
999        let loaded_identity = crate::Identity::from_secret_str(&loaded_nsec).unwrap();
1000        assert_eq!(loaded_identity.npub(), identity.npub());
1001    }
1002
1003    #[test]
1004    fn test_resolve_identity_from_config() {
1005        let mut config = Config::new();
1006        config.node.identity.nsec =
1007            Some("0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20".to_string());
1008
1009        let resolved = resolve_identity(&config, &[]).unwrap();
1010        assert!(matches!(resolved.source, IdentitySource::Config));
1011    }
1012
1013    #[test]
1014    fn test_resolve_identity_ephemeral_by_default() {
1015        let temp_dir = TempDir::new().unwrap();
1016        let config_path = temp_dir.path().join("fips.yaml");
1017
1018        fs::write(&config_path, "node:\n  identity: {}\n").unwrap();
1019
1020        let config = Config::load_file(&config_path).unwrap();
1021        assert!(!config.node.identity.persistent);
1022
1023        let resolved = resolve_identity(&config, std::slice::from_ref(&config_path)).unwrap();
1024        assert!(matches!(resolved.source, IdentitySource::Ephemeral));
1025
1026        // Key files should still be written for operator visibility
1027        let key_path = temp_dir.path().join("fips.key");
1028        let pub_path = temp_dir.path().join("fips.pub");
1029        assert!(key_path.exists());
1030        assert!(pub_path.exists());
1031    }
1032
1033    #[test]
1034    fn test_resolve_identity_ephemeral_changes_each_call() {
1035        let temp_dir = TempDir::new().unwrap();
1036        let config_path = temp_dir.path().join("fips.yaml");
1037
1038        fs::write(&config_path, "node:\n  identity: {}\n").unwrap();
1039
1040        let config = Config::load_file(&config_path).unwrap();
1041        let first = resolve_identity(&config, std::slice::from_ref(&config_path)).unwrap();
1042        let second = resolve_identity(&config, std::slice::from_ref(&config_path)).unwrap();
1043
1044        // Each call generates a different key
1045        assert_ne!(first.nsec, second.nsec);
1046    }
1047
1048    #[test]
1049    fn test_resolve_identity_persistent_from_key_file() {
1050        let temp_dir = TempDir::new().unwrap();
1051        let config_path = temp_dir.path().join("fips.yaml");
1052        let key_path = temp_dir.path().join("fips.key");
1053
1054        fs::write(&config_path, "node:\n  identity:\n    persistent: true\n").unwrap();
1055
1056        // Write a key file
1057        let identity = crate::Identity::generate();
1058        let nsec = crate::encode_nsec(&identity.keypair().secret_key());
1059        write_key_file(&key_path, &nsec).unwrap();
1060
1061        let config = Config::load_file(&config_path).unwrap();
1062        assert!(config.node.identity.persistent);
1063
1064        let resolved = resolve_identity(&config, &[config_path]).unwrap();
1065        assert!(matches!(resolved.source, IdentitySource::KeyFile(_)));
1066        assert_eq!(resolved.nsec, nsec);
1067    }
1068
1069    #[test]
1070    fn test_resolve_identity_persistent_generates_and_persists() {
1071        let temp_dir = TempDir::new().unwrap();
1072        let config_path = temp_dir.path().join("fips.yaml");
1073
1074        fs::write(&config_path, "node:\n  identity:\n    persistent: true\n").unwrap();
1075
1076        let config = Config::load_file(&config_path).unwrap();
1077        let resolved = resolve_identity(&config, std::slice::from_ref(&config_path)).unwrap();
1078
1079        assert!(matches!(resolved.source, IdentitySource::Generated(_)));
1080
1081        // Key file and pub file should now exist
1082        let key_path = temp_dir.path().join("fips.key");
1083        let pub_path = temp_dir.path().join("fips.pub");
1084        assert!(key_path.exists());
1085        assert!(pub_path.exists());
1086
1087        // Second resolve should load from key file (not generate new)
1088        let resolved2 = resolve_identity(&config, std::slice::from_ref(&config_path)).unwrap();
1089        assert!(matches!(resolved2.source, IdentitySource::KeyFile(_)));
1090        assert_eq!(resolved.nsec, resolved2.nsec);
1091    }
1092
1093    #[test]
1094    fn test_to_yaml_empty_nsec_omitted() {
1095        let config = Config::new();
1096        let yaml = config.to_yaml().unwrap();
1097
1098        // Empty nsec should not be serialized
1099        assert!(!yaml.contains("nsec:"));
1100    }
1101
1102    #[test]
1103    fn test_parse_transport_single_instance() {
1104        let yaml = r#"
1105transports:
1106  udp:
1107    bind_addr: "0.0.0.0:2121"
1108    mtu: 1400
1109"#;
1110        let config: Config = serde_yaml::from_str(yaml).unwrap();
1111
1112        assert_eq!(config.transports.udp.len(), 1);
1113        let instances: Vec<_> = config.transports.udp.iter().collect();
1114        assert_eq!(instances.len(), 1);
1115        assert_eq!(instances[0].0, None); // Single instance has no name
1116        assert_eq!(instances[0].1.bind_addr(), "0.0.0.0:2121");
1117        assert_eq!(instances[0].1.mtu(), 1400);
1118    }
1119
1120    #[test]
1121    fn test_parse_transport_named_instances() {
1122        let yaml = r#"
1123transports:
1124  udp:
1125    main:
1126      bind_addr: "0.0.0.0:2121"
1127    backup:
1128      bind_addr: "192.168.1.100:2122"
1129      mtu: 1280
1130"#;
1131        let config: Config = serde_yaml::from_str(yaml).unwrap();
1132
1133        assert_eq!(config.transports.udp.len(), 2);
1134
1135        let instances: std::collections::HashMap<_, _> = config.transports.udp.iter().collect();
1136
1137        // Named instances have Some(name)
1138        assert!(instances.contains_key(&Some("main")));
1139        assert!(instances.contains_key(&Some("backup")));
1140        assert_eq!(instances[&Some("main")].bind_addr(), "0.0.0.0:2121");
1141        assert_eq!(instances[&Some("backup")].bind_addr(), "192.168.1.100:2122");
1142        assert_eq!(instances[&Some("backup")].mtu(), 1280);
1143    }
1144
1145    #[test]
1146    fn test_parse_transport_empty() {
1147        let yaml = r#"
1148transports: {}
1149"#;
1150        let config: Config = serde_yaml::from_str(yaml).unwrap();
1151        assert!(config.transports.udp.is_empty());
1152        assert!(config.transports.is_empty());
1153    }
1154
1155    #[test]
1156    fn test_transport_instances_iter() {
1157        // Single instance - no name
1158        let single = TransportInstances::Single(UdpConfig {
1159            bind_addr: Some("0.0.0.0:2121".to_string()),
1160            mtu: None,
1161            ..Default::default()
1162        });
1163        let items: Vec<_> = single.iter().collect();
1164        assert_eq!(items.len(), 1);
1165        assert_eq!(items[0].0, None);
1166
1167        // Named instances - have names
1168        let mut map = HashMap::new();
1169        map.insert("a".to_string(), UdpConfig::default());
1170        map.insert("b".to_string(), UdpConfig::default());
1171        let named = TransportInstances::Named(map);
1172        let items: Vec<_> = named.iter().collect();
1173        assert_eq!(items.len(), 2);
1174        // All named instances should have Some(name)
1175        assert!(items.iter().all(|(name, _)| name.is_some()));
1176    }
1177
1178    #[test]
1179    fn test_parse_peer_config() {
1180        let yaml = r#"
1181peers:
1182  - npub: "npub1abc123"
1183    alias: "gateway"
1184    addresses:
1185      - transport: udp
1186        addr: "192.168.1.1:2121"
1187        priority: 1
1188      - transport: tor
1189        addr: "xyz.onion:2121"
1190        priority: 2
1191    connect_policy: auto_connect
1192"#;
1193        let config: Config = serde_yaml::from_str(yaml).unwrap();
1194
1195        assert_eq!(config.peers.len(), 1);
1196        let peer = &config.peers[0];
1197        assert_eq!(peer.npub, "npub1abc123");
1198        assert_eq!(peer.alias, Some("gateway".to_string()));
1199        assert_eq!(peer.addresses.len(), 2);
1200        assert!(peer.is_auto_connect());
1201
1202        // Check addresses are sorted by priority
1203        let sorted = peer.addresses_by_priority();
1204        assert_eq!(sorted[0].transport, "udp");
1205        assert_eq!(sorted[0].priority, 1);
1206        assert_eq!(sorted[1].transport, "tor");
1207        assert_eq!(sorted[1].priority, 2);
1208    }
1209
1210    #[test]
1211    fn test_parse_peer_minimal() {
1212        let yaml = r#"
1213peers:
1214  - npub: "npub1xyz"
1215    addresses:
1216      - transport: udp
1217        addr: "10.0.0.1:2121"
1218"#;
1219        let config: Config = serde_yaml::from_str(yaml).unwrap();
1220
1221        assert_eq!(config.peers.len(), 1);
1222        let peer = &config.peers[0];
1223        assert_eq!(peer.npub, "npub1xyz");
1224        assert!(peer.alias.is_none());
1225        // Default connect_policy is auto_connect
1226        assert!(peer.is_auto_connect());
1227        // Default priority is 100
1228        assert_eq!(peer.addresses[0].priority, 100);
1229    }
1230
1231    #[test]
1232    fn test_parse_multiple_peers() {
1233        let yaml = r#"
1234peers:
1235  - npub: "npub1peer1"
1236    addresses:
1237      - transport: udp
1238        addr: "10.0.0.1:2121"
1239  - npub: "npub1peer2"
1240    addresses:
1241      - transport: udp
1242        addr: "10.0.0.2:2121"
1243    connect_policy: on_demand
1244"#;
1245        let config: Config = serde_yaml::from_str(yaml).unwrap();
1246
1247        assert_eq!(config.peers.len(), 2);
1248        assert_eq!(config.auto_connect_peers().count(), 1);
1249    }
1250
1251    #[test]
1252    fn test_peer_config_builder() {
1253        let peer = PeerConfig::new("npub1test", "udp", "192.168.1.1:2121")
1254            .with_alias("test-peer")
1255            .with_address(PeerAddress::with_priority("tor", "xyz.onion:2121", 50));
1256
1257        assert_eq!(peer.npub, "npub1test");
1258        assert_eq!(peer.alias, Some("test-peer".to_string()));
1259        assert_eq!(peer.addresses.len(), 2);
1260        assert!(peer.is_auto_connect());
1261    }
1262
1263    #[test]
1264    fn test_parse_nostr_discovery_config() {
1265        let yaml = r#"
1266node:
1267  discovery:
1268    nostr:
1269      enabled: true
1270      advertise: false
1271      policy: configured_only
1272      open_discovery_max_pending: 12
1273      app: "fips.nat.test.v1"
1274      signal_ttl_secs: 45
1275      advert_relays:
1276        - "wss://relay-a.example"
1277      dm_relays:
1278        - "wss://relay-b.example"
1279      stun_servers:
1280        - "stun:stun.example.org:3478"
1281peers:
1282  - npub: "npub1peer"
1283    addresses:
1284      - transport: udp
1285        addr: "nat"
1286"#;
1287        let config: Config = serde_yaml::from_str(yaml).unwrap();
1288        assert!(config.node.discovery.nostr.enabled);
1289        assert!(!config.node.discovery.nostr.advertise);
1290        assert_eq!(config.node.discovery.nostr.app, "fips.nat.test.v1");
1291        assert_eq!(config.node.discovery.nostr.signal_ttl_secs, 45);
1292        assert_eq!(
1293            config.node.discovery.nostr.policy,
1294            NostrDiscoveryPolicy::ConfiguredOnly
1295        );
1296        assert_eq!(config.node.discovery.nostr.open_discovery_max_pending, 12);
1297        assert_eq!(
1298            config.node.discovery.nostr.advert_relays,
1299            vec!["wss://relay-a.example".to_string()]
1300        );
1301        assert_eq!(
1302            config.node.discovery.nostr.dm_relays,
1303            vec!["wss://relay-b.example".to_string()]
1304        );
1305        assert_eq!(
1306            config.node.discovery.nostr.stun_servers,
1307            vec!["stun:stun.example.org:3478".to_string()]
1308        );
1309        assert_eq!(
1310            config.peers[0].addresses[0].addr, "nat",
1311            "udp:nat address should parse without special-casing in YAML"
1312        );
1313    }
1314
1315    #[test]
1316    fn test_validate_transport_advert_requires_nostr_enabled() {
1317        let mut config = Config::default();
1318        config.transports.udp = TransportInstances::Single(UdpConfig {
1319            advertise_on_nostr: Some(true),
1320            ..Default::default()
1321        });
1322        config.node.discovery.nostr.enabled = false;
1323
1324        let err = config.validate().expect_err("validation should fail");
1325        assert!(err.to_string().contains("advertise_on_nostr"));
1326    }
1327
1328    #[test]
1329    fn test_validate_empty_peer_addresses_require_nostr_enabled() {
1330        let mut config = Config {
1331            peers: vec![PeerConfig {
1332                npub: "npub1peer".to_string(),
1333                ..Default::default()
1334            }],
1335            ..Default::default()
1336        };
1337        config.node.discovery.nostr.enabled = false;
1338
1339        let err = config.validate().expect_err("validation should fail");
1340        assert!(err.to_string().contains("node.discovery.nostr"));
1341    }
1342
1343    #[test]
1344    fn test_validate_peer_addresses_optional_with_nostr_enabled() {
1345        // Empty addresses + Nostr discovery disabled -> error.
1346        let mut config = Config {
1347            peers: vec![PeerConfig {
1348                npub: "npub1peer".to_string(),
1349                ..Default::default()
1350            }],
1351            ..Default::default()
1352        };
1353        let err = config.validate().expect_err("validation should fail");
1354        assert!(err.to_string().contains("at least one address"));
1355
1356        // Empty addresses + Nostr discovery enabled -> ok.
1357        config.node.discovery.nostr.enabled = true;
1358        config
1359            .validate()
1360            .expect("Nostr discovery should allow empty addresses");
1361    }
1362
1363    #[test]
1364    fn test_validate_nat_udp_advert_requires_relays_and_stun() {
1365        let mut config = Config::default();
1366        config.node.discovery.nostr.enabled = true;
1367        config.node.discovery.nostr.dm_relays.clear();
1368        config.transports.udp = TransportInstances::Single(UdpConfig {
1369            advertise_on_nostr: Some(true),
1370            public: Some(false),
1371            ..Default::default()
1372        });
1373
1374        let err = config.validate().expect_err("validation should fail");
1375        assert!(err.to_string().contains("dm_relays"));
1376
1377        config.node.discovery.nostr.dm_relays = vec!["wss://relay.example".to_string()];
1378        config.node.discovery.nostr.stun_servers.clear();
1379        let err = config.validate().expect_err("validation should fail");
1380        assert!(err.to_string().contains("stun_servers"));
1381    }
1382
1383    #[test]
1384    fn test_is_loopback_addr_str() {
1385        assert!(is_loopback_addr_str("127.0.0.1:2121"));
1386        assert!(is_loopback_addr_str("127.0.0.5:9999"));
1387        assert!(is_loopback_addr_str("[::1]:2121"));
1388        assert!(is_loopback_addr_str("::1:2121"));
1389        assert!(is_loopback_addr_str("localhost:80"));
1390        assert!(!is_loopback_addr_str("0.0.0.0:2121"));
1391        assert!(!is_loopback_addr_str("192.168.1.1:2121"));
1392        assert!(!is_loopback_addr_str("[fd00::1]:2121"));
1393        assert!(!is_loopback_addr_str("core-vm.tail65015.ts.net:2121"));
1394        assert!(!is_loopback_addr_str("example.com:443"));
1395    }
1396
1397    #[cfg(unix)]
1398    #[test]
1399    fn test_resolve_default_socket_call_sites_agree() {
1400        let _guard = ENV_MUTEX.lock().unwrap();
1401
1402        let control_client = default_control_path().to_string_lossy().into_owned();
1403        let gateway_client = default_gateway_path().to_string_lossy().into_owned();
1404        let control_daemon = ControlConfig::default().socket_path;
1405
1406        assert_eq!(control_daemon, control_client);
1407
1408        let control_dir = Path::new(&control_client)
1409            .parent()
1410            .map(|p| p.to_string_lossy().into_owned())
1411            .unwrap_or_default();
1412        let gateway_dir = Path::new(&gateway_client)
1413            .parent()
1414            .map(|p| p.to_string_lossy().into_owned())
1415            .unwrap_or_default();
1416        assert_eq!(control_dir, gateway_dir);
1417    }
1418
1419    #[cfg(unix)]
1420    #[test]
1421    fn test_resolve_default_socket_xdg_when_no_run_fips() {
1422        let _guard = ENV_MUTEX.lock().unwrap();
1423
1424        let temp_dir = TempDir::new().unwrap();
1425        let prev_xdg = std::env::var("XDG_RUNTIME_DIR").ok();
1426
1427        // SAFETY: serialized by ENV_MUTEX, so no other test in this module
1428        // observes the transient process environment.
1429        unsafe {
1430            std::env::set_var("XDG_RUNTIME_DIR", temp_dir.path());
1431        }
1432
1433        let path = resolve_default_socket("control.sock");
1434
1435        // SAFETY: serialized by ENV_MUTEX.
1436        unsafe {
1437            match prev_xdg {
1438                Some(value) => std::env::set_var("XDG_RUNTIME_DIR", value),
1439                None => std::env::remove_var("XDG_RUNTIME_DIR"),
1440            }
1441        }
1442
1443        assert!(
1444            path.starts_with("/run/fips/")
1445                || path.starts_with(&format!("{}/fips/", temp_dir.path().display())),
1446            "expected /run/fips or XDG path, got: {path}"
1447        );
1448    }
1449
1450    #[cfg(unix)]
1451    #[test]
1452    fn test_resolve_default_socket_tmp_when_xdg_invalid() {
1453        let _guard = ENV_MUTEX.lock().unwrap();
1454
1455        let prev_xdg = std::env::var("XDG_RUNTIME_DIR").ok();
1456        let bogus = "/nonexistent-xdg-runtime-dir-for-fips-test-zzz";
1457
1458        // SAFETY: serialized by ENV_MUTEX.
1459        unsafe {
1460            std::env::set_var("XDG_RUNTIME_DIR", bogus);
1461        }
1462
1463        let path = resolve_default_socket("gateway.sock");
1464
1465        // SAFETY: serialized by ENV_MUTEX.
1466        unsafe {
1467            match prev_xdg {
1468                Some(value) => std::env::set_var("XDG_RUNTIME_DIR", value),
1469                None => std::env::remove_var("XDG_RUNTIME_DIR"),
1470            }
1471        }
1472
1473        assert!(
1474            path.starts_with("/run/fips/") || path == "/tmp/fips-gateway.sock",
1475            "expected /run/fips or /tmp fallback, got: {path}"
1476        );
1477        assert!(
1478            !path.starts_with(bogus),
1479            "stale XDG_RUNTIME_DIR leaked into resolver: {path}"
1480        );
1481    }
1482
1483    #[test]
1484    fn test_validate_loopback_bind_with_external_peer_rejected() {
1485        use crate::config::PeerAddress;
1486        let mut config = Config::default();
1487        config.transports.udp = TransportInstances::Single(UdpConfig {
1488            bind_addr: Some("127.0.0.1:2121".to_string()),
1489            ..Default::default()
1490        });
1491        config.peers = vec![PeerConfig {
1492            npub: "npub1peer".to_string(),
1493            addresses: vec![PeerAddress::new("udp", "core-vm.tail65015.ts.net:2121")],
1494            ..Default::default()
1495        }];
1496
1497        let err = config.validate().expect_err("validation should fail");
1498        let msg = err.to_string();
1499        assert!(msg.contains("loopback"), "got: {msg}");
1500        assert!(msg.contains("non-loopback"), "got: {msg}");
1501    }
1502
1503    #[test]
1504    fn test_validate_loopback_bind_with_loopback_peer_ok() {
1505        use crate::config::PeerAddress;
1506        let mut config = Config::default();
1507        config.transports.udp = TransportInstances::Single(UdpConfig {
1508            bind_addr: Some("127.0.0.1:2121".to_string()),
1509            ..Default::default()
1510        });
1511        config.peers = vec![PeerConfig {
1512            npub: "npub1peer".to_string(),
1513            addresses: vec![PeerAddress::new("udp", "127.0.0.2:2121")],
1514            ..Default::default()
1515        }];
1516
1517        config
1518            .validate()
1519            .expect("loopback peer with loopback bind should validate");
1520    }
1521
1522    #[test]
1523    fn test_validate_outbound_only_exempt_from_loopback_check() {
1524        use crate::config::PeerAddress;
1525        let mut config = Config::default();
1526        // outbound_only overrides bind_addr → 0.0.0.0:0; the loopback
1527        // check must skip this transport entirely.
1528        config.transports.udp = TransportInstances::Single(UdpConfig {
1529            bind_addr: Some("127.0.0.1:2121".to_string()),
1530            outbound_only: Some(true),
1531            ..Default::default()
1532        });
1533        config.peers = vec![PeerConfig {
1534            npub: "npub1peer".to_string(),
1535            addresses: vec![PeerAddress::new("udp", "core-vm.tail65015.ts.net:2121")],
1536            ..Default::default()
1537        }];
1538
1539        config
1540            .validate()
1541            .expect("outbound_only should be exempt from the loopback check");
1542    }
1543
1544    #[test]
1545    fn test_outbound_only_forces_ephemeral_bind() {
1546        let cfg = UdpConfig {
1547            bind_addr: Some("127.0.0.1:2121".to_string()),
1548            outbound_only: Some(true),
1549            ..Default::default()
1550        };
1551        assert_eq!(cfg.bind_addr(), "0.0.0.0:0");
1552        assert!(cfg.outbound_only());
1553    }
1554
1555    #[test]
1556    fn test_outbound_only_forces_advertise_off() {
1557        let cfg = UdpConfig {
1558            advertise_on_nostr: Some(true),
1559            outbound_only: Some(true),
1560            ..Default::default()
1561        };
1562        assert!(!cfg.advertise_on_nostr());
1563    }
1564
1565    #[test]
1566    fn test_udp_accept_connections_default_true() {
1567        let cfg = UdpConfig::default();
1568        assert!(cfg.accept_connections());
1569    }
1570}