Files
ngit-grasp/tests/sync/naughty_list_scheduling.rs
DanConwayDev d36b1227cf feat(sync): keep GRASP-08 private services out of public sync
A public mirror gains nothing from dialing a GRASP-08 private service:
the service will never admit it, and even attempting the connection
performs an AUTH exchange with a relay that only wants members. Worse,
retry machinery would hammer it indefinitely.

Approach: public instances fetch the NIP-11 document before the
WebSocket dial (`preflight_limit_hints`). When it advertises GRASP-08,
the worker returns a new `ConnectAttemptOutcome::PrivateService`
without dialing. The actor parks the relay in `private_service_relays`
(warn once, stable message tests grep for), retires all sync state
without the re-registration path, and both `register_relay` and
`schedule_connect_relay` refuse parked targets thereafter. Private
instances treat GRASP-08 peers as ordinary sync targets and skip the
probe. Session limit hints deliberately keep coming from the existing
post-connect fetch: reusing the pre-dial probe for hints would remove
the post-connect setup window whose stale-success handling
(disconnect during NIP-11 setup) is separately guaranteed and tested.

Correctness assumptions: the pre-dial NIP-11 probe is an outbound TCP
connection, so `preflight_limit_hints` re-runs the resolved outbound
target policy for event-directed URLs and skips the HTTP request
entirely on rejection - `connect()` then fails with the same policy
rejection through its own gate (tests/outbound_policy.rs stays green).
The park set is in-memory by design: a service that stops being
private becomes reachable again after a process restart at the latest.

Deliberately excluded: private-instance behavior toward GRASP-08 peers
(NIP-98 credentials on git fetches) lands separately.

Test infrastructure: `wait_for_log_line` moved from outbound_policy.rs
into the shared sync helpers; TestRelay gained a sync constructor with
identity publication disabled so log assertions about the bootstrap
connection are not confounded by user-index traffic. SetupDropRelay
now answers pre-dial NIP-11 probes directly and only runs its
drop-during-setup choreography for a fetch that arrives during a live
WebSocket session; the naughty-list scheduling test accounts for the
probe as a second accepted connection on the first attempt.

Validation: new tests/sync/outbound_auth.rs proves the park warning
appears exactly once and that, across a 2s observation window, the
private bootstrap relay is never connected to and no NIP-42
authentication occurs. cargo test --test sync -- sync::outbound_auth
sync::stale_connect_result sync::naughty_list_scheduling and
--test outbound_policy pass.
2026-08-15 14:34:01 +00:00

114 lines
4.0 KiB
Rust

//! Scenario regression coverage for relay naughty-list scheduling.
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use crate::common::{TestClient, TestRelay};
use nostr_sdk::prelude::*;
use tokio::io::AsyncWriteExt;
const OBSERVATION_DEADLINE: Duration = Duration::from_secs(30);
const RECONNECT_OBSERVATION: Duration = Duration::from_secs(4);
async fn wait_for_log_line<F>(log_path: &Path, predicate: F) -> bool
where
F: Fn(&str) -> bool,
{
let deadline = tokio::time::Instant::now() + OBSERVATION_DEADLINE;
loop {
if let Ok(content) = tokio::fs::read_to_string(log_path).await {
if content.lines().any(&predicate) {
return true;
}
}
if tokio::time::Instant::now() >= deadline {
return false;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
/// A reachable TCP endpoint that deliberately violates the WebSocket
/// handshake. This produces a persistent protocol failure without relying on
/// external DNS or network state.
async fn start_broken_websocket() -> (String, Arc<AtomicUsize>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind broken websocket endpoint");
let address = listener.local_addr().expect("broken endpoint address");
let accepted = Arc::new(AtomicUsize::new(0));
let task_accepted = Arc::clone(&accepted);
tokio::spawn(async move {
while let Ok((mut stream, _)) = listener.accept().await {
task_accepted.fetch_add(1, Ordering::SeqCst);
let _ = stream.write_all(b"not a websocket handshake\r\n").await;
let _ = stream.shutdown().await;
}
});
(format!("ws://{address}"), accepted)
}
#[tokio::test]
async fn naughty_relay_is_not_scheduled_for_reconnection() {
let relay = TestRelay::start_with_sync(None).await;
let (broken_relay, accepted) = start_broken_websocket().await;
let keys = Keys::generate();
let identifier = "naughty-relay-scheduling";
let npub = keys.public_key().to_bech32().expect("npub");
let own_clone = format!("http://{}/{npub}/{identifier}.git", relay.domain());
let own_relay = format!("ws://{}", relay.domain());
let announcement = EventBuilder::new(Kind::GitRepoAnnouncement, "")
.tags(vec![
Tag::identifier(identifier),
Tag::custom("clone", vec![own_clone]),
Tag::custom("relays", vec![own_relay, broken_relay.clone()]),
])
.finalize(&keys)
.expect("sign announcement");
let client = TestClient::new(relay.url(), keys)
.await
.expect("connect client");
client
.send_event(&announcement)
.await
.expect("publish announcement");
assert!(
wait_for_log_line(&relay.log_path(), |line| {
line.contains("added to naughty list") && line.contains(&broken_relay)
})
.await,
"broken endpoint must be classified as naughty"
);
// The first attempt opens two connections: the pre-dial NIP-11 probe
// (GRASP-08 private-service detection) and the WebSocket dial itself.
assert_eq!(accepted.load(Ordering::SeqCst), 2, "first dial is required");
let reconnect_deadline = tokio::time::Instant::now() + RECONNECT_OBSERVATION;
while tokio::time::Instant::now() < reconnect_deadline && accepted.load(Ordering::SeqCst) == 2 {
tokio::time::sleep(Duration::from_millis(100)).await;
}
assert_eq!(
accepted.load(Ordering::SeqCst),
2,
"a naughty relay must not receive another dial across reconnect ticks"
);
let log = tokio::fs::read_to_string(relay.log_path())
.await
.expect("read relay log");
assert!(
!log.lines().any(|line| {
line.contains("Attempting reconnection relay=") && line.contains(&broken_relay)
}),
"a naughty relay must be excluded before reconnect intent is logged"
);
client.disconnect().await;
relay.stop().await;
}