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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! `plan`: inventory the cache and repository and emit a reviewable map.
//!
//! The local cache is read read-only: the service's [`DbHandle`] exposes point
//! lookups only, so bulk inventory uses a read-only SQLite connection to the
//! same file. Nothing is written to the cache or the PDS.
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use anyhow::{Context, Result};
use rusqlite::{Connection, OpenFlags};
use serde_json::Value;
use super::remap::{LegacyReleaseKind, RemapMap, StrongRef, legacy_release_records, project_ref};
use super::{
ALL_COLLECTIONS, MigrationAction, MigrationEntry, MigrationPlan, RemoteInventory, RemoteRecord,
project_uri, slug_of_project_uri, split_uri,
};
use crate::constants::{
ATPROTO_COLLECTION, CHANNEL_COLLECTION, MANIFEST_COLLECTION, PROJECT_COLLECTION,
PURL_COLLECTION, SOFTWARE_COLLECTION, STATUS_COLLECTION, VERSION_COLLECTION,
};
use crate::db::purl2cpe::{cpe_product_key, load_purl_map, versionless_purl};
use crate::identity::{
ObservedProduct, aliases, canonical_slug, canonicalize, canonicalize_all, observations_from_cve,
};
use crate::pds::Publisher;
/// Legacy `vendor-product` slug exactly as pre-identity `software.rs` produced it.
///
/// The migration must match rows already present in old caches, so this keeps
/// the old rules (lowercase ASCII, non-alphanumeric runs to `-`, 64-char cap,
/// part as empty fallback) even though the live sync path no longer uses them.
fn slugify(part: &str, vendor: &str, product: &str) -> String {
let mut raw = String::new();
let mut pending_dash = false;
for ch in format!("{vendor}-{product}").to_lowercase().chars() {
if ch.is_ascii_alphanumeric() {
raw.push(ch);
pending_dash = false;
} else if !pending_dash && !raw.is_empty() {
raw.push('-');
pending_dash = true;
}
}
let mut raw = raw.trim_matches('-').to_owned();
if raw.is_empty() {
raw = part.to_owned();
}
let mut slug: String = raw.chars().take(64).collect();
slug = slug.trim_matches('-').to_owned();
if slug.is_empty() {
"software".to_owned()
} else {
slug
}
}
/// One cached software row (`software` table).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LocalSoftwareRow {
pub slug: String,
pub part: Option<String>,
pub vendor: Option<String>,
pub product: Option<String>,
}
/// One cached PURL row (`software_purls` table).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LocalPurlRow {
pub purl: String,
pub software_slug: String,
}
/// Cached CVE JSON plus its id.
#[derive(Debug, Clone, PartialEq)]
pub struct LocalCve {
pub id: String,
pub value: Value,
}
#[derive(Debug, Clone, Default)]
pub struct LocalInventory {
pub software: Vec<LocalSoftwareRow>,
pub purls: Vec<LocalPurlRow>,
pub cves: Vec<LocalCve>,
}
impl LocalInventory {
pub fn load(cache_db: &Path, repo_did: &str) -> Result<Self> {
let connection = Connection::open_with_flags(cache_db, OpenFlags::SQLITE_OPEN_READ_ONLY)
.with_context(|| format!("open cache {} read-only", cache_db.display()))?;
connection.execute_batch("PRAGMA query_only=ON;")?;
let software = {
let mut statement = connection.prepare(
"SELECT slug, part, vendor, product FROM software \
WHERE repo_did=?1 ORDER BY slug",
)?;
let rows = statement.query_map([repo_did], |row| {
Ok(LocalSoftwareRow {
slug: row.get(0)?,
part: row.get(1)?,
vendor: row.get(2)?,
product: row.get(3)?,
})
})?;
rows.collect::<rusqlite::Result<Vec<_>>>()?
};
let purls = {
let mut statement = connection.prepare(
"SELECT purl, software_slug FROM software_purls \
WHERE repo_did=?1 ORDER BY purl",
)?;
let rows = statement.query_map([repo_did], |row| {
Ok(LocalPurlRow {
purl: row.get(0)?,
software_slug: row.get(1)?,
})
})?;
rows.collect::<rusqlite::Result<Vec<_>>>()?
};
let mut cves = Vec::new();
{
let mut statement = connection.prepare("SELECT id, data FROM cves ORDER BY id")?;
let rows = statement.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
for row in rows {
let (id, data) = row?;
let value = serde_json::from_str(&data)
.with_context(|| format!("parse cached CVE {id}"))?;
cves.push(LocalCve { id, value });
}
}
Ok(Self {
software,
purls,
cves,
})
}
}
fn row_observation(row: &LocalSoftwareRow) -> ObservedProduct {
ObservedProduct {
source: "software-row".to_owned(),
part: row.part.clone(),
vendor: row.vendor.clone().unwrap_or_default(),
product: row.product.clone().unwrap_or_default(),
..ObservedProduct::default()
}
}
fn row_cpe_key(row: &LocalSoftwareRow) -> Option<String> {
let part = row.part.as_deref().filter(|part| !part.is_empty())?;
let vendor = row.vendor.as_deref().unwrap_or_default();
let product = row.product.as_deref().unwrap_or_default();
if vendor.is_empty() || product.is_empty() {
return None;
}
Some(format!(
"{part}:{}:{}",
vendor.replace(' ', "_").to_lowercase(),
product.replace(' ', "_").to_lowercase()
))
}
fn reason_for(observed: &ObservedProduct, assigned: &str) -> String {
let Some(identity) = canonicalize(observed) else {
return format!("no canonical identity (placeholder or empty vendor/product); {assigned}");
};
let base = canonical_slug(&identity.canonical_vendor, &identity.canonical_family);
let mut reason = format!(
"canonical identity {}:{}:{} -> {assigned}",
identity.class.as_str(),
identity.canonical_vendor,
identity.canonical_family
);
if assigned != base {
reason.push_str(" (slug collision: deterministic hash suffix)");
} else if aliases::aliases()
.families
.contains_key(&identity.canonical_family)
{
reason.push_str(" (curated alias)");
}
reason
}
fn ref_field<'a>(value: &'a Value, key: &str, field: &str) -> Option<&'a str> {
value.get(key)?.get(field)?.as_str()
}
fn project_cid<'a>(remote: &'a RemoteInventory, slug: &str) -> Option<&'a str> {
remote
.find_rkey(PROJECT_COLLECTION, slug)
.map(|record| record.cid.as_str())
}
/// The project a release record belongs to. Channels/versions repeat it in the
/// rkey prefix as a fallback for records written before the field was required.
fn record_project_slug(record: &RemoteRecord) -> Option<String> {
if record.collection == PROJECT_COLLECTION {
return Some(record.rkey.clone());
}
if let Some(uri) = record.value.get("project").and_then(Value::as_str)
&& let Some((_, _, rkey)) = split_uri(uri)
{
return Some(rkey.to_owned());
}
if matches!(
record.collection.as_str(),
CHANNEL_COLLECTION | VERSION_COLLECTION
) {
return record
.rkey
.split_once(':')
.map(|(project, _)| project.to_owned());
}
None
}
/// Build the migration plan. Read-only on both the cache and the PDS.
pub async fn build_plan(
publisher: &Publisher,
repo_did: &str,
cache_db: &Path,
purldb: Option<&Path>,
) -> Result<MigrationPlan> {
let local = LocalInventory::load(cache_db, repo_did)?;
let remote = RemoteInventory::load(publisher, ALL_COLLECTIONS).await?;
let mut observations: Vec<ObservedProduct> = local
.software
.iter()
.map(row_observation)
.filter(|observed| !observed.vendor.is_empty() && !observed.product.is_empty())
.collect();
for cve in &local.cves {
observations.extend(observations_from_cve(&cve.value));
}
observations.sort();
observations.dedup();
let identities = canonicalize_all(&observations);
let mut assigned_slug: BTreeMap<String, String> = BTreeMap::new();
for identity in &identities {
assigned_slug.insert(identity.identity_key.clone(), identity.slug.clone());
}
let mut cpe_identity: BTreeMap<String, String> = BTreeMap::new();
for observed in &observations {
let Some(identity) = canonicalize(observed) else {
continue;
};
for cpe in &observed.cpes {
if let Some(key) = cpe_product_key(cpe) {
cpe_identity
.entry(key)
.or_insert_with(|| identity.identity_key.clone());
}
}
}
let mut purl_identity: BTreeMap<String, String> = BTreeMap::new();
if let Some(purldb) = purldb.filter(|path| path.exists()) {
let mut wanted: BTreeSet<String> = cpe_identity.keys().cloned().collect();
wanted.extend(local.software.iter().filter_map(row_cpe_key));
let purl_map = load_purl_map(purldb, &wanted).await?;
for (key, purls) in purl_map {
let Some(identity_key) = cpe_identity.get(&key) else {
continue;
};
for purl in purls {
purl_identity.insert(versionless_purl(&purl), identity_key.clone());
}
}
}
// Legacy raw slug -> canonical slug. Software rows are authoritative;
// CVE observations and purl2cpe fill gaps for variants without a row.
let mut canonical_for_slug: BTreeMap<String, String> = BTreeMap::new();
let mut canonical_slugs: BTreeSet<String> = BTreeSet::new();
let mut reason_for_slug: BTreeMap<String, String> = BTreeMap::new();
for row in &local.software {
let observed = row_observation(row);
let Some(identity) = canonicalize(&observed) else {
continue;
};
let Some(slug) = assigned_slug.get(&identity.identity_key) else {
continue;
};
canonical_for_slug.insert(row.slug.clone(), slug.clone());
canonical_slugs.insert(slug.clone());
reason_for_slug.insert(row.slug.clone(), reason_for(&observed, slug));
}
for observed in &observations {
let Some(identity) = canonicalize(observed) else {
continue;
};
let Some(slug) = assigned_slug.get(&identity.identity_key) else {
continue;
};
let legacy = slugify(
observed.part.as_deref().unwrap_or("a"),
&observed.vendor,
&observed.product,
);
if !legacy.is_empty() && !canonical_for_slug.contains_key(&legacy) {
canonical_for_slug.insert(legacy.clone(), slug.clone());
reason_for_slug.insert(legacy, reason_for(observed, slug));
}
}
for row in &local.purls {
let normalized = super::normalized_purl_slug(&row.software_slug).to_owned();
let Some(identity_key) = purl_identity.get(&versionless_purl(&row.purl)) else {
continue;
};
let Some(slug) = assigned_slug.get(identity_key) else {
continue;
};
canonical_for_slug
.entry(normalized)
.or_insert_with(|| slug.clone());
canonical_slugs.insert(slug.clone());
}
let mut entries: Vec<MigrationEntry> = Vec::new();
// Release projects that are legacy variants of a canonical project. The
// mapping covers orphan channel/version/manifest records whose project
// record is already gone. A slug owned by any identity as its canonical
// project is never treated as legacy (collision safety).
let canonical_owner: BTreeSet<String> = assigned_slug.values().cloned().collect();
let mut legacy_project: BTreeMap<String, String> = BTreeMap::new();
for (slug, target) in &canonical_for_slug {
if slug != target && !canonical_owner.contains(slug) {
legacy_project.insert(slug.clone(), target.clone());
}
}
for record in remote.records(PROJECT_COLLECTION) {
if let Some(target) = canonical_for_slug.get(&record.rkey)
&& target != &record.rkey
&& !canonical_owner.contains(&record.rkey)
{
legacy_project.insert(record.rkey.clone(), target.clone());
canonical_slugs.insert(target.clone());
}
}
// Map every legacy project and existing canonical project, then mark the
// release records that will be retired.
let mut remap = RemapMap::new(repo_did);
for (legacy, canonical) in &legacy_project {
canonical_slugs.insert(canonical.clone());
let reference = project_ref(&remote, repo_did, canonical);
remap.add_project(&project_uri(repo_did, legacy), reference.clone());
remap.add_project(legacy, reference);
}
for record in remote.records(PROJECT_COLLECTION) {
if legacy_project.contains_key(&record.rkey) {
remap.mark_deleted(&record.uri);
continue;
}
let reference = StrongRef::new(record.uri.clone(), record.cid.clone());
remap.add_project(&record.uri, reference.clone());
remap.add_project(&record.rkey, reference);
}
// Legacy channel/version records follow the canonical record with the same
// suffix when one exists, so status subjects can be repointed before the
// legacy record is deleted.
for collection in [CHANNEL_COLLECTION, VERSION_COLLECTION] {
for record in remote.records(collection) {
let Some(project) = record_project_slug(record) else {
continue;
};
let Some(target) = legacy_project.get(&project) else {
continue;
};
remap.mark_deleted(&record.uri);
let Some((_, suffix)) = record.rkey.split_once(':') else {
continue;
};
let canonical_rkey = format!("{target}:{suffix}");
if let Some(canonical_record) = remote.find_rkey(collection, &canonical_rkey) {
remap.add_release(
&record.uri,
StrongRef::new(canonical_record.uri.clone(), canonical_record.cid.clone()),
);
}
}
}
for record in remote.records(MANIFEST_COLLECTION) {
if record_project_slug(record).is_some_and(|project| legacy_project.contains_key(&project))
{
remap.mark_deleted(&record.uri);
}
}
for legacy in legacy_release_records(&remote, &remap)? {
if let Some(canonical) = &legacy.canonical_slug {
canonical_slugs.insert(canonical.clone());
}
entries.push(MigrationEntry {
action: MigrationAction::DeleteReleaseRecord,
legacy_slug: legacy.legacy_project.clone().or_else(|| {
(legacy.kind == LegacyReleaseKind::Project).then(|| legacy.rkey.clone())
}),
legacy_uri: Some(legacy.uri.clone()),
canonical_slug: legacy.canonical_slug.clone(),
canonical_uri: legacy
.canonical_slug
.as_ref()
.map(|slug| project_uri(repo_did, slug)),
reason: format!("{}: {}", legacy.reason.code(), legacy.reason.describe()),
});
}
// Repoint raw software records at their canonical project.
let mut repointed_software: BTreeSet<String> = BTreeSet::new();
for record in remote.records(SOFTWARE_COLLECTION) {
let Some(target) = canonical_for_slug.get(&record.rkey) else {
continue;
};
canonical_slugs.insert(target.clone());
let expected_uri = project_uri(repo_did, target);
let expected_cid = project_cid(&remote, target);
let current_uri = ref_field(&record.value, "project", "uri");
let current_cid = ref_field(&record.value, "project", "cid");
let needs = current_uri != Some(expected_uri.as_str())
|| expected_cid.is_none()
|| current_cid != expected_cid;
if !needs {
continue;
}
let reason = reason_for_slug
.get(&record.rkey)
.cloned()
.unwrap_or_else(|| format!("raw software slug maps to {target}"));
entries.push(MigrationEntry {
action: MigrationAction::RepointSoftware,
legacy_slug: Some(record.rkey.clone()),
legacy_uri: Some(record.uri.clone()),
canonical_slug: Some(target.clone()),
canonical_uri: Some(expected_uri),
reason,
});
repointed_software.insert(record.uri.clone());
}
// Repoint CVEs. A repoint is needed when a project ref is legacy, stale,
// duplicated, or carries a strongRef to a record being deleted.
for record in remote.records(ATPROTO_COLLECTION) {
let Some(software) = record.value.get("software").and_then(Value::as_array) else {
continue;
};
if software.is_empty() {
continue;
}
let mut needs = false;
let mut targets: Vec<String> = Vec::new();
for item in software {
if let Some(project) = item.get("project") {
let uri = project
.get("uri")
.and_then(Value::as_str)
.unwrap_or_default();
if let Some(slug) = slug_of_project_uri(uri) {
let target = canonical_for_slug
.get(slug)
.cloned()
.or_else(|| canonical_slugs.contains(slug).then(|| slug.to_owned()));
if let Some(target) = target {
canonical_slugs.insert(target.clone());
if target != slug {
needs = true;
}
match project_cid(&remote, &target) {
Some(expected) => {
if project.get("cid").and_then(Value::as_str) != Some(expected) {
needs = true;
}
}
None => needs = true,
}
targets.push(target);
}
}
}
}
let unique: BTreeSet<&String> = targets.iter().collect();
if unique.len() != targets.len() {
needs = true;
}
if !needs {
continue;
}
let canonical_slug = if unique.len() == 1 {
unique.first().map(|slug| (*slug).clone())
} else {
None
};
entries.push(MigrationEntry {
action: MigrationAction::RepointCve,
legacy_slug: Some(
record
.value
.get("cve")
.and_then(Value::as_str)
.unwrap_or(&record.rkey)
.to_owned(),
),
legacy_uri: Some(record.uri.clone()),
canonical_slug,
canonical_uri: Some(record.uri.clone()),
reason: format!(
"CVE software refs move to canonical projects ({} distinct)",
unique.len()
),
});
}
// PURL records hold strongRefs to the software records repointed above.
for record in remote.records(PURL_COLLECTION) {
let Some(refs) = record.value.get("software").and_then(Value::as_array) else {
continue;
};
let needs = refs.iter().any(|reference| {
let uri = reference
.get("uri")
.and_then(Value::as_str)
.unwrap_or_default();
if repointed_software.contains(uri) {
return true;
}
match remote.find_uri(uri) {
Some(software) => {
reference.get("cid").and_then(Value::as_str) != Some(software.cid.as_str())
}
None => false,
}
});
if !needs {
continue;
}
entries.push(MigrationEntry {
action: MigrationAction::RepointPurl,
legacy_slug: record
.value
.get("purl")
.and_then(Value::as_str)
.map(str::to_owned),
legacy_uri: Some(record.uri.clone()),
canonical_slug: None,
canonical_uri: Some(record.uri.clone()),
reason: "purl software strongRefs follow the repointed software records".to_owned(),
});
}
// Status records follow a remappable subject; orphaned statuses were
// classified for deletion above.
for record in remote.records(STATUS_COLLECTION) {
let Some(subject) = record.value.get("subject").and_then(Value::as_str) else {
continue;
};
let Some(target) = remap
.release_for(subject)
.or_else(|| remap.project_for(subject))
.filter(|target| target.uri != subject)
else {
continue;
};
let canonical_slug = slug_of_project_uri(&target.uri).map(str::to_owned);
if let Some(slug) = &canonical_slug {
canonical_slugs.insert(slug.clone());
}
entries.push(MigrationEntry {
action: MigrationAction::RepointStatus,
legacy_slug: record
.rkey
.split_once(':')
.map(|(project, _)| project.to_owned()),
legacy_uri: Some(record.uri.clone()),
canonical_slug,
canonical_uri: Some(target.uri.clone()),
reason: format!("status subject {subject} moves to {}", target.uri),
});
}
// Canonical projects must exist before any reference points at them.
for slug in &canonical_slugs {
if remote.find_rkey(PROJECT_COLLECTION, slug).is_some() {
continue;
}
entries.push(MigrationEntry {
action: MigrationAction::CreateProject,
legacy_slug: None,
legacy_uri: None,
canonical_slug: Some(slug.clone()),
canonical_uri: Some(project_uri(repo_did, slug)),
reason: format!("canonical project {slug} is missing; create before repointing refs"),
});
}
for row in &local.purls {
if !row.software_slug.starts_with("at://") {
continue;
}
let normalized = super::normalized_purl_slug(&row.software_slug);
entries.push(MigrationEntry {
action: MigrationAction::NormalizePurlSlug,
legacy_slug: Some(row.software_slug.clone()),
legacy_uri: None,
canonical_slug: Some(normalized.to_owned()),
canonical_uri: None,
reason: format!(
"software_purls.software_slug stores an AT-URI; normalize to {normalized}"
),
});
}
let mut plan = MigrationPlan {
repo_did: repo_did.to_owned(),
generated_at: crate::time::created_at(chrono::Utc::now()),
entries,
};
plan.sort();
Ok(plan)
}