roughenough-client 2.2.0

Command-line Roughtime client for querying time servers
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
//! Representing lists of Roughtime servers

use roughenough_common::crypto::secure_shuffle;
use serde::{Deserialize, Serialize};

/// Represents a Roughtime server list
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerList {
    /// List of Roughtime servers
    servers: Vec<Server>,

    /// Optional list of URLs where updated versions of the list may be acquired
    #[serde(skip_serializing_if = "Option::is_none")]
    sources: Option<Vec<String>>,

    /// Optional URL where malfeasance reports can be sent
    #[serde(rename = "reports", skip_serializing_if = "Option::is_none")]
    reporting_url: Option<String>,
}

/// Represents a single Roughtime server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Server {
    /// Server name suitable for display to a user
    name: String,

    /// Highest Roughtime version number supported by the server
    version: ServerVersion,

    /// Signature scheme used by the server (e.g., "ed25519")
    #[serde(rename = "publicKeyType")]
    public_key_type: String,

    /// Base64-encoded long-term public key of the server
    #[serde(rename = "publicKey")]
    public_key: String,

    /// List of network addresses for the server
    addresses: Vec<Address>,
}

/// The `version` of a server list entry. RFC 8.3 specifies an integer. Lists
/// written before RFC 10049 use strings such as "IETF-Roughtime"; those are
/// accepted and kept as-is. Neither form is interpreted.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ServerVersion {
    Integer(u32),
    Legacy(String),
}

/// Represents a network address for a Roughtime server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Address {
    /// Transport protocol ("tcp" or "udp")
    protocol: Protocol,

    /// Host and port in the format "host:port"
    address: String,
}

/// Transport protocol
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
    Tcp,
    Udp,
}

/// Validation errors for json server lists
#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("field '{field}' is empty")]
    EmptyField { field: String },

    #[error("Invalid address: expected 'host:port', got '{address}'")]
    InvalidAddress { address: String },

    #[error("Invalid URL: {reason}")]
    InvalidUrl { reason: String },

    #[error("JSON error: {0}")]
    InvalidJson(#[from] serde_json::Error),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Configuration error: {0}")]
    ConfigError(String),
}

impl ServerList {
    /// Creates a new server list
    pub fn new(
        servers: Vec<Server>,
        sources: Option<Vec<String>>,
        reports: Option<String>,
    ) -> Result<Self, Error> {
        let server_list = Self {
            servers,
            sources,
            reporting_url: reports,
        };
        server_list.validate()?;
        Ok(server_list)
    }

    /// Validates the server list according to RFC requirements
    pub fn validate(&self) -> Result<(), Error> {
        if self.servers.is_empty() {
            return Err(Error::EmptyField {
                field: "server list".to_string(),
            });
        }

        for server in self.servers.iter() {
            server.validate()?;
        }

        if let Some(sources) = &self.sources {
            for url in sources.iter() {
                if !url.starts_with("https://") {
                    return Err(Error::InvalidUrl {
                        reason: format!("Source URL must use HTTPS scheme: {url}"),
                    });
                }
            }
        }

        if let Some(reports) = &self.reporting_url
            && !reports.starts_with("https://")
        {
            return Err(Error::InvalidUrl {
                reason: format!("Reports URL must use HTTPS scheme: {reports}"),
            });
        }

        Ok(())
    }

    /// Parses a server list from JSON and validates it
    pub fn from_json(json: &str) -> Result<Self, Error> {
        let server_list: ServerList = serde_json::from_str(json)?;
        server_list.validate()?;
        Ok(server_list)
    }

    /// Serializes the server list to JSON
    pub fn to_json(&self) -> Result<String, Error> {
        serde_json::to_string_pretty(self).map_err(Into::into)
    }

    /// Loads a server list from a file
    pub fn from_file(file_name: &str) -> Result<Self, Error> {
        let json = std::fs::read_to_string(file_name)?;
        Self::from_json(&json)
    }

    /// Randomly selects n servers from the list
    pub fn choose_random(&self, n: usize) -> Result<Vec<Server>, Error> {
        if n > self.servers.len() {
            return Err(Error::ConfigError(format!(
                "requested {} servers but only {} available",
                n,
                self.servers.len()
            )));
        }

        let mut servers = self.servers.clone();
        secure_shuffle(&mut servers);
        Ok(servers[..n].to_vec())
    }

    pub fn servers(&self) -> &[Server] {
        &self.servers
    }

    /// Returns the malfeasance reports URL if configured
    pub fn reporting_url(&self) -> Option<&str> {
        self.reporting_url.as_deref()
    }

