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
//! `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)
}
}
}