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

johnandersen777.bsky.social/vuln-notif

0
0
main
391 lines · 12.8 KB Raw History
//! `identity-migrate`: out-of-band admin tool for the one-time canonical
//! identity migration.
//!
//! The service never calls this binary. Run `plan` (or `--dry-run`) first and
//! review the JSON map; only then `apply` with a snapshot directory. Exit
//! codes: 0 success, 2 usage, 1 runtime failure.

use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use serde_json::json;

use vuln_notif::config::{
    DEFAULT_CACHE, DEFAULT_PLC_URL, DEFAULT_PURLDB, EXIT_FATAL, EXIT_OK, EXIT_USAGE,
};
use vuln_notif::constants::{COLLECTION, PDS_REQUESTS_PER_5MIN, PDS_WRITE_DAILY, PDS_WRITE_HOURLY};
use vuln_notif::db::DbHandle;
use vuln_notif::log::{Level, Logger};
use vuln_notif::migrate::apply::{ApplyOptions, apply_plan};
use vuln_notif::migrate::plan::build_plan;
use vuln_notif::migrate::snapshot::{snapshot_all, write_snapshot};
use vuln_notif::migrate::verify::verify_plan;
use vuln_notif::migrate::{MigrationPlan, local_repo_dids, normalize_purl_slugs};
use vuln_notif::pds::{Publisher, PublisherConfig, RateGovernor, resolve_pds_url};
use vuln_notif::time::RealTime;

#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    Plan,
    Apply,
    Verify,
    Snapshot,
    Normalize,
}

#[derive(Parser)]
#[command(
    name = "identity-migrate",
    version,
    about = "One-time canonical software identity migration (admin only)"
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,

    /// atproto handle or DID (env ATP_HANDLE).
    #[arg(long, env = "ATP_HANDLE", global = true)]
    handle: Option<String>,

    /// atproto app password (env ATP_APP_PASSWORD; never logged).
    #[arg(long, env = "ATP_APP_PASSWORD", hide_env_values = true, global = true)]
    app_password: Option<String>,

    /// PDS base URL (env ATP_PDS_URL); resolved from the handle when omitted.
    #[arg(long, env = "ATP_PDS_URL", global = true)]
    pds_url: Option<String>,

    /// PLC directory base URL when resolving the PDS endpoint.
    #[arg(long, default_value = DEFAULT_PLC_URL, global = true)]
    plc_url: String,

    /// SQLite cache path.
    #[arg(long, default_value = DEFAULT_CACHE, global = true)]
    cache_db: PathBuf,

    /// purl2cpe SQLite path (skipped when absent).
    #[arg(long, default_value = DEFAULT_PURLDB, global = true)]
    purldb: PathBuf,

    /// Plan output path.
    #[arg(long, global = true)]
    out: Option<PathBuf>,

    /// Plan input path for apply/verify.
    #[arg(long, global = true)]
    map: Option<PathBuf>,

    /// Records per applyWrites delete batch.
    #[arg(long, default_value_t = 200, global = true)]
    batch: usize,

    /// Maximum plan entries to apply in this invocation (0 = all).
    #[arg(long, default_value_t = 0, global = true)]
    limit: usize,

    /// Plan only; never write the PDS or cache.
    #[arg(long, global = true)]
    dry_run: bool,

    /// Apply the plan.
    #[arg(long, global = true)]
    apply: bool,

    /// Verify the plan against the repository.
    #[arg(long, global = true)]
    verify: bool,

    /// Snapshot the affected records to this directory before apply.
    #[arg(long, global = true)]
    snapshot_dir: Option<PathBuf>,

    /// Retry entries left pending/error by an earlier run.
    #[arg(long, global = true)]
    resume: bool,

    /// Run the one-time software_purls slug normalization.
    #[arg(long, global = true)]
    normalize_purl_slugs: bool,
}

#[derive(Subcommand, Clone, Copy, PartialEq, Eq)]
enum Command {
    /// Inventory the cache and PDS and write a reviewable plan.
    Plan,
    /// Execute a plan in dependency order.
    Apply,
    /// Re-read the repository and report migration errors.
    Verify,
    /// Write affected records to JSONL before apply.
    Snapshot,
    /// Normalize legacy AT-URI values in software_purls.
    NormalizePurlSlugs,
}

