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
//! Curated identity aliases, embedded at compile time.
//!
//! The table is the only supported merge mechanism: editing
//! `data/identity/aliases.json` is reviewable, while fuzzy matching is not.
//! Embedded data is validated when first used; invalid data panics with a
//! clear message naming every problem.
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::marker::PhantomData;
use std::sync::LazyLock;
use serde::Deserialize;
use serde::de::{self, Deserializer, MapAccess, Visitor};
use super::IdentityClass;
use super::normalize_token;
/// Deserialize a set while rejecting duplicate entries.
fn unique_set<'de, D>(deserializer: D) -> Result<BTreeSet<String>, D::Error>
where
D: Deserializer<'de>,
{
struct UniqueSetVisitor;
impl<'de> Visitor<'de> for UniqueSetVisitor {
type Value = BTreeSet<String>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("an array of unique strings")
}
fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
where
A: de::SeqAccess<'de>,
{
let mut set = BTreeSet::new();
while let Some(entry) = access.next_element::<String>()? {
if !set.insert(entry.clone()) {
return Err(de::Error::custom(format!("duplicate entry `{entry}`")));
}
}
Ok(set)
}
}
deserializer.deserialize_seq(UniqueSetVisitor)
}
/// Deserialize a map while rejecting duplicate keys.
fn unique_map<'de, D, V>(deserializer: D) -> Result<BTreeMap<String, V>, D::Error>
where
D: Deserializer<'de>,
V: Deserialize<'de>,
{
struct UniqueMapVisitor<V>(PhantomData<V>);
impl<'de, V: Deserialize<'de>> Visitor<'de> for UniqueMapVisitor<V> {
type Value = BTreeMap<String, V>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a map with unique string keys")
}
fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry::<String, V>()? {
if map.insert(key.clone(), value).is_some() {
return Err(de::Error::custom(format!("duplicate key `{key}`")));
}
}
Ok(map)
}
}
deserializer.deserialize_map(UniqueMapVisitor(PhantomData))
}
/// Curated alias and class data used by canonicalization.
#[derive(Debug, Clone, Deserialize)]
pub struct AliasTable {
/// Raw normalized vendor token -> canonical vendor.
#[serde(deserialize_with = "unique_map")]
pub vendors: BTreeMap<String, String>,
/// Normalized product prefix -> canonical family. An entry matches the
/// product exactly or a `-`-separated prefix of it.
#[serde(deserialize_with = "unique_map")]
pub products: BTreeMap<String, String>,
/// Curated canonical family -> canonical vendor. Curated families own
/// their base slug during collision resolution.
#[serde(deserialize_with = "unique_map")]
pub families: BTreeMap<String, String>,
/// Families whose trailing text may be a stream/version.
#[serde(deserialize_with = "unique_set")]
pub versioned_families: BTreeSet<String>,
/// Canonical family -> forced identity class.
#[serde(deserialize_with = "unique_map")]
pub class_overrides: BTreeMap<String, IdentityClass>,
}
impl AliasTable {
/// Validate the table invariants. Returns every problem found so a loader
/// can report all of them at once.
pub fn validate(&self) -> Result<(), Vec<String>> {
validate_table(self)
}
/// Deserialize and validate a table. The error is a single line suitable
/// for a panic message; [`load`] panics with it for the embedded table.
pub fn from_json(raw: &str) -> Result<Self, String> {
let table: Self = serde_json::from_str(raw).map_err(|error| error.to_string())?;
table.validate().map_err(|errors| errors.join("; "))?;
Ok(table)
}
}
static ALIASES: LazyLock<AliasTable> = LazyLock::new(load);
fn load() -> AliasTable {
let raw = include_str!("../../data/identity/aliases.json");
AliasTable::from_json(raw)
.unwrap_or_else(|error| panic!("invalid embedded identity aliases: {error}"))
}
/// Validated alias table.
pub fn aliases() -> &'static AliasTable {
&ALIASES
}
fn is_normalized(token: &str) -> bool {
!token.is_empty() && normalize_token(token) == token
}
fn validate_table(table: &AliasTable) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
for (name, map) in [
("vendors", &table.vendors),
("products", &table.products),
("families", &table.families),
] {
if map.is_empty() {
errors.push(format!("{name} must not be empty"));
}
for (key, value) in map {
if !is_normalized(key) {
errors.push(format!("{name} key `{key}` is not normalized"));
}
if !is_normalized(value) {
errors.push(format!(
"{name} value `{value}` for `{key}` is not normalized"
));
}
}
}
if table.versioned_families.is_empty() {
errors.push("versioned_families must not be empty".to_owned());
}
for family in &table.versioned_families {
if !is_normalized(family) {
errors.push(format!("versioned family `{family}` is not normalized"));
}
if !table.families.contains_key(family) {
errors.push(format!("versioned family `{family}` is not in families"));
}
}
if table.class_overrides.is_empty() {
errors.push("class_overrides must not be empty".to_owned());
}
for family in table.class_overrides.keys() {
if !is_normalized(family) {
errors.push(format!("class override `{family}` is not normalized"));
}
}
for (alias, family) in &table.products {
if !table.families.contains_key(family) {
errors.push(format!(
"product alias `{alias}` points at unknown family `{family}`"
));
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_table_is_valid_and_covers_plan_aliases() {
let table = aliases();
assert_eq!(
table.vendors.get("redhat").map(String::as_str),
Some("red-hat")
);
assert_eq!(
table.vendors.get("red-hat").map(String::as_str),
Some("red-hat")
);
assert_eq!(
table.vendors.get("fedoraproject").map(String::as_str),
Some("fedora")
);
assert_eq!(
table.vendors.get("gleam").map(String::as_str),
Some("gleam-lang")
);
assert_eq!(table.vendors.get("ni").map(String::as_str), Some("ni"));
assert_eq!(
table.vendors.get("avb-disc-soft").map(String::as_str),
Some("disc-soft")
);
assert_eq!(
table.vendors.get("arm").map(String::as_str),
Some("trustedfirmware")
);
assert_eq!(
table.class_overrides.get("red-hat-enterprise-linux"),
Some(&IdentityClass::Os)
);
assert!(table.families.contains_key("red-hat-enterprise-linux"));
assert!(
table
.versioned_families
.contains("red-hat-enterprise-linux")
);
}
const MINIMAL_TABLE: &str = r#"{
"vendors": {"acme": "acme"},
"products": {"widget": "widget"},
"families": {"widget": "acme"},
"versioned_families": ["widget"],
"class_overrides": {"widget": "app"}
}"#;
fn load_strict(raw: &str) -> AliasTable {
AliasTable::from_json(raw)
.unwrap_or_else(|error| panic!("invalid embedded identity aliases: {error}"))
}
#[test]
fn minimal_table_is_valid() {
let table = load_strict(MINIMAL_TABLE);
assert_eq!(table.vendors.get("acme").map(String::as_str), Some("acme"));
assert_eq!(table.validate(), Ok(()));
}
#[test]
#[should_panic(expected = "duplicate key")]
fn duplicate_alias_key_panics() {
load_strict(
r#"{
"vendors": {"acme": "acme", "acme": "acme"},
"products": {"widget": "widget"},
"families": {"widget": "acme"},
"versioned_families": ["widget"],
"class_overrides": {"widget": "app"}
}"#,
);
}
#[test]
#[should_panic(expected = "not normalized")]
fn invalid_alias_key_panics() {
load_strict(
r#"{
"vendors": {"Acme Inc": "acme"},
"products": {"widget": "widget"},
"families": {"widget": "acme"},
"versioned_families": ["widget"],
"class_overrides": {"widget": "app"}
}"#,
);
}
#[test]
#[should_panic(expected = "duplicate entry")]
fn duplicate_versioned_family_panics() {
load_strict(
r#"{
"vendors": {"acme": "acme"},
"products": {"widget": "widget"},
"families": {"widget": "acme"},
"versioned_families": ["widget", "widget"],
"class_overrides": {"widget": "app"}
}"#,
);
}
}