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
use crate::crypto::{sign, verify};
use crate::host_id::HostId;
use crate::host_info::HostInfo;
use crate::local_host_options::LocalHostOptions;
use crate::Host;
use ed25519_dalek;
use ed25519_dalek::Keypair;
use rand07::rngs::OsRng;
use serde::{Deserialize, Serialize};
use std::fmt::Formatter;
use url::{ParseError, Url};
/// LocalHost is a host for which this instance of the program
/// is responsible.
///
/// It holds the private key for the host, which
/// should never be transmitted over the wire to any other peer.
///
/// It is serializable because you may want to re-use a host
/// after a program restart, to inform other peers that yes,
/// you are still the same host, after all.
#[derive(Debug, Serialize, Deserialize)]
pub struct LocalHost {
info: HostInfo,
keypair: ed25519_dalek::Keypair,
}
impl LocalHost {
/// Create a new local host.
///
/// Parameters typically come from a UI or config, user specifying
/// what is the name of the host and how it can be reached.
///
/// # Examples
/// ```
/// use confitul::LocalHost;
///
/// let lh = LocalHost::new(None).unwrap();
/// print!("{}", lh);
/// ```
pub fn new(options: Option<LocalHostOptions>) -> Result<LocalHost, ParseError> {
let mut csprng = OsRng {};
let keypair: Keypair = Keypair::generate(&mut csprng);
let real_options = options.unwrap_or(LocalHostOptions::default());
let mut local_host = LocalHost {
info: HostInfo {
id: HostId::new(&keypair),
name: real_options.name,
description: real_options.description,
urls: Vec::new(),
sig: None,
},
keypair: keypair,
};
local_host.update_urls(&real_options.urls)?; // update_urls will update the sig
Ok(local_host)
}
fn update_sig(&mut self) {
let sig = sign(&self.keypair, &self.info.content_to_verify());
self.info.sig = Some(sig);
}
/// Sign a message.
///
/// Anything sent over the wire should be signed. Only local hosts
/// can sign, by design, as the only host you can trust for this
/// is yourself.
///
/// # Examples
/// ```
/// use confitul::LocalHost;
/// use confitul::Host;
///
/// let local_host = LocalHost::new(None).unwrap();
/// let msg = "a message".as_bytes();
/// let sig = local_host.sign_msg(msg);
/// assert!(matches!(local_host.verify_msg(msg, &sig), Ok(())));
/// assert!(matches!(local_host.verify_msg(msg, msg), Err(_)));
/// ```
pub fn sign_msg(&self, msg: &[u8]) -> Vec<u8> {
sign(&self.keypair, msg)
}
/// Update local host name.
///
/// A special call is needed for this as the signature depends on
/// the name, so this function ensure that the signature
/// is updated after the name is modified.
///
/// # Examples
/// ```
/// use confitul::LocalHost;
/// use confitul::Host;
///
/// let mut local_host = LocalHost::new(None).unwrap();
/// local_host.update_name("another test");
/// ```
pub fn update_name(&mut self, name: &str) {
self.info.name = name.to_string();
self.update_sig();
}
/// Update local host description.
///
/// A special call is needed for this as the signature depends on
/// the description, so this function ensure that the signature
/// is updated after the description is modified.
///
/// # Examples
/// ```
/// use confitul::LocalHost;
/// use confitul::Host;
///
/// let mut local_host = LocalHost::new(None).unwrap();
/// local_host.update_description("another test");
/// ```
pub fn update_description(&mut self, description: &str) {
self.info.description = description.to_string();
self.update_sig();
}
/// Update local host URLs.
///
/// A special call is needed for this as the signature depends on
/// the URLs, so this function ensure that the signature
/// is updated after the URLs are modified.
///
/// # Examples
/// ```
/// use confitul::LocalHost;
/// use confitul::Host;
/// use url::Url;
///
/// let mut local_host = LocalHost::new(None).unwrap();
/// local_host.update_urls(&vec![String::from("https://a-location"), String::from("https://another-location")]).unwrap();
/// ```
pub fn update_urls(&mut self, urls: &Vec<String>) -> Result<(), ParseError> {
let mut parsed_urls: Vec<Url> = Vec::new();
for url in urls {
let parsed_url = Url::parse(url)?;
parsed_urls.push(parsed_url);
}
self.info.urls = parsed_urls;
self.update_sig();
Ok(())
}
}
impl Host for LocalHost {
fn info(&self) -> &HostInfo {
&self.info
}
fn verify_msg(&self, msg: &[u8], sig: &[u8]) -> Result<(), signature::Error> {
verify(&self.keypair.public, msg, sig)
}
}
impl std::fmt::Display for LocalHost {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{{\"type\":\"local\",\"info\":{}}}", self.info)
}
}
#[cfg(test)]
mod tests {
use super::Host;
use super::LocalHost;
use serde_json;
#[test]
fn test_local_host_serde_json() {
let host = LocalHost::new(None).unwrap();
let serialized = serde_json::to_string(&host).unwrap();
let deserialized: LocalHost = serde_json::from_str(&serialized).unwrap();
assert_eq!(host.info(), deserialized.info());
let msg = "message".as_bytes();
let sig = deserialized.sign_msg(msg);
assert!(matches!(host.verify_msg(msg, &sig), Ok(())));
}
#[test]
fn test_local_host_description_update() {
use super::Host;
use super::LocalHost;
let mut local_host = LocalHost::new(None).unwrap();
let msg = "message".as_bytes();
let sig = local_host.sign_msg(msg);
local_host.update_description("another test");
assert_eq!("another test", local_host.info().description.as_str());
assert!(
matches!(local_host.verify_self(), Ok(())),
"updating description should update signature as well"
);
assert!(
matches!(local_host.verify_msg(msg, &sig), Ok(())),
"description update has no impact on previous sig"
);
}
#[test]
fn test_local_host_urls_update() {
use super::Host;
use super::LocalHost;
use url::Url;
let mut local_host = LocalHost::new(None).unwrap();
let msg = "message".as_bytes();
let sig = local_host.sign_msg(msg);
local_host
.update_urls(&vec![
String::from("https://a-location"),
String::from("https://another-location"),
])
.unwrap();
assert_eq!(
vec![
Url::parse("https://a-location").unwrap(),
Url::parse("https://another-location").unwrap()
],
local_host.info().urls
);
assert!(
matches!(local_host.verify_self(), Ok(())),
"updating URLs should update signature as well"
);
assert!(
matches!(local_host.verify_msg(msg, &sig), Ok(())),
"URLs update has no impact on previous sig"
);
}
}