impl Cli {
    fn mode(&self) -> std::result::Result<Mode, String> {
        if let Some(command) = self.command {
            if self.dry_run && command != Command::Plan {
                return Err("--dry-run is only valid for plan".to_owned());
            }
            return Ok(match command {
                Command::Plan => Mode::Plan,
                Command::Apply => Mode::Apply,
                Command::Verify => Mode::Verify,
                Command::Snapshot => Mode::Snapshot,
                Command::NormalizePurlSlugs => Mode::Normalize,
            });
        }
        if self.dry_run && (self.apply || self.verify || self.normalize_purl_slugs) {
            return Err(
                "--dry-run cannot be combined with --apply, --verify or --normalize-purl-slugs"
                    .to_owned(),
            );
        }
        // --apply --verify is valid: verify after a successful apply.
        if self.normalize_purl_slugs && (self.apply || self.verify) {
            return Err("--normalize-purl-slugs cannot be combined with apply/verify".to_owned());
        }
        if self.apply {
            Ok(Mode::Apply)
        } else if self.verify {
            Ok(Mode::Verify)
        } else if self.normalize_purl_slugs {
            Ok(Mode::Normalize)
        } else {
            Ok(Mode::Plan)
        }
    }

    fn needs_credentials(&self, mode: Mode) -> bool {
        mode != Mode::Normalize
    }

    fn plan_path(&self, mode: Mode) -> Result<PathBuf> {
        match mode {
            Mode::Plan => Ok(self
                .out
                .clone()
                .unwrap_or_else(|| PathBuf::from("identity-migration-plan.json"))),
            _ => self
                .map
                .clone()
                .or_else(|| self.out.clone())
                .ok_or_else(|| anyhow::anyhow!("--map is required for this command")),
        }
    }
}

fn load_plan(path: &Path) -> Result<MigrationPlan> {
    let raw =
        std::fs::read_to_string(path).with_context(|| format!("read plan {}", path.display()))?;
    serde_json::from_str(&raw).with_context(|| format!("parse plan {}", path.display()))
}

fn write_plan(plan: &MigrationPlan, path: &Path) -> Result<()> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("create plan directory {}", parent.display()))?;
    }
    let mut json = serde_json::to_string_pretty(plan)?;
    json.push('\n');
    std::fs::write(path, json).with_context(|| format!("write plan {}", path.display()))
}

async fn connect(cli: &Cli, db: DbHandle) -> Result<Publisher> {
    let handle = cli
        .handle
        .clone()
        .filter(|handle| !handle.is_empty())
        .context("missing ATP_HANDLE")?;
    let app_password = cli
        .app_password
        .clone()
        .filter(|password| !password.is_empty())
        .context("missing ATP_APP_PASSWORD")?;
    let pds_url = match cli.pds_url.clone().filter(|url| !url.is_empty()) {
        Some(url) => url,
        None => resolve_pds_url(&handle, &cli.plc_url).await?,
    };
    let governor = Arc::new(RateGovernor::new(
        db,
        PDS_WRITE_HOURLY,
        PDS_WRITE_DAILY,
        PDS_REQUESTS_PER_5MIN,
        Arc::new(RealTime),
    ));
    let publisher = Publisher::new(PublisherConfig {
        pds_url,
        handle,
        app_password,
        collection: COLLECTION.to_owned(),
        timeout_secs: 60.0,
        governor,
    })?;
    publisher.login().await?;
    Ok(publisher)
}

