Skip to content

Commit ac0ad7c

Browse files
committed
fix(pairing): align relay budgets negotiation and session expiry
Signed-off-by: kenny lopez <[email protected]>
1 parent beed7cd commit ac0ad7c

11 files changed

Lines changed: 329 additions & 20 deletions

File tree

‎Cargo.lock‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/buzz-core/src/pairing/session.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -549,9 +549,15 @@ impl PairingSession {
549549
}
550550
}
551551

552+
/// Absolute protocol deadline. Transports must use this same deadline for
553+
/// UI expiry so connection setup never adds time to an expired QR.
554+
pub fn deadline(&self) -> Instant {
555+
self.created_at + self.timeout
556+
}
557+
552558
/// Check if the session has expired.
553559
pub fn is_expired(&self) -> bool {
554-
self.created_at.elapsed() > self.timeout
560+
Instant::now() >= self.deadline()
555561
}
556562

557563
/// Current protocol state.

‎crates/buzz-core/src/pairing/session_code_entry_tests.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,27 @@ fn legacy_capabilities_never_enable_automatic_release() {
170170
assert_eq!(source.start_desktop_code().is_ok(), enabled);
171171
}
172172
}
173+
174+
#[test]
175+
fn readiness_delay_and_late_scan_share_the_original_deadline() {
176+
let (mut source, qr) = PairingSession::new_source("wss://relay.test".into());
177+
// Simulate the maximum 35-second readiness wait without sleeping.
178+
source.created_at = Instant::now() - Duration::from_secs(35);
179+
let deadline = source.deadline();
180+
let remaining = deadline.saturating_duration_since(Instant::now());
181+
assert!(remaining <= Duration::from_secs(85));
182+
assert!(remaining > Duration::from_secs(84));
183+
// A scan 84 seconds after readiness still has one second to be accepted.
184+
source.created_at -= Duration::from_secs(84);
185+
let (_, offer) = PairingSession::new_target(&qr).unwrap();
186+
assert!(source.handle_offer(&offer).is_ok());
187+
assert!(!source.is_expired());
188+
// The transport deadline and protocol expiry both end the original window.
189+
source.created_at -= Duration::from_secs(2);
190+
assert!(source.deadline() < Instant::now());
191+
assert!(source.is_expired());
192+
assert!(matches!(
193+
source.confirm_sas(),
194+
Err(PairingError::SessionExpired)
195+
));
196+
}

‎crates/buzz-pair-relay/Cargo.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ secp256k1 = { version = "0.31", features = ["global-context"] }
2929
sha2 = "0.11"
3030

3131
[dev-dependencies]
32+
buzz-core = { path = "../buzz-core" }
33+
nostr = { workspace = true }
34+
zeroize = { workspace = true }
3235
tokio = { workspace = true, features = ["test-util"] }
3336
tokio-tungstenite = { workspace = true }
3437
secp256k1 = { version = "0.31", features = ["global-context", "rand", "std"] }

‎crates/buzz-pair-relay/src/lib.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
//! NIP-01 event ID hash. Events with invalid signatures are rejected.
2222
//! - **No persistence** — events exist only in-flight between matched pub/sub.
2323
//! - **Bounded resources** — 128 max WS connections, 4 KiB max frame, 120s TTL.
24-
//! - **Session cap** — at most 6 accepted EVENTs per connection.
24+
//! - **Session cap** — at most 8 attempted EVENTs per connection.
2525
//! - **Freshness** — `created_at` must be within ±120 s of relay wall-clock.
2626
//! - **Deduplication** — duplicate event IDs are rejected; dedup entries expire after 300 s.
2727
@@ -70,10 +70,12 @@ const RATE_EVENT_MAX: u32 = 10;
7070
const SUB_ID_MAX: usize = 64;
7171

7272
/// Hard session cap: at most this many attempted EVENTs (post-sig-check) per connection.
73-
const MAX_EVENTS_PER_CONN: u32 = 6;
73+
// Desktop-code pairing needs seven events per peer at the fifth successful
74+
// guess (including offer/challenge, proof, payload and completion), plus abort.
75+
const MAX_EVENTS_PER_CONN: u32 = 8;
7476

7577
/// Per-#p delivery budget: enough for one full pairing from each direction.
76-
const MAX_DELIVERED_PER_P: u32 = 12;
78+
const MAX_DELIVERED_PER_P: u32 = 2 * MAX_EVENTS_PER_CONN;
7779