    /// Adds a server to the list
    pub fn add_server(&mut self, server: Server) {
        self.servers.push(server);
    }
}

impl Server {
    pub fn new(
        name: String,
        version: ServerVersion,
        public_key_type: String,
        public_key: String,
        addresses: Vec<Address>,
    ) -> Result<Self, Error> {
        let server = Self {
            name,
            version,
            public_key_type,
            public_key,
            addresses,
        };
        server.validate()?;
        Ok(server)
    }

    /// Validates the server entry
    pub fn validate(&self) -> Result<(), Error> {
        if self.name.is_empty() {
            return Err(Error::EmptyField {
                field: "name".to_string(),
            });
        }

        if self.version == ServerVersion::Legacy(String::new()) {
            return Err(Error::EmptyField {
                field: "version".to_string(),
            });
        }

        if self.public_key_type.is_empty() {
            return Err(Error::EmptyField {
                field: "publicKeyType".to_string(),
            });
        }

        if self.public_key.is_empty() {
            return Err(Error::EmptyField {
                field: "publicKey".to_string(),
            });
        }

        if self.addresses.is_empty() {
            return Err(Error::EmptyField {
                field: format!("{}.addresses", self.name.clone()),
            });
        }

        for address in &self.addresses {
            address.validate()?;
        }

        Ok(())
    }

    pub fn addresses(&self) -> &[Address] {
        &self.addresses
    }

    pub fn first_address(&self) -> &Address {
        &self.addresses[0]
    }

    pub fn first_udp_address(&self) -> Option<&Address> {
        self.addresses.iter().find(|a| a.protocol == Protocol::Udp)
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn version(&self) -> &ServerVersion {
        &self.version
    }

    pub fn public_key_type(&self) -> &str {
        &self.public_key_type
    }

    pub fn public_key(&self) -> &str {
        &self.public_key
    }
}

impl Address {
    pub fn new(protocol: Protocol, address: String) -> Result<Self, Error> {
        let addr = Self { protocol, address };
        addr.validate()?;
        Ok(addr)
    }

    pub fn validate(&self) -> Result<(), Error> {
        // IP literals -- including bracketed IPv6 like "[2001:db8::1]:2003" --
        // parse as socket addresses.
        if self.address.parse::<std::net::SocketAddr>().is_ok() {
            return Ok(());
        }

        match self.address.rsplit_once(':') {
            Some((host, port)) if !host.is_empty() && port.parse::<u16>().is_ok() => Ok(()),
            _ => Err(Error::InvalidAddress {
                address: self.address.clone(),
            }),
        }
    }

    pub fn host(&self) -> &str {
        // Strip brackets from IPv6 literals
        match self.address.rsplit_once(':') {
            Some((host, _port)) => host.trim_start_matches('[').trim_end_matches(']'),
            None => &self.address,
        }
    }

    pub fn port(&self) -> u16 {
        self.address
            .rsplit_once(':')
            .and_then(|(_host, port)| port.parse().ok())
            .expect("was validated at construction")
    }

    /// The transport protocol of this address
    pub fn protocol(&self) -> &Protocol {
        &self.protocol
    }
}

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

    #[test]
    fn test_server_list_creation() {
        let address =
            Address::new(Protocol::Udp, "roughtime.example.com:2002".to_string()).unwrap();
        let server = Server::new(
            "Example Server".to_string(),
            ServerVersion::Integer(1),
            "ed25519".to_string(),
            "base64encodedkey==".to_string(),
            vec![address],
        )
        .unwrap();

        let mut server_list = ServerList::new(vec![server], None, None).unwrap();
        assert_eq!(server_list.servers.len(), 1);

        let address2 = Address::new(Protocol::Tcp, "other.example.com:2003".to_string()).unwrap();
        let server2 = Server::new(
            "Other Server".to_string(),
            ServerVersion::Integer(1),
            "ed25519".to_string(),
            "anotherkeyhere==".to_string(),
            vec![address2],
        )
        .unwrap();

        server_list.add_server(server2);
        assert_eq!(server_list.servers.len(), 2);
    }

