fips-core 0.3.10

Reusable FIPS mesh, endpoint, transport, and protocol library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! Host-to-npub static mapping.
//!
//! Provides a `HostMap` that resolves human-readable hostnames to Nostr
//! public keys (npubs). Populated from two sources:
//!
//! 1. Peer `alias` fields in the YAML configuration
//! 2. An operator-maintained hosts file (`/etc/fips/hosts`)
//!
//! The DNS resolver checks the host map before falling back to direct
//! npub resolution, enabling `gateway.fips` instead of `npub1...xyz.fips`.

use crate::config::PeerConfig;
use crate::{NodeAddr, PeerIdentity};
use std::collections::HashMap;
use std::path::Path;
use std::time::SystemTime;
use tracing::{debug, info, warn};

/// Default path for the FIPS hosts file.
#[cfg(unix)]
pub const DEFAULT_HOSTS_PATH: &str = "/etc/fips/hosts";
#[cfg(windows)]
pub const DEFAULT_HOSTS_PATH: &str = r"C:\ProgramData\fips\hosts";

/// Bidirectional hostname ↔ npub mapping table.
#[derive(Debug, Clone, Default)]
pub struct HostMap {
    /// hostname (lowercase) → npub string
    by_name: HashMap<String, String>,
    /// NodeAddr → hostname (for reverse display lookups)
    by_addr: HashMap<NodeAddr, String>,
}

/// Errors from host map operations.
#[derive(Debug, thiserror::Error)]
pub enum HostMapError {
    #[error("invalid hostname '{hostname}': {reason}")]
    InvalidHostname { hostname: String, reason: String },

    #[error("invalid npub '{npub}': {source}")]
    InvalidNpub {
        npub: String,
        source: crate::IdentityError,
    },

    #[error("I/O error reading {path}: {source}")]
    Io {
        path: String,
        source: std::io::Error,
    },

    #[error("{path}:{line}: {reason}")]
    Parse {
        path: String,
        line: usize,
        reason: String,
    },
}

impl HostMap {
    /// Create an empty host map.
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a hostname → npub mapping.
    ///
    /// Validates the hostname and npub before inserting. The hostname is
    /// stored in lowercase for case-insensitive matching.
    pub fn insert(&mut self, hostname: &str, npub: &str) -> Result<(), HostMapError> {
        validate_hostname(hostname)?;

        let peer = PeerIdentity::from_npub(npub).map_err(|e| HostMapError::InvalidNpub {
            npub: npub.to_string(),
            source: e,
        })?;

        let key = hostname.to_ascii_lowercase();
        self.by_name.insert(key.clone(), npub.to_string());
        self.by_addr.insert(*peer.node_addr(), key);
        Ok(())
    }

    /// Look up the npub for a hostname (case-insensitive).
    pub fn lookup_npub(&self, hostname: &str) -> Option<&str> {
        self.by_name
            .get(&hostname.to_ascii_lowercase())
            .map(|s| s.as_str())
    }

    /// Look up the hostname for a NodeAddr (reverse lookup for display).
    pub fn lookup_hostname(&self, node_addr: &NodeAddr) -> Option<&str> {
        self.by_addr.get(node_addr).map(|s| s.as_str())
    }

    /// Number of entries in the map.
    pub fn len(&self) -> usize {
        self.by_name.len()
    }

    /// Whether the map is empty.
    pub fn is_empty(&self) -> bool {
        self.by_name.is_empty()
    }

    /// Build a host map from configured peer aliases.
    ///
    /// Peers with a valid `alias` field are inserted. Invalid hostnames
    /// or npubs are logged as warnings and skipped.
    pub fn from_peer_configs(peers: &[PeerConfig]) -> Self {
        let mut map = Self::new();
        for peer in peers {
            if let Some(alias) = &peer.alias
                && let Err(e) = map.insert(alias, &peer.npub)
            {
                warn!(alias = %alias, npub = %peer.npub, error = %e, "Skipping invalid peer alias for host map");
            }
        }
        if !map.is_empty() {
            debug!(count = map.len(), "Host map entries from peer config");
        }
        map
    }