7880
/// Dedup vec rejects new events when still at capacity after TTL eviction (fail closed).
7981
const DEDUP_CAP: usize = 1024;
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
//! Full desktop-code wire exchange through the production relay and source state machine.
2+
use std::{sync::Arc, time::Duration};
3+
4+
use buzz_core::pairing::{crypto, PairingSession, PayloadType, SessionState};
5+
use buzz_pair_relay::{run_server, Relay};
6+
use futures_util::{SinkExt, StreamExt};
7+
use nostr::{nips::nip44, Event, EventBuilder, Keys, Kind, PublicKey, Tag, ToBech32};
8+
use serde_json::{json, Value};
9+
use tokio::net::TcpListener;
10+
use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};
11+
use zeroize::Zeroizing;
12+
13+
type Socket = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
14+
15+
async fn receive(socket: &mut Socket) -> Value {
16+
let frame = tokio::time::timeout(Duration::from_secs(2), socket.next())
17+
.await
18+
.expect("relay response deadline")
19+
.expect("connection open")
20+
.expect("frame");
21+
serde_json::from_str(frame.to_text().expect("text frame")).expect("relay JSON")
22+
}
23+
24+
async fn subscribe(socket: &mut Socket, pubkey: PublicKey) {
25+
socket
26+
.send(Message::Text(
27+
json!(["REQ", "pair", {
28+
"kinds": [24134], "#p": [pubkey.to_hex()]
29+
}])
30+
.to_string()
31+
.into(),
32+
))
33+
.await
34+
.unwrap();
35+
assert_eq!(receive(socket).await[0], "EOSE");
36+
}
37+
38+
async fn forward(sender: &mut Socket, receiver: &mut Socket, event: Event) -> Event {
39+
sender
40+
.send(Message::Text(json!(["EVENT", event]).to_string().into()))
41+
.await
42+
.unwrap();
43+
let ack = receive(sender).await;
44+
assert_eq!(ack[0], "OK");
45+
assert_eq!(ack[2], true, "relay must accept each protocol event: {ack}");
46+
let delivery = receive(receiver).await;
47+
assert_eq!(delivery[0], "EVENT");
48+
let received: Event = serde_json::from_value(delivery[2].clone()).unwrap();
49+
received.verify().unwrap();
50+
received
51+
}
52+
53+
fn target_message(keys: &Keys, source: PublicKey, message: Value) -> Event {
54+
let encrypted = nip44::encrypt(
55+
keys.secret_key(),
56+
&source,
57+
message.to_string(),
58+
nip44::Version::V2,
59+
)
60+
.unwrap();
61+
EventBuilder::new(Kind::Custom(24134), encrypted)
62+
.tags([Tag::public_key(source)])
63+
.sign_with_keys(keys)
64+
.unwrap()
65+
}
66+
67+
fn decrypt(keys: &Keys, event: &Event) -> Value {
68+
serde_json::from_str(&nip44::decrypt(keys.secret_key(), &event.pubkey, &event.content).unwrap())
69+
.unwrap()
70+
}
71+
72+
#[tokio::test]
73+
async fn fifth_correct_guess_delivers_identity_and_completion() {
74+
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
75+
let url = format!("ws://{}", listener.local_addr().unwrap());
76+
let server = tokio::spawn(run_server(listener, Arc::new(Relay::new())));
77+
let (mut source, qr) = PairingSession::new_source(url.clone());
78+
let target = Keys::generate();
79+
let (mut source_socket, _) = connect_async(&url).await.unwrap();
80+
let (mut target_socket, _) = connect_async(&url).await.unwrap();
81+
subscribe(&mut source_socket, source.pubkey()).await;
82+
subscribe(&mut target_socket, target.public_key()).await;
83+
let session_id = crypto::derive_session_id(&qr.session_secret);
84+
let hex = |bytes: &[u8]| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>();
85+
let offer = target_message(
86+
&target,
87+
source.pubkey(),
88+
json!({
89+
"type": "offer", "session_id": hex(&session_id), "version": 1,
90+
"confirmation": "desktop-code-v1"
91+
}),
92+
);
93+
let offer = forward(&mut target_socket, &mut source_socket, offer).await;
94+
assert!(source.handle_offer_with_confirmation(&offer).unwrap().1);
95+
let (code, challenge) = source.start_desktop_code().unwrap();
96+
let challenge = forward(&mut source_socket, &mut target_socket, challenge).await;
97+
assert_eq!(
98+
decrypt(&target, &challenge),
99+
json!({"type": "desktop-code"})
100+
);
101+
let wrong = if code == "000000" { "000001" } else { "000000" };
102+
for attempt in 1..=5 {
103+
let submission = target_message(
104+
&target,
105+
source.pubkey(),
106+
json!({
107+
"type": "code-submit", "code": if attempt == 5 { &code } else { wrong },
108+
"request_id": attempt.to_string()
109+
}),
110+
);
111+
let submission = forward(&mut target_socket, &mut source_socket, submission).await;
112+
let (response, accepted) = source.handle_target_code(&submission).unwrap();
113+
assert_eq!(accepted, attempt == 5);
114+
let response = forward(&mut source_socket, &mut target_socket, response).await;
115+
let message = decrypt(&target, &response);
116+
if attempt < 5 {
117+
assert_eq!(
118+
message,
119+
json!({"type":"code-rejected", "request_id":attempt.to_string(), "remaining_attempts":5-attempt})
120+
);
121+
} else {
122+
let ecdh =
123+
nostr::util::generate_shared_key(target.secret_key(), &source.pubkey()).unwrap();
124+
let (_, sas_input) = crypto::derive_sas(&ecdh, &qr.session_secret);
125+
let proof = crypto::derive_transcript_hash(
126+
&session_id,
127+
&source.pubkey().to_bytes(),
128+
&target.public_key().to_bytes(),
129+
&sas_input,
130+
&qr.session_secret,
131+
);
132+
assert_eq!(
133+
message,
134+
json!({"type":"sas-confirm", "transcript_hash":hex(&proof)})
135+
);
136+
}
137+
}
138+
// Source event seven must reach the target and decrypt to the identity.
139+
let identity = Keys::generate();
140+
let secret = identity.secret_key().to_bech32().unwrap();
141+
let payload = source
142+
.send_payload(PayloadType::Nsec, Zeroizing::new(secret.clone()))
143+
.unwrap();
144+
let payload = forward(&mut source_socket, &mut target_socket, payload).await;
145+
let imported = decrypt(&target, &payload);
146+
assert_eq!(imported["payload"], secret);
147+
assert_eq!(
148+
Keys::parse(imported["payload"].as_str().unwrap())
149+
.unwrap()
150+
.public_key(),
151+
identity.public_key()
152+
);
153+
// Target event seven must reach source and finish the session.
154+
let complete = target_message(
155+
&target,
156+
source.pubkey(),
157+
json!({"type":"complete", "success":true}),
158+
);
159+
let complete = forward(&mut target_socket, &mut source_socket, complete).await;
160+
source.handle_complete(&complete).unwrap();
161+
assert_eq!(source.state(), SessionState::Completed);
162+
server.abort();
163+
}