    #[test]
    fn test_empty_server_list_fails() {
        match ServerList::new(vec![], None, None) {
            Err(Error::EmptyField { field }) => assert_eq!(field, "server list"),
            Err(e) => panic!("expected Error::EmptyField, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }
    }

    #[test]
    fn test_address_parsing() {
        let address = Address::new(Protocol::Udp, "example.com:2002".to_string()).unwrap();
        assert_eq!(address.host(), "example.com");
        assert_eq!(address.port(), 2002);
    }

    #[test]
    fn test_invalid_addresses() {
        // Missing port
        match Address::new(Protocol::Udp, "invalid_address".to_string()) {
            Err(Error::InvalidAddress { address }) => assert_eq!(address, "invalid_address"),
            Err(e) => panic!("expected Error::InvalidAddress, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }

        // Invalid port
        match Address::new(Protocol::Udp, "example.com:not_a_port".to_string()) {
            Err(Error::InvalidAddress { address }) => assert_eq!(address, "example.com:not_a_port"),
            Err(e) => panic!("expected Error::InvalidAddress, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }
    }

    #[test]
    fn test_ipv6_address_parses() {
        // A bracketed IPv6 literal must not poison the whole list
        let json = r#"{
            "servers": [{
                "name": "V6 Server",
                "version": 1,
                "publicKeyType": "ed25519",
                "publicKey": "key==",
                "addresses": [{"protocol": "udp", "address": "[2001:db8::1]:2003"}]
            }]
        }"#;

        let server_list = ServerList::from_json(json).unwrap();
        let address = server_list.servers()[0].first_address();
        assert_eq!(address.host(), "2001:db8::1");
        assert_eq!(address.port(), 2003);
    }

    #[test]
    fn test_ipv4_and_hostname_addresses_still_parse() {
        let v4 = Address::new(Protocol::Udp, "192.0.2.7:2003".to_string()).unwrap();
        assert_eq!(v4.host(), "192.0.2.7");
        assert_eq!(v4.port(), 2003);

        let hostname =
            Address::new(Protocol::Udp, "roughtime.example.com:2002".to_string()).unwrap();
        assert_eq!(hostname.host(), "roughtime.example.com");
        assert_eq!(hostname.port(), 2002);
    }

    #[test]
    fn test_tcp_only_server_has_no_udp_address() {
        let tcp = Address::new(Protocol::Tcp, "example.com:2003".to_string()).unwrap();
        let server = Server::new(
            "TCP Only".to_string(),
            ServerVersion::Integer(1),
            "ed25519".to_string(),
            "key==".to_string(),
            vec![tcp],
        )
        .unwrap();

        assert!(server.first_udp_address().is_none());
    }

    #[test]
    fn test_mixed_addresses_select_udp() {
        let tcp = Address::new(Protocol::Tcp, "example.com:2003".to_string()).unwrap();
        let udp = Address::new(Protocol::Udp, "example.com:2004".to_string()).unwrap();
        let server = Server::new(
            "Mixed".to_string(),
            ServerVersion::Integer(1),
            "ed25519".to_string(),
            "key==".to_string(),
            vec![tcp, udp],
        )
        .unwrap();

        let selected = server.first_udp_address().unwrap();
        assert_eq!(*selected.protocol(), Protocol::Udp);
        assert_eq!(selected.port(), 2004);
    }

    #[test]
    fn test_json_serialization_roundtrip() {
        let address =
            Address::new(Protocol::Udp, "roughtime.example.com:2002".to_string()).unwrap();
        let server = Server::new(
            "Example Server".to_string(),
            ServerVersion::Integer(1),
            "ed25519".to_string(),
            "base64encodedkey==".to_string(),
            vec![address],
        )
        .unwrap();
        let servers = vec![server];
        let server_list = ServerList::new(servers, None, None).unwrap();

        let json = server_list.to_json().unwrap();
        let parsed: ServerList = ServerList::from_json(&json).unwrap();

        assert_eq!(parsed.servers.len(), 1);
        assert_eq!(parsed.servers[0].name, "Example Server");
    }

    #[test]
    fn integer_and_legacy_versions_parse() {
        let json = r#"{
            "servers": [
                {
                    "name": "RFC",
                    "version": 1,
                    "publicKeyType": "ed25519",
                    "publicKey": "key==",
                    "addresses": [{"protocol": "udp", "address": "example.com:5319"}]
                },
                {
                    "name": "Legacy",
                    "version": "IETF-Roughtime",
                    "publicKeyType": "ed25519",
                    "publicKey": "key==",
                    "addresses": [{"protocol": "udp", "address": "example.com:2002"}]
                }
            ]
        }"#;

        let server_list = ServerList::from_json(json).unwrap();
        assert_eq!(
            server_list.servers()[0].version(),
            &ServerVersion::Integer(1)
        );
        assert_eq!(
            server_list.servers()[1].version(),
            &ServerVersion::Legacy("IETF-Roughtime".to_string())
        );

        // RFC 8.3: written lists carry an integer
        let json = server_list.to_json().unwrap();
        assert!(json.contains(r#""version": 1"#) || json.contains(r#""version":1"#));
    }

    #[test]
    fn empty_legacy_version_is_rejected() {
        let json = r#"{
            "servers": [{
                "name": "Server",
                "version": "",
                "publicKeyType": "ed25519",
                "publicKey": "key==",
                "addresses": [{"protocol": "udp", "address": "example.com:5319"}]
            }]
        }"#;
        match ServerList::from_json(json) {
            Err(Error::EmptyField { field }) => assert_eq!(field, "version"),
            Err(e) => panic!("expected Error::EmptyField, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }
    }

    #[test]
    fn can_read_cloudflare_list() {
        let json = include_str!("../testdata/serverlist-cloudflare.json");
        let server_list: ServerList = ServerList::from_json(json).unwrap();
        assert_eq!(server_list.servers.len(), 4);
    }

    #[test]
    fn test_invalid_json_fails() {
        // Empty server list
        let json = r#"{"servers": []}"#;
        match ServerList::from_json(json) {
            Err(Error::EmptyField { field }) => assert_eq!(field, "server list"),
            Err(e) => panic!("expected Error::EmptyField, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }

        // Empty server name
        let json = r#"{
            "servers": [{
                "name": "",
                "version": 1,
                "publicKeyType": "ed25519",
                "publicKey": "key==",
                "addresses": [{"protocol": "udp", "address": "example.com:2002"}]
            }]
        }"#;
        match ServerList::from_json(json) {
            Err(Error::EmptyField { field }) => assert_eq!(field, "name"),
            Err(e) => panic!("expected Error::EmptyField, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }

        // Invalid address format
        let json = r#"{
            "servers": [{
                "name": "Server",
                "version": 1,
                "publicKeyType": "ed25519",
                "publicKey": "key==",
                "addresses": [{"protocol": "udp", "address": "no_port"}]
            }]
        }"#;
        match ServerList::from_json(json) {
            Err(Error::InvalidAddress { address }) => assert_eq!(address, "no_port"),
            Err(e) => panic!("expected Error::InvalidAddress, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }

        // Non-HTTPS source URL
        let json = r#"{
            "servers": [{
                "name": "Server",
                "version": 1,
                "publicKeyType": "ed25519",
                "publicKey": "key==",
                "addresses": [{"protocol": "udp", "address": "example.com:2002"}]
            }],
            "sources": ["http://example.com"]
        }"#;
        match ServerList::from_json(json) {
            Err(Error::InvalidUrl { reason }) => assert!(reason.contains("HTTPS scheme")),
            Err(e) => panic!("expected Error::InvalidUrl, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }
    }

    #[test]
    fn test_server_validation() {
        // Empty name
        match Server::new(
            "".to_string(),
            ServerVersion::Integer(1),
            "ed25519".to_string(),
            "key==".to_string(),
            vec![Address::new(Protocol::Udp, "example.com:2002".to_string()).unwrap()],
        ) {
            Err(Error::EmptyField { field }) => assert_eq!(field, "name"),
            Err(e) => panic!("expected Error::EmptyField, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }

        // Empty addresses
        match Server::new(
            "Server".to_string(),
            ServerVersion::Integer(1),
            "ed25519".to_string(),
            "key==".to_string(),
            vec![],
        ) {
            Err(Error::EmptyField { field }) => assert!(field.contains("addresses")),
            Err(e) => panic!("expected Error::EmptyField, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }
    }

    #[test]
    fn test_sources_validation() {
        let address = Address::new(Protocol::Udp, "example.com:2002".to_string()).unwrap();
        let server = Server::new(
            "Server".to_string(),
            ServerVersion::Integer(1),
            "ed25519".to_string(),
            "key==".to_string(),
            vec![address],
        )
        .unwrap();

        // Valid HTTPS sources
        let result = ServerList::new(
            vec![server.clone()],
            Some(vec!["https://example.com/list.json".to_string()]),
            None,
        );
        assert!(result.is_ok());

        // Invalid HTTP source
        match ServerList::new(
            vec![server.clone()],
            Some(vec!["http://example.com/list.json".to_string()]),
            None,
        ) {
            Err(Error::InvalidUrl { reason }) => assert!(reason.contains("HTTPS scheme")),
            Err(e) => panic!("expected Error::InvalidUrl, got {e:?}"),
            Ok(_) => panic!("expected validation to fail"),
        }
    }
}