    /// Load a host map from a hosts file.
    ///
    /// If the file does not exist, returns an empty map (not an error).
    /// Parse errors on individual lines are logged as warnings and skipped.
    pub fn load_hosts_file(path: &Path) -> Self {
        let contents = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                debug!(path = %path.display(), "No hosts file found, skipping");
                return Self::new();
            }
            Err(e) => {
                warn!(path = %path.display(), error = %e, "Failed to read hosts file");
                return Self::new();
            }
        };

        let mut map = Self::new();
        for (line_num, line) in contents.lines().enumerate() {
            let trimmed = line.trim();

            // Skip empty lines and comments
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }

            let fields: Vec<&str> = trimmed.split_whitespace().collect();
            if fields.len() != 2 {
                warn!(
                    path = %path.display(),
                    line = line_num + 1,
                    content = %trimmed,
                    "Expected 'hostname npub', skipping"
                );
                continue;
            }

            let hostname = fields[0];
            let npub = fields[1];

            if let Err(e) = map.insert(hostname, npub) {
                warn!(
                    path = %path.display(),
                    line = line_num + 1,
                    error = %e,
                    "Skipping invalid hosts file entry"
                );
            }
        }

        if !map.is_empty() {
            info!(path = %path.display(), count = map.len(), "Loaded hosts file");
        }
        map
    }

    /// Merge another host map into this one. The other map wins on conflicts.
    pub fn merge(&mut self, other: HostMap) {
        for (name, npub) in other.by_name {
            self.by_name.insert(name, npub);
        }
        for (addr, name) in other.by_addr {
            self.by_addr.insert(addr, name);
        }
    }
}

/// Return the modification time of a file, or `None` if it doesn't exist or
/// the metadata can't be read.
pub fn file_mtime(path: &Path) -> Option<SystemTime> {
    std::fs::metadata(path).ok().and_then(|m| m.modified().ok())
}

/// Tracks a hosts file and reloads it when the modification time changes.
///
/// Holds the base host map (from peer config aliases) and the current
/// effective map (base + hosts file). On each `check_reload()`, stats the
/// hosts file and rebuilds the effective map if the mtime has changed.
pub struct HostMapReloader {
    /// Base map from peer config aliases (never changes).
    base: HostMap,
    /// Current effective map (base merged with hosts file).
    effective: HostMap,
    /// Whether to watch and reload an operator-managed hosts file.
    file_backed: bool,
    /// Path to the hosts file.
    path: std::path::PathBuf,
    /// Last observed modification time (None if file didn't exist).
    last_mtime: Option<SystemTime>,
}

impl HostMapReloader {
    /// Create a new reloader.
    ///
    /// Performs the initial load of the hosts file and merges with the base map.
    pub fn new(base: HostMap, path: std::path::PathBuf) -> Self {
        let last_mtime = file_mtime(&path);
        let hosts_file = HostMap::load_hosts_file(&path);
        let mut effective = base.clone();
        effective.merge(hosts_file);

        Self {
            base,
            effective,
            file_backed: true,
            path,
            last_mtime,
        }
    }

    /// Create a memory-only reloader from the base host map.
    ///
    /// Embedded applications use this to avoid probing daemon-oriented system
    /// paths such as `/etc/fips/hosts` inside mobile sandboxes.
    pub fn memory_only(base: HostMap) -> Self {
        Self {
            effective: base.clone(),
            base,
            file_backed: false,
            path: std::path::PathBuf::new(),
            last_mtime: None,
        }
    }

    /// Get a reference to the current effective host map.
    pub fn hosts(&self) -> &HostMap {
        &self.effective
    }

    /// Check if the hosts file has been modified and reload if so.
    ///
    /// Returns `true` if the map was reloaded.
    pub fn check_reload(&mut self) -> bool {
        if !self.file_backed {
            return false;
        }

        let current_mtime = file_mtime(&self.path);

        if current_mtime == self.last_mtime {
            return false;
        }

        // File appeared, disappeared, or was modified
        self.last_mtime = current_mtime;
        let hosts_file = HostMap::load_hosts_file(&self.path);
        let mut new_effective = self.base.clone();
        new_effective.merge(hosts_file);

        let count = new_effective.len();
        self.effective = new_effective;

        info!(
            path = %self.path.display(),
            entries = count,
            "Reloaded hosts file"
        );
        true
    }
}

