-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmod.rs
More file actions
399 lines (357 loc) · 12.6 KB
/
Copy pathmod.rs
File metadata and controls
399 lines (357 loc) · 12.6 KB
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
use std::collections::HashMap;
use crate::crypto::{Hash, PublicKey};
mod parsing;
pub use parsing::ParsePolicyError;
/// A Sigsum policy.
///
/// The Sigsum policy dictates if a signed tree head is considered valid (and by extension, if a
/// Sigsum signature is valid).
#[derive(Debug, Eq, PartialEq)]
pub struct Policy {
// logs keeps the list of log keys and URLs indexed by keyhash.
logs: HashMap<Hash, Entity>,
// witnesses keeps the list of witness keys and URLs indexed by keyhash.
witnesses: HashMap<Hash, Entity>,
// quorums keeps the quorum entries (witnesses and groups), indexed by name.
quorums: HashMap<String, Quorum>,
// quorum is the quorum required by the policy. Invariant: if present, quorum must be an
// existing key in quorums.
quorum: Option<String>,
}
#[derive(Debug)]
pub struct Log {
pub pubkey: PublicKey,
pub url: Option<String>,
}
#[derive(Debug)]
pub struct Witness {
pub name: String,
pub pubkey: PublicKey,
pub url: Option<String>,
}
pub struct Logs<'a> {
inner: std::collections::hash_map::Iter<'a, Hash, Entity>,
}
impl<'a> Iterator for Logs<'a> {
type Item = Log;
fn next(&mut self) -> Option<Self::Item> {
let (_, entity) = self.inner.next()?;
Some(Log {
pubkey: entity.0.clone(),
url: entity.1.clone(),
})
}
}
impl Policy {
pub fn logs(&self) -> Logs<'_> {
Logs {
inner: self.logs.iter(),
}
}
pub fn get_witness_by_keyhash(&self, keyhash: &Hash) -> Option<Witness> {
let entity = self.witnesses.get(keyhash)?;
let name = self
.quorums
.iter()
.filter_map(|(n, q)| match q {
Quorum::Witness(h) if h == keyhash => Some(n),
_ => None,
})
.next()
.unwrap();
Some(Witness {
name: name.clone(),
pubkey: entity.0.clone(),
url: entity.1.clone(),
})
}
}
// Quorum is an internal enum that represent possible quorum values, i.e. witnesses and groups.
#[derive(Debug, Eq, PartialEq)]
enum Quorum {
// A single witness, identified by its keyhash.
// Invariant: if Witness(h) is in Policy.quorums, then h must be in Policy.witnesses.
Witness(Hash),
// A Group that requires at least k of its subquorums to pass.
// Invariant: k <= length(members)
// Invariant: if a group is in Policy.quorums, then all its members must be in
// Policy.quorums as well.
Group { k: usize, members: Vec<String> },
}
// Entity is a struct that is used internally to keep track of log/witness keys and URLs.
#[derive(Debug, Eq, PartialEq)]
struct Entity(PublicKey, Option<String>);
#[derive(Debug, Eq, PartialEq, thiserror::Error)]
pub enum PolicyError {
#[error("duplicate log key: {0:x}")]
DuplicateLogKey(PublicKey),
#[error("duplicate witness")]
DuplicateWitnessKey(PublicKey),
#[error("duplicate name")]
DuplicateName(String),
#[error("{0}: no sutch witness")]
UnknownName(String),
#[error("quorum already set")]
QuorumAlreadySet,
}
pub struct PolicyBuilder(Policy);
impl Default for PolicyBuilder {
fn default() -> Self {
Self::new()
}
}
impl PolicyBuilder {
pub fn new() -> Self {
Self(Policy {
logs: HashMap::new(),
witnesses: HashMap::new(),
quorums: HashMap::new(),
quorum: None,
})
}
pub fn add_log(&mut self, key: PublicKey, url: Option<String>) -> Result<(), PolicyError> {
let keyhash = Hash::new(&key);
if self.0.logs.contains_key(&keyhash) {
return Err(PolicyError::DuplicateLogKey(key));
}
self.0.logs.insert(keyhash, Entity(key, url));
Ok(())
}
pub fn add_witness(
&mut self,
name: String,
key: PublicKey,
url: Option<String>,
) -> Result<(), PolicyError> {
let keyhash = Hash::new(&key);
if self.0.witnesses.contains_key(&keyhash) {
return Err(PolicyError::DuplicateWitnessKey(key));
}
if self.0.quorums.contains_key(&name) {
return Err(PolicyError::DuplicateName(name));
}
self.0.witnesses.insert(keyhash.clone(), Entity(key, url));
self.0.quorums.insert(name, Quorum::Witness(keyhash));
Ok(())
}
pub fn add_group(
&mut self,
name: String,
k: usize,
members: Vec<String>,
) -> Result<(), PolicyError> {
if self.0.quorums.contains_key(&name) {
return Err(PolicyError::DuplicateName(name));
}
for name in members.iter() {
if !self.0.quorums.contains_key(name) {
return Err(PolicyError::UnknownName(name.into()));
}
}
self.0.quorums.insert(name, Quorum::Group { k, members });
Ok(())
}
pub fn set_quorum(&mut self, name: String) -> Result<(), PolicyError> {
if self.0.quorum.is_some() {
return Err(PolicyError::QuorumAlreadySet);
}
if !self.0.quorums.contains_key(&name) {
return Err(PolicyError::UnknownName(name));
}
self.0.quorum = Some(name);
Ok(())
}
pub fn build(self) -> Policy {
self.0
}
}
#[cfg(test)]
mod tests {
use hex_literal::hex;
use super::*;
#[test]
fn build_empty_policy() {
let builder = PolicyBuilder::new();
let expected = Policy {
logs: HashMap::new(),
witnesses: HashMap::new(),
quorums: HashMap::new(),
quorum: None,
};
assert_eq!(expected, builder.build());
}
#[test]
fn build_policy() {
let mut builder = PolicyBuilder::new();
builder
.add_log(
hex!("ec5681da2b676ab81df2daea3254cd8c4a5149318a62ae3bec6b4e80504b3b24").into(),
Some(String::from("https://log.example.org")),
)
.unwrap();
builder
.add_log(
hex!("7808644343ae328487d1a9f226c2448af70c9517580217f5a4872f28ee7b94e2").into(),
None,
)
.unwrap();
builder
.add_witness(
String::from("witness01"),
hex!("eb091ebb478efd464c38eaeccd0c20591d187cd461fb71bc0c1077acd2a6dc48").into(),
Some(String::from("https://witness.example.org")),
)
.unwrap();
builder
.add_witness(
String::from("witness02"),
hex!("1f79dd39c4f08fa50236836aa931ab673476a6426eaec3c5927ca92f7c99d0d6").into(),
None,
)
.unwrap();
builder
.add_group(
String::from("mygroup"),
2,
vec![String::from("witness01"), String::from("witness02")],
)
.unwrap();
builder.set_quorum(String::from("mygroup")).unwrap();
let expected = Policy {
logs: HashMap::from([
(
hex!("e919506c3a798f2030f14046e39f03773c12b390e1010c95d2256d0ae594354e").into(),
Entity(
hex!("7808644343ae328487d1a9f226c2448af70c9517580217f5a4872f28ee7b94e2")
.into(),
None,
),
),
(
hex!("d05a4bb520e4699e424b0f7f891746bd176fd0d581a5fdc55cb5c2cb57e3adf2").into(),
Entity(
hex!("ec5681da2b676ab81df2daea3254cd8c4a5149318a62ae3bec6b4e80504b3b24")
.into(),
Some("https://log.example.org".into()),
),
),
]),
witnesses: HashMap::from([
(
hex!("d9440882ae2bd57076d4da2e7a12d4b26e137d56116419a69f8d6969709ed747").into(),
Entity(
hex!("1f79dd39c4f08fa50236836aa931ab673476a6426eaec3c5927ca92f7c99d0d6")
.into(),
None,
),
),
(
hex!("76d1d63740b74b4bb06f0d8c3a5eab35e07481b53df4c086eb3ae6f04f3922aa").into(),
Entity(
hex!("eb091ebb478efd464c38eaeccd0c20591d187cd461fb71bc0c1077acd2a6dc48")
.into(),
Some("https://witness.example.org".into()),
),
),
]),
quorums: HashMap::from([
(
"witness01".into(),
Quorum::Witness(
hex!("76d1d63740b74b4bb06f0d8c3a5eab35e07481b53df4c086eb3ae6f04f3922aa")
.into(),
),
),
(
"witness02".into(),
Quorum::Witness(
hex!("d9440882ae2bd57076d4da2e7a12d4b26e137d56116419a69f8d6969709ed747")
.into(),
),
),
(
"mygroup".into(),
Quorum::Group {
k: 2,
members: vec!["witness01".into(), "witness02".into()],
},
),
]),
quorum: Some("mygroup".into()),
};
assert_eq!(expected, builder.build());
}
#[test]
fn duplicate_log_key() {
let key: PublicKey =
hex!("ec5681da2b676ab81df2daea3254cd8c4a5149318a62ae3bec6b4e80504b3b24").into();
let mut builder = PolicyBuilder::new();
builder.add_log(key.clone(), None).unwrap();
let res = builder.add_log(key.clone(), Some("https://example.org".into()));
assert_eq!(Err(PolicyError::DuplicateLogKey(key)), res);
insta::assert_debug_snapshot!(builder.build());
}
#[test]
fn duplicate_witness_key() {
let key: PublicKey =
hex!("ec5681da2b676ab81df2daea3254cd8c4a5149318a62ae3bec6b4e80504b3b24").into();
let mut builder = PolicyBuilder::new();
builder
.add_witness("mywitness1".into(), key.clone(), None)
.unwrap();
let res = builder.add_witness(
"mywitness2".into(),
key.clone(),
Some("https://example.com".into()),
);
assert_eq!(Err(PolicyError::DuplicateWitnessKey(key)), res);
insta::assert_debug_snapshot!(builder.build());
}
#[test]
fn duplicate_quorum_name() {
let key1: PublicKey =
hex!("ec5681da2b676ab81df2daea3254cd8c4a5149318a62ae3bec6b4e80504b3b24").into();
let key2: PublicKey =
hex!("d9440882ae2bd57076d4da2e7a12d4b26e137d56116419a69f8d6969709ed747").into();
let name: String = "foo".into();
let mut builder = PolicyBuilder::new();
builder.add_witness(name.clone(), key1, None).unwrap();
let res1 = builder.add_group(name.clone(), 1, vec!["foo".into()]);
assert_eq!(Err(PolicyError::DuplicateName(name.clone())), res1);
let res2 = builder.add_witness(name.clone(), key2, None);
assert_eq!(Err(PolicyError::DuplicateName(name)), res2);
insta::assert_debug_snapshot!(builder.build());
}
#[test]
fn uplicate_unknown_member_name() {
let mut builder = PolicyBuilder::new();
let res = builder.add_group("mygroup".into(), 1, vec!["mywitness".into()]);
assert_eq!(Err(PolicyError::UnknownName("mywitness".into())), res);
insta::assert_debug_snapshot!(builder.build());
}
#[test]
fn unknown_quorum_name() {
let mut builder = PolicyBuilder::new();
let res = builder.set_quorum("mywitness".into());
assert_eq!(Err(PolicyError::UnknownName("mywitness".into())), res);
insta::assert_debug_snapshot!(builder.build());
}
#[test]
fn quorum_set_twice() {
let key1: PublicKey =
hex!("ec5681da2b676ab81df2daea3254cd8c4a5149318a62ae3bec6b4e80504b3b24").into();
let key2: PublicKey =
hex!("d9440882ae2bd57076d4da2e7a12d4b26e137d56116419a69f8d6969709ed747").into();
let mut builder = PolicyBuilder::new();
builder
.add_witness("mywitness1".into(), key1, None)
.unwrap();
builder
.add_witness("mywitness2".into(), key2, None)
.unwrap();
builder.set_quorum("mywitness1".into()).unwrap();
let res = builder.set_quorum("mywitness2".into());
assert_eq!(Err(PolicyError::QuorumAlreadySet), res);
assert_eq!(Some("mywitness1".into()), builder.build().quorum);
}
}