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

johnandersen777.bsky.social/vuln-notif

0
0
main
579 lines · 20.0 KB Raw History
//! Pure record-body rewrites for the identity migration.
//!
//! Planning resolves the legacy-to-canonical map; these functions apply it to
//! record bodies without touching the network or the cache. Every strongRef
//! (and release `project`/status `subject` URI) that is rewritten is asserted
//! to be same-DID, so a cross-repository reference fails instead of silently
//! producing a record the PDS would reject.

use std::collections::{BTreeMap, BTreeSet};

use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::{RemoteInventory, assert_same_did, project_uri, slug_of_project_uri, split_uri};
use crate::constants::{
    ATPROTO_COLLECTION, CHANNEL_COLLECTION, MANIFEST_COLLECTION, PROJECT_COLLECTION, PROJECT_TYPE,
    PURL_COLLECTION, SOFTWARE_COLLECTION, STATUS_COLLECTION, VERSION_COLLECTION,
};

/// One same-DID strongRef target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StrongRef {
    pub uri: String,
    pub cid: String,
}

impl StrongRef {
    pub fn new(uri: impl Into<String>, cid: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            cid: cid.into(),
        }
    }

    pub fn as_value(&self) -> Value {
        json!({ "uri": self.uri, "cid": self.cid })
    }
}

/// Resolution table for one migration run.
///
/// * `projects` maps a project URI or slug to its canonical project ref.
/// * `software` maps a software record URI to its rewritten ref (the URI stays
///   stable because rkeys are never renamed, only the CID changes).
/// * `releases` maps a legacy channel/version URI to the canonical equivalent
///   when one exists, so status subjects can follow it.
/// * `deleted` lists records that the plan removes.
#[derive(Debug, Clone, Default)]
pub struct RemapMap {
    repo: String,
    projects: BTreeMap<String, StrongRef>,
    software: BTreeMap<String, StrongRef>,
    releases: BTreeMap<String, StrongRef>,
    deleted: BTreeSet<String>,
}

impl RemapMap {
    pub fn new(repo: impl Into<String>) -> Self {
        Self {
            repo: repo.into(),
            ..Self::default()
        }
    }

    pub fn repo(&self) -> &str {
        &self.repo
    }

    pub fn add_project(&mut self, key: &str, reference: StrongRef) {
        self.projects.insert(key.to_owned(), reference);
    }

    /// Point every existing alias of `canonical_uri` at a fresh ref (used after
    /// the canonical project is created and its CID is known).
    pub fn refresh_project(&mut self, canonical_uri: &str, reference: StrongRef) {
        for existing in self.projects.values_mut() {
            if existing.uri == canonical_uri {
                *existing = reference.clone();
            }
        }
        self.projects.insert(canonical_uri.to_owned(), reference);
    }

    pub fn add_software(&mut self, legacy_uri: &str, reference: StrongRef) {
        self.software.insert(legacy_uri.to_owned(), reference);
    }

    pub fn add_release(&mut self, legacy_uri: &str, reference: StrongRef) {
        self.releases.insert(legacy_uri.to_owned(), reference);
    }

    pub fn mark_deleted(&mut self, uri: &str) {
        self.deleted.insert(uri.to_owned());
    }

    pub fn project_for(&self, uri_or_slug: &str) -> Option<&StrongRef> {
        self.projects
            .get(uri_or_slug)
            .or_else(|| slug_of_project_uri(uri_or_slug).and_then(|slug| self.projects.get(slug)))
    }

    pub fn software_for(&self, uri: &str) -> Option<&StrongRef> {
        self.software.get(uri)
    }

    pub fn release_for(&self, uri: &str) -> Option<&StrongRef> {
        self.releases.get(uri)
    }

    pub fn is_deleted(&self, uri: &str) -> bool {
        self.deleted.contains(uri)
    }
}

/// The canonical project record body.
pub fn canonical_project_record(slug: &str) -> Value {
    json!({ "$type": PROJECT_TYPE, "name": slug })
}

/// Rewrite one record body. `Ok(None)` means the record already matches the
/// map (or the collection is not rewritten in place, for example a release
/// record that the plan deletes instead).
pub fn repoint_record(collection: &str, value: &Value, map: &RemapMap) -> Result<Option<Value>> {
    match collection {
        SOFTWARE_COLLECTION => repoint_software(value, map),
        PURL_COLLECTION => repoint_purl(value, map),
        ATPROTO_COLLECTION => repoint_cve(value, map),
        STATUS_COLLECTION => repoint_status(value, map),
        _ => Ok(None),
    }
}

