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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Deterministic canonical software identity.
//!
//! One observation maps to at most one identity:
//!
//! ```text
//! identity = (class, canonical_vendor, canonical_family)
//! slug = truncate64(join(canonical_vendor, canonical_family, '-'))
//! ```
//!
//! The CPE `part` is deliberately excluded from the identity key so the same
//! product observed as `a` and `o` (or as `Red Hat Enterprise Linux 8` text
//! and `cpe:2.3:o:redhat:enterprise_linux:8.0`) collapses to one project.
//! Merges are driven only by curated aliases in
//! `data/identity/aliases.json`; there is no fuzzy matching and no dependence
//! on input or batch order.
pub mod aliases;
pub mod cve_refs;
pub mod observe;
use std::collections::{BTreeMap, BTreeSet};
use data_encoding::HEXLOWER;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
pub use observe::{Cpe, observations_from_cve, parse_cpe};
/// Classification of a canonical identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IdentityClass {
Os,
App,
Hardware,
Firmware,
}
impl IdentityClass {
pub fn as_str(self) -> &'static str {
match self {
Self::Os => "os",
Self::App => "app",
Self::Hardware => "hardware",
Self::Firmware => "firmware",
}
}
}
/// One observation of a product from an upstream source.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct ObservedProduct {
pub source: String,
pub part: Option<String>,
pub vendor: String,
pub product: String,
pub version: Option<String>,
pub update: Option<String>,
pub edition: Option<String>,
pub target_sw: Option<String>,
pub target_hw: Option<String>,
pub ranges: Vec<VersionRange>,
pub cpes: Vec<String>,
pub purls: Vec<String>,
}
/// Version range endpoints carried through from NVD CPE matches.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct VersionRange {
pub start_including: Option<String>,
pub start_excluding: Option<String>,
pub end_including: Option<String>,
pub end_excluding: Option<String>,
}
/// Canonical project identity plus the optional channel/version reference.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct CanonicalIdentity {
pub class: IdentityClass,
pub canonical_vendor: String,
pub canonical_family: String,
pub slug: String,
pub identity_key: String,
pub channel: Option<String>,
pub version: Option<String>,
}
/// Edition/stream tokens that become channel suffixes.
const EDITION_TOKENS: &[&str] = &[
"eus",
"aus",
"tus",
"sap",
"els",
"rt",
"nfv",
"av",
"crb",
"desktop",
"workstation",
"hpc",
];
/// Architecture tokens that become channel suffixes. `x86_64` is the default
/// and is intentionally absent.
const ARCH_TOKENS: &[&str] = &["aarch64", "ppc64le", "ppc64", "s390x"];
/// Lowercase ASCII token: CPE-unescaped, non-alphanumerics collapsed to `-`.
pub fn normalize_token(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
let mut pending_dash = false;
let mut chars = raw.chars();
while let Some(ch) = chars.next() {
let ch = if ch == '\\' {
chars.next().unwrap_or(ch)
} else {
ch
};
if ch.is_ascii_alphanumeric() {
if pending_dash && !out.is_empty() {
out.push('-');
}
pending_dash = false;
out.push(ch.to_ascii_lowercase());
} else {
pending_dash = true;
}
}
out
}
/// Join vendor and family into a slug without repeating a vendor prefix, and
/// truncate at a hyphen boundary to 64 characters.
pub fn canonical_slug(vendor: &str, family: &str) -> String {
let vendor = normalize_token(vendor);
let family = normalize_token(family);
let raw = if vendor.is_empty() || family == vendor || family.starts_with(&format!("{vendor}-"))
{
family
} else {
format!("{vendor}-{family}")
};
truncate64(raw.trim_matches('-'))
}
/// Truncate to at most 64 characters at a hyphen boundary.
pub fn truncate64(input: &str) -> String {
truncate_at(input, 64)
}
fn truncate_at(input: &str, max: usize) -> String {
let chars: Vec<char> = input.chars().collect();
if chars.len() <= max {
return input.to_owned();
}
let mut cut = max;
if chars.get(max) != Some(&'-')
&& let Some(position) = chars[..max].iter().rposition(|ch| *ch == '-')
&& position > 0
{
cut = position;
}
chars[..cut]
.iter()
.collect::<String>()
.trim_matches('-')
.to_owned()
}
/// Split a version into a channel and an optional immutable version reference.
///
/// NVD uses `X` and single-digit `X.0` as major sentinels: those produce only
/// a channel. `X.Y` preserves the full version under channel `X`. Multi-digit
/// `X.0` values (for example RHEL `10.0`, Keycloak `26.0`) are real versions,
/// not sentinels. `ponytail:` single-digit heuristic; extend with a curated
/// sentinel policy if NVD starts emitting multi-digit sentinels.
pub fn split_channel_version(version: &str) -> (Option<String>, Option<String>) {
let version = version.trim();
if version.is_empty() {
return (None, None);
}
let parts: Vec<&str> = version.split('.').collect();
let numeric = parts
.iter()
.all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()));
if !numeric {
return (None, Some(version.to_owned()));
}
let major = parts[0].to_owned();
if parts.len() == 1 {
return (Some(major), None);
}
if parts.len() == 2 && parts[1] == "0" && major.len() == 1 {
return (Some(major), None);
}
(Some(major), Some(version.to_owned()))
}
fn is_absent(token: &str) -> bool {
token.is_empty() || matches!(token, "n-a" | "any" | "unknown")
}
fn clean_version(raw: &str) -> Option<String> {
let trimmed = raw.trim();
if trimmed.is_empty() || is_absent(&normalize_token(trimmed)) {
None
} else {
Some(trimmed.to_owned())
}
}
fn matches_prefix(product: &str, alias: &str) -> bool {
product == alias
|| product
.strip_prefix(alias)
.is_some_and(|rest| rest.starts_with('-'))
}
/// Find the longest curated alias matching `product`, returning the canonical
/// family and the unconsumed suffix.
fn match_alias(product: &str, table: &aliases::AliasTable) -> Option<(String, String)> {
let mut best: Option<(&str, &str)> = None;
for (alias, family) in &table.products {
if matches_prefix(product, alias) && is_better(alias, best) {
best = Some((alias, family));
}
}
for family in table.families.keys() {
if matches_prefix(product, family) && is_better(family, best) {
best = Some((family, family));
}
}
best.map(|(alias, family)| {
(
family.to_owned(),
product[alias.len()..].trim_start_matches('-').to_owned(),
)
})
}
fn is_better(alias: &str, best: Option<(&str, &str)>) -> bool {
best.is_none_or(|(current, _)| alias.len() > current.len())
}
fn strip_prefix<'a>(product: &'a str, vendor: &str) -> Option<&'a str> {
product
.strip_prefix(vendor)
.and_then(|rest| rest.strip_prefix('-'))
}
/// Split leading numeric tokens into a dotted version; remaining tokens are
/// stream/edition candidates.
fn split_trailing_version(trailing: &str) -> (Option<String>, Vec<String>) {
let tokens: Vec<&str> = trailing
.split('-')
.filter(|token| !token.is_empty())
.collect();
let version_end = tokens
.iter()
.position(|token| !token.bytes().all(|byte| byte.is_ascii_digit()))
.unwrap_or(tokens.len());
let version = if version_end == 0 {
None
} else {
Some(tokens[..version_end].join("."))
};
let rest = tokens[version_end..]
.iter()
.map(|token| (*token).to_owned())
.collect();
(version, rest)
}
fn add_variant(variants: &mut BTreeSet<String>, token: &str) {
if EDITION_TOKENS.contains(&token) || ARCH_TOKENS.contains(&token) {
variants.insert(token.to_owned());
}
}
/// Add every curated edition/arch token found in a normalized value.
fn add_variants_from(variants: &mut BTreeSet<String>, value: &str) {
let token = normalize_token(value);
for part in token.split('-').filter(|part| !part.is_empty()) {
add_variant(variants, part);
}
}
fn split_for_family(family: &str, version: &str) -> (Option<String>, Option<String>) {
if family == "ubuntu" && version.contains('.') {
return (Some(version.replace('.', "-")), Some(version.to_owned()));
}
split_channel_version(version)
}
fn identity_class(family: &str, part: Option<&str>, table: &aliases::AliasTable) -> IdentityClass {
if let Some(class) = table.class_overrides.get(family) {
return *class;
}
match part {
Some("o") => IdentityClass::Os,
Some("h") => IdentityClass::Hardware,
_ => IdentityClass::App,
}
}
/// Canonicalize one observation. Returns `None` for placeholder identities
/// (`n/a`, `any`, `unknown`, `*`, `-`).
///
/// Collision suffixes are batch-level and applied by [`canonicalize_all`];
/// this function always returns the base slug.
pub fn canonicalize(observed: &ObservedProduct) -> Option<CanonicalIdentity> {
let table = aliases::aliases();
let vendor_raw = normalize_token(&observed.vendor);
let product_raw = normalize_token(&observed.product);
if is_absent(&vendor_raw) || is_absent(&product_raw) {
return None;
}
let canonical_vendor = table
.vendors
.get(&vendor_raw)
.cloned()
.unwrap_or_else(|| vendor_raw.clone());
if is_absent(&canonical_vendor) {
return None;
}
// Try the full product first so products that legitimately repeat the
// vendor (for example `centos-stream`) keep their longer curated alias.
// Only a prefix strip that reaches a curated alias counts, so
// `Canonical` + `Ubuntu Linux` cannot become `linux`.
let mut search = product_raw.clone();
let mut matched = match_alias(&search, table);
if matched.is_none() {
for vendor in [&vendor_raw, &canonical_vendor] {
let Some(stripped) = strip_prefix(&product_raw, vendor) else {
continue;
};
if stripped == search {
continue;
}
if let Some(found) = match_alias(stripped, table) {
search = stripped.to_owned();
matched = Some(found);
break;
}
}
}
// A redundant vendor prefix is stripped even when no curated alias
// matches, so the same product observed with `redhat`, `red-hat`, or
// `Red Hat` keeps one identity key.
let (canonical_family, trailing) = match matched {
Some((family, trailing)) => (family, trailing),
None => (
strip_prefix(&product_raw, &vendor_raw)
.or_else(|| strip_prefix(&product_raw, &canonical_vendor))
.unwrap_or(&product_raw)
.to_owned(),
String::new(),
),
};
if is_absent(&canonical_family) {
return None;
}
let versioned = table.versioned_families.contains(&canonical_family);
let (trailing_version, trailing_tokens) = if versioned {
split_trailing_version(&trailing)
} else {
(None, Vec::new())
};
let explicit_version = observed.version.as_deref().and_then(clean_version);
let (mut channel, version) = match explicit_version.or(trailing_version) {
Some(version) => split_for_family(&canonical_family, &version),
None => (None, None),
};
let mut variants = BTreeSet::new();
for value in [
observed.edition.as_deref(),
observed.update.as_deref(),
observed.target_hw.as_deref(),
]
.into_iter()
.flatten()
{
add_variants_from(&mut variants, value);
}
if versioned {
for token in trailing_tokens {
add_variant(&mut variants, &token);
}
for token in search.split('-') {
add_variant(&mut variants, token);
}
}
if !variants.is_empty() {
let suffix = variants.into_iter().collect::<Vec<_>>().join("-");
channel = Some(match channel {
Some(channel) => format!("{channel}-{suffix}"),
None => suffix,
});
}
let class = identity_class(&canonical_family, observed.part.as_deref(), table);
let slug = canonical_slug(&canonical_vendor, &canonical_family);
let identity_key = format!(
"{}:{}:{}",
class.as_str(),
canonical_vendor,
canonical_family
);
Some(CanonicalIdentity {
class,
canonical_vendor,
canonical_family,
slug,
identity_key,
channel,
version,
})
}
/// Identity key (`class:vendor:family`) for one observation without resolving
/// the display slug or batch-level collision suffixes. One product has exactly
/// one key across all of its channels and versions.
pub fn identity_key_for(observed: &ObservedProduct) -> Option<String> {
canonicalize(observed).map(|identity| identity.identity_key)
}
fn is_curated(table: &aliases::AliasTable, identity_key: &str) -> bool {
identity_key
.splitn(3, ':')
.nth(2)
.is_some_and(|family| table.families.contains_key(family))
}
fn suffixed_slug(base: &str, identity_key: &str) -> String {
let prefix = truncate_at(base, 57);
let prefix = prefix.trim_matches('-');
let digest = Sha256::digest(identity_key.as_bytes());
let hash = HEXLOWER.encode(&digest[..3]);
if prefix.is_empty() {
hash
} else {
format!("{prefix}-{hash}")
}
}
/// Canonicalize a batch and resolve slug collisions deterministically.
///
/// Curated families own their base slug; otherwise the lexicographically
/// smallest identity key owns it and every other identity gets a stable
/// `-<sha256(identity_key)[:6]>` suffix. Results are deduplicated and sorted,
/// so input order never changes the output.
pub fn canonicalize_all(observations: &[ObservedProduct]) -> Vec<CanonicalIdentity> {
let table = aliases::aliases();
let identities: BTreeSet<CanonicalIdentity> =
observations.iter().filter_map(canonicalize).collect();
let mut keys_by_slug: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for identity in &identities {
keys_by_slug
.entry(identity.slug.clone())
.or_default()
.insert(identity.identity_key.clone());
}
let mut slug_for_key: BTreeMap<String, String> = BTreeMap::new();
for (slug, keys) in &keys_by_slug {
if keys.len() == 1 {
if let Some(key) = keys.first() {
slug_for_key.insert(key.clone(), slug.clone());
}
continue;
}
let owner = keys
.iter()
.find(|key| is_curated(table, key))
.or_else(|| keys.first())
.expect("keys_by_slug groups are non-empty");
for key in keys {
let assigned = if key == owner {
slug.clone()
} else {
suffixed_slug(slug, key)
};
slug_for_key.insert(key.clone(), assigned);
}
}
let mut result: Vec<CanonicalIdentity> = identities
.into_iter()
.map(|mut identity| {
if let Some(slug) = slug_for_key.get(&identity.identity_key) {
identity.slug = slug.clone();
}
identity
})
.collect();
result.sort();
result
}