async fn execute(cli: &Cli, mode: Mode) -> Result<u8> {
    match mode {
        Mode::Plan => {
            let publisher = connect(cli, DbHandle::open_in_memory().await?).await?;
            let plan = build_plan(
                &publisher,
                publisher.repo(),
                &cli.cache_db,
                Some(cli.purldb.as_path()),
            )
            .await?;
            let path = cli.plan_path(mode)?;
            write_plan(&plan, &path)?;
            if let Some(dir) = &cli.snapshot_dir {
                let snapshot = write_snapshot(&publisher, &plan, dir).await?;
                println!(
                    "{}",
                    json!({"event": "identity_snapshot", "records": snapshot, "dir": dir})
                );
            }
            println!(
                "{}",
                json!({
                    "event": "identity_plan",
                    "entries": plan.entries.len(),
                    "created": plan.count(vuln_notif::migrate::MigrationAction::CreateProject),
                    "deleted": plan.count(vuln_notif::migrate::MigrationAction::DeleteReleaseRecord),
                    "out": path,
                })
            );
            Ok(EXIT_OK)
        }
        Mode::Apply => {
            let db = DbHandle::open(&cli.cache_db).await?;
            let publisher = connect(cli, db.clone()).await?;
            let plan = load_plan(&cli.plan_path(mode)?)?;
            if let Some(dir) = &cli.snapshot_dir {
                let snapshot = write_snapshot(&publisher, &plan, dir).await?;
                println!(
                    "{}",
                    json!({"event": "identity_snapshot", "records": snapshot, "dir": dir})
                );
            }
            let report = apply_plan(
                &publisher,
                &db,
                &plan,
                &ApplyOptions {
                    batch: cli.batch,
                    limit: cli.limit,
                    resume: cli.resume,
                },
            )
            .await?;
            println!("{}", json!({"event": "identity_apply", "report": report}));
            if cli.verify {
                return verify_with(&publisher, &db, &plan).await;
            }
            Ok(EXIT_OK)
        }
        Mode::Verify => {
            let db = DbHandle::open(&cli.cache_db).await?;
            let publisher = connect(cli, db.clone()).await?;
            let plan = load_plan(&cli.plan_path(mode)?)?;
            verify_with(&publisher, &db, &plan).await
        }
        Mode::Snapshot => {
            let publisher = connect(cli, DbHandle::open_in_memory().await?).await?;
            let dir = cli
                .snapshot_dir
                .clone()
                .context("--snapshot-dir is required for snapshot")?;
            let records = match cli.map.as_deref() {
                Some(path) => {
                    let plan = load_plan(path)?;
                    write_snapshot(&publisher, &plan, &dir).await?
                }
                None => snapshot_all(&publisher, &dir).await?,
            };
            println!(
                "{}",
                json!({"event": "identity_snapshot", "records": records, "dir": dir})
            );
            Ok(EXIT_OK)
        }
        Mode::Normalize => {
            let db = DbHandle::open(&cli.cache_db).await?;
            let repo_did = normalize_repo(cli)?;
            let updated = normalize_purl_slugs(&db, &repo_did).await?;
            db.close().await?;
            println!(
                "{}",
                json!({"event": "identity_normalize_purl_slugs", "repo_did": repo_did, "updated": updated})
            );
            Ok(EXIT_OK)
        }
    }
}

async fn verify_with(publisher: &Publisher, db: &DbHandle, plan: &MigrationPlan) -> Result<u8> {
    let report = verify_plan(publisher, db, plan).await?;
    let ok = report.ok();
    println!("{}", json!({"event": "identity_verify", "report": report}));
    Ok(if ok { EXIT_OK } else { EXIT_FATAL })
}

fn normalize_repo(cli: &Cli) -> Result<String> {
    if let Some(handle) = cli
        .handle
        .as_deref()
        .filter(|handle| handle.starts_with("did:"))
    {
        return Ok(handle.to_owned());
    }
    let dids = local_repo_dids(&cli.cache_db)?;
    match dids.as_slice() {
        [did] => Ok(did.clone()),
        [] => bail!("no repository DID in cache; pass --handle did:..."),
        _ => bail!("multiple repository DIDs in cache; pass --handle did:..."),
    }
}

fn usage_error(message: &str) -> ExitCode {
    let logger = Logger::stderr(Level::Info);
    logger.error(
        "cli_error",
        Some("identity-migrate"),
        json!({ "error": message }),
    );
    ExitCode::from(EXIT_USAGE)
}

#[tokio::main]
async fn main() -> ExitCode {
    let cli = Cli::parse();
    let mode = match cli.mode() {
        Ok(mode) => mode,
        Err(message) => return usage_error(&message),
    };
    if cli.needs_credentials(mode)
        && (cli.handle.as_deref().is_none_or(str::is_empty)
            || cli.app_password.as_deref().is_none_or(str::is_empty))
    {
        return usage_error("missing credentials: ATP_HANDLE, ATP_APP_PASSWORD");
    }
    match execute(&cli, mode).await {
        Ok(code) => ExitCode::from(code),
        Err(error) => {
            let logger = Logger::stderr(Level::Info);
            logger.error(
                "fatal",
                Some("identity-migrate"),
                json!({ "error": error.to_string() }),
            );
            ExitCode::from(EXIT_FATAL)
        }
    }
}