~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
316 lines · 10.1 KB Raw History
//! One-time canonical identity migration (admin tool only).
//!
//! The service never runs this implicitly. `plan` inventories the local cache
//! and the remote repository, emits a reviewable JSON map, `apply` executes
//! that map in dependency order with a persisted cursor, `verify` re-reads the
//! repository, and `snapshot` writes the affected records to JSONL before any
//! write. The migration is idempotent: a `done` cursor row is skipped.
//!
//! `software_purls.software_slug` is normalized in place by the one-time
//! `normalize-purl-slugs` command (there is no startup `ALTER`).

pub mod apply;
pub mod plan;
pub mod remap;
pub mod snapshot;
pub mod verify;

use std::collections::BTreeMap;
use std::path::Path;

use anyhow::{Context, Result, bail};
use rusqlite::{Connection, OpenFlags};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::constants::{
    ATPROTO_COLLECTION, CHANNEL_COLLECTION, MANIFEST_COLLECTION, PROJECT_COLLECTION,
    PURL_COLLECTION, SOFTWARE_COLLECTION, STATUS_COLLECTION, VERSION_COLLECTION,
};
use crate::pds::{Publisher, RecordItem};

/// Default `applyWrites` batch size for delete records.
pub const DEFAULT_BATCH: usize = 200;
const LIST_PAGE: usize = 100;

pub const RELEASE_COLLECTIONS: &[&str] = &[
    PROJECT_COLLECTION,
    CHANNEL_COLLECTION,
    VERSION_COLLECTION,
    MANIFEST_COLLECTION,
    STATUS_COLLECTION,
];

pub const NAHDIG_COLLECTIONS: &[&str] = &[SOFTWARE_COLLECTION, PURL_COLLECTION, ATPROTO_COLLECTION];

pub const ALL_COLLECTIONS: &[&str] = &[
    PROJECT_COLLECTION,
    CHANNEL_COLLECTION,
    VERSION_COLLECTION,
    MANIFEST_COLLECTION,
    STATUS_COLLECTION,
    SOFTWARE_COLLECTION,
    PURL_COLLECTION,
    ATPROTO_COLLECTION,
];

/// One reviewable migration step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MigrationAction {
    CreateProject,
    RepointSoftware,
    RepointPurl,
    RepointCve,
    RepointStatus,
    DeleteReleaseRecord,
    NormalizePurlSlug,
}

impl MigrationAction {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::CreateProject => "create_project",
            Self::RepointSoftware => "repoint_software",
            Self::RepointPurl => "repoint_purl",
            Self::RepointCve => "repoint_cve",
            Self::RepointStatus => "repoint_status",
            Self::DeleteReleaseRecord => "delete_release_record",
            Self::NormalizePurlSlug => "normalize_purl_slug",
        }
    }

    /// Apply order: create projects, then move refs, then delete old records.
    fn order(self) -> u8 {
        match self {
            Self::CreateProject => 0,
            Self::RepointSoftware => 1,
            Self::RepointPurl => 2,
            Self::RepointCve => 3,
            Self::RepointStatus => 4,
            Self::NormalizePurlSlug => 5,
            Self::DeleteReleaseRecord => 6,
        }
    }
}

/// One planned write. `legacy_uri` identifies the record being changed or
/// deleted; `canonical_uri` is the successor record or the same in-place
/// record for repoints. Values are resolved from the live inventory at apply
/// time, never rebuilt from stale plan data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MigrationEntry {
    pub action: MigrationAction,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub legacy_slug: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub legacy_uri: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonical_slug: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonical_uri: Option<String>,
    pub reason: String,
}

impl MigrationEntry {
    /// Stable cursor key inside `identity_migration` (phase = action).
    pub fn key(&self) -> String {
        match self.action {
            MigrationAction::CreateProject => self.canonical_slug.clone().unwrap_or_default(),
            _ => self
                .legacy_uri
                .clone()
                .or_else(|| self.legacy_slug.clone())
                .unwrap_or_default(),
        }
    }
}

/// The complete, reviewable map written to `--out`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationPlan {
    pub repo_did: String,
    pub generated_at: String,
    pub entries: Vec<MigrationEntry>,
}

impl MigrationPlan {
    pub fn sort(&mut self) {
        self.entries.sort_by(|left, right| {
            left.action
                .order()
                .cmp(&right.action.order())
                .then_with(|| left.key().cmp(&right.key()))
        });
    }

    pub fn count(&self, action: MigrationAction) -> usize {
        self.entries
            .iter()
            .filter(|entry| entry.action == action)
            .count()
    }
}

/// One record read back from the repository through `listRecords`.
#[derive(Debug, Clone, PartialEq)]
pub struct RemoteRecord {
    pub collection: String,
    pub rkey: String,
    pub uri: String,
    pub cid: String,
    pub value: Value,
}