fn object_mut(value: &mut Value) -> Result<&mut serde_json::Map<String, Value>> {
    value
        .as_object_mut()
        .ok_or_else(|| anyhow!("record body is not an object"))
}

fn repoint_software(value: &Value, map: &RemapMap) -> Result<Option<Value>> {
    let Some(project) = value.get("project") else {
        return Ok(None);
    };
    let Some(uri) = project.get("uri").and_then(Value::as_str) else {
        return Ok(None);
    };
    assert_same_did(map.repo(), uri)?;
    let Some(target) = map.project_for(uri) else {
        return Ok(None);
    };
    if uri == target.uri && project.get("cid").and_then(Value::as_str) == Some(target.cid.as_str())
    {
        return Ok(None);
    }
    let mut rewritten = value.clone();
    object_mut(&mut rewritten)?.insert("project".to_owned(), target.as_value());
    Ok(Some(rewritten))
}

fn repoint_purl(value: &Value, map: &RemapMap) -> Result<Option<Value>> {
    let Some(refs) = value.get("software").and_then(Value::as_array) else {
        return Ok(None);
    };
    let mut rewritten = Vec::with_capacity(refs.len());
    let mut seen: BTreeSet<(String, String)> = BTreeSet::new();
    let mut changed = false;
    for reference in refs {
        let new_ref = match reference.get("uri").and_then(Value::as_str) {
            Some(uri) => {
                assert_same_did(map.repo(), uri)?;
                match map.software_for(uri) {
                    Some(target) => {
                        if target.uri != uri
                            || reference.get("cid").and_then(Value::as_str)
                                != Some(target.cid.as_str())
                        {
                            changed = true;
                        }
                        target.as_value()
                    }
                    None => reference.clone(),
                }
            }
            None => reference.clone(),
        };
        let key = (
            new_ref
                .get("uri")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_owned(),
            new_ref
                .get("cid")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_owned(),
        );
        if seen.insert(key) {
            rewritten.push(new_ref);
        } else {
            changed = true;
        }
    }
    if !changed {
        return Ok(None);
    }
    let mut value = value.clone();
    object_mut(&mut value)?.insert("software".to_owned(), Value::Array(rewritten));
    Ok(Some(value))
}

fn repoint_cve(value: &Value, map: &RemapMap) -> Result<Option<Value>> {
    let Some(items) = value.get("software").and_then(Value::as_array) else {
        return Ok(None);
    };
    let mut kept = Vec::with_capacity(items.len());
    let mut seen_projects: BTreeSet<String> = BTreeSet::new();
    let mut changed = false;
    for item in items {
        let mut item = item.clone();
        // Copy the ref out before mutating the item.
        if let Some((uri, cid)) = item.get("project").and_then(|project| {
            let uri = project.get("uri")?.as_str()?.to_owned();
            let cid = project
                .get("cid")
                .and_then(Value::as_str)
                .map(str::to_owned);
            Some((uri, cid))
        }) {
            assert_same_did(map.repo(), &uri)?;
            let canonical = match map.project_for(&uri) {
                Some(target) => {
                    if target.uri != uri || cid.as_deref() != Some(target.cid.as_str()) {
                        object_mut(&mut item)?.insert("project".to_owned(), target.as_value());
                        changed = true;
                    }
                    target.uri.clone()
                }
                None => uri,
            };
            if !seen_projects.insert(canonical) {
                // One canonical project ref per CVE.
                changed = true;
                continue;
            }
        }
        // Version/channel/manifest arrays may point at legacy records that the
        // migration deletes. Repoint known successors, drop deleted targets,
        // and never leave a dangling strongRef behind.
        for field in ["versions", "channels", "manifests"] {
            if rewrite_release_refs(&mut item, field, map)? {
                changed = true;
            }
        }
        kept.push(item);
    }
    if !changed {
        return Ok(None);
    }
    let mut value = value.clone();
    object_mut(&mut value)?.insert("software".to_owned(), Value::Array(kept));
    Ok(Some(value))
}

/// Rewrite one release-ref array on a CVE software item.
///
/// Known successors are repointed; refs to records the migration deletes are
/// removed; unknown same-DID refs are preserved. Cross-DID refs are rejected.
fn rewrite_release_refs(item: &mut Value, field: &str, map: &RemapMap) -> Result<bool> {
    let Some(refs) = item.get(field).and_then(Value::as_array) else {
        return Ok(false);
    };
    let mut rewritten = Vec::with_capacity(refs.len());
    let mut changed = false;
    for reference in refs {
        let Some(uri) = reference.get("uri").and_then(Value::as_str) else {
            changed = true;
            continue;
        };
        assert_same_did(map.repo(), uri)?;
        if let Some(target) = map.release_for(uri) {
            if target.as_value() != *reference {
                rewritten.push(target.as_value());
                changed = true;
            } else {
                rewritten.push(reference.clone());
            }
        } else if map.is_deleted(uri) {
            changed = true;
        } else {
            rewritten.push(reference.clone());
        }
    }
    if changed {
        object_mut(item)?.insert(field.to_owned(), Value::Array(rewritten));
    }
    Ok(changed)
}

