Skip to content

Commit e74abf3

Browse files
jemiahwSon of Antonclaude
committed
Merge origin/main into jemiah/events-pruning-search
Resolve the conflict in store/event.rs: keep get_events_by_ids_routed deleted. Port main's route_read changes (fallible route_read; release the reader before the writer re-run) onto the exact-key hydrator in store/event_hydration.rs, its only remaining routed by-id hydrator. Signed-off-by: Jemiah Westerman <[email protected]> Co-authored-by: Son of Anton <8e0ef2ab02d69a7ac089ef5eca90d1a3fbbdc546f6322dc34d0c4f3deecea7f4@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <[email protected]>
2 parents 882d89a + 2bd4917 commit e74abf3

149 files changed

Lines changed: 10286 additions & 1354 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ Before planning or reviewing a non-trivial change:
1717
4. For any change to `migrations/`, `schema/`, or schema-dependent `buzz-db`
1818
queries, read [docs/database.md](docs/database.md): no new triggers,
1919
functions, or foreign keys; no data backfills in migrations; update every
20-
schema location; and keep every migration compatible with the relay that
21-
is currently deployed.
20+
schema location; keep every migration compatible with the relay that
21+
is currently deployed; and never make a migration refuse a populated
22+
table.
2223
5. Check that the proposed design advances, or at least does not contradict,
2324
that product intent. Call out any intentional tension explicitly.
2425

‎Justfile‎

Lines changed: 11 additions & 6 deletions
Large diffs are not rendered by default.

‎PLANS/REPLICA_FULL_READ_ROUTING_DESIGN.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,12 @@ routing**: the read may be served from a read replica when
1414
`RoutePredicate::for_query` derives from the query shape. The seam fails closed
1515
to the writer on replica errors, with one deliberate exception: a statement
1616
cancelled by `statement_timeout` (SQLSTATE `57014`) is surfaced rather than
17-
re-run, because the writer would run the same slow statement. It is a genuine
18-
no-op until the budget is configured (`crates/buzz-db/src/lib.rs`).
17+
re-run, because the writer would run the same slow statement. A busy reader
18+
is the other exception: a subscription-history read that cannot get a reader
19+
connection within its bounded wait is rejected as retryable instead of moving
20+
to the writer, and history reads are capped per pod below the reader pool
21+
size (`Db::route_read`). It is a genuine no-op until the budget is configured
22+
(`crates/buzz-db/src/lib.rs`).
1923

2024
## Routing rule
2125

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub mod session;
2525
pub mod types;
2626

2727
pub use qr::QrPayload;
28-
pub use session::{PairingSession, Role, SessionState};
28+
pub use session::{PairingBinding, PairingSession, Role, SessionState};
2929
pub use types::{AbortReason, PairingMessage, PayloadType};
3030

3131
use thiserror::Error;

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

Lines changed: 88 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,20 @@ pub enum Role {
6262
Target,
6363
}
6464

