Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -522,9 +522,10 @@ test-unit:
-E 'test(=bucket_index::tests::bucket_snapshot_json_round_trip_preserves_community_keys)'
# buzz-admin: storage-snapshot worker, the community archive command
# parser, validation, and propagation-evidence tests, and the partition
# audit outcome contract, NIP-FI policy/backfill, and user-deletion intake.
# audit outcome contract, NIP-FI policy/backfill, user-deletion intake,
# and channel-discovery completeness mode boundaries.
cargo nextest run -p buzz-admin \
-E 'test(storage_snapshot) + test(/^communities::tests::/) + test(/^tests::communities_/) + test(=tests::partition_audit_outcomes_keep_their_json_names_and_exit_codes) + test(/^nip_fi::tests::/) + test(/^nip_fi_policy::tests::/) + test(/^user_deletions::tests::/)'
-E 'test(storage_snapshot) + test(/^communities::tests::/) + test(/^tests::communities_/) + test(=tests::partition_audit_outcomes_keep_their_json_names_and_exit_codes) + test(/^nip_fi::tests::/) + test(/^nip_fi_policy::tests::/) + test(/^user_deletions::tests::/) + test(/^channel_discovery::tests::/)'
# Multi-tenant conformance gate (buzz-conformance): the independent
# replay checker + golden fixtures. No infra — pure in-process trace
# replay — so it belongs in the unit job. Run all targets (lib + the
Expand Down
4 changes: 4 additions & 0 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ just test-postgres # full PostgreSQL-backed lane (auto-starts Docker servic
cargo test -p buzz-test-client -- --ignored
```

For the synthetic historical discovery-repair journey and operator checks, see
[Checking and repairing channel discovery](docs/operator-channel-discovery.md).
The script there deliberately damages discovery in a disposable loopback database.

### Review-Proven Test Standards

Mined from the last 25 PRs' review threads (see Review-Proven Rules in
Expand Down
357 changes: 357 additions & 0 deletions crates/buzz-admin/src/channel_discovery.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,357 @@
//! Bounded operator checks and missing-only repair of signed channel discovery.

use anyhow::{bail, Context, Result};
use buzz_core::tenant::TenantContext;
use buzz_db::Db;
use clap::Args as ClapArgs;
use nostr::{EventBuilder, Keys, Kind, PublicKey, Tag};
use serde::Serialize;
use std::time::Duration;
use uuid::Uuid;

const KINDS: [i32; 3] = [39000, 39001, 39002];

#[derive(ClapArgs)]
pub(crate) struct Args {
/// Channel UUID; without a completeness mode, force-republish its roster.
#[arg(long, conflicts_with = "after")]
channel: Option<Uuid>,
/// Exclusive UUID cursor from the preceding page's next_after.
#[arg(long, requires = "completeness")]
after: Option<Uuid>,
/// Maximum channels in completeness mode (default 100); no age cutoff.
#[arg(long, requires = "completeness", value_parser = clap::value_parser!(u16).range(1..=1000))]
limit: Option<u16>,
/// Read-only completeness check. Exit 6 if anything is missing.
#[arg(long, group = "completeness", conflicts_with = "repair_missing")]
check: bool,
/// Write only missing events, rechecking behind the existing publisher locks.
#[arg(long, group = "completeness")]
repair_missing: bool,
/// Override conflicting stored metadata authorship after independently
/// verifying the relay identity. Does not perform a signing-key rotation.
#[arg(long, requires = "repair_missing", conflicts_with = "check")]
allow_unrecognized_relay_key: bool,
/// Expected relay public key; sufficient for read-only completeness checks.
#[arg(long, requires = "completeness")]
relay_pubkey: Option<String>,
/// Relay signing key; defaults to BUZZ_RELAY_PRIVATE_KEY. Completeness
/// modes require a configured identity; legacy backfill retains its fallback.
#[arg(long)]
relay_key: Option<String>,
/// Whole-command deadline in seconds. A timeout is a failure, safe to rerun.
#[arg(long, requires = "completeness", value_parser = clap::value_parser!(u16).range(1..=3600))]
timeout_seconds: Option<u16>,
}

#[derive(Serialize)]
struct ChannelReport {
channel: Uuid,
missing_before: Vec<i32>,
written: Vec<i32>,
missing_after: Vec<i32>,
}

#[derive(Serialize)]
struct Report {
relay_pubkey: String,
channels: Vec<ChannelReport>,
next_after: Option<Uuid>,
}

pub(crate) async fn run(args: Args) -> Result<i32> {
if !args.check && !args.repair_missing {
super::reconcile_channels(args.channel.map(|id| id.to_string()), args.relay_key).await?;
return Ok(0);
}
tokio::time::timeout(
Duration::from_secs(args.timeout_seconds.unwrap_or(60).into()),
execute(args),
)
.await
.context("channel discovery deadline exceeded; rerun the same page")?
}

async fn execute(args: Args) -> Result<i32> {
let keys = args
.relay_key
.or_else(|| std::env::var("BUZZ_RELAY_PRIVATE_KEY").ok())
.map(|key| Keys::parse(&key).map_err(|_| anyhow::anyhow!("invalid relay signing key")))
.transpose()?;
let pubkey = args
.relay_pubkey
.map(|key| PublicKey::parse(&key).context("invalid relay public key"))
.transpose()?
.or_else(|| keys.as_ref().map(Keys::public_key))
.context("provide --relay-pubkey or the configured relay signing key")?;
if let Some(keys) = &keys {
if keys.public_key() != pubkey {
bail!("relay signing key does not match --relay-pubkey");
}
}
if args.repair_missing && keys.is_none() {
bail!("writes require --relay-key or BUZZ_RELAY_PRIVATE_KEY");
}
let db = super::connect_db().await?;
let tenant = super::resolve_admin_tenant(&db).await?;
if args.repair_missing && !args.allow_unrecognized_relay_key {
require_recognized_relay_key(&db, &tenant, &pubkey).await?;
}
// Keyset pagination, not list_channels' newest-1000 window. Never cross a
// community boundary or resurrect a deleted channel; archived ones count.
let limit = args.limit.unwrap_or(100);
let mut ids: Vec<Uuid> = sqlx::query_scalar(
"SELECT id FROM channels WHERE community_id = $1 AND deleted_at IS NULL \
AND ($2::uuid IS NULL OR id > $2) AND ($3::uuid IS NULL OR id = $3) \
ORDER BY id LIMIT $4",
)
.bind(tenant.community().as_uuid())
.bind(args.after)
.bind(args.channel)
.bind(i64::from(limit) + 1)
.fetch_all(db.pool())
.await?;
if args.channel.is_some() && ids.is_empty() {
bail!("channel not found in configured community");
}
let has_more = ids.len() > usize::from(limit);
ids.truncate(usize::from(limit));
let next_after = if has_more { ids.last().copied() } else { None };
let mut channels = Vec::with_capacity(ids.len());
for channel in ids {
let missing_before = missing(&db, &tenant, channel, &pubkey).await?;
let mut written = Vec::new();
if let Some(keys) = &keys {
for kind in KINDS {
if args.repair_missing
&& missing_before.contains(&kind)
&& repair(&db, &tenant, channel, keys, kind).await?
{
written.push(kind);
}
}
}
let missing_after = if args.repair_missing {
missing(&db, &tenant, channel, &pubkey).await?
} else {
missing_before.clone()
};
channels.push(ChannelReport {
channel,
missing_before,
written,
missing_after,
});
}
let incomplete = channels
.iter()
.any(|channel| !channel.missing_after.is_empty());
println!(
"{}",
serde_json::to_string(&Report {
relay_pubkey: pubkey.to_hex(),
channels,
next_after,
})?
);
Ok(if incomplete { 6 } else { 0 })
}

async fn require_recognized_relay_key(
db: &Db,
tenant: &TenantContext,
pubkey: &PublicKey,
) -> Result<()> {
// Check the whole community BEFORE the page can write anything. A typo in
// the configured key must not turn a healthy community into a backfill for
// a new author (which also prevents account cleanup under the real key).
// A genuinely empty discovery store remains bootstrappable.
let conflicting_authority: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM events WHERE community_id = $1 AND kind = 39000 \
AND deleted_at IS NULL AND pubkey <> $2) \
AND NOT EXISTS (SELECT 1 FROM events WHERE community_id = $1 AND kind = 39000 \
AND deleted_at IS NULL AND pubkey = $2)",
)
.bind(tenant.community().as_uuid())
.bind(pubkey.to_bytes().as_slice())
.fetch_one(db.pool())
.await?;
if conflicting_authority {
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");
}
Ok(())
}

async fn missing(
db: &Db,
tenant: &TenantContext,
channel: Uuid,
pubkey: &PublicKey,
) -> Result<Vec<i32>> {
let present: Vec<i32> = sqlx::query_scalar(
"SELECT DISTINCT kind FROM events WHERE community_id = $1 AND channel_id = $2 \
AND pubkey = $3 AND d_tag = $4 AND kind = ANY($5) AND deleted_at IS NULL",
)
.bind(tenant.community().as_uuid())
.bind(channel)
.bind(pubkey.to_bytes().as_slice())
.bind(channel.to_string())
.bind(KINDS.as_slice())
.fetch_all(db.pool())
.await?;
Ok(KINDS
.into_iter()
.filter(|kind| !present.contains(kind))
.collect())
}

async fn repair(
db: &Db,
tenant: &TenantContext,
channel: Uuid,
keys: &Keys,
kind: i32,
) -> Result<bool> {
let relay = keys.public_key().to_bytes();
if kind == 39002 {
let mut snapshot = db
.lock_member_snapshot(tenant.community(), channel, &relay)
.await?;
// A channel deleted between selection and capture must not be rebuilt.
if !snapshot.has_live_channel().await? {
bail!("channel disappeared during repair");
}
let latest = snapshot.latest_member_event_timestamp().await?;
if latest.is_some() {
snapshot.release().await?;
return Ok(false);
}
let tags = buzz_db::channel::group_members_tags(
&channel.to_string(),
snapshot.identity.as_ref(),
&snapshot.members,
)?;
let event = sign(keys, kind, tags)?;
let (_, inserted) = snapshot.replace_member_event(&event).await?;
if !inserted {
bail!("member discovery replacement was not inserted");
}
snapshot.release().await?;
} else {
let snapshot = db
.lock_group_state_snapshot(tenant.community(), channel, kind, &relay)
.await?;
if snapshot.latest_created_at.is_some() {
return Ok(false);
}
let tags = if kind == 39000 {
buzz_db::channel::group_metadata_tags(&snapshot.channel, &snapshot.members)
.into_iter()
.map(Tag::parse)
.collect::<Result<Vec<_>, _>>()?
} else {
buzz_db::channel::group_admins_tags(
&channel.to_string(),
&snapshot.channel.identity(),
&snapshot.members,
)?
};
let event = sign(keys, kind, tags)?;
let (_, inserted) = snapshot.replace(&event).await?;
if !inserted {
bail!("group discovery replacement was not inserted");
}
}
Ok(true)
}

fn sign(keys: &Keys, kind: i32, tags: Vec<Tag>) -> Result<nostr::Event> {
let builder = EventBuilder::new(Kind::Custom(kind as u16), "").tags(tags);
// Match the serving publisher: only a roster retains the signer's own p tag.
let builder = if kind == 39002 {
builder.allow_self_tagging()
} else {
builder
};
Ok(builder.sign_with_keys(keys)?)
}

#[cfg(test)]
mod tests {
use clap::Parser;

#[test]
fn bounds_and_write_modes_are_explicit() {
for args in [
vec!["--limit", "0"],
vec!["--limit", "1001"],
vec!["--timeout-seconds", "0"],
vec!["--timeout-seconds", "3601"],
vec!["--repair-missing"],
vec!["--allow-unrecognized-relay-key"],
vec![
"--channel",
"00000000-0000-0000-0000-000000000001",
"--after",
"00000000-0000-0000-0000-000000000002",
],
] {
assert!(
crate::Cli::try_parse_from(
["buzz-admin", "reconcile-channels", "--check"]
.into_iter()
.chain(args.iter().copied())
)
.is_err(),
"accepted invalid check options: {args:?}"
);
}
let cli = crate::Cli::try_parse_from(["buzz-admin", "reconcile-channels"]).unwrap();
let crate::Command::ReconcileChannels(args) = cli.command else {
panic!("wrong command")
};
assert!(!args.repair_missing && !args.check);
assert_eq!(args.limit, None);
for args in [
vec!["--limit", "100"],
vec!["--after", "00000000-0000-0000-0000-000000000001"],
vec!["--timeout-seconds", "60"],
vec![
"--relay-pubkey",
"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
],
vec!["--allow-unrecognized-relay-key"],
] {
assert!(crate::Cli::try_parse_from(
["buzz-admin", "reconcile-channels"].into_iter().chain(args)
)
.is_err());
}
assert!(crate::Cli::try_parse_from([
"buzz-admin",
"reconcile-channels",
"--check",
"--limit",
"1"
])
.is_ok());
assert!(crate::Cli::try_parse_from([
"buzz-admin",
"reconcile-channels",
"--repair-missing",
"--allow-unrecognized-relay-key"
])
.is_ok());
}

#[test]
fn signing_matches_serving_self_tag_policy() {
let keys = nostr::Keys::generate();
for kind in super::KINDS {
let tag = nostr::Tag::parse(["p", &keys.public_key().to_hex(), "", "member"]).unwrap();
let event = super::sign(&keys, kind, vec![tag]).unwrap();
let keeps_self = event.tags.iter().any(|tag| tag.as_slice()[0] == "p");
assert_eq!(keeps_self, kind == 39002);
}
}
}
Loading
Loading