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
// 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::stores::borrow_stores;
use super::traits::{
DeRecChannelStore, DeRecSecretStore, DeRecShareStore, DeRecStateStore, DeRecTransport,
DeRecUserSecretStore,
};
use super::{DeRecProtocol, handlers};
use crate::Result;
use crate::extensions::channel_store::ChannelStoreExt as _;
use derec_proto::StatusEnum;
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.
#[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 mut events = self.accept_inner(action).await?;
let auto_publish_events = self.maybe_auto_publish_after_pair(&events).await?;
events.extend(auto_publish_events);
Ok(events)
}
/// 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 its own limits on inbound shares.
/// The protocol imposes none of its own: it does not bound share
/// size, storage per sharer, or update frequency, and the
/// `maxShareSize` negotiated from [`derec_proto::ParameterRange`] is
/// only checked for range overlap at pairing time, never against an
/// actual share.
///
/// [`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.
#[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<()> {
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,
},
&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,
},
&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,
},
&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,
},
&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,
},
&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,
},
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
}
}
}
/// 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.
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,
});
let accept_events = self.accept_inner(action).await?;
out.extend(accept_events);
}
other => out.push(other),
}
}
Ok(out)
}
/// Auto-publish the cached secret if `events` contain a
/// helper-side `PairingCompleted` (the freshly-paired Helper needs
/// shares). The replica-side equivalent fires from
/// `verify_fingerprint` once the channel leaves `Pending`.
///
/// 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.
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: derec_proto::SenderKind::Owner,
channel_id,
..
} = event
else {
continue;
};
if self
.channel_store
.load(
self.secret_id,
crate::protocol::types::ChannelQuery::Helper {
channel_id: *channel_id,
},
)
.await?
.is_some_and(|record| {
record.status() == crate::protocol::types::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<derec_proto::TransportProtocol> = if self.auto_reply_to {
self.own_transports.clone()
} else {
Vec::new()
};
self.start_protect_secret(
secrets,
description,
&Round {
reply_to: &reply_to,
trace_id: crate::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,
crate::protocol::types::ReplicaFilter {
status: vec![crate::protocol::types::ChannelStatus::Paired],
role: Some(crate::protocol::types::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<crate::types::ReplicaId> {
self.replica_id
.map(crate::types::ReplicaId)
.into_iter()
.collect()
}
async fn accept_inner(&mut self, action: PendingAction) -> 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,
},
&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,
},
&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,
},
&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,
},
&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,
},
&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,
},
&request,
)
.await
}
PendingAction::PrePair {
channel_id,
request,
trace_id,
} => {
handlers::pairing::pre_pair::accept(
&mut borrow_stores!(self),
&local!(self),
channel_id,
&request,
trace_id,
)
.await
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocol::builder::DeRecProtocolBuilder;
use crate::protocol::test::{
InMemChannelStore, InMemSecretStore, InMemShareStore, InMemStateStore,
InMemUserSecretStore, NoopTransport, run_async,
};
use crate::protocol::types::SecretValue;
use crate::types::ChannelId;
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(derec_proto::ContactMessage {
channel_id: CHANNEL.0,
contact_mode: derec_proto::ContactMode::NoKeys as i32,
nonce: NONCE,
..Default::default()
}),
)
.await
.expect("seed NoKeys pairing contact");
}
fn request_answering_on(uri: &str, protocol: derec_proto::Protocol) -> PendingAction {
PendingAction::PrePair {
channel_id: CHANNEL,
request: derec_proto::PrePairRequestMessage {
nonce: NONCE,
supported_transports: vec![derec_proto::TransportProtocol {
uri: uri.to_owned(),
protocol: protocol as i32,
}],
timestamp: None,
},
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",
derec_proto::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, crate::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",
derec_proto::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: derec_proto::PrePairRequestMessage {
nonce: NONCE,
supported_transports: vec![
derec_proto::TransportProtocol {
uri: "http://192.168.1.42:8080".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
},
derec_proto::TransportProtocol {
uri: "https://helper.example.com".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
},
],
timestamp: None,
},
trace_id: 0,
})
.await
.expect("the secure entry survives the plaintext one");
});
}
/// 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",
derec_proto::Protocol::Https,
))
.await
.expect("a secure reply endpoint is dialled by default");
});
}
}