65+
/// Public channel binding for independently authenticated application approval.
66+
/// This identifies the locked peers and transcript, not their account identity.
67+
#[derive(Debug, Clone, PartialEq, Eq)]
68+
pub struct PairingBinding {
69+
/// Identifier derived from this QR session's random secret.
70+
pub session_id: [u8; 32],
71+
/// The initiating device's ephemeral public key.
72+
pub source_pubkey: PublicKey,
73+
/// The receiving device's ephemeral public key.
74+
pub target_pubkey: PublicKey,
75+
/// The commitment verified by `sas-confirm`.
76+
pub transcript_hash: [u8; 32],
77+
}
78+
6579
/// Protocol state.
6680
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6781
pub enum SessionState {
@@ -115,6 +129,8 @@ pub struct PairingSession {
115129
desktop_code_requested: bool,
116130
desktop_code: Option<Zeroizing<String>>,
117131
code_attempts: u8,
132+
/// Strict target-side code-entry negotiation and request correlation.
133+
target_desktop_code: Option<desktop_code::TargetDesktopCode>,
118134
}
119135

120136
impl PairingSession {
@@ -150,6 +166,7 @@ impl PairingSession {
150166
desktop_code_requested: false,
151167
desktop_code: None,
152168
code_attempts: 0,
169+
target_desktop_code: None,
153170
};
154171

155172
(session, qr)
@@ -357,6 +374,13 @@ impl PairingSession {
357374
///
358375
/// Returns the session and the `offer` event to publish.
359376
pub fn new_target(qr: &QrPayload) -> Result<(Self, Event), PairingError> {
377+
Self::new_target_with_confirmation(qr, false)
378+
}
379+
380+
fn new_target_with_confirmation(
381+
qr: &QrPayload,
382+
desktop_code: bool,
383+
) -> Result<(Self, Event), PairingError> {
360384
let keys = Keys::generate();
361385
let session_id = derive_session_id(&qr.session_secret);
362386

@@ -383,13 +407,14 @@ impl PairingSession {
383407
desktop_code_requested: false,
384408
desktop_code: None,
385409
code_attempts: 0,
410+
target_desktop_code: desktop_code.then(desktop_code::TargetDesktopCode::default),
386411
};
387412

388413
// Build and return the offer event.
389414
let msg = PairingMessage::Offer {
390415
session_id: hex::encode(session_id),
391416
version: 1,
392-
confirmation: None,
417+
confirmation: desktop_code.then(|| "desktop-code-v1".into()),
393418
};
394419
let event = session.build_event(&msg)?;
395420
session.state = SessionState::Confirming;
@@ -408,6 +433,14 @@ impl PairingSession {
408433
self.expect_state(SessionState::Confirming)?;
409434
self.expect_role(Role::Target)?;
410435
self.validate_event_from_peer(event)?;
436+
if let Some(code) = &self.target_desktop_code {
437+
if !code.challenged || code.pending_request_id.is_none() {
438+
return Err(PairingError::UnexpectedMessage {
439+
expected: "desktop code challenge and submission".into(),
440+
got: "sas-confirm".into(),
441+
});
442+
}
443+
}
411444

412445
let msg = self.decrypt_message(event)?;
413446
let received_hash = match &msg {
@@ -443,6 +476,9 @@ impl PairingSession {
443476
}
444477

445478
self.state = SessionState::AwaitingConfirmation;
479+
if let Some(code) = &mut self.target_desktop_code {
480+
code.pending_request_id = None;
481+
}
446482
self.record_event(event);
447483
let code = self.sas_code.ok_or(PairingError::SasMismatch)?;
448484
Ok(format_sas(code))
@@ -487,13 +523,23 @@ impl PairingSession {
487523

488524
/// (Target) Build the `complete` event to publish.
489525
pub fn send_complete(&mut self) -> Result<Event, PairingError> {
526+
self.send_complete_with_result(true)
527+
}
528+
529+
/// (Target) Acknowledge whether the received payload was durably imported.
530+
/// Call only after the application has completed its secure-storage attempt.
531+
pub fn send_complete_with_result(&mut self, success: bool) -> Result<Event, PairingError> {
490532
self.check_expired()?;
491533
self.expect_state(SessionState::PayloadExchanged)?;
492534
self.expect_role(Role::Target)?;
493535

494-
let msg = PairingMessage::Complete { success: true };
536+
let msg = PairingMessage::Complete { success };
495537
let event = self.build_event(&msg)?;
496-
self.state = SessionState::Completed;
538+
self.state = if success {
539+
SessionState::Completed
540+
} else {
541+
SessionState::Aborted
542+
};
497543
Ok(event)
498544
}
499545
}
@@ -608,6 +654,45 @@ impl PairingSession {
608654
relays: self.relay_urls.clone(),
609655
}))
610656
}
657+
658+
/// Capture the live exchange's public channel binding, in source/target
659+
/// order on both devices. Source must first accept an offer. Applications
660+
/// submit this independently through each user's authenticated session;
661+
/// no application credential needs to travel over the pairing protocol.
662+
/// This method does not authorize exporting identity material.
663+
pub fn binding(&self) -> Result<PairingBinding, PairingError> {
664+
self.check_expired()?;
665+
if !matches!(
666+
self.state,
667+
SessionState::Confirming
668+
| SessionState::AwaitingConfirmation
669+
| SessionState::Transferring
670+
) {
671+
return Err(PairingError::UnexpectedMessage {
672+
expected: "live pairing with a locked peer".into(),
673+
got: "unbound or terminal session".into(),
674+
});
675+
}
676+
let peer = self.peer_pubkey.ok_or(PairingError::SasMismatch)?;
677+
let sas_input = self.sas_input.ok_or(PairingError::SasMismatch)?;
678+
let own = self.keys.public_key();
679+
let (source_pubkey, target_pubkey) = match self.role {
680+
Role::Source => (own, peer),
681+
Role::Target => (peer, own),
682+
};
683+
Ok(PairingBinding {
684+
session_id: self.session_id,
685+
source_pubkey,
686+
target_pubkey,
687+
transcript_hash: derive_transcript_hash(
688+
&self.session_id,
689+
&source_pubkey.to_bytes(),
690+
&target_pubkey.to_bytes(),
691+
&sas_input,
692+
&self.session_secret,
693+
),
694+
})
695+
}
611696
}
612697

613698
#[cfg(test)]

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,29 @@ fn readiness_delay_and_late_scan_share_the_original_deadline() {
194194
Err(PairingError::SessionExpired)
195195
));
196196
}
197+
198+
#[test]
199+
fn strict_target_expiry_and_cancellation_block_every_entry_point() {
200+
for cancel in [false, true] {
201+
let (mut source, qr) = PairingSession::new_source("wss://relay.test".into());
202+
let (mut target, offer) = PairingSession::new_target_with_desktop_code(&qr).unwrap();
203+
source.handle_offer_with_confirmation(&offer).unwrap();
204+
let (code, challenge) = source.start_desktop_code().unwrap();
205+
target.handle_desktop_code(&challenge).unwrap();
206+
let submission = target.submit_desktop_code(Zeroizing::new(code)).unwrap();
207+
let (proof, _) = source.handle_target_code(&submission).unwrap();
208+
if cancel {
209+
target.abort(AbortReason::UserDenied).unwrap();
210+
} else {
211+
target.created_at = Instant::now() - target.timeout - Duration::from_secs(1);
212+
}
213+
assert!(target.handle_desktop_code(&challenge).is_err());
214+
assert!(target
215+
.submit_desktop_code(Zeroizing::new("123456".into()))
216+
.is_err());
217+
assert!(target.handle_code_rejected(&proof).is_err());
218+
assert!(target.handle_sas_confirm(&proof).is_err());
219+
assert!(target.confirm_target_sas().is_err());
220+
assert!(target.send_complete_with_result(true).is_err());
221+
}
222+
}

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

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,117 @@ impl PairingSession {
5555
Ok((rejection, false))
5656
}
5757
}
58+
59+
/// Target-only state. The source never learns the pending code locally.
60+
#[derive(Default)]
61+
pub(super) struct TargetDesktopCode {
62+
pub(super) challenged: bool,
63+
pub(super) pending_request_id: Option<String>,
64+
remaining_attempts: Option<u8>,
65+
}
66+
67+
impl PairingSession {
68+
/// Create a target that requires `desktop-code-v1`, with no SAS fallback.
69+
///
70+
/// The caller must handle the source challenge, submit the user-entered code,
71+
/// verify the source proof, and call `confirm_target_sas` before importing.
72+
pub fn new_target_with_desktop_code(qr: &QrPayload) -> Result<(Self, Event), PairingError> {
73+
Self::new_target_with_confirmation(qr, true)
74+
}
75+
76+
/// Validate the locked source's code-entry challenge. It contains no code.
77+
/// Duplicate or replacement challenges never reset an outstanding attempt.
78+
pub fn handle_desktop_code(&mut self, event: &Event) -> Result<(), PairingError> {
79+
self.check_expired()?;
80+
self.expect_role(Role::Target)?;
81+
self.expect_state(SessionState::Confirming)?;
82+
self.validate_event_from_peer(event)?;
83+
let code = self
84+
.target_desktop_code
85+
.as_ref()
86+
.ok_or(PairingError::SasMismatch)?;
87+
if code.challenged {
88+
return Err(PairingError::SasMismatch);
89+
}
90+
match self.decrypt_message(event)? {
91+
PairingMessage::DesktopCode {} => {}
92+
other => return Err(unexpected("desktop-code", &other)),
93+
}
94+
if let Some(code) = &mut self.target_desktop_code {
95+
code.challenged = true;
96+
}
97+
self.record_event(event);
98+
Ok(())
99+
}
100+
101+
/// Encrypt one six-ASCII-digit user submission with a fresh request ID.
102+
///
103+
/// Only one request may be outstanding. A correlated rejection allows the
104+
/// next submission; callers must not retry a pending guess with a new ID.
105+
pub fn submit_desktop_code(&mut self, code: Zeroizing<String>) -> Result<Event, PairingError> {
106+
self.check_expired()?;
107+
self.expect_role(Role::Target)?;
108+
self.expect_state(SessionState::Confirming)?;
109+
let target = self
110+
.target_desktop_code
111+
.as_ref()
112+
.ok_or(PairingError::SasMismatch)?;
113+
if !target.challenged
114+
|| target.pending_request_id.is_some()
115+
|| code.len() != 6
116+
|| !code.bytes().all(|b| b.is_ascii_digit())
117+
{
118+
return Err(PairingError::SasMismatch);
119+
}
120+
let request_id = hex::encode(rand::random::<[u8; 16]>());
121+
let mut message = PairingMessage::CodeSubmit {
122+
code: (*code).clone(),
123+
request_id: request_id.clone(),
124+
};
125+
let result = self.build_event(&message);
126+
if let PairingMessage::CodeSubmit { code, .. } = &mut message {
127+
code.zeroize();
128+
}
129+
let event = result?;
130+
if let Some(target) = &mut self.target_desktop_code {
131+
target.pending_request_id = Some(request_id);
132+
}
133+
Ok(event)
134+
}
135+
136+
/// Validate a rejection for the pending request and return guesses remaining.
137+
///
138+
/// Unrelated, stale, duplicate and non-decreasing budgets leave the pending
139+
/// request unchanged. Zero remaining guesses permanently aborts the session.
140+
pub fn handle_code_rejected(&mut self, event: &Event) -> Result<u8, PairingError> {
141+
self.check_expired()?;
142+
self.expect_role(Role::Target)?;
143+
self.expect_state(SessionState::Confirming)?;
144+
self.validate_event_from_peer(event)?;
145+
let (request_id, remaining_attempts) = match self.decrypt_message(event)? {
146+
PairingMessage::CodeRejected {
147+
request_id,
148+
remaining_attempts,
149+
} => (request_id, remaining_attempts),
150+
other => return Err(unexpected("code-rejected", &other)),
151+
};
152+
let target = self
153+
.target_desktop_code
154+
.as_ref()
155+
.ok_or(PairingError::SasMismatch)?;
156+
if target.pending_request_id.as_deref() != Some(request_id.as_str())
157+
|| remaining_attempts >= target.remaining_attempts.unwrap_or(5)
158+
{
159+
return Err(PairingError::SasMismatch);
160+
}
161+
if let Some(target) = &mut self.target_desktop_code {
162+
target.pending_request_id = None;
163+
target.remaining_attempts = Some(remaining_attempts);
164+
}
165+
self.record_event(event);
166+
if remaining_attempts == 0 {
167+
self.state = SessionState::Aborted;
168+
}
169+
Ok(remaining_attempts)
170+
}
171+
}

0 commit comments

Comments
 (0)