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
//! Canonical atprotoV1 software refs with channel/version strongRefs.
//!
//! Refs are grouped by canonical project slug. Raw `part`, `vendor`,
//! `product`, `cpes`, and `purls` from existing refs are preserved and merged;
//! `channels`, `versions`, and `manifests` point only at records already
//! present in [`ResolvedProject`]. A version without a resolved record becomes
//! a `versionLabels` entry, and range-only observations keep their
//! `affectedRanges`. URIs are never fabricated and every emitted URI must
//! share the repository DID.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use crate::constants::{ATPROTO_TYPE, PROJECT_COLLECTION};
use crate::identity::{CanonicalIdentity, IdentityClass, ObservedProduct, canonicalize};
/// atproto strong reference.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct StrongRef {
pub uri: String,
pub cid: String,
}
/// Records already present for one canonical project.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedProject {
pub project: StrongRef,
#[serde(default)]
pub channels: BTreeMap<String, StrongRef>,
#[serde(default)]
pub versions: BTreeMap<String, StrongRef>,
#[serde(default)]
pub manifests: BTreeMap<String, StrongRef>,
}
/// Merged material for one canonical project slug.
#[derive(Debug, Default)]
struct RefGroup {
raw: Option<(String, String, String)>,
cpes: BTreeSet<String>,
purls: BTreeSet<String>,
channels: BTreeSet<String>,
versions: BTreeSet<String>,
ranges: BTreeSet<String>,
fallback_project: Option<StrongRef>,
}
fn strings(value: &Value, key: &str) -> Vec<String> {
value
.get(key)
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect()
}
/// Split `at://<did>/<collection>/<rkey>` into its three components.
fn at_uri_parts(uri: &str) -> Option<(&str, &str, &str)> {
let rest = uri.strip_prefix("at://")?;
let (did, path) = rest.split_once('/')?;
let (collection, rkey) = path.split_once('/')?;
if did.is_empty() || collection.is_empty() || rkey.is_empty() || rkey.contains('/') {
return None;
}
Some((did, collection, rkey))
}
fn assert_same_did(uri: &str, repo_did: &str) {
let did = at_uri_parts(uri)
.map(|(did, _, _)| did)
.unwrap_or_else(|| panic!("not an at-uri: {uri}"));
assert_eq!(
did, repo_did,
"cross-DID ref {uri}: every ref must start with at://{repo_did}/"
);
}
/// Existing canonical project strongRef for `slug`, if the raw record has one.
/// Legacy project rkeys are rejected here rather than remapped.
fn existing_project_ref(value: &Value, slug: &str) -> Option<StrongRef> {
let project = value.get("project")?;
let uri = project.get("uri")?.as_str()?;
let cid = project.get("cid")?.as_str()?;
let (_, collection, rkey) = at_uri_parts(uri)?;
(collection == PROJECT_COLLECTION && rkey == slug && !cid.is_empty()).then(|| StrongRef {
uri: uri.to_owned(),
cid: cid.to_owned(),
})
}
fn observation_from_ref(value: &Value) -> Option<ObservedProduct> {
let vendor = value.get("vendor")?.as_str()?.trim();
let product = value.get("product")?.as_str()?.trim();
if vendor.is_empty() || product.is_empty() {
return None;
}
Some(ObservedProduct {
part: value.get("part").and_then(Value::as_str).map(str::to_owned),
vendor: vendor.to_owned(),
product: product.to_owned(),
cpes: strings(value, "cpes"),
purls: strings(value, "purls"),
..ObservedProduct::default()
})
}
fn part_for_class(class: IdentityClass) -> &'static str {
match class {
IdentityClass::Os | IdentityClass::Firmware => "o",
IdentityClass::Hardware => "h",
IdentityClass::App => "a",
}
}
/// Repository DID shared by every resolved project. A mixed-DID map is a
/// cross-DID violation.
fn resolved_repo_did(resolved: &BTreeMap<String, ResolvedProject>) -> Option<String> {
let mut repo_did: Option<String> = None;
for (slug, resolved_project) in resolved {
let (did, collection, rkey) =
at_uri_parts(&resolved_project.project.uri).unwrap_or_else(|| {
panic!(
"resolved project for {slug} is not an at-uri: {}",
resolved_project.project.uri
)
});
assert_eq!(
collection, PROJECT_COLLECTION,
"resolved project for {slug} is not a {PROJECT_COLLECTION} record"
);
assert_eq!(
rkey, slug,
"resolved project ref {} is not canonical for {slug}",
resolved_project.project.uri
);
match &repo_did {
None => repo_did = Some(did.to_owned()),
Some(expected) => assert_eq!(
expected, did,
"cross-DID resolved project for {slug}: {}",
resolved_project.project.uri
),
}
}
repo_did
}
/// Build canonical atprotoV1 software refs, one per canonical project slug.
///
/// `identities` supply the affected channels and versions, `existing` supplies
/// raw alias fields and CPE/PURL sets, and `resolved` supplies only strongRefs
/// that actually exist. Output order, array order, and dedupe are independent
/// of input order.
///
/// # Panics
///
/// Panics when a resolved or emitted URI is not an `at://` URI or belongs to a
/// different repository DID than the resolved projects.
pub fn build_software_refs(
existing: &[Value],
identities: &[CanonicalIdentity],
resolved: &BTreeMap<String, ResolvedProject>,
) -> Vec<Value> {
let mut slug_for_key: BTreeMap<String, String> = BTreeMap::new();
for identity in identities {
if let Some(previous) =
slug_for_key.insert(identity.identity_key.clone(), identity.slug.clone())
{
assert_eq!(
previous, identity.slug,
"identity key {} maps to multiple slugs",
identity.identity_key
);
}
}
let mut groups: BTreeMap<String, RefGroup> = BTreeMap::new();
let mut fallback_identity: BTreeMap<String, CanonicalIdentity> = BTreeMap::new();
for identity in identities {
let group = groups.entry(identity.slug.clone()).or_default();
if let Some(channel) = &identity.channel {
group.channels.insert(channel.clone());
}
if let Some(version) = &identity.version {
group.versions.insert(version.clone());
}
let replace = fallback_identity
.get(&identity.slug)
.is_none_or(|current| identity < current);
if replace {
fallback_identity.insert(identity.slug.clone(), identity.clone());
}
}
for value in existing {
let Some(observed) = observation_from_ref(value) else {
continue;
};
let Some(identity) = canonicalize(&observed) else {
continue;
};
let slug = slug_for_key
.get(&identity.identity_key)
.cloned()
.unwrap_or_else(|| identity.slug.clone());
let group = groups.entry(slug.clone()).or_default();
group.cpes.extend(strings(value, "cpes"));
group.purls.extend(strings(value, "purls"));
group.ranges.extend(strings(value, "affectedRanges"));
let candidate = (
value
.get("part")
.and_then(Value::as_str)
.map(str::to_owned)
.unwrap_or_else(|| part_for_class(identity.class).to_owned()),
value
.get("vendor")
.and_then(Value::as_str)
.unwrap_or_default()
.trim()
.to_owned(),
value
.get("product")
.and_then(Value::as_str)
.unwrap_or_default()
.trim()
.to_owned(),
);
let replace_raw = match &group.raw {
None => true,
Some(current) => candidate < *current,
};
if replace_raw {
group.raw = Some(candidate);
}
if let Some(project) = existing_project_ref(value, &slug) {
let replace_project = match &group.fallback_project {
None => true,
Some(current) => project < *current,
};
if replace_project {
group.fallback_project = Some(project);
}
}
fallback_identity.entry(slug).or_insert(identity);
}
let mut repo_did = resolved_repo_did(resolved);
let mut refs = Vec::with_capacity(groups.len());
for (slug, group) in groups {
let resolved_project = resolved.get(&slug);
let Some(project) = resolved_project
.map(|resolved_project| resolved_project.project.clone())
.or(group.fallback_project.clone())
else {
// No canonical project record exists; never fabricate a URI and
// never emit a legacy project ref.
continue;
};
match &repo_did {
Some(expected) => assert_same_did(&project.uri, expected),
None => {
repo_did = Some(
at_uri_parts(&project.uri)
.map(|(did, _, _)| did.to_owned())
.unwrap_or_else(|| panic!("not an at-uri: {}", project.uri)),
);
}
}
let repo_did = repo_did.as_deref().expect("repo did set above");
assert_same_did(&project.uri, repo_did);
let mut record = Map::new();
record.insert("project".to_owned(), json!(project));
let (part, vendor, product) = match group.raw {
Some(raw) => raw,
None => {
let identity = fallback_identity
.get(&slug)
.unwrap_or_else(|| panic!("no raw fields or identity for project {slug}"));
(
part_for_class(identity.class).to_owned(),
identity.canonical_vendor.clone(),
identity.canonical_family.clone(),
)
}
};
record.insert("part".to_owned(), json!(part));
record.insert("vendor".to_owned(), json!(vendor));
record.insert("product".to_owned(), json!(product));
if !group.cpes.is_empty() {
record.insert(
"cpes".to_owned(),
json!(group.cpes.into_iter().collect::<Vec<_>>()),
);
}
if !group.purls.is_empty() {
record.insert(
"purls".to_owned(),
json!(group.purls.into_iter().collect::<Vec<_>>()),
);
}
let mut channels = Vec::new();
if let Some(resolved_project) = resolved_project {
for name in &group.channels {
if let Some(reference) = resolved_project.channels.get(name) {
assert_same_did(&reference.uri, repo_did);
channels.push(json!(reference));
}
}
}
if !channels.is_empty() {
record.insert("channels".to_owned(), Value::Array(channels));
}
let mut versions = Vec::new();
let mut manifests = Vec::new();
let mut labels = BTreeSet::new();
for name in &group.versions {
match resolved_project.and_then(|resolved_project| resolved_project.versions.get(name))
{
Some(reference) => {
assert_same_did(&reference.uri, repo_did);
versions.push(json!(reference));
if let Some(manifest) = resolved_project
.and_then(|resolved_project| resolved_project.manifests.get(name))
{
assert_same_did(&manifest.uri, repo_did);
manifests.push(json!(manifest));
}
}
None => {
labels.insert(name.clone());
}
}
}
let has_versions = !versions.is_empty();
if has_versions {
record.insert("versions".to_owned(), Value::Array(versions));
}
if !manifests.is_empty() {
record.insert("manifests".to_owned(), Value::Array(manifests));
}
if !labels.is_empty() {
record.insert(
"versionLabels".to_owned(),
json!(labels.into_iter().collect::<Vec<_>>()),
);
}
if !has_versions && !group.ranges.is_empty() {
record.insert(
"affectedRanges".to_owned(),
json!(group.ranges.into_iter().collect::<Vec<_>>()),
);
}
refs.push(Value::Object(record));
}
refs
}
/// Build a complete `com.nahdig.cve.atprotoV1` record.
///
/// `$type` and `createdAt` are taken from `existing` when present; otherwise
/// the provided defaults are used. `cve`, `nvd`, and `software` are replaced.
pub fn build_cve_record(
existing: &Value,
cve_id: &str,
nvd: &StrongRef,
software: &[Value],
created_at: &str,
) -> Value {
let record_type = existing
.get("$type")
.and_then(Value::as_str)
.unwrap_or(ATPROTO_TYPE);
let created = existing
.get("createdAt")
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.unwrap_or(created_at);
json!({
"$type": record_type,
"createdAt": created,
"cve": cve_id,
"nvd": nvd,
"software": software,
})
}