fn repoint_status(value: &Value, map: &RemapMap) -> Result<Option<Value>> {
    let Some(subject) = value.get("subject").and_then(Value::as_str) else {
        return Ok(None);
    };
    assert_same_did(map.repo(), subject)?;
    let Some(target) = map
        .release_for(subject)
        .or_else(|| map.project_for(subject))
    else {
        return Ok(None);
    };
    if target.uri == subject {
        return Ok(None);
    }
    let mut rewritten = value.clone();
    object_mut(&mut rewritten)?.insert("subject".to_owned(), Value::String(target.uri.clone()));
    Ok(Some(rewritten))
}

/// Release collection kinds that the migration can retire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LegacyReleaseKind {
    Project,
    Channel,
    Version,
    Manifest,
    Status,
}

impl LegacyReleaseKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Project => "project",
            Self::Channel => "channel",
            Self::Version => "version",
            Self::Manifest => "manifest",
            Self::Status => "status",
        }
    }

    fn for_collection(collection: &str) -> Option<Self> {
        match collection {
            PROJECT_COLLECTION => Some(Self::Project),
            CHANNEL_COLLECTION => Some(Self::Channel),
            VERSION_COLLECTION => Some(Self::Version),
            MANIFEST_COLLECTION => Some(Self::Manifest),
            STATUS_COLLECTION => Some(Self::Status),
            _ => None,
        }
    }
}

/// Why a release record is legacy. Serialized into the reviewable plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "code", rename_all = "snake_case")]
pub enum LegacyReason {
    /// The project record is replaced by a canonical project.
    ReplacedProject { canonical: String },
    /// The record belongs to a project record being replaced.
    LegacyProjectRecord { project: String, canonical: String },
    /// The status subject is deleted and has no canonical equivalent.
    OrphanedStatusSubject { subject: String },
    /// The plan marked the record itself for deletion.
    MarkedDeleted,
}

impl LegacyReason {
    pub fn code(&self) -> &'static str {
        match self {
            Self::ReplacedProject { .. } => "replaced_project",
            Self::LegacyProjectRecord { .. } => "legacy_project_record",
            Self::OrphanedStatusSubject { .. } => "orphaned_status_subject",
            Self::MarkedDeleted => "marked_deleted",
        }
    }

    pub fn describe(&self) -> String {
        match self {
            Self::ReplacedProject { canonical } => {
                format!("legacy project is replaced by {canonical}")
            }
            Self::LegacyProjectRecord { project, canonical } => {
                format!("belongs to legacy project {project}; canonical is {canonical}")
            }
            Self::OrphanedStatusSubject { subject } => {
                format!("status subject {subject} is deleted and has no canonical equivalent")
            }
            Self::MarkedDeleted => "record is marked for deletion".to_owned(),
        }
    }
}

/// One release record that must be deleted after every reference is repointed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacyRelease {
    pub uri: String,
    pub collection: String,
    pub rkey: String,
    pub kind: LegacyReleaseKind,
    pub legacy_project: Option<String>,
    pub canonical_slug: Option<String>,
    pub reason: LegacyReason,
}

