Skip to content

Commit 0056b18

Browse files
committed
fix(pairing): preserve pending code checks and clear transferred secrets
Signed-off-by: kenny lopez <[email protected]>
1 parent 66edf50 commit 0056b18

6 files changed

Lines changed: 225 additions & 24 deletions

File tree

‎desktop/src-tauri/src/commands/pairing.rs‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,35 @@ enum PairingMode {
4646

4747
#[derive(Clone)]
4848
struct PairingTaskContext {
49-
payload: Option<Zeroizing<String>>,
49+
payload: Arc<std::sync::Mutex<Option<Zeroizing<String>>>>,
5050
mode: PairingMode,
5151
generation: Arc<AtomicU64>,
5252
generation_fence: Arc<std::sync::Mutex<()>>,
5353
task_generation: u64,
5454
}
5555

56+
impl PairingTaskContext {
57+
fn take_payload(&self) -> Result<Zeroizing<String>, String> {
58+
let _fence = self.generation_fence.lock().map_err(|e| e.to_string())?;
59+
ensure_pairing_task_is_current(&self.generation, self.task_generation)?;
60+
self.payload
61+
.lock()
62+
.map_err(|e| e.to_string())?
63+
.take()
64+
.ok_or_else(|| "Pairing payload missing".into())
65+
}
66+
67+
fn clear_payload_if_current(&self) {
68+
let _fence = self
69+
.generation_fence
70+
.lock()
71+
.unwrap_or_else(|e| e.into_inner());
72+
if pairing_task_is_current(&self.generation, self.task_generation) {
73+
*self.payload.lock().unwrap_or_else(|e| e.into_inner()) = None;
74+
}
75+
}
76+
}
77+
5678
/// Managed Tauri state for an active pairing session.
5779
pub struct PairingHandle {
5880
session: Arc<tokio::sync::Mutex<Option<PairingSession>>>,
@@ -67,7 +89,7 @@ pub struct PairingHandle {
6789
outbound_tx: std::sync::Mutex<Option<mpsc::Sender<String>>>,
6890
/// Pre-built payload string (contains nsec) to send after SAS confirmation.
6991
/// Wrapped in Zeroizing so the nsec is cleared from memory on drop.
70-
payload: std::sync::Mutex<Option<Zeroizing<String>>>,
92+
payload: Arc<std::sync::Mutex<Option<Zeroizing<String>>>>,
7193
mode: Arc<std::sync::Mutex<PairingMode>>,
7294
}
7395

@@ -80,7 +102,7 @@ impl PairingHandle {
80102
start_lock: tokio::sync::Mutex::new(()),
81103
cancel: std::sync::Mutex::new(None),
82104
outbound_tx: std::sync::Mutex::new(None),
83-
payload: std::sync::Mutex::new(None),
105+
payload: Arc::new(std::sync::Mutex::new(None)),
84106
mode: Arc::new(std::sync::Mutex::new(PairingMode::SendIdentity)),
85107
}
86108
}
@@ -172,7 +194,7 @@ async fn start_pairing_session(
172194
pairing_relay_url,
173195
Arc::clone(&pairing.session),
174196
PairingTaskContext {
175-
payload: pairing.payload.lock().map_err(|e| e.to_string())?.clone(),
197+
payload: Arc::clone(&pairing.payload),
176198
mode,
177199
generation: Arc::clone(&pairing.generation),
178200
generation_fence: Arc::clone(&pairing.generation_fence),
@@ -322,6 +344,7 @@ async fn pairing_ws_task(
322344
let _ = app.emit("pairing-error", PairingErrorPayload { message: e });
323345
}
324346
}
347+
context.clear_payload_if_current();
325348
clear_pairing_session_if_current(&session, &context.generation, context.task_generation).await;
326349
}
327350

@@ -362,7 +385,6 @@ async fn pairing_ws_task_inner(
362385
let mut read = futures_util::stream::iter(pending.into_iter().map(Ok)).chain(read);
363386

364387
let mut code_entry = false;
365-
let mut payload = context.payload.clone();
366388
let hard_timeout = tokio::time::sleep(Duration::from_secs(130));
367389
tokio::pin!(hard_timeout);
368390

@@ -438,7 +460,7 @@ async fn pairing_ws_task_inner(
438460
continue;
439461
}
440462
Ok((proof, true)) => {
441-
let identity = payload.take().ok_or("Pairing payload missing")?;
463+
let identity = context.take_payload()?;
442464
let transfer = s.send_payload(PayloadType::Custom, identity)
443465
.map_err(|e| e.to_string())?;
444466
ensure_pairing_task_is_current(&context.generation, context.task_generation)?;

‎desktop/src-tauri/src/commands/pairing_generation_tests.rs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,37 @@ async fn current_task_clears_its_session() {
127127

128128
assert!(session.lock().await.is_none());
129129
}
130+
131+
fn prepared_context(pairing: &PairingHandle) -> super::PairingTaskContext {
132+
*pairing.payload.lock().unwrap() = Some(zeroize::Zeroizing::new("test-identity".into()));
133+
super::PairingTaskContext {
134+
payload: Arc::clone(&pairing.payload),
135+
mode: super::PairingMode::SendIdentity,
136+
generation: Arc::clone(&pairing.generation),
137+
generation_fence: Arc::clone(&pairing.generation_fence),
138+
task_generation: pairing.generation.load(Ordering::SeqCst),
139+
}
140+
}
141+
142+
#[test]
143+
fn code_entry_transfer_consumes_the_managed_secret() {
144+
let pairing = PairingHandle::new();
145+
let context = prepared_context(&pairing);
146+
let identity = context.take_payload().unwrap();
147+
assert_eq!(identity.as_str(), "test-identity");
148+
assert!(pairing.payload.lock().unwrap().is_none());
149+
assert!(context.take_payload().is_err());
150+
}
151+
152+
#[test]
153+
fn terminal_worker_clears_secret_but_stale_worker_cannot_touch_replacement() {
154+
let pairing = PairingHandle::new();
155+
let context = prepared_context(&pairing);
156+
context.clear_payload_if_current();
157+
assert!(pairing.payload.lock().unwrap().is_none());
158+
let context = prepared_context(&pairing);
159+
pairing.generation.fetch_add(1, Ordering::SeqCst);
160+
context.clear_payload_if_current();
161+
assert!(context.take_payload().is_err());
162+
assert!(pairing.payload.lock().unwrap().is_some());
163+
}

‎mobile/lib/app.dart‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,13 @@ class App extends HookConsumerWidget {
415415
child: Stack(
416416
fit: StackFit.expand,
417417
children: [
418-
child ?? const SizedBox.shrink(),
418+
ExcludeSemantics(
419+
excluding: pairedCommunity != null,
420+
child: AbsorbPointer(
421+
absorbing: pairedCommunity != null,
422+
child: child ?? const SizedBox.shrink(),
423+
),
424+
),
419425
// Cover the navigator while onboarding is removed and the
420426
// destination installs the matching avatar-flight route.
421427
if (pairedCommunity != null)

‎mobile/lib/features/pairing/pairing_provider.dart‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,9 @@ class PairingNotifier extends Notifier<PairingState> {
161161
],
162162
);
163163
try {
164-
return await result.future.timeout(const Duration(seconds: 10));
164+
// Keep this logical attempt pending until its response or session cleanup.
165+
// A local deadline cannot undo a guess already consumed by the source.
166+
return await result.future;
165167
} finally {
166168
if (identical(_codeResult, result)) {
167169
_codeResult = null;

‎mobile/test/features/pairing/pairing_provider_test.dart‎

Lines changed: 78 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import 'package:buzz/features/pairing/pairing_page.dart';
2+
import 'package:buzz/shared/theme/theme.dart';
3+
import 'package:flutter/material.dart';
14
import 'package:buzz/shared/community/paired_community_landing.dart';
25
import 'dart:async';
36
import 'dart:convert';
@@ -294,10 +297,13 @@ void main() {
294297
expect(container.read(pairingProvider).status, PairingStatus.storing);
295298
}
296299

297-
test(
298-
'desktop-only code is verified remotely before import approval',
299-
() async {
300-
await notifier.pair(pairingCode);
300+
testWidgets(
301+
'delayed desktop responses retain one attempt and leave code entry',
302+
(tester) async {
303+
final pairing = notifier.pair(pairingCode);
304+
await tester.pump();
305+
await tester.pump(const Duration(milliseconds: 500));
306+
await pairing;
301307
expect(socket.published.single['tags'], hasLength(1));
302308
expect(
303309
socket
@@ -315,6 +321,17 @@ void main() {
315321
final first = socket.decryptedPublishedMessages(sourceSecret).last;
316322
expect(first['type'], 'code-submit');
317323
expect(first['code'], '111111');
324+
bool? wrongResult;
325+
unawaited(wrong.then((value) => wrongResult = value));
326+
await tester.pump(const Duration(seconds: 11));
327+
expect(wrongResult, isNull);
328+
expect(await notifier.verifyDesktopCode('111111'), isFalse);
329+
expect(
330+
socket
331+
.decryptedPublishedMessages(sourceSecret)
332+
.where((m) => m['type'] == 'code-submit'),
333+
hasLength(1),
334+
);
318335
socket.sendSourceMessage(
319336
sourceSecret: sourceSecret,
320337
sessionSecretHex: sessionSecretHex,
@@ -326,46 +343,88 @@ void main() {
326343
);
327344
expect(await wrong, isFalse);
328345
expect(importAuth.lastCommunity, isNull);
329-
final correct = notifier.verifyDesktopCode('222222');
346+
await tester.pumpWidget(
347+
UncontrolledProviderScope(
348+
container: container,
349+
child: MaterialApp(
350+
theme: AppTheme.light(),
351+
home: const PairingPage(),
352+
),
353+
),
354+
);
355+
await tester.enterText(
356+
find.byKey(const Key('pairing-code-input')),
357+
'222222',
358+
);
359+
await tester.pump(const Duration(seconds: 11));
360+
expect(find.text('Enter pairing code'), findsOneWidget);
361+
expect(
362+
find.text('Couldn’t check the code. Try again.'),
363+
findsNothing,
364+
);
365+
expect(
366+
socket
367+
.decryptedPublishedMessages(sourceSecret)
368+
.where((m) => m['type'] == 'code-submit'),
369+
hasLength(2),
370+
);
330371
socket.sendSourceMessage(
331372
sourceSecret: sourceSecret,
332373
sessionSecretHex: sessionSecretHex,
333374
message: {'type': 'sas-confirm'},
334375
includeTranscriptHash: true,
335376
);
336-
expect(await correct, isTrue);
377+
socket.sendSourceMessage(
378+
sourceSecret: sourceSecret,
379+
sessionSecretHex: sessionSecretHex,
380+
message: {
381+
'type': 'payload',
382+
'payload_type': 'credentials',
383+
'payload': jsonEncode({
384+
'relayUrl': 'https://relay.test',
385+
'pubkey': nostr.Keys(sourceSecret).public,
386+
'nsec': nostr.Keys(sourceSecret).nsec,
387+
}),
388+
},
389+
);
390+
await tester.pump();
391+
expect(find.text('Enter pairing code'), findsNothing);
392+
expect(find.text('Protect your identity'), findsOneWidget);
337393
expect(
338394
container.read(pairingProvider).status,
339395
PairingStatus.confirmingSas,
340396
);
341397
expect(importAuth.lastCommunity, isNull);
342398
notifier.setProtectSensitiveActions(false);
343399
notifier.confirmSas();
344-
await Future<void>.delayed(Duration.zero);
345-
expect(
346-
container.read(pairingProvider).status,
347-
PairingStatus.transferring,
348-
);
400+
await tester.pump();
401+
expect(container.read(pairingProvider).status, PairingStatus.storing);
349402
expect(
350403
socket
351404
.decryptedPublishedMessages(sourceSecret)
352405
.where((m) => m['type'] == 'sas-confirm'),
353406
isEmpty,
354407
);
408+
notifier.reset();
409+
await tester.pumpWidget(const SizedBox.shrink());
355410
},
356411
);
357412

358-
test(
359-
'final rejected guess exits the session and reset cancels pending verification',
360-
() async {
361-
await notifier.pair(pairingCode);
413+
testWidgets(
414+
'delayed final rejection exits the session and reset cancels pending verification',
415+
(tester) async {
416+
final pairing = notifier.pair(pairingCode);
417+
await tester.pump();
418+
await tester.pump(const Duration(milliseconds: 500));
419+
await pairing;
362420
socket.sendSourceMessage(
363421
sourceSecret: sourceSecret,
364422
sessionSecretHex: sessionSecretHex,
365423
message: {'type': 'desktop-code'},
366424
);
367425
final result = notifier.verifyDesktopCode('111111');
368426
final request = socket.decryptedPublishedMessages(sourceSecret).last;
427+
await tester.pump(const Duration(seconds: 11));
369428
socket.sendSourceMessage(
370429
sourceSecret: sourceSecret,
371430
sessionSecretHex: sessionSecretHex,
@@ -379,7 +438,10 @@ void main() {
379438
expect(container.read(pairingProvider).status, PairingStatus.error);
380439
expect(importAuth.lastCommunity, isNull);
381440
notifier.reset();
382-
await notifier.pair(pairingCode);
441+
final nextPairing = notifier.pair(pairingCode);
442+
await tester.pump();
443+
await tester.pump(const Duration(milliseconds: 500));
444+
await nextPairing;
383445
socket.sendSourceMessage(
384446
sourceSecret: sourceSecret,
385447
sessionSecretHex: sessionSecretHex,

‎mobile/test/widget_test.dart‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import 'dart:async';
2+
import 'package:flutter/material.dart';
3+
import 'package:buzz/shared/community/paired_community_landing.dart';
14
import 'package:flutter_test/flutter_test.dart';
25
import 'package:hooks_riverpod/hooks_riverpod.dart';
36
import 'package:shared_preferences/shared_preferences.dart';
@@ -7,6 +10,78 @@ import 'package:buzz/shared/auth/auth.dart';
710
import 'package:buzz/shared/theme/theme_provider.dart';
811

912
void main() {
13+
testWidgets('pairing loading cover blocks hidden input and semantics', (
14+
tester,
15+
) async {
16+
SharedPreferences.setMockInitialValues({});
17+
final prefs = await SharedPreferences.getInstance();
18+
final container = ProviderContainer(
19+
overrides: [
20+
authProvider.overrideWith(() => _FakeAuthNotifier()),
21+
ageSignalProvider.overrideWith(() => _AllowedAgeSignalNotifier()),
22+
savedPrefsProvider.overrideWithValue(prefs),
23+
],
24+
);
25+
addTearDown(container.dispose);
26+
final semantics = tester.ensureSemantics();
27+
String semanticsTree() => tester
28+
.binding
29+
.renderViews
30+
.single
31+
.owner!
32+
.semanticsOwner!
33+
.rootSemanticsNode!
34+
.toStringDeep();
35+
await tester.pumpWidget(
36+
UncontrolledProviderScope(container: container, child: const App()),
37+
);
38+
await tester.pump();
39+
var taps = 0;
40+
final navigator = tester.state<NavigatorState>(
41+
find.byType(Navigator).first,
42+
);
43+
unawaited(
44+
navigator.push(
45+
MaterialPageRoute<void>(
46+
builder: (_) => Scaffold(
47+
body: Align(
48+
alignment: Alignment.topLeft,
49+
child: TextButton(
50+
onPressed: () => taps++,
51+
child: const Text('Hidden action'),
52+
),
53+
),
54+
),
55+
),
56+
),
57+
);
58+
await tester.pumpAndSettle();
59+
final button = find.text('Hidden action');
60+
final location = tester.getCenter(button);
61+
expect(semanticsTree(), contains('Hidden action'));
62+
container
63+
.read(pairedCommunityLandingProvider.notifier)
64+
.request(
65+
Community(
66+
id: 'test',
67+
addedAt: DateTime(2026),
68+
name: 'Test',
69+
relayUrl: 'https://relay.test',
70+
),
71+
);
72+
await tester.pump();
73+
await tester.tapAt(location);
74+
expect(taps, 0);
75+
expect(semanticsTree(), isNot(contains('Hidden action')));
76+
container.read(pairedCommunityLandingProvider.notifier).clear();
77+
await tester.pump();
78+
expect(semanticsTree(), contains('Hidden action'));
79+
await tester.tapAt(location);
80+
expect(taps, 1);
81+
await tester.pumpWidget(const SizedBox.shrink());
82+
semantics.dispose();
83+
});
84+
1085
testWidgets('App renders pairing page when unauthenticated', (
1186
WidgetTester tester,
1287
) async {

0 commit comments

Comments
 (0)