/// Validate a hostname for use as a FIPS DNS alias.
///
/// Rules:
/// - ASCII alphanumeric and hyphens only `[a-zA-Z0-9-]`
/// - Must not start or end with a hyphen
/// - 1–63 characters
/// - Must not start with `npub1` (prevents ambiguity with npub resolution)
pub fn validate_hostname(hostname: &str) -> Result<(), HostMapError> {
    let err = |reason: &str| HostMapError::InvalidHostname {
        hostname: hostname.to_string(),
        reason: reason.to_string(),
    };

    if hostname.is_empty() {
        return Err(err("empty hostname"));
    }

    if hostname.len() > 63 {
        return Err(err("exceeds 63 characters"));
    }

    if hostname.to_ascii_lowercase().starts_with("npub1") {
        return Err(err(
            "must not start with 'npub1' (ambiguous with npub resolution)",
        ));
    }

    if hostname.starts_with('-') {
        return Err(err("must not start with a hyphen"));
    }

    if hostname.ends_with('-') {
        return Err(err("must not end with a hyphen"));
    }

    for ch in hostname.chars() {
        if !ch.is_ascii_alphanumeric() && ch != '-' {
            return Err(err(&format!("invalid character '{ch}'")));
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Identity;

    // --- validate_hostname tests ---

    #[test]
    fn test_valid_hostnames() {
        let valid = [
            "gateway",
            "core-vm",
            "a",
            "node1",
            "my-peer-2",
            "A",
            "GATEWAY",
            "a1b2c3",
            &"x".repeat(63),
        ];
        for h in valid {
            assert!(validate_hostname(h).is_ok(), "should be valid: {h}");
        }
    }

    #[test]
    fn test_invalid_hostnames() {
        let cases = [
            ("", "empty"),
            ("-starts", "starts with hyphen"),
            ("ends-", "ends with hyphen"),
            ("has space", "space"),
            ("has.dot", "dot"),
            ("has_underscore", "underscore"),
            (&"x".repeat(64), "too long"),
            ("npub1foo", "npub1 prefix"),
            ("NPUB1bar", "npub1 prefix case"),
        ];
        for (h, desc) in cases {
            assert!(
                validate_hostname(h).is_err(),
                "should be invalid ({desc}): {h}"
            );
        }
    }

    // --- HostMap insert / lookup tests ---

    #[test]
    fn test_insert_and_lookup() {
        let id = Identity::generate();
        let npub = id.npub();

        let mut map = HostMap::new();
        map.insert("gateway", &npub).unwrap();

        assert_eq!(map.lookup_npub("gateway"), Some(npub.as_str()));
        assert_eq!(map.lookup_npub("GATEWAY"), Some(npub.as_str()));
        assert_eq!(map.lookup_npub("Gateway"), Some(npub.as_str()));
        assert_eq!(map.lookup_hostname(id.node_addr()), Some("gateway"));
        assert_eq!(map.len(), 1);
    }

    #[test]
    fn test_insert_invalid_hostname() {
        let id = Identity::generate();
        let mut map = HostMap::new();
        assert!(map.insert("", &id.npub()).is_err());
        assert!(map.is_empty());
    }

    #[test]
    fn test_insert_invalid_npub() {
        let mut map = HostMap::new();
        assert!(map.insert("gateway", "not-an-npub").is_err());
        assert!(map.is_empty());
    }

    #[test]
    fn test_insert_duplicate_overwrites() {
        let id1 = Identity::generate();
        let id2 = Identity::generate();

        let mut map = HostMap::new();
        map.insert("gateway", &id1.npub()).unwrap();
        map.insert("gateway", &id2.npub()).unwrap();

        assert_eq!(map.lookup_npub("gateway"), Some(id2.npub().as_str()));
        assert_eq!(map.len(), 1);
    }

    #[test]
    fn test_lookup_missing() {
        let map = HostMap::new();
        assert!(map.lookup_npub("nonexistent").is_none());
    }

    // --- from_peer_configs tests ---

    #[test]
    fn test_from_peer_configs_with_alias() {
        let id = Identity::generate();
        let peers = vec![PeerConfig {
            npub: id.npub(),
            alias: Some("core".to_string()),
            ..Default::default()
        }];

        let map = HostMap::from_peer_configs(&peers);
        assert_eq!(map.lookup_npub("core"), Some(id.npub().as_str()));
    }

    #[test]
    fn test_from_peer_configs_without_alias() {
        let id = Identity::generate();
        let peers = vec![PeerConfig {
            npub: id.npub(),
            alias: None,
            ..Default::default()
        }];

        let map = HostMap::from_peer_configs(&peers);
        assert!(map.is_empty());
    }

    #[test]
    fn test_from_peer_configs_invalid_alias_skipped() {
        let id = Identity::generate();
        let peers = vec![PeerConfig {
            npub: id.npub(),
            alias: Some("has space".to_string()),
            ..Default::default()
        }];

        let map = HostMap::from_peer_configs(&peers);
        assert!(map.is_empty());
    }

    // --- load_hosts_file tests ---

    #[test]
    fn test_load_hosts_file_not_found() {
        let map = HostMap::load_hosts_file(Path::new("/nonexistent/path/hosts"));
        assert!(map.is_empty());
    }

    #[test]
    fn test_load_hosts_file_valid() {
        let id1 = Identity::generate();
        let id2 = Identity::generate();
        let content = format!(
            "# A comment\n\
             gateway   {}\n\
             \n\
             # Another comment\n\
             core-vm   {}\n",
            id1.npub(),
            id2.npub()
        );

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        std::fs::write(&path, content).unwrap();

        let map = HostMap::load_hosts_file(&path);
        assert_eq!(map.len(), 2);
        assert_eq!(map.lookup_npub("gateway"), Some(id1.npub().as_str()));
        assert_eq!(map.lookup_npub("core-vm"), Some(id2.npub().as_str()));
    }

    #[test]
    fn test_load_hosts_file_skips_bad_lines() {
        let id = Identity::generate();
        let content = format!(
            "gateway   {}\n\
             bad_host   {}\n\
             too many fields here\n\
             good-host   {}\n",
            id.npub(),
            id.npub(),
            id.npub()
        );

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        std::fs::write(&path, content).unwrap();

        let map = HostMap::load_hosts_file(&path);
        // "gateway" is valid, "bad_host" has underscore, middle line has 3 fields
        // "good-host" is valid
        assert_eq!(map.len(), 2);
        assert!(map.lookup_npub("gateway").is_some());
        assert!(map.lookup_npub("good-host").is_some());
    }

    #[test]
    fn test_load_hosts_file_whitespace_handling() {
        let id = Identity::generate();
        let content = format!(
            "  # indented comment  \n\
             \t gateway \t {} \t \n\
             \n\
             \t  \n",
            id.npub()
        );

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        std::fs::write(&path, content).unwrap();

        let map = HostMap::load_hosts_file(&path);
        assert_eq!(map.len(), 1);
        assert!(map.lookup_npub("gateway").is_some());
    }

    // --- merge tests ---

    #[test]
    fn test_merge_non_overlapping() {
        let id1 = Identity::generate();
        let id2 = Identity::generate();

        let mut map1 = HostMap::new();
        map1.insert("alpha", &id1.npub()).unwrap();

        let mut map2 = HostMap::new();
        map2.insert("beta", &id2.npub()).unwrap();

        map1.merge(map2);
        assert_eq!(map1.len(), 2);
        assert!(map1.lookup_npub("alpha").is_some());
        assert!(map1.lookup_npub("beta").is_some());
    }

    #[test]
    fn test_merge_overlapping_other_wins() {
        let id1 = Identity::generate();
        let id2 = Identity::generate();

        let mut map1 = HostMap::new();
        map1.insert("gateway", &id1.npub()).unwrap();

        let mut map2 = HostMap::new();
        map2.insert("gateway", &id2.npub()).unwrap();

        map1.merge(map2);
        assert_eq!(map1.len(), 1);
        assert_eq!(map1.lookup_npub("gateway"), Some(id2.npub().as_str()));
    }

    // --- HostMapReloader tests ---

    #[test]
    fn test_reloader_initial_load() {
        let id1 = Identity::generate();
        let id2 = Identity::generate();

        // Base map from peer config
        let mut base = HostMap::new();
        base.insert("core", &id1.npub()).unwrap();

        // Hosts file with another entry
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        std::fs::write(&path, format!("gateway   {}\n", id2.npub())).unwrap();

        let reloader = HostMapReloader::new(base, path);
        assert_eq!(reloader.hosts().len(), 2);
        assert!(reloader.hosts().lookup_npub("core").is_some());
        assert!(reloader.hosts().lookup_npub("gateway").is_some());
    }

    #[test]
    fn test_reloader_no_hosts_file() {
        let id = Identity::generate();
        let mut base = HostMap::new();
        base.insert("core", &id.npub()).unwrap();

        let reloader = HostMapReloader::new(base, std::path::PathBuf::from("/nonexistent/hosts"));
        // Only base entries present
        assert_eq!(reloader.hosts().len(), 1);
        assert!(reloader.hosts().lookup_npub("core").is_some());
    }

    #[test]
    fn test_reloader_detects_file_change() {
        let id1 = Identity::generate();
        let id2 = Identity::generate();

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        std::fs::write(&path, format!("gateway   {}\n", id1.npub())).unwrap();

        let mut reloader = HostMapReloader::new(HostMap::new(), path.clone());
        assert_eq!(reloader.hosts().len(), 1);
        assert_eq!(
            reloader.hosts().lookup_npub("gateway"),
            Some(id1.npub().as_str())
        );

        // No change yet
        assert!(!reloader.check_reload());

        // Modify the file — bump mtime by writing new content
        // Sleep briefly to ensure mtime changes (filesystem granularity)
        std::thread::sleep(std::time::Duration::from_millis(50));
        std::fs::write(
            &path,
            format!("gateway   {}\nnew-host   {}\n", id1.npub(), id2.npub()),
        )
        .unwrap();

        assert!(reloader.check_reload());
        assert_eq!(reloader.hosts().len(), 2);
        assert!(reloader.hosts().lookup_npub("new-host").is_some());
    }

    #[test]
    fn test_reloader_detects_file_deletion() {
        let id = Identity::generate();

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        std::fs::write(&path, format!("gateway   {}\n", id.npub())).unwrap();

        let mut reloader = HostMapReloader::new(HostMap::new(), path.clone());
        assert_eq!(reloader.hosts().len(), 1);

        // Delete the file
        std::fs::remove_file(&path).unwrap();

        assert!(reloader.check_reload());
        assert!(reloader.hosts().is_empty());
    }

    #[test]
    fn test_reloader_detects_file_creation() {
        let id = Identity::generate();

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");

        // Start with no file
        let mut reloader = HostMapReloader::new(HostMap::new(), path.clone());
        assert!(reloader.hosts().is_empty());

        // Create the file
        std::fs::write(&path, format!("gateway   {}\n", id.npub())).unwrap();

        assert!(reloader.check_reload());
        assert_eq!(reloader.hosts().len(), 1);
        assert!(reloader.hosts().lookup_npub("gateway").is_some());
    }

    #[test]
    fn test_reloader_preserves_base_on_reload() {
        let id_base = Identity::generate();
        let id_file = Identity::generate();

        let mut base = HostMap::new();
        base.insert("core", &id_base.npub()).unwrap();

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        std::fs::write(&path, format!("gateway   {}\n", id_file.npub())).unwrap();

        let mut reloader = HostMapReloader::new(base, path.clone());
        assert_eq!(reloader.hosts().len(), 2);

        // Delete hosts file — base entries should remain
        std::fs::remove_file(&path).unwrap();
        assert!(reloader.check_reload());
        assert_eq!(reloader.hosts().len(), 1);
        assert!(reloader.hosts().lookup_npub("core").is_some());
        assert!(reloader.hosts().lookup_npub("gateway").is_none());
    }
}