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
use crate::TinkError;
pub fn validate_key_version(version: u32, max_expected: u32) -> Result<(), TinkError> {
if version > max_expected {
Err(format!(
"key has version {}; only keys with version in range [0..{}] are supported",
version, max_expected
)
.into())
} else {
Ok(())
}
}
pub fn validate(keyset: &tink_proto::Keyset) -> Result<(), TinkError> {
if keyset.key.is_empty() {
return Err("empty keyset".into());
}
let primary_key_id = keyset.primary_key_id;
let mut has_primary_key = false;
let mut contains_only_pub = true;
let mut num_enabled_keys = 0;
for key in &keyset.key {
validate_key(&key)?;
if key.status != tink_proto::KeyStatusType::Enabled as i32 {
continue;
}
if key.key_id == primary_key_id {
if has_primary_key {
return Err("keyset contains multiple primary keys".into());
}
has_primary_key = true;
}
if let Some(key_data) = &key.key_data {
if key_data.key_material_type
!= tink_proto::key_data::KeyMaterialType::AsymmetricPublic as i32
{
contains_only_pub = false;
}
}
num_enabled_keys += 1;
}
if num_enabled_keys == 0 {
Err("keyset must contain at least one ENABLED key".into())
} else if !has_primary_key && !contains_only_pub {
Err("keyset does not contain a valid primary key".into())
} else {
Ok(())
}
}
pub fn validate_key(key: &tink_proto::keyset::Key) -> Result<(), TinkError> {
if key.key_id == 0 {
Err(format!("key has zero key id: {}", key.key_id).into())
} else if key.key_data.is_none() {
Err(format!("key {} has no key data", key.key_id).into())
} else if key.output_prefix_type != tink_proto::OutputPrefixType::Tink as i32
&& key.output_prefix_type != tink_proto::OutputPrefixType::Legacy as i32
&& key.output_prefix_type != tink_proto::OutputPrefixType::Raw as i32
&& key.output_prefix_type != tink_proto::OutputPrefixType::Crunchy as i32
{
Err(format!("key {} has unknown prefix", key.key_id).into())
} else if key.status != tink_proto::KeyStatusType::Enabled as i32
&& key.status != tink_proto::KeyStatusType::Disabled as i32
&& key.status != tink_proto::KeyStatusType::Destroyed as i32
{
Err(format!("key {} has unknown status", key.key_id).into())
} else {
Ok(())
}
}