/// Enumerate legacy project/channel/version/manifest/status records.
///
/// Records are legacy when their project maps to a different canonical project
/// or when the plan marked them deleted. A status record is only deleted when
/// its subject is deleted and cannot be remapped; otherwise the plan emits a
/// `RepointStatus` entry with [`repoint_record`].
pub fn legacy_release_records(
    remote: &RemoteInventory,
    map: &RemapMap,
) -> Result<Vec<LegacyRelease>> {
    let mut found = Vec::new();
    for record in remote.all() {
        let Some(kind) = LegacyReleaseKind::for_collection(&record.collection) else {
            continue;
        };
        match kind {
            LegacyReleaseKind::Project => {
                if let Some(target) = map
                    .project_for(&record.uri)
                    .filter(|target| target.uri != record.uri)
                {
                    found.push(legacy(
                        record,
                        kind,
                        Some(record.rkey.clone()),
                        slug_of_project_uri(&target.uri).map(str::to_owned),
                        LegacyReason::ReplacedProject {
                            canonical: slug_of_project_uri(&target.uri)
                                .unwrap_or(&target.uri)
                                .to_owned(),
                        },
                    ));
                } else if map.is_deleted(&record.uri) {
                    found.push(legacy(
                        record,
                        kind,
                        None,
                        None,
                        LegacyReason::MarkedDeleted,
                    ));
                }
            }
            LegacyReleaseKind::Channel
            | LegacyReleaseKind::Version
            | LegacyReleaseKind::Manifest => {
                let project = record.value.get("project").and_then(Value::as_str);
                let legacy_project = project.and_then(|project| {
                    map.project_for(project)
                        .filter(|target| target.uri != project)
                        .map(|target| (project.to_owned(), target))
                });
                if let Some((project, target)) = legacy_project {
                    if project.starts_with("at://") {
                        assert_same_did(map.repo(), &project)?;
                    }
                    let canonical = slug_of_project_uri(&target.uri).map(str::to_owned);
                    let legacy_slug = split_uri(&project)
                        .map(|(_, _, rkey)| rkey.to_owned())
                        .unwrap_or(project);
                    found.push(legacy(
                        record,
                        kind,
                        Some(legacy_slug.clone()),
                        canonical.clone(),
                        LegacyReason::LegacyProjectRecord {
                            project: legacy_slug,
                            canonical: canonical.unwrap_or_default(),
                        },
                    ));
                } else if map.is_deleted(&record.uri) {
                    found.push(legacy(
                        record,
                        kind,
                        None,
                        None,
                        LegacyReason::MarkedDeleted,
                    ));
                }
            }
            LegacyReleaseKind::Status => {
                let Some(subject) = record.value.get("subject").and_then(Value::as_str) else {
                    continue;
                };
                assert_same_did(map.repo(), subject)?;
                let repointable = map
                    .release_for(subject)
                    .or_else(|| map.project_for(subject))
                    .is_some_and(|target| target.uri != subject);
                if !repointable && map.is_deleted(subject) {
                    found.push(legacy(
                        record,
                        kind,
                        status_subject_project(subject),
                        None,
                        LegacyReason::OrphanedStatusSubject {
                            subject: subject.to_owned(),
                        },
                    ));
                }
            }
        }
    }
    found.sort_by(|left, right| left.uri.cmp(&right.uri));
    Ok(found)
}

fn status_subject_project(subject: &str) -> Option<String> {
    let (_, collection, rkey) = split_uri(subject)?;
    match collection {
        PROJECT_COLLECTION => Some(rkey.to_owned()),
        CHANNEL_COLLECTION | VERSION_COLLECTION => {
            rkey.split_once(':').map(|(project, _)| project.to_owned())
        }
        _ => None,
    }
}

fn legacy(
    record: &super::RemoteRecord,
    kind: LegacyReleaseKind,
    legacy_project: Option<String>,
    canonical_slug: Option<String>,
    reason: LegacyReason,
) -> LegacyRelease {
    LegacyRelease {
        uri: record.uri.clone(),
        collection: record.collection.clone(),
        rkey: record.rkey.clone(),
        kind,
        legacy_project,
        canonical_slug,
        reason,
    }
}

/// Canonical strongRef for a project slug, falling back to an empty CID when
/// the project record is about to be created.
pub fn project_ref(remote: &RemoteInventory, repo: &str, slug: &str) -> StrongRef {
    let uri = project_uri(repo, slug);
    let cid = remote
        .find_rkey(PROJECT_COLLECTION, slug)
        .map(|record| record.cid.clone())
        .unwrap_or_default();
    StrongRef::new(uri, cid)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn canonical_project_record_matches_rkey() {
        let record = canonical_project_record("red-hat-enterprise-linux");
        assert_eq!(record["$type"], PROJECT_TYPE);
        assert_eq!(record["name"], "red-hat-enterprise-linux");
    }

    #[test]
    fn project_lookup_accepts_uri_and_slug() {
        let mut map = RemapMap::new("did:plc:test");
        let reference = StrongRef::new(
            "at://did:plc:test/software.release.project/red-hat-enterprise-linux",
            "bafy",
        );
        map.add_project("red-hat-enterprise-linux", reference.clone());
        assert_eq!(
            map.project_for("red-hat-enterprise-linux"),
            Some(&reference)
        );
        assert_eq!(
            map.project_for("at://did:plc:test/software.release.project/red-hat-enterprise-linux"),
            Some(&reference)
        );
    }
}