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
//! Client to query Roughtime servers.
//!
//! This module provides a client to make Roughtime requests to a single time server. For
//! multi-server measurement sequences see [`MeasurementSequence`](crate::sequence::MeasurementSequence).
//!
//! # Quick Start
//!
//! Use the [`query`] function:
//!
//! ```no_run
//! use roughenough_client::query;
//!
//! // Query with authentication. The client verifies the server's signature.
//! let pub_key = Some("AW5uAoTSTDfG5NfY1bTh08GUnOqlRb+HVhbJ3ODJvsE=");
//! let measurement = query("roughtime.int08h.com", 2003, pub_key).unwrap();
//! if let Some(utc) = measurement.midpoint_datetime() {
//!     println!("Server time: {utc}");
//! }
//!
//! // Unauthenticated query, not recommended.
//! let measurement = query("roughtime.int08h.com", 2003, None).unwrap();
//! if let Some(utc) = measurement.midpoint_datetime() {
//!     println!("Server time: {utc}");
//! }
//! ```
//!
//! # Advanced Usage
//!
//! A customized [Client] can be configured using [ClientBuilder]:
//!
//! ```no_run
//! use roughenough_client::Client;
//! use std::time::Duration;
//! use std::net::SocketAddr;
//!
//! let server: SocketAddr = "roughtime.int08h.com:2003".parse().unwrap();
//! let client = Client::builder(server)
//!     .timeout(Duration::from_secs(5))
//!     .build();
//!
//! let measurement = client.query().unwrap();
//! ```
//!
//! # Transport Layer
//!
//! The client uses UDP for network transport. Custom transport implementations can be provided
//! through the [`ClientTransport`] trait for testing or specialized network configurations.
//!
//! [`ClientTransport`]: crate::transport::ClientTransport

use std::net::{SocketAddr, ToSocketAddrs};
use std::time::Duration;

use roughenough_common::crypto::{make_srv_commitment, random_bytes};
use roughenough_common::encoding::try_decode_key;
use roughenough_protocol::cursor::ParseCursor;
use roughenough_protocol::request::{MAX_RESPONSE_SIZE, Request};
use roughenough_protocol::response::Response;
use roughenough_protocol::tags::{Nonce, ProtocolVersion, PublicKey, SrvCommitment};
use roughenough_protocol::{FromFrame, ToFrame};

use crate::measurement::Measurement;
use crate::transport::{ClientTransport, UdpTransport};
use crate::{ResponseValidator, validation};

/// Get the time from a single Roughtime server, optionally authenticating the response with the
/// server's public key.
///
/// Performs DNS lookup to resolve `hostname` to an IP address. Uses the first IP address found
/// if `hostname` resolves to more than one address.
///
/// The returned [Measurement] holds the remote server's timestamp along the full [Request] and
/// [Response] structs for more advanced use.
///
/// ```no_run,rust
/// // You can get the public key from the `ecosystem.json` file, or
/// // use `None` for an unauthenticated response.
/// let pub_key = Some("AW5uAoTSTDfG5NfY1bTh08GUnOqlRb+HVhbJ3ODJvsE=");
///
/// // Query the server
/// let measurement = roughenough_client::query("roughtime.int08h.com", 2003, pub_key).unwrap();
///
/// // The returned time in Unix epoch seconds
/// println!("Server's time, epoch: {}", measurement.midpoint());
/// // Returned time in human format
/// println!("Server's time, UTC: {:?}", measurement.midpoint_datetime())
/// ```
pub fn query(hostname: &str, port: u16, key: Option<&str>) -> Result<Measurement, ClientError> {
    let client = Client::new(hostname, port, key)?;
    client.query()
}

/// Things that can go wrong when querying a server
#[derive(thiserror::Error, Debug)]
pub enum ClientError {
    #[error("timeout waiting for server response")]
    ServerTimeout,

