|
| 1 | +//! Bounded operator checks and missing-only repair of signed channel discovery. |
| 2 | +
|
| 3 | +use anyhow::{bail, Context, Result}; |
| 4 | +use buzz_core::tenant::TenantContext; |
| 5 | +use buzz_db::Db; |
| 6 | +use clap::Args as ClapArgs; |
| 7 | +use nostr::{EventBuilder, Keys, Kind, PublicKey, Tag}; |
| 8 | +use serde::Serialize; |
| 9 | +use std::time::Duration; |
| 10 | +use uuid::Uuid; |
| 11 | + |
| 12 | +const KINDS: [i32; 3] = [39000, 39001, 39002]; |
| 13 | + |
| 14 | +#[derive(ClapArgs)] |
| 15 | +pub(crate) struct Args { |
| 16 | + /// Channel UUID; without a completeness mode, force-republish its roster. |
| 17 | + #[arg(long, conflicts_with = "after")] |
| 18 | + channel: Option<Uuid>, |
| 19 | + /// Exclusive UUID cursor from the preceding page's next_after. |
| 20 | + #[arg(long, requires = "completeness")] |
| 21 | + after: Option<Uuid>, |
| 22 | + /// Maximum channels in completeness mode (default 100); no age cutoff. |
| 23 | + #[arg(long, requires = "completeness", value_parser = clap::value_parser!(u16).range(1..=1000))] |
| 24 | + limit: Option<u16>, |
| 25 | + /// Read-only completeness check. Exit 6 if anything is missing. |
| 26 | + #[arg(long, group = "completeness", conflicts_with = "repair_missing")] |
| 27 | + check: bool, |
| 28 | + /// Write only missing events, rechecking behind the existing publisher locks. |
| 29 | + #[arg(long, group = "completeness")] |
| 30 | + repair_missing: bool, |
| 31 | + /// Override conflicting stored metadata authorship after independently |
| 32 | + /// verifying the relay identity. Does not perform a signing-key rotation. |
| 33 | + #[arg(long, requires = "repair_missing", conflicts_with = "check")] |
| 34 | + allow_unrecognized_relay_key: bool, |
| 35 | + /// Expected relay public key; sufficient for read-only completeness checks. |
| 36 | + #[arg(long, requires = "completeness")] |
| 37 | + relay_pubkey: Option<String>, |
| 38 | + /// Relay signing key; defaults to BUZZ_RELAY_PRIVATE_KEY. Completeness |
| 39 | + /// modes require a configured identity; legacy backfill retains its fallback. |
| 40 | + #[arg(long)] |
| 41 | + relay_key: Option<String>, |
| 42 | + /// Whole-command deadline in seconds. A timeout is a failure, safe to rerun. |
| 43 | + #[arg(long, requires = "completeness", value_parser = clap::value_parser!(u16).range(1..=3600))] |
| 44 | + timeout_seconds: Option<u16>, |
| 45 | +} |
| 46 | + |
| 47 | +#[derive(Serialize)] |
| 48 | +struct ChannelReport { |
| 49 | + channel: Uuid, |
| 50 | + missing_before: Vec<i32>, |
| 51 | + written: Vec<i32>, |
| 52 | + missing_after: Vec<i32>, |
| 53 | +} |
| 54 | + |
| 55 | +#[derive(Serialize)] |
| 56 | +struct Report { |
| 57 | + relay_pubkey: String, |
| 58 | + channels: Vec<ChannelReport>, |
| 59 | + next_after: Option<Uuid>, |
| 60 | +} |
| 61 | + |
| 62 | +pub(crate) async fn run(args: Args) -> Result<i32> { |
| 63 | + if !args.check && !args.repair_missing { |
| 64 | + super::reconcile_channels(args.channel.map(|id| id.to_string()), args.relay_key).await?; |
| 65 | + return Ok(0); |
| 66 | + } |
| 67 | + tokio::time::timeout( |
| 68 | + Duration::from_secs(args.timeout_seconds.unwrap_or(60).into()), |
| 69 | + execute(args), |
| 70 | + ) |
| 71 | + .await |
| 72 | + .context("channel discovery deadline exceeded; rerun the same page")? |
| 73 | +} |
| 74 | + |
| 75 | +async fn execute(args: Args) -> Result<i32> { |
| 76 | + let keys = args |
| 77 | + .relay_key |
| 78 | + .or_else(|| std::env::var("BUZZ_RELAY_PRIVATE_KEY").ok()) |
| 79 | + .map(|key| Keys::parse(&key).map_err(|_| anyhow::anyhow!("invalid relay signing key"))) |
| 80 | + .transpose()?; |
| 81 | + let pubkey = args |
| 82 | + .relay_pubkey |
| 83 | + .map(|key| PublicKey::parse(&key).context("invalid relay public key")) |
| 84 | + .transpose()? |
| 85 | + .or_else(|| keys.as_ref().map(Keys::public_key)) |
| 86 | + .context("provide --relay-pubkey or the configured relay signing key")?; |
| 87 | + if let Some(keys) = &keys { |
| 88 | + if keys.public_key() != pubkey { |
| 89 | + bail!("relay signing key does not match --relay-pubkey"); |
| 90 | + } |
| 91 | + } |
| 92 | + if args.repair_missing && keys.is_none() { |
| 93 | + bail!("writes require --relay-key or BUZZ_RELAY_PRIVATE_KEY"); |
| 94 | + } |
| 95 | + let db = super::connect_db().await?; |
| 96 | + let tenant = super::resolve_admin_tenant(&db).await?; |
| 97 | + if args.repair_missing && !args.allow_unrecognized_relay_key { |
| 98 | + require_recognized_relay_key(&db, &tenant, &pubkey).await?; |
| 99 | + } |
| 100 | + // Keyset pagination, not list_channels' newest-1000 window. Never cross a |
| 101 | + // community boundary or resurrect a deleted channel; archived ones count. |
| 102 | + let limit = args.limit.unwrap_or(100); |
| 103 | + let mut ids: Vec<Uuid> = sqlx::query_scalar( |
| 104 | + "SELECT id FROM channels WHERE community_id = $1 AND deleted_at IS NULL \ |
| 105 | + AND ($2::uuid IS NULL OR id > $2) AND ($3::uuid IS NULL OR id = $3) \ |
| 106 | + ORDER BY id LIMIT $4", |
| 107 | + ) |
| 108 | + .bind(tenant.community().as_uuid()) |
| 109 | + .bind(args.after) |
| 110 | + .bind(args.channel) |
| 111 | + .bind(i64::from(limit) + 1) |
| 112 | + .fetch_all(db.pool()) |
| 113 | + .await?; |
| 114 | + if args.channel.is_some() && ids.is_empty() { |
| 115 | + bail!("channel not found in configured community"); |
| 116 | + } |
| 117 | + let has_more = ids.len() > usize::from(limit); |
| 118 | + ids.truncate(usize::from(limit)); |
| 119 | + let next_after = if has_more { ids.last().copied() } else { None }; |
| 120 | + let mut channels = Vec::with_capacity(ids.len()); |
| 121 | + for channel in ids { |
| 122 | + let missing_before = missing(&db, &tenant, channel, &pubkey).await?; |
| 123 | + let mut written = Vec::new(); |
| 124 | + if let Some(keys) = &keys { |
| 125 | + for kind in KINDS { |
| 126 | + if args.repair_missing |
| 127 | + && missing_before.contains(&kind) |
| 128 | + && repair(&db, &tenant, channel, keys, kind).await? |
| 129 | + { |
| 130 | + written.push(kind); |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + let missing_after = if args.repair_missing { |
| 135 | + missing(&db, &tenant, channel, &pubkey).await? |
| 136 | + } else { |
| 137 | + missing_before.clone() |
| 138 | + }; |
| 139 | + channels.push(ChannelReport { |
| 140 | + channel, |
| 141 | + missing_before, |
| 142 | + written, |
| 143 | + missing_after, |
| 144 | + }); |
| 145 | + } |
| 146 | + let incomplete = channels |
| 147 | + .iter() |
| 148 | + .any(|channel| !channel.missing_after.is_empty()); |
| 149 | + println!( |
| 150 | + "{}", |
| 151 | + serde_json::to_string(&Report { |
| 152 | + relay_pubkey: pubkey.to_hex(), |
| 153 | + channels, |
| 154 | + next_after, |
| 155 | + })? |
| 156 | + ); |
| 157 | + Ok(if incomplete { 6 } else { 0 }) |
| 158 | +} |
| 159 | + |
| 160 | +async fn require_recognized_relay_key( |
| 161 | + db: &Db, |
| 162 | + tenant: &TenantContext, |
| 163 | + pubkey: &PublicKey, |
| 164 | +) -> Result<()> { |
| 165 | + // Check the whole community BEFORE the page can write anything. A typo in |
| 166 | + // the configured key must not turn a healthy community into a backfill for |
| 167 | + // a new author (which also prevents account cleanup under the real key). |
| 168 | + // A genuinely empty discovery store remains bootstrappable. |
| 169 | + let conflicting_authority: bool = sqlx::query_scalar( |
| 170 | + "SELECT EXISTS (SELECT 1 FROM events WHERE community_id = $1 AND kind = 39000 \ |
| 171 | + AND deleted_at IS NULL AND pubkey <> $2) \ |
| 172 | + AND NOT EXISTS (SELECT 1 FROM events WHERE community_id = $1 AND kind = 39000 \ |
| 173 | + AND deleted_at IS NULL AND pubkey = $2)", |
| 174 | + ) |
| 175 | + .bind(tenant.community().as_uuid()) |
| 176 | + .bind(pubkey.to_bytes().as_slice()) |
| 177 | + .fetch_one(db.pool()) |
| 178 | + .await?; |
| 179 | + if conflicting_authority { |
| 180 | + bail!("unrecognized relay signing key: another key authors live metadata in this community; no repair writes performed. Verify the configured relay identity before considering --allow-unrecognized-relay-key"); |
| 181 | + } |
| 182 | + Ok(()) |
| 183 | +} |
| 184 | + |
| 185 | +async fn missing( |
| 186 | + db: &Db, |
| 187 | + tenant: &TenantContext, |
| 188 | + channel: Uuid, |
| 189 | + pubkey: &PublicKey, |
| 190 | +) -> Result<Vec<i32>> { |
| 191 | + let present: Vec<i32> = sqlx::query_scalar( |
| 192 | + "SELECT DISTINCT kind FROM events WHERE community_id = $1 AND channel_id = $2 \ |
| 193 | + AND pubkey = $3 AND d_tag = $4 AND kind = ANY($5) AND deleted_at IS NULL", |
| 194 | + ) |
| 195 | + .bind(tenant.community().as_uuid()) |
| 196 | + .bind(channel) |
| 197 | + .bind(pubkey.to_bytes().as_slice()) |
| 198 | + .bind(channel.to_string()) |
| 199 | + .bind(KINDS.as_slice()) |
| 200 | + .fetch_all(db.pool()) |
| 201 | + .await?; |
| 202 | + Ok(KINDS |
| 203 | + .into_iter() |
| 204 | + .filter(|kind| !present.contains(kind)) |
| 205 | + .collect()) |
| 206 | +} |
| 207 | + |
| 208 | +async fn repair( |
| 209 | + db: &Db, |
| 210 | + tenant: &TenantContext, |
| 211 | + channel: Uuid, |
| 212 | + keys: &Keys, |
| 213 | + kind: i32, |
| 214 | +) -> Result<bool> { |
| 215 | + let relay = keys.public_key().to_bytes(); |
| 216 | + if kind == 39002 { |
| 217 | + let mut snapshot = db |
| 218 | + .lock_member_snapshot(tenant.community(), channel, &relay) |
| 219 | + .await?; |
| 220 | + // A channel deleted between selection and capture must not be rebuilt. |
| 221 | + if !snapshot.has_live_channel().await? { |
| 222 | + bail!("channel disappeared during repair"); |
| 223 | + } |
| 224 | + let latest = snapshot.latest_member_event_timestamp().await?; |
| 225 | + if latest.is_some() { |
| 226 | + snapshot.release().await?; |
| 227 | + return Ok(false); |
| 228 | + } |
| 229 | + let tags = buzz_db::channel::group_members_tags( |
| 230 | + &channel.to_string(), |
| 231 | + snapshot.identity.as_ref(), |
| 232 | + &snapshot.members, |
| 233 | + )?; |
| 234 | + let event = sign(keys, kind, tags)?; |
| 235 | + let (_, inserted) = snapshot.replace_member_event(&event).await?; |
| 236 | + if !inserted { |
| 237 | + bail!("member discovery replacement was not inserted"); |
| 238 | + } |
| 239 | + snapshot.release().await?; |
| 240 | + } else { |
| 241 | + let snapshot = db |
| 242 | + .lock_group_state_snapshot(tenant.community(), channel, kind, &relay) |
| 243 | + .await?; |
| 244 | + if snapshot.latest_created_at.is_some() { |
| 245 | + return Ok(false); |
| 246 | + } |
| 247 | + let tags = if kind == 39000 { |
| 248 | + buzz_db::channel::group_metadata_tags(&snapshot.channel, &snapshot.members) |
| 249 | + .into_iter() |
| 250 | + .map(Tag::parse) |
| 251 | + .collect::<Result<Vec<_>, _>>()? |
| 252 | + } else { |
| 253 | + buzz_db::channel::group_admins_tags( |
| 254 | + &channel.to_string(), |
| 255 | + &snapshot.channel.identity(), |
| 256 | + &snapshot.members, |
| 257 | + )? |
| 258 | + }; |
| 259 | + let event = sign(keys, kind, tags)?; |
| 260 | + let (_, inserted) = snapshot.replace(&event).await?; |
| 261 | + if !inserted { |
| 262 | + bail!("group discovery replacement was not inserted"); |
| 263 | + } |
| 264 | + } |
| 265 | + Ok(true) |
| 266 | +} |
| 267 | + |
| 268 | +fn sign(keys: &Keys, kind: i32, tags: Vec<Tag>) -> Result<nostr::Event> { |
| 269 | + let builder = EventBuilder::new(Kind::Custom(kind as u16), "").tags(tags); |
| 270 | + // Match the serving publisher: only a roster retains the signer's own p tag. |
| 271 | + let builder = if kind == 39002 { |
| 272 | + builder.allow_self_tagging() |
| 273 | + } else { |
| 274 | + builder |
| 275 | + }; |
| 276 | + Ok(builder.sign_with_keys(keys)?) |
| 277 | +} |
| 278 | + |
| 279 | +#[cfg(test)] |
| 280 | +mod tests { |
| 281 | + use clap::Parser; |
| 282 | + |
| 283 | + #[test] |
| 284 | + fn bounds_and_write_modes_are_explicit() { |
| 285 | + for args in [ |
| 286 | + vec!["--limit", "0"], |
| 287 | + vec!["--limit", "1001"], |
| 288 | + vec!["--timeout-seconds", "0"], |
| 289 | + vec!["--timeout-seconds", "3601"], |
| 290 | + vec!["--repair-missing"], |
| 291 | + vec!["--allow-unrecognized-relay-key"], |
| 292 | + vec![ |
| 293 | + "--channel", |
| 294 | + "00000000-0000-0000-0000-000000000001", |
| 295 | + "--after", |
| 296 | + "00000000-0000-0000-0000-000000000002", |
| 297 | + ], |
| 298 | + ] { |
| 299 | + assert!( |
| 300 | + crate::Cli::try_parse_from( |
| 301 | + ["buzz-admin", "reconcile-channels", "--check"] |
| 302 | + .into_iter() |
| 303 | + .chain(args.iter().copied()) |
| 304 | + ) |
| 305 | + .is_err(), |
| 306 | + "accepted invalid check options: {args:?}" |
| 307 | + ); |
| 308 | + } |
| 309 | + let cli = crate::Cli::try_parse_from(["buzz-admin", "reconcile-channels"]).unwrap(); |
| 310 | + let crate::Command::ReconcileChannels(args) = cli.command else { |
| 311 | + panic!("wrong command") |
| 312 | + }; |
| 313 | + assert!(!args.repair_missing && !args.check); |
| 314 | + assert_eq!(args.limit, None); |
| 315 | + for args in [ |
| 316 | + vec!["--limit", "100"], |
| 317 | + vec!["--after", "00000000-0000-0000-0000-000000000001"], |
| 318 | + vec!["--timeout-seconds", "60"], |
| 319 | + vec![ |
| 320 | + "--relay-pubkey", |
| 321 | + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", |
| 322 | + ], |
| 323 | + vec!["--allow-unrecognized-relay-key"], |
| 324 | + ] { |
| 325 | + assert!(crate::Cli::try_parse_from( |
| 326 | + ["buzz-admin", "reconcile-channels"].into_iter().chain(args) |
| 327 | + ) |
| 328 | + .is_err()); |
| 329 | + } |
| 330 | + assert!(crate::Cli::try_parse_from([ |
| 331 | + "buzz-admin", |
| 332 | + "reconcile-channels", |
| 333 | + "--check", |
| 334 | + "--limit", |
| 335 | + "1" |
| 336 | + ]) |
| 337 | + .is_ok()); |
| 338 | + assert!(crate::Cli::try_parse_from([ |
| 339 | + "buzz-admin", |
| 340 | + "reconcile-channels", |
| 341 | + "--repair-missing", |
| 342 | + "--allow-unrecognized-relay-key" |
| 343 | + ]) |
| 344 | + .is_ok()); |
| 345 | + } |
| 346 | + |
| 347 | + #[test] |
| 348 | + fn signing_matches_serving_self_tag_policy() { |
| 349 | + let keys = nostr::Keys::generate(); |
| 350 | + for kind in super::KINDS { |
| 351 | + let tag = nostr::Tag::parse(["p", &keys.public_key().to_hex(), "", "member"]).unwrap(); |
| 352 | + let event = super::sign(&keys, kind, vec![tag]).unwrap(); |
| 353 | + let keeps_self = event.tags.iter().any(|tag| tag.as_slice()[0] == "p"); |
| 354 | + assert_eq!(keeps_self, kind == 39002); |
| 355 | + } |
| 356 | + } |
| 357 | +} |
0 commit comments