‎crates/buzz-pair-relay/tests/integration.rs‎

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -439,16 +439,20 @@ async fn test_second_sub_same_id() {
439439
}
440440

441441
/// 9. Connection closes after 120 s (virtual time).
442-
#[tokio::test(start_paused = true)]
442+
#[tokio::test]
443443
async fn test_120s_timeout() {
444444
let url = start_relay().await;
445445
let mut ws = connect(&url).await;
446446

447+
subscribe(&mut ws, "ready", P_A).await;
448+
tokio::time::pause();
447449
// Advance virtual time past the connection timeout.
448450
tokio::time::advance(Duration::from_secs(121)).await;
449451
// Yield to let the relay task run its deadline branch.
450452
tokio::task::yield_now().await;
451453

454+
// Real network I/O must not race an auto-advancing assertion timeout.
455+
tokio::time::resume();
452456
assert_closed(&mut ws).await;
453457
}
454458

@@ -605,8 +609,8 @@ async fn test_global_conn_cap() {
605609
let _new = connect(&url).await;
606610
}
607611

608-
/// 18. Session event cap: 6 EVENTs are accepted; 7th is rejected with
609-
/// "session event limit reached". (The relay's hard cap is 6 per
612+
/// 18. Session event cap: 8 EVENTs are accepted; 9th is rejected with
613+
/// "session event limit reached". (The relay's hard cap is 8 per
610614
/// connection, which is tighter than the per-window rate limit of 10.)
611615
#[tokio::test]
612616
async fn test_event_rate_limit() {
@@ -619,8 +623,8 @@ async fn test_event_rate_limit() {
619623

620624
let mut pub_ws = connect(&url).await;
621625

622-
// First 6 events must be accepted (session cap = 6).
623-
for i in 0..6u64 {
626+
// First 8 events must be accepted (session cap = 8).
627+
for i in 0..8u64 {
624628
send(
625629
&mut pub_ws,
626630
&json!(["EVENT", make_signed_event(&sk, &pk, P_A, i)]),
@@ -637,10 +641,10 @@ async fn test_event_rate_limit() {
637641
let _ = recv(&mut sub_ws).await;
638642
}
639643

640-
// 7th must be rejected by the session cap.
644+
// 9th must be rejected by the session cap.
641645
send(
642646
&mut pub_ws,
643-
&json!(["EVENT", make_signed_event(&sk, &pk, P_A, 6)]),
647+
&json!(["EVENT", make_signed_event(&sk, &pk, P_A, 8)]),
644648
)
645649
.await;
646650
let resp = recv(&mut pub_ws).await;
@@ -931,9 +935,9 @@ async fn test_write_timeout() {
931935
send(&mut sub_ws, &json!(["REQ", "s1", {"#p": [P_A]}])).await;
932936
// Don't call recv — leave the EOSE unread.
933937

934-
// Flood from a publisher — stay within the 6-event session cap.
938+
// Flood from a publisher — stay within the 8-event session cap.
935939
let mut pub_ws = connect(&url).await;
936-
for i in 0..6u64 {
940+
for i in 0..8u64 {
937941
send(
938942
&mut pub_ws,
939943
&json!(["EVENT", make_signed_event(&sk, &pk, P_A, i)]),
@@ -1016,9 +1020,9 @@ async fn test_control_msg_backpressure() {
10161020
send(&mut sub_ws, &json!(["REQ", "s1", {"#p": [P_A]}])).await;
10171021
// Leave EOSE unread to fill the channel quickly.
10181022

1019-
// Flood within the 6-event session cap.
1023+
// Flood within the 8-event session cap.
10201024
let mut pub_ws = connect(&url).await;
1021-
for i in 0..6u64 {
1025+
for i in 0..8u64 {
10221026
send(
10231027
&mut pub_ws,
10241028
&json!(["EVENT", make_signed_event(&sk, &pk, P_A, i)]),
@@ -1132,9 +1136,9 @@ async fn test_fan_out_drop_doesnt_close() {
11321136
let mut sub_ws = connect(&url).await;
11331137
send(&mut sub_ws, &json!(["REQ", "s1", {"#p": [P_A]}])).await;
11341138

1135-
// Flood from a publisher — stay within the 6-event session cap.
1139+
// Flood from a publisher — stay within the 8-event session cap.
11361140
let mut pub_ws = connect(&url).await;
1137-
for i in 0..6u64 {
1141+
for i in 0..8u64 {
11381142
send(
11391143
&mut pub_ws,
11401144
&json!(["EVENT", make_signed_event(&sk, &pk, P_A, i)]),
@@ -1164,7 +1168,7 @@ async fn test_reader_backpressure_closes() {
11641168

11651169
// Publisher floods events up to the session cap.
11661170
let mut pub_ws = connect(&url).await;
1167-
for i in 0..6u64 {
1171+
for i in 0..8u64 {
11681172
send(
11691173
&mut pub_ws,
11701174
&json!(["EVENT", make_signed_event(&sk, &pk, P_A, i)]),
@@ -1178,14 +1182,21 @@ async fn test_reader_backpressure_closes() {
11781182

11791183
/// 42. Connection closes promptly after 120 s (virtual time).
11801184
/// Explicit duplicate of test 9 with a slightly different assertion style.
1181-
#[tokio::test(start_paused = true)]
1185+
#[tokio::test]
11821186
async fn test_cancellation_immediate() {
11831187
let url = start_relay().await;
11841188
let mut ws = connect(&url).await;
11851189

1190+
// Observe a relay response so the connection deadline is installed.
1191+
subscribe(&mut ws, "ready", P_A).await;
1192+
tokio::time::pause();
11861193
tokio::time::advance(Duration::from_secs(121)).await;
11871194
tokio::task::yield_now().await;
11881195

1196+
// TCP closure is real I/O; do not auto-advance the assertion timeout
1197+
// while the OS is still delivering the close frame.
1198+
tokio::time::resume();
1199+
11891200
// The connection must be closed — not just slow.
11901201
assert_closed(&mut ws).await;
11911202
}

0 commit comments

Comments
 (0)