    #[error("bad server response: {0}")]
    BadResponse(#[from] roughenough_protocol::error::Error),

    #[error("public key decode failed: {0}")]
    BadPublicKey(#[from] data_encoding::DecodeError),

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

    #[error("validation of the server's response failed: {0}")]
    ValidationFailed(#[from] validation::ValidationError),

    #[error("invalid configuration: {0}")]
    InvalidConfiguration(String),

    #[error("could not find IP address for '{0}'")]
    DnsLookupFailed(String),
}

pub struct ClientBuilder {
    server: SocketAddr,
    hostname: String,
    transport: Option<Box<dyn ClientTransport>>,
    timeout: Option<Duration>,
    public_key: Option<PublicKey>,
    versions: Option<Vec<ProtocolVersion>>,
}

impl ClientBuilder {
    const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2);

    pub fn new(server: SocketAddr) -> Self {
        Self {
            server,
            hostname: "unknown".to_string(),
            transport: None,
            timeout: None,
            public_key: None,
            versions: None,
        }
    }

    pub fn hostname(mut self, hostname: &str) -> Self {
        self.hostname = hostname.to_string();
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    pub fn transport(mut self, transport: Box<dyn ClientTransport>) -> Self {
        self.transport = Some(transport);
        self
    }

    pub fn public_key(mut self, public_key: PublicKey) -> Self {
        self.public_key = Some(public_key);
        self
    }

    /// Protocol versions to offer in requests instead of the default. Must be
    /// non-empty and sorted in ascending wire order (RFC 5.1.1).
    pub fn versions(mut self, versions: &[ProtocolVersion]) -> Self {
        assert!(!versions.is_empty(), "versions must be non-empty");
        self.versions = Some(versions.to_vec());
        self
    }

    pub fn build(self) -> Client {
        let timeout = self.timeout.unwrap_or(Self::DEFAULT_TIMEOUT);

        let transport = self
            .transport
            .unwrap_or_else(|| Box::new(UdpTransport::new(&self.server, timeout)));

        let srv_commit = self
            .public_key
            .map(|public_key| make_srv_commitment(&public_key));

        let validator = match self.public_key {
            Some(public_key) => ResponseValidator::new_with_key(public_key),
            None => ResponseValidator::new(),
        };

        Client {
            transport,
            validator,
            srv_commit,
            server: self.server,
            hostname: self.hostname,
            public_key: self.public_key,
            versions: self.versions,
        }
    }
}

pub struct Client {
    pub(crate) server: SocketAddr,
    pub(crate) hostname: String,
    pub(crate) transport: Box<dyn ClientTransport>,
    pub(crate) validator: ResponseValidator,
    pub(crate) public_key: Option<PublicKey>,
    pub(crate) srv_commit: Option<SrvCommitment>,
    /// Protocol versions to offer instead of the default, if configured
    pub(crate) versions: Option<Vec<ProtocolVersion>>,
}

/// Make requests to servers and receive responses
impl Client {
    pub fn builder(server: SocketAddr) -> ClientBuilder {
        ClientBuilder::new(server)
    }

    /// Create a client from a hostname and port, with an optional public key. Performs DNS lookup
    /// to resolve `hostname` to an IP address. Uses the first IP address found if `hostname`
    /// resolves to more than one address.
    pub fn new(
        hostname: &str,
        port: u16,
        pub_key: Option<impl AsRef<str>>,
    ) -> Result<Self, ClientError> {
        Self::new_with_versions(hostname, port, pub_key, None)
    }

    /// Like [`Client::new`], additionally configuring the protocol versions to
    /// offer in requests (see [`ClientBuilder::versions`]).
    pub fn new_with_versions(
        hostname: &str,
        port: u16,
        pub_key: Option<impl AsRef<str>>,
        versions: Option<&[ProtocolVersion]>,
    ) -> Result<Self, ClientError> {
        let host_port = format!("{hostname}:{port}");
        let sock_addr = host_port
            .to_socket_addrs()?
            .next()
            .ok_or(ClientError::DnsLookupFailed(host_port))?;

        let mut builder = Self::builder(sock_addr).hostname(hostname);

        if let Some(encoded_key) = pub_key {
            let pub_key = try_decode_key(encoded_key.as_ref())?;
            builder = builder.public_key(pub_key);
        }

        if let Some(versions) = versions {
            builder = builder.versions(versions);
        }

        Ok(builder.build())
    }

    /// Get the time from a server, optionally authenticating the response.
    ///
    /// ```no_run,rust
    /// use roughenough_client::Client;
    ///
    /// // You can get the public key from the `ecosystem.json` file, or
    /// // use `None` for an unauthenticated response.
    /// let pub_key = Some("AW5uAoTSTDfG5NfY1bTh08GUnOqlRb+HVhbJ3ODJvsE=");
    ///
    /// // Create the client
    /// let client = Client::new("roughtime.int08h.com", 5319, pub_key).unwrap();
    ///
    /// // Query the server
    /// let measurement = client.query().unwrap();
    ///
    /// // Returned time in human format
    /// println!("Server's time, UTC: {:?}", measurement.midpoint_datetime());
    /// // Time in Unix epoch seconds
    /// println!("Server's time, epoch: {}", measurement.midpoint());
    /// ```
    pub fn query(&self) -> Result<Measurement, ClientError> {
        let request = self.create_request(None);
        let nbytes = self.send_request(&request)?;
        assert_eq!(nbytes, request.frame_size());

        let (response, response_bytes) = self.recv_response()?;
        let request_bytes = request.as_frame_bytes()?;

        // validate() ensures that the response is valid and authentic; it
        // verifies signatures over the bytes as received
        let _midpoint = self
            .validator
            .validate(&request_bytes, &response_bytes, &response)?;

        Measurement::builder()
            .server(self.server)
            .hostname(self.hostname.clone())
            .public_key(self.public_key)
            .request(request)
            .response(response)
            .response_bytes(response_bytes)
            .rand_value(None)
            .build()
    }

    /// Create a new Roughtime [Request] using the provided [Nonce], or generate a random nonce
    /// if none was provided.
    fn create_request(&self, nonce: Option<Nonce>) -> Request {
        let nonce = nonce.unwrap_or_else(|| Nonce::from(random_bytes::<32>()));

        match (&self.srv_commit, &self.versions) {
            (Some(srv), Some(versions)) => {
                Request::new_with_server_and_versions(&nonce, srv, versions)
            }
            (Some(srv), None) => Request::new_with_server(&nonce, srv),
            (None, Some(versions)) => Request::new_with_versions(&nonce, versions),
            (None, None) => Request::new(&nonce),
        }
    }

    fn send_request(&self, request: &Request) -> Result<usize, ClientError> {
        let request_bytes = request.as_frame_bytes()?;
        self.transport.send(&request_bytes, self.server)
    }

    /// Receive a response, returning the parsed [Response] together with the
    /// packet exactly as received (used for signature verification, nonce
    /// chaining, and malfeasance reports)
    fn recv_response(&self) -> Result<(Response, Vec<u8>), ClientError> {
        let mut buf = [0u8; MAX_RESPONSE_SIZE];
        let (nbytes, _addr) = self.transport.recv(&mut buf)?;
        let response_bytes = buf[..nbytes].to_vec();

        let mut cursor = ParseCursor::new(&mut buf[..nbytes]);
        let response = Response::from_frame(&mut cursor)?;

        Ok((response, response_bytes))
    }
}

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

    fn test_addr() -> SocketAddr {
        "127.0.0.1:2003".parse().unwrap()
    }

    fn test_key() -> PublicKey {
        PublicKey::from([0x42u8; 32])
    }

    #[test]
    fn builder_defaults() {
        let client = Client::builder(test_addr()).build();

        assert_eq!(client.server, test_addr());
        assert_eq!(client.hostname, "unknown");
        assert!(client.public_key.is_none());
        assert!(client.srv_commit.is_none());
        assert!(client.versions.is_none());
    }

    #[test]
    fn builder_with_key_derives_srv_commitment() {
        let key = test_key();
        let client = Client::builder(test_addr()).public_key(key).build();

        assert_eq!(client.public_key, Some(key));
        assert_eq!(client.srv_commit, Some(make_srv_commitment(&key)));
    }

    #[test]
    fn request_without_key_omits_srv() {
        let client = Client::builder(test_addr()).build();
        let request = client.create_request(None);

        assert!(request.srv().is_none());
    }

    #[test]
    fn request_with_key_carries_srv_commitment() {
        let key = test_key();
        let client = Client::builder(test_addr()).public_key(key).build();

        let request = client.create_request(None);
        assert_eq!(request.srv(), Some(&make_srv_commitment(&key)));
    }

    #[test]
    fn request_carries_configured_versions() {
        let versions = [ProtocolVersion::RFC];
        let client = Client::builder(test_addr()).versions(&versions).build();

        let request = client.create_request(None);
        assert_eq!(request.ver().versions(), &versions[..]);
    }

    #[test]
    fn request_uses_provided_nonce() {
        let client = Client::builder(test_addr()).build();
        let nonce = Nonce::from([0x77u8; 32]);

        let request = client.create_request(Some(nonce));
        assert_eq!(request.nonc(), &nonce);
    }

    #[test]
    fn query_surfaces_transport_timeout() {
        // Transport that never receives anything
        struct DeafTransport;
        impl ClientTransport for DeafTransport {
            fn send(&self, data: &[u8], _addr: SocketAddr) -> Result<usize, ClientError> {
                Ok(data.len())
            }
            fn recv(&self, _buf: &mut [u8]) -> Result<(usize, SocketAddr), ClientError> {
                Err(ClientError::ServerTimeout)
            }
        }

        let client = Client::builder(test_addr())
            .transport(Box::new(DeafTransport))
            .build();

        match client.query() {
            Err(ClientError::ServerTimeout) => {}
            other => panic!("expected ServerTimeout, got {other:?}"),
        }
    }
}