/// Remote records grouped by collection. Built only from `listRecords`; local
/// link rows are never rebuilt from it.
#[derive(Debug, Clone, Default)]
pub struct RemoteInventory {
    records: BTreeMap<String, Vec<RemoteRecord>>,
}

impl RemoteInventory {
    pub async fn load(publisher: &Publisher, collections: &[&str]) -> Result<Self> {
        let mut inventory = Self::default();
        for collection in collections {
            let mut cursor: Option<String> = None;
            loop {
                let page = publisher
                    .list_records(collection, cursor.as_deref(), Some(LIST_PAGE))
                    .await?;
                for item in page.records {
                    inventory.insert(collection, item);
                }
                match page.cursor {
                    Some(next) if Some(next.as_str()) != cursor.as_deref() => cursor = Some(next),
                    _ => break,
                }
            }
        }
        Ok(inventory)
    }

    fn insert(&mut self, collection: &str, item: RecordItem) {
        let Some((_, _, rkey)) = split_uri(&item.uri) else {
            return;
        };
        self.records
            .entry(collection.to_owned())
            .or_default()
            .push(RemoteRecord {
                collection: collection.to_owned(),
                rkey: rkey.to_owned(),
                uri: item.uri,
                cid: item.cid,
                value: item.value,
            });
    }

    pub fn records(&self, collection: &str) -> &[RemoteRecord] {
        self.records
            .get(collection)
            .map(Vec::as_slice)
            .unwrap_or_default()
    }

    pub fn all(&self) -> impl Iterator<Item = &RemoteRecord> {
        self.records.values().flatten()
    }

    pub fn find_uri(&self, uri: &str) -> Option<&RemoteRecord> {
        self.all().find(|record| record.uri == uri)
    }

    pub fn find_rkey(&self, collection: &str, rkey: &str) -> Option<&RemoteRecord> {
        self.records(collection)
            .iter()
            .find(|record| record.rkey == rkey)
    }
}

pub fn record_uri(repo: &str, collection: &str, rkey: &str) -> String {
    format!("at://{repo}/{collection}/{rkey}")
}

pub fn project_uri(repo: &str, slug: &str) -> String {
    record_uri(repo, PROJECT_COLLECTION, slug)
}

/// Split `at://did/collection/rkey`.
pub fn split_uri(uri: &str) -> Option<(&str, &str, &str)> {
    let rest = uri.strip_prefix("at://")?;
    let mut parts = rest.splitn(3, '/');
    let did = parts.next()?;
    let collection = parts.next()?;
    let rkey = parts.next()?;
    if did.is_empty() || collection.is_empty() || rkey.is_empty() {
        return None;
    }
    Some((did, collection, rkey))
}

pub fn slug_of_project_uri(uri: &str) -> Option<&str> {
    let (_, collection, rkey) = split_uri(uri)?;
    (collection == PROJECT_COLLECTION).then_some(rkey)
}

/// Normalize a legacy `software_purls.software_slug`: some rows store the full
/// AT-URI instead of the slug.
pub fn normalized_purl_slug(raw: &str) -> &str {
    if raw.starts_with("at://") {
        split_uri(raw).map(|(_, _, rkey)| rkey).unwrap_or(raw)
    } else {
        raw
    }
}

/// Every write in the migration is same-DID with the plan's repository.
pub fn assert_same_did(repo: &str, uri: &str) -> Result<()> {
    match split_uri(uri) {
        Some((did, _, _)) if did == repo => Ok(()),
        Some((did, _, _)) => bail!("cross-DID reference {uri:?}: expected {repo}, got {did}"),
        None => bail!("invalid at-uri {uri:?}"),
    }
}

pub fn collect_strong_refs(value: &Value, out: &mut Vec<(String, String)>) {
    match value {
        Value::Object(map) => {
            if let (Some(uri), Some(cid)) = (
                map.get("uri").and_then(Value::as_str),
                map.get("cid").and_then(Value::as_str),
            ) {
                out.push((uri.to_owned(), cid.to_owned()));
            }
            for item in map.values() {
                collect_strong_refs(item, out);
            }
        }
        Value::Array(items) => {
            for item in items {
                collect_strong_refs(item, out);
            }
        }
        _ => {}
    }
}

/// Run the one-time `software_purls.software_slug` normalization.
pub async fn normalize_purl_slugs(db: &crate::db::DbHandle, repo_did: &str) -> Result<usize> {
    let updated = db.normalize_purl_slugs(repo_did).await?;
    db.commit().await?;
    Ok(updated)
}

/// Read the repository DIDs recorded in a cache, for local-only commands.
pub fn local_repo_dids(cache_db: &Path) -> Result<Vec<String>> {
    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 mut statement = connection.prepare(
        "SELECT repo_did FROM software UNION SELECT repo_did FROM software_purls \
         UNION SELECT repo_did FROM identity_migration ORDER BY repo_did",
    )?;
    let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}