1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.
//! Resolving a [`PendingAction`].
//!
//! A flow that needs the application's decision surfaces
//! [`DeRecEvent::ActionRequired`](crate::protocol::DeRecEvent::ActionRequired) and stops. [`DeRecProtocol::accept`] and
//! [`DeRecProtocol::reject`] are how that decision comes back, and each
//! dispatches on the action to the handler that raised it.
use super::context::{Exchange, Round, local, pairing_config};
use super::events::{DeRecEvent, PendingAction};
use super::obligation::{Obligation, respond_to_failure, settle};
use super::stores::borrow_stores;
use super::traits::{
DeRecChannelStore, DeRecSecretStore, DeRecShareStore, DeRecStateStore, DeRecTransport,
DeRecUserSecretStore,
};
use super::{DeRecProtocol, handlers};
use crate::Error;
use crate::Result;
use crate::derec_message;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::protocol::types::ReplicaFilter;
use crate::protocol::types::ReplicaRole;
use crate::protocol::types::{ChannelQuery, ChannelStatus};
use crate::types::ReplicaId;
use derec_proto::SenderKind;
use derec_proto::StatusEnum;
use derec_proto::TransportProtocol;
impl<
Ch: DeRecChannelStore,
Sh: DeRecShareStore,
Ss: DeRecSecretStore,
Us: DeRecUserSecretStore,
T: DeRecTransport,
St: DeRecStateStore,
> DeRecProtocol<Ch, Sh, Ss, Us, St, T>
{
/// Accept a pending action from an [`DeRecEvent::ActionRequired`] event.
///
/// Executes the "do work + send response" path for the given action,
/// returning the same events that auto-respond would have produced.
///
/// # Failures
///
/// A failure of the request the action answers is **not** an `Err`. It is
/// reported as [`DeRecEvent::RequestFailed`] in the returned events, and
/// the request is answered exactly once: by the library under
/// [`with_auto_respond_on_failure`](crate::protocol::DeRecProtocolBuilder::with_auto_respond_on_failure),
/// or by passing the event's [`PendingAction::RespondToFailure`] to
/// [`reject`](Self::reject).
///
/// Before acting, a persisted action is checked against its channel. A
/// channel that is gone or no longer `Paired` has nothing to answer on,
/// so that is an `Err` ([`crate::Error::InvalidInput`]) and nothing is
/// stored or sent. A channel whose peer no longer holds the role the flow
/// requires is answered `REJECTED`, like any other answerable failure.
///
/// `Err` is left for what cannot be answered: the checks above, a
/// [`PendingAction::RespondToFailure`] (which only `reject` resolves),
/// failures of the pairing handshake, and a failure of the publish that
/// follows a completed pairing.
///
/// That publish runs after the pairing is complete and its response has
/// been sent. It reuses every Helper's stored weight, and a stored weight
/// the round's threshold no longer allows fails it with
/// [`SharingError::InvalidWeight`](crate::primitives::sharing::SharingError::InvalidWeight)
/// before anything is sent. `accept` then returns that `Err`: the channel
/// is `Paired` on both sides, but the [`DeRecEvent::PairingCompleted`]
/// event is not returned. Call
/// `start(`[`DeRecFlow::ProtectSecret`](crate::protocol::DeRecFlow::ProtectSecret)`)`
/// with valid weights to publish to every Helper, the new one included.
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = action.trace_id())))]
pub async fn accept(&mut self, action: PendingAction) -> Result<Vec<DeRecEvent>> {
let obligation = Obligation::for_action(&action, local!(self).policy);
let mut events = match &obligation {
Some(obligation) => {
let outcome = match self.still_answerable(&action).await? {
Ok(()) => self.accept_inner(action, Some(obligation)).await,
Err(failure) => Err(failure),
};
settle(
&mut borrow_stores!(self),
&local!(self),
obligation,
self.auto_respond_on_failure,
outcome,
)
.await
}
None => self.accept_inner(action, None).await?,
};
let auto_publish_events = self.maybe_auto_publish_after_pair(&events).await?;
events.extend(auto_publish_events);
Ok(events)
}
/// Re-check a persisted action against the channel it answers on.
///
/// `Err` when the channel is gone or no longer `Paired`: there is nothing
/// to answer on. `Ok(Err(..))` is an answerable failure — the peer no
/// longer holds the role the flow requires, or the channel could not be
/// read — for the router to answer.
async fn still_answerable(&self, action: &PendingAction) -> Result<Result<()>> {
let (channel_id, required) = match action {
PendingAction::StoreShare { channel_id, .. }
| PendingAction::VerifyShare { channel_id, .. }
| PendingAction::Discovery { channel_id, .. }
| PendingAction::GetShare { channel_id, .. }
| PendingAction::Unpair { channel_id, .. } => (*channel_id, Some(SenderKind::Owner)),
PendingAction::UpdateChannelInfo { channel_id, .. } => (*channel_id, None),
PendingAction::Pairing { .. }
| PendingAction::PrePair { .. }
| PendingAction::RespondToFailure { .. } => return Ok(Ok(())),
};
let record = match self
.channel_store
.load(self.secret_id, ChannelQuery::Helper { channel_id })
.await
{
Ok(record) => record,
Err(error) => return Ok(Err(error.into())),
};
let Some(channel) = record
.as_ref()
.and_then(|r| r.as_helper())
.filter(|c| c.status == ChannelStatus::Paired)
else {
return Err(Error::InvalidInput(
"the action's channel is no longer paired",
));
};
Ok(match required {
Some(expected) if channel.peer_role != expected => Err(Error::RoleMismatch {
channel_id,
expected,
actual: channel.peer_role,
}),
_ => Ok(()),
})
}
/// Reject a pending action from an [`DeRecEvent::ActionRequired`] event.
///
/// Builds and sends a rejection response to the peer with the given status
/// and memo. The `status` parameter allows the caller to specify the exact
/// failure reason (e.g. [`StatusEnum::Rejected`], [`StatusEnum::Fail`],
/// [`StatusEnum::TooFrequent`], etc.).
///
/// # Helper-side admission control
///
/// This is where a helper enforces limits on inbound shares beyond
/// what the library already checks. This device's own configured
/// `minShareSize`/`maxShareSize` from [`derec_proto::ParameterRange`]
/// (see [`DeRecProtocolBuilder::with_parameter_range`](crate::protocol::DeRecProtocolBuilder::with_parameter_range))
/// is enforced by the library itself against every inbound share's
/// actual length, before `ActionRequired` is ever raised — a share
/// outside that range never reaches this gate at all. The protocol
/// still imposes no bound of its own on storage per sharer or update
/// frequency; an app with a *tighter or per-user* size limit, or any
/// other reason to decline a share, uses this gate for that.
///
/// [`PendingAction::StoreShare`] carries the already-decrypted,
/// already-parsed [`derec_proto::StoreShareRequestMessage`], so the
/// application inspects the share without touching wire bytes,
/// envelopes or key material:
///
/// The application context (`my_app`, its per-user limits) is yours, so
/// this is illustrative rather than a compiled example:
///
/// ```text
/// for event in protocol.process(&wire_bytes).await? {
/// let DeRecEvent::ActionRequired { action, channel_id } = event else { continue };
/// match &action {
/// PendingAction::StoreShare { request, .. } => {
/// // `channel_id` maps to a user in the application's own
/// // store, so the limit can be per-user, per-plan, or
/// // whatever the deployment needs.
/// let limit = my_app.share_limit_for(channel_id);
/// if request.share.len() > limit {
/// protocol
/// .reject(
/// action,
/// StatusEnum::SizeLimitExceeded,
/// &format!("share exceeds the {limit}-byte limit"),
/// )
/// .await?;
/// } else {
/// protocol.accept(action).await?;
/// }
/// }
/// _ => { protocol.accept(action).await?; }
/// }
/// }
/// ```
///
/// The owner receives a `StoreShareResponse` carrying that status and
/// memo, surfacing as [`DeRecEvent::ShareRejected`] on its side — so
/// the failure is attributable rather than a silent timeout.
///
/// [`StatusEnum::SizeLimitExceeded`] is the protocol's designated code
/// for this case; [`StatusEnum::TooFrequent`] covers rate limiting and
/// [`StatusEnum::Rejected`] a user-declined request.
///
/// This gate exists only while
/// [`AutoAcceptPolicy::store_share`](crate::protocol::AutoAcceptPolicy::store_share)
/// is `false`. Enabling it makes `process()` accept and store every
/// inbound share internally, and no `ActionRequired` is emitted to
/// reject.
///
/// # Answering a failed request
///
/// [`PendingAction::RespondToFailure`], carried by
/// [`DeRecEvent::RequestFailed`], is resolved here: the request is sent
/// its own response type with `status` and `memo`, encrypted under the
/// key of the token's reply channel and delivered to its endpoints. A
/// body that could not be decoded or a request the channel cannot carry
/// names no request type the channel answers, so its token is answered
/// with an `ErrorResponseMessage`. Passing the event's own `status` and
/// `memo` sends the response `auto_respond_on_failure` would have sent.
///
/// The library is stateless and never expires an action, so it cannot
/// tell an action it has already resolved from a fresh one: rejecting the
/// same token twice, or rejecting a copy of an action already accepted,
/// sends a second response. Resolving each action once is the
/// application's part.
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = action.trace_id())))]
pub async fn reject(
&mut self,
action: PendingAction,
status: StatusEnum,
memo: &str,
) -> Result<()> {
let obligation = Obligation::for_action(&action, local!(self).policy);
let obligation = obligation.as_ref();
match action {
PendingAction::Pairing {
channel_id,
request,
trace_id,
..
} => {
handlers::pairing::pair::reject(
&mut borrow_stores!(self),
&local!(self),
channel_id,
&request,
status,
memo,
trace_id,
)
.await
}
PendingAction::StoreShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::sharing::reject(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
status,
memo,
)
.await
}
PendingAction::VerifyShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::verification::reject(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
status,
memo,
)
.await
}
PendingAction::Discovery {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::discovery::reject(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
status,
memo,
)
.await
}
PendingAction::GetShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::recovery::reject(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
status,
memo,
)
.await
}
PendingAction::Unpair {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::unpairing::reject(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
status,
memo,
)
.await
}
PendingAction::UpdateChannelInfo {
channel_id,
shared_key,
trace_id,
..
} => {
handlers::update_channel_info::reject(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
status,
memo,
)
.await
}
PendingAction::PrePair {
channel_id,
request,
trace_id,
} => {
handlers::pairing::pre_pair::reject(
&mut borrow_stores!(self),
&local!(self),
channel_id,
&request,
status,
memo,
trace_id,
)
.await
}
PendingAction::RespondToFailure {
channel_id,
trace_id,
reply,
request,
} => {
let obligation = Obligation::for_failure(
channel_id,
trace_id,
&reply,
request,
local!(self).policy,
);
respond_to_failure(
&mut borrow_stores!(self),
&local!(self),
&obligation,
status,
memo,
)
.await
}
}
}
/// Walk the post-`process_inner` event list and apply the
/// [`AutoAcceptPolicy`]: each `ActionRequired` whose action kind
/// the policy opts into is replaced with `AutoAccepted` plus the
/// flow events `accept_inner(action)` produces. Other events pass
/// through unchanged.
///
/// An answerable failure of the accepted request is settled in place —
/// answered or tokenized as [`DeRecEvent::RequestFailed`] — so
/// `AutoAccepted` and the rest of the batch are kept. Only a pairing
/// failure, which has no channel request to answer, is an `Err`.
pub(super) async fn apply_auto_accept(
&mut self,
events: Vec<DeRecEvent>,
) -> Result<Vec<DeRecEvent>> {
let mut out = Vec::with_capacity(events.len());
for event in events {
match event {
DeRecEvent::ActionRequired { channel_id, action }
if self.auto_accept.allows(&action) =>
{
let action_kind = action.kind();
out.push(DeRecEvent::AutoAccepted {
channel_id,
action_kind,
});
match Obligation::for_action(&action, local!(self).policy) {
Some(obligation) => {
let outcome = self.accept_inner(action, Some(&obligation)).await;
out.extend(
settle(
&mut borrow_stores!(self),
&local!(self),
&obligation,
self.auto_respond_on_failure,
outcome,
)
.await,
);
}
None => out.extend(self.accept_inner(action, None).await?),
}
}
other => out.push(other),
}
}
Ok(out)
}
/// Auto-publish the cached secret if `events` contain a
/// helper-side `PairingCompleted` (the freshly-paired Helper needs
/// shares). Confirming a replica pairing publishes nothing: releasing
/// the vault and the group key to the new device is the application's
/// call.
///
/// The completion event is not on its own enough: a `NoKeys` pairing
/// completes into `ChannelStatus::Pending` and is not a publish target
/// until its fingerprint is confirmed. Publishing then would bump the
/// version for every *other* helper while reaching the new one with
/// nothing, and `verify_fingerprint` would publish again the moment the
/// gate opened — two rounds where the flow calls for one. So the hook
/// fires only for a helper that is already usable, and the gated case is
/// left to `verify_fingerprint`.
///
/// The payload comes from `user_secret_store.load_latest()` when one
/// has been cached by an earlier `start(ProtectSecret)`. When no
/// snapshot exists yet **and** at least one Replica Destination is
/// already paired, the hook publishes an empty payload so the roster
/// snapshot still reaches every Destination — that's how a
/// multi-device sync stays consistent before the application has
/// added any user secrets.
///
/// The publish reuses every Helper's stored weight, and the new Helper
/// starts at `1`. A stored weight that is invalid under the round's
/// threshold fails the publish with
/// [`SharingError::InvalidWeight`](crate::primitives::sharing::SharingError::InvalidWeight)
/// before anything is sent; `process` returns it as a `ProcessError`
/// carrying the message's events, and `accept` returns it as its error.
pub(super) async fn maybe_auto_publish_after_pair(
&mut self,
events: &[DeRecEvent],
) -> Result<Vec<DeRecEvent>> {
let mut a_usable_helper_just_paired = false;
for event in events {
let DeRecEvent::PairingCompleted {
kind: SenderKind::Owner,
channel_id,
..
} = event
else {
continue;
};
if self
.channel_store
.load(
self.secret_id,
ChannelQuery::Helper {
channel_id: *channel_id,
},
)
.await?
.is_some_and(|record| record.status() == ChannelStatus::Paired)
{
a_usable_helper_just_paired = true;
break;
}
}
if !a_usable_helper_just_paired {
return Ok(Vec::new());
}
let snapshot = self.user_secret_store.load_latest(self.secret_id).await?;
let (secrets, description) = match snapshot {
Some(s) => (s.secrets, s.description),
None => {
if !self.has_paired_replica_destination().await? {
return Ok(Vec::new());
}
(Vec::new(), None)
}
};
let reply_to: Vec<TransportProtocol> = if self.auto_reply_to {
self.own_transports.clone()
} else {
Vec::new()
};
self.start_protect_secret(
secrets,
description,
None,
None,
&Round {
reply_to: &reply_to,
trace_id: derec_message::fresh_trace_id(),
},
)
.await
}
/// Returns `true` when at least one channel records a
/// `ReplicaDestination` peer in `Paired` status — i.e. a Destination
/// that is fully verified and eligible for secret sync.
pub(super) async fn has_paired_replica_destination(&self) -> Result<bool> {
let members = self
.channel_store
.replicas_matching(
self.secret_id,
ReplicaFilter {
status: vec![ChannelStatus::Paired],
role: Some(ReplicaRole::Destination),
exclude: self.exclude_self(),
..Default::default()
},
)
.await?;
Ok(!members.is_empty())
}
/// This device's own row, as a
/// [`ReplicaFilter::exclude`](crate::protocol::types::ChannelFilter::exclude)
/// list. See [`Local::exclude_self`](crate::protocol::context::Local::exclude_self).
pub(super) fn exclude_self(&self) -> Vec<ReplicaId> {
self.replica_id.map(ReplicaId).into_iter().collect()
}
async fn accept_inner(
&mut self,
action: PendingAction,
obligation: Option<&Obligation>,
) -> Result<Vec<DeRecEvent>> {
match action {
PendingAction::Pairing {
channel_id,
request,
kind,
trace_id,
..
} => {
handlers::pairing::pair::accept(
&mut borrow_stores!(self),
&local!(self),
&pairing_config!(self),
channel_id,
&request,
kind,
trace_id,
)
.await
}
PendingAction::StoreShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::sharing::accept(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
)
.await
}
PendingAction::VerifyShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::verification::accept(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
)
.await
}
PendingAction::Discovery {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::discovery::accept(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
)
.await
}
PendingAction::GetShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::recovery::accept(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
)
.await
}
PendingAction::Unpair {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::unpairing::accept(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
)
.await
}
PendingAction::UpdateChannelInfo {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::update_channel_info::accept(
&mut borrow_stores!(self),
&local!(self),
&Exchange {
channel_id,
shared_key: &shared_key,
trace_id,
obligation,
},
&request,
)
.await
}
PendingAction::PrePair {
channel_id,
request,
trace_id,
} => {
handlers::pairing::pre_pair::accept(
&mut borrow_stores!(self),
&local!(self),
&pairing_config!(self),
channel_id,
&request,
trace_id,
)
.await
}
PendingAction::RespondToFailure { .. } => {
Err(Error::InvalidInput("a failed request can only be rejected"))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::derec_message::current_timestamp;
use crate::protocol::FailedRequest;
use crate::protocol::ReplyTarget;
use crate::protocol::builder::DeRecProtocolBuilder;
use crate::protocol::tests::{
InMemChannelStore, InMemSecretStore, InMemShareStore, InMemStateStore,
InMemUserSecretStore, NoopTransport, run_async,
};
use crate::protocol::types::SecretValue;
use crate::types::ChannelId;
use derec_proto::ContactMessage;
use derec_proto::ContactMode;
use derec_proto::PrePairRequestMessage;
use derec_proto::Protocol;
const SECRET_ID: u64 = 0xF2;
const CHANNEL: ChannelId = ChannelId(4242);
const NONCE: u64 = 0xABCD;
/// A NoKeys contact is the cheapest way into `pre_pair::accept`: it needs
/// only a stored `PairingContact` whose nonce the request echoes.
async fn seed_no_keys_contact(secrets: &mut InMemSecretStore) {
secrets
.save(
SECRET_ID,
CHANNEL,
SecretValue::PairingContact(ContactMessage {
channel_id: CHANNEL.0,
contact_mode: ContactMode::NoKeys as i32,
nonce: NONCE,
timestamp: Some(current_timestamp()),
..Default::default()
}),
)
.await
.expect("seed NoKeys pairing contact");
}
fn request_answering_on(uri: &str, protocol: Protocol) -> PendingAction {
PendingAction::PrePair {
channel_id: CHANNEL,
request: PrePairRequestMessage {
nonce: NONCE,
supported_transports: vec![TransportProtocol {
uri: uri.to_owned(),
protocol: protocol as i32,
}],
timestamp: Some(current_timestamp()),
},
trace_id: 0,
}
}
fn build(
secrets: InMemSecretStore,
unsafe_connection: bool,
) -> DeRecProtocol<
InMemChannelStore,
InMemShareStore,
InMemSecretStore,
InMemUserSecretStore,
InMemStateStore,
NoopTransport,
> {
DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(InMemChannelStore::default())
.with_share_store(InMemShareStore::default())
.with_secret_store(secrets)
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemStateStore)
.with_own_transports(["https://owner.example.com"])
.with_threshold(2)
.with_unsafe_connection(unsafe_connection)
.build()
.expect("test protocol builds")
}
/// The gap this guards: a peer asking to be answered over LAN plaintext
/// was dialled regardless of `unsafe_connection`, because this path
/// validated the endpoint's *structure* and never applied the policy.
#[test]
fn lan_plaintext_reply_endpoint_is_refused() {
run_async(async {
let secrets = InMemSecretStore::default();
let mut seeded = secrets.clone();
seed_no_keys_contact(&mut seeded).await;
let mut protocol = build(secrets, false);
let err = protocol
.accept(request_answering_on(
"http://192.168.1.42:8080",
Protocol::Https,
))
.await
.expect_err("LAN plaintext must not be dialled without the flag");
// Endpoints are filtered rather than fail-fasted, so a request
// whose *every* endpoint is refused reports that none was usable.
// The guarantee is unchanged: plaintext is not dialled.
assert!(
matches!(err, Error::NoUsableEndpoint { offered: 1 }),
"expected a no-usable-endpoint refusal, got {err:?}"
);
});
}
/// Same request succeeds once plaintext is opted into, proving the
/// refusal above comes from the policy rather than from the fixture.
#[test]
fn lan_plaintext_reply_endpoint_is_accepted_with_the_flag() {
run_async(async {
let secrets = InMemSecretStore::default();
let mut seeded = secrets.clone();
seed_no_keys_contact(&mut seeded).await;
let mut protocol = build(secrets, true);
protocol
.accept(request_answering_on(
"http://192.168.1.42:8080",
Protocol::Https,
))
.await
.expect("plaintext is dialled once unsafe_connection is set");
});
}
/// A requester offering both is answered over the secure one rather than
/// refused outright — one bad endpoint does not sink the request.
#[test]
fn a_plaintext_entry_is_skipped_when_a_secure_one_is_offered() {
run_async(async {
let secrets = InMemSecretStore::default();
let mut seeded = secrets.clone();
seed_no_keys_contact(&mut seeded).await;
let mut protocol = build(secrets, false);
protocol
.accept(PendingAction::PrePair {
channel_id: CHANNEL,
request: PrePairRequestMessage {
nonce: NONCE,
supported_transports: vec![
TransportProtocol {
uri: "http://192.168.1.42:8080".to_owned(),
protocol: Protocol::Https as i32,
},
TransportProtocol {
uri: "https://helper.example.com".to_owned(),
protocol: Protocol::Https as i32,
},
],
timestamp: Some(current_timestamp()),
},
trace_id: 0,
})
.await
.expect("the secure entry survives the plaintext one");
});
}
/// A failed request has no success to send, so the token can only be
/// rejected.
#[test]
fn accepting_a_failed_request_is_refused() {
run_async(async {
let mut protocol = build(InMemSecretStore::default(), false);
let err = protocol
.accept(PendingAction::RespondToFailure {
channel_id: CHANNEL,
trace_id: 1,
reply: ReplyTarget {
channel_id: CHANNEL,
endpoints: Vec::new(),
},
request: FailedRequest::Undecodable,
})
.await
.expect_err("a failed request cannot be accepted");
assert!(
matches!(
err,
Error::InvalidInput("a failed request can only be rejected")
),
"expected InvalidInput, got {err:?}"
);
});
}
/// The ordinary case stays working: a secure endpoint needs no flag.
#[test]
fn secure_reply_endpoint_needs_no_flag() {
run_async(async {
let secrets = InMemSecretStore::default();
let mut seeded = secrets.clone();
seed_no_keys_contact(&mut seeded).await;
let mut protocol = build(secrets, false);
protocol
.accept(request_answering_on(
"https://helper.example.com",
Protocol::Https,
))
.await
.expect("a secure reply endpoint is dialled by default");
});
}
}