derec-library 0.1.0

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
Documentation
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! The replica side of unpairing — removing a member from the group.
//!
//! An `UnpairRequest` naming a group member is a roster removal, not a helper
//! channel teardown. The owner↔helper side lives in
//! [`handlers::unpairing`](super::super::unpairing), which routes here when
//! the payload names an author.
//!
//! Both directions live here. [`start`] announces a removal — the message the
//! application asks for as [`DeRecFlow::UnpairReplica`](crate::protocol::DeRecFlow)
//! — and [`handle`] is what a peer does with it.
//!
//! The device running the removal drops the member at once and publishes a
//! roster without it; the removed member drops everything as soon as it is
//! told, and receives nothing afterwards. Every other member flags the
//! departing member when told, and removes it once a roster arrives that both
//! omits it and post-dates the flag: absence from a roster alone never
//! removes anyone, since a device may hold members a roster has not caught up
//! with yet. [`reconcile`] is that second half, driven from the sharing flow
//! as each new roster lands.
use super::{flag_unpairing, load_member_keys};
use crate::derec_message::apply_trace_id;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::primitives::unpairing::request;
use crate::protocol::context::Local;
use crate::protocol::stores::{StoreSet, Stores};
use crate::protocol::types::{
    ChannelQuery, ChannelRecord, ChannelStatus, HelperFilter, ReplicaFilter, ReplicaMember,
    ReplicaRole,
};
use crate::protocol::{
    DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecShareStore, DeRecTransport,
    DeRecUserSecretStore, SecretKind,
};
use crate::types::{ChannelId, ReplicaId};
use crate::{Error, Result};
use derec_proto::{MessageBody, UnpairRequestMessage};

/// Handle an unpairing message that names a group member.
///
/// Unlike the other flows here, the `replica_id` on an `UnpairRequest` names
/// the member being **removed**, not the member that sent it — a removal is
/// announced to every peer, so the target is the only thing they all agree
/// on. There is no replica reading of `UnpairResponse`: a removal is
/// completed by the roster that omits the member, not by an acknowledgement.
pub(in crate::protocol) async fn handle<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    target: u64,
    inner: MessageBody,
) -> Result<Vec<DeRecEvent>> {
    match inner {
        MessageBody::UnpairRequest(request) => on_request(stores, local, &request, target).await,
        _ => Err(Error::Invariant(
            "replica identity on a message that is not an unpair request",
        )),
    }
}

/// Tell every member that `target` is leaving, and take it out of the group
/// here.
///
/// Another member is dropped at once: its row, and any key only it used, are
/// removed and [`DeRecEvent::ReplicaRemoved`] is reported. When `target` is
/// this device, its own row is flagged instead, which keeps it out of the
/// roster the caller publishes before tearing down. Either way the caller
/// publishes the roster without `target` next; `target` is no longer on any
/// distribution list, so it receives nothing more.
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = trace_id, local.secret_id)))]
pub(in crate::protocol) async fn start<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    target: u64,
    memo: Option<String>,
    trace_id: u64,
) -> Result<Vec<DeRecEvent>> {
    let secret_id = local.secret_id;
    let own = local.replica_id.ok_or(Error::ReplicaIdNotConfigured)?;
    let target = ReplicaId::try_from(target)?;

    // Unfiltered deliberately: this flow reads the whole roster three ways —
    // the member being removed, the successor that replaces it, and the
    // notification list, which is every member. Narrowing any one of them
    // would cost a second listing to recover the rest.
    let roster = stores
        .channels
        .replicas_matching(secret_id, ReplicaFilter::default())
        .await?;
    let member = roster
        .iter()
        .find(|m| m.replica_id == target)
        .ok_or(Error::InvalidInput("no such member in this replica group"))?
        .clone();

    let successor = if member.role == ReplicaRole::Source {
        roster
            .iter()
            .find(|m| m.replica_id != target && m.status == ChannelStatus::Paired)
            .cloned()
    } else {
        None
    };

    // Every member is told, the departing one included. The remaining members
    // need the flag to satisfy the safety rule when the new roster arrives;
    // without it they would be acting on absence alone.
    let peers: Vec<ReplicaMember> = roster
        .iter()
        .filter(|m| m.replica_id.0 != own)
        .cloned()
        .collect();
    let keys = load_member_keys(stores, local, &peers).await?;
    let memo = memo.unwrap_or_default();
    let mut notified = Vec::new();
    for peer in &peers {
        let key = &keys[&peer.channel_id];
        let request = request::produce(peer.channel_id, &memo, key, &[], Some(target.0))?;
        let envelope = apply_trace_id(&request.envelope, trace_id)?;
        if stores
            .transport
            .send(&peer.transports, envelope)
            .await
            .is_ok()
        {
            notified.push(peer.replica_id);
        }
    }

    let mut events = Vec::new();
    if target.0 == own {
        flag_unpairing(stores, local, &member).await?;
    } else {
        drop_member(stores, local, &member).await?;
        events.push(DeRecEvent::ReplicaRemoved {
            replica_id: target.0,
        });
    }

    // Promoted before the roster is built, so the completing publish carries the
    // new source. The departing row and the promoted row are distinct members,
    // so the two writes cannot collide.
    if let Some(successor) = successor {
        stores
            .channels
            .save(
                secret_id,
                ChannelRecord::Replica(ReplicaMember {
                    role: ReplicaRole::Source,
                    ..successor.clone()
                }),
            )
            .await?;
        events.push(DeRecEvent::ReplicaSourceChanged {
            replica_id: successor.replica_id.0,
        });
    }

    #[cfg(feature = "logging")]
    tracing::info!(
        secret_id,
        target = target.0,
        voluntary = target.0 == own,
        notified = notified.len(),
        "replica removal announced"
    );

    Ok(events)
}

/// What an arriving roster means for members already flagged as leaving.
pub(in crate::protocol) enum RemovalOutcome {
    /// Nothing was flagged, or nothing flagged is yet absent.
    Nothing,
    /// These members completed their departure; their rows were removed.
    Removed(Vec<u64>),
    /// This device completed its own departure. The caller must acknowledge
    /// **before** tearing down: dropping the group key first would leave it
    /// unable to encrypt the acknowledgement, failing the publisher's round
    /// against a member that did exactly the right thing.
    SelfRemoved,
}

/// Apply the second half of the safety rule against a freshly arrived roster.
///
/// A flagged member that is *still present* has not completed anything — a
/// removal can be announced and then superseded by a roster that keeps the
/// member, and that must leave no trace.
pub(in crate::protocol) async fn reconcile<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    roster_ids: &[u64],
) -> Result<RemovalOutcome> {
    let stored = stores
        .channels
        .replicas_matching(
            local.secret_id,
            ReplicaFilter {
                status: vec![ChannelStatus::Unpairing],
                ..Default::default()
            },
        )
        .await?;

    let mut removed = Vec::new();
    let mut self_removed = false;
    for member in stored.iter() {
        if roster_ids.contains(&member.replica_id.0) {
            continue;
        }
        if Some(member.replica_id.0) == local.replica_id {
            self_removed = true;
            continue;
        }
        if let Some(handover) = member.handover_channel {
            let _ = stores
                .secrets
                .remove(local.secret_id, handover, SecretKind::SharedKey)
                .await;
        }
        stores
            .channels
            .remove(
                local.secret_id,
                ChannelQuery::Replica {
                    channel_id: member.channel_id,
                    replica_id: member.replica_id,
                },
            )
            .await?;
        removed.push(member.replica_id.0);
    }

    if self_removed {
        return Ok(RemovalOutcome::SelfRemoved);
    }
    if removed.is_empty() {
        Ok(RemovalOutcome::Nothing)
    } else {
        Ok(RemovalOutcome::Removed(removed))
    }
}

/// Drop this device's entire `secret_id` partition.
///
/// Wider than a remaining member's single-row edit: a departing device keeps
/// nothing. Called only after the acknowledgement has been sent.
pub(in crate::protocol) async fn tear_down<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
) -> Result<()> {
    let secret_id = local.secret_id;
    for helper in stores
        .channels
        .helpers_matching(secret_id, HelperFilter::default())
        .await?
    {
        drop_channel(
            stores,
            local,
            helper.channel_id,
            ChannelQuery::Helper {
                channel_id: helper.channel_id,
            },
        )
        .await?;
    }

    for member in stores
        .channels
        .replicas_matching(secret_id, ReplicaFilter::default())
        .await?
    {
        if let Some(handover) = member.handover_channel {
            let _ = stores
                .secrets
                .remove(secret_id, handover, SecretKind::SharedKey)
                .await;
        }
        drop_channel(
            stores,
            local,
            member.channel_id,
            ChannelQuery::Replica {
                channel_id: member.channel_id,
                replica_id: member.replica_id,
            },
        )
        .await?;
    }

    stores.user_secrets.remove(secret_id).await?;
    Ok(())
}

async fn drop_channel<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel_id: ChannelId,
    query: ChannelQuery,
) -> Result<()> {
    let secret_id = local.secret_id;
    // The share and secret rows may or may not exist — a member removed
    // before it ever received a share has neither. Removal is idempotent and
    // their absence is not an error, so only the channel row below is
    // required to succeed; that one is what makes the teardown observable.
    let _ = stores.shares.remove_channel(secret_id, channel_id).await;
    for kind in [
        SecretKind::SharedKey,
        SecretKind::PairingSecret,
        SecretKind::PairingContact,
    ] {
        let _ = stores.secrets.remove(secret_id, channel_id, kind).await;
    }
    stores.channels.remove(secret_id, query).await?;
    Ok(())
}

/// Handle an inbound `UnpairRequest` that names a group member.
///
/// A notice naming this device tears it down at once, since nothing more is
/// sent to it. A notice naming another member flags that member's row; the
/// member is dropped when the roster without it arrives.
async fn on_request<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    request: &UnpairRequestMessage,
    target: u64,
) -> Result<Vec<DeRecEvent>> {
    // The request body carries only a `memo` — the human-readable reason the
    // publisher gave for the removal. Nothing on the replica path can surface
    // it: this leg raises no `ActionRequired` (a roster removal is not the
    // application's to confirm), and `ReplicaRemoved`, emitted later by
    // `reconcile`, carries no memo field. The owner↔helper leg does surface
    // it, by handing the whole request to `PendingAction::Unpair`.
    let _ = request;
    let target = ReplicaId::try_from(target)?;
    let member = stores
        .channels
        .replicas_matching(
            local.secret_id,
            ReplicaFilter {
                ids: vec![target],
                ..Default::default()
            },
        )
        .await?
        .into_iter()
        // Re-checked against the id we asked for. `replicas_matching` already
        // guarantees this, but the consequence of being wrong here is flagging
        // the wrong member for eviction, so the site states its own invariant.
        .find(|m| m.replica_id == target)
        .ok_or(Error::InvalidInput(
            "unpair names a member that is not in the group",
        ))?;

    // Told to leave: nothing more is sent to this device, so it drops
    // everything now rather than waiting for a roster.
    if Some(target.0) == local.replica_id {
        let version = stores
            .user_secrets
            .load_latest(local.secret_id)
            .await?
            .map_or(0, |held| held.version);
        tear_down(stores, local).await?;

        #[cfg(feature = "logging")]
        tracing::info!(
            version,
            "told to leave the replica group; partition dropped"
        );

        return Ok(vec![DeRecEvent::SelfRemovedFromGroup { version }]);
    }

    flag_unpairing(stores, local, &member).await?;

    // No event yet: nothing has been removed. The row is flagged, and the
    // removal is reported when the completing roster arrives.
    Ok(vec![DeRecEvent::NoOp])
}

/// Remove `member`'s row, and every key that only it used.
///
/// A member admitted here and not yet moved onto the group channel is still
/// on its pairing channel, and a member this device joined through may hold a
/// [`handover_channel`](ReplicaMember::handover_channel); either key is
/// removed once no remaining member is recorded on that channel. The group
/// channel's key stays: the remaining members use it.
async fn drop_member<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    member: &ReplicaMember,
) -> Result<()> {
    let secret_id = local.secret_id;
    stores
        .channels
        .remove(
            secret_id,
            ChannelQuery::Replica {
                channel_id: member.channel_id,
                replica_id: member.replica_id,
            },
        )
        .await?;
    let remaining = stores
        .channels
        .replicas_matching(secret_id, ReplicaFilter::default())
        .await?;
    for channel_id in [Some(member.channel_id), member.handover_channel]
        .into_iter()
        .flatten()
    {
        if !remaining.iter().any(|m| m.channel_id == channel_id) {
            let _ = stores
                .secrets
                .remove(secret_id, channel_id, SecretKind::SharedKey)
                .await;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::derec_message::extract_inner_message;
    use crate::protocol::tests::{InMemChannelStore, InMemSecretStore, StoreRig, run_async};
    use crate::protocol::tests::{LocalFixture, NoopTransport};
    use crate::protocol::types::{
        HelperChannel, HelperFilter, ReplicaFilter, SecretValue, UserSecrets,
    };
    use crate::protocol::{DeRecSecretStore, DeRecUserSecretStore};
    use crate::types::SharedKey;
    use derec_proto::{DeRecMessage, Protocol, SenderKind, TransportProtocol};
    use prost::Message as _;
    use std::collections::HashMap;

    const SECRET_ID: u64 = 0xDE9A27;
    const GROUP: ChannelId = ChannelId(5001);

    fn endpoint(uri: &str) -> TransportProtocol {
        TransportProtocol {
            uri: uri.to_owned(),
            protocol: Protocol::Https as i32,
        }
    }

    async fn seed_member(
        channels: &mut InMemChannelStore,
        id: u64,
        role: ReplicaRole,
        status: ChannelStatus,
    ) {
        channels
            .save(
                SECRET_ID,
                ChannelRecord::Replica(ReplicaMember {
                    channel_id: GROUP,
                    replica_id: ReplicaId(id),
                    transports: vec![endpoint("https://peer.example")],
                    communication_info: HashMap::new(),
                    role,
                    status,
                    created_at: 0,
                    handover_channel: None,
                }),
            )
            .await
            .expect("seed member");
    }

    /// A fixed round token, so a test can assert what reaches the wire.
    const TRACE_ID: u64 = 0x7ACE;

    /// U5 — the omission guard. A member absent from a newer roster but never
    /// told to leave keeps its row. This is the half that stops a publisher
    /// bug from escalating into destroyed state.
    #[test]
    fn absence_alone_removes_nothing() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1001);
            let mut rig = StoreRig::new();
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Paired,
            )
            .await;

            // A roster that simply forgot 1002.
            let outcome = super::reconcile(&mut rig.stores(), &lf.local(), &[1001])
                .await
                .expect("reconcile");

            assert!(matches!(outcome, RemovalOutcome::Nothing));
            assert_eq!(
                rig.channels
                    .replicas(SECRET_ID, ReplicaFilter::default())
                    .await
                    .expect("roster")
                    .len(),
                2,
                "a member never told to leave survives being omitted"
            );
        });
    }

    /// U6 — the other half. A member told to leave, but still present in the
    /// newest roster, has completed nothing: an announced removal can be
    /// superseded, and that must leave no trace.
    #[test]
    fn being_flagged_alone_removes_nothing() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1001);
            let mut rig = StoreRig::new();
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Unpairing,
            )
            .await;

            let outcome = super::reconcile(&mut rig.stores(), &lf.local(), &[1001, 1002])
                .await
                .expect("reconcile");

            assert!(matches!(outcome, RemovalOutcome::Nothing));
            assert_eq!(
                rig.channels
                    .replicas(SECRET_ID, ReplicaFilter::default())
                    .await
                    .expect("roster")
                    .len(),
                2,
                "a flagged member still in the roster keeps its row"
            );
        });
    }

    /// U3 / U10 — both halves hold: the row goes, and the group channel and
    /// every helper channel survive for the members that remain.
    #[test]
    fn both_halves_remove_the_row_and_nothing_else() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1001);
            let mut rig = StoreRig::new();
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Unpairing,
            )
            .await;
            rig.channels
                .save(
                    SECRET_ID,
                    ChannelRecord::Helper(HelperChannel {
                        channel_id: ChannelId(9001),
                        transports: vec![endpoint("https://helper.example")],
                        communication_info: HashMap::new(),
                        peer_role: SenderKind::Helper,
                        status: ChannelStatus::Paired,
                        created_at: 0,
                        weight: 1,
                    }),
                )
                .await
                .expect("seed helper");

            let outcome = super::reconcile(&mut rig.stores(), &lf.local(), &[1001])
                .await
                .expect("reconcile");

            assert!(matches!(outcome, RemovalOutcome::Removed(ref ids) if ids == &[1002]));
            let roster = rig
                .channels
                .replicas(SECRET_ID, ReplicaFilter::default())
                .await
                .expect("roster");
            assert_eq!(roster.len(), 1, "only the departing row goes");
            assert_eq!(
                roster[0].channel_id, GROUP,
                "the shared group channel is untouched"
            );
            assert_eq!(
                rig.channels
                    .helpers(SECRET_ID, HelperFilter::default())
                    .await
                    .expect("helpers")
                    .len(),
                1,
                "a remaining member keeps every helper channel"
            );
        });
    }

    /// The departing device reports itself rather than deleting its own row in
    /// place — the caller must acknowledge first, then tear down.
    #[test]
    fn a_departing_device_defers_to_its_caller() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1002);
            let mut rig = StoreRig::new();
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Unpairing,
            )
            .await;

            let outcome = super::reconcile(&mut rig.stores(), &lf.local(), &[1001])
                .await
                .expect("reconcile");

            assert!(
                matches!(outcome, RemovalOutcome::SelfRemoved),
                "the device being removed is reported, not silently torn down"
            );
            assert_eq!(
                rig.channels
                    .replicas(SECRET_ID, ReplicaFilter::default())
                    .await
                    .expect("roster")
                    .len(),
                2,
                "nothing is dropped before the acknowledgement is sent"
            );
        });
    }

    /// U4 / U8 — teardown is the whole partition, not one row.
    #[test]
    fn tear_down_drops_the_whole_partition() {
        run_async(async {
            let lf = LocalFixture::new(SECRET_ID);
            let mut rig = StoreRig::new();

            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Unpairing,
            )
            .await;
            rig.channels
                .save(
                    SECRET_ID,
                    ChannelRecord::Helper(HelperChannel {
                        channel_id: ChannelId(9001),
                        transports: vec![endpoint("https://helper.example")],
                        communication_info: HashMap::new(),
                        peer_role: SenderKind::Helper,
                        status: ChannelStatus::Paired,
                        created_at: 0,
                        weight: 1,
                    }),
                )
                .await
                .expect("seed helper");
            rig.secrets
                .save(SECRET_ID, GROUP, SecretValue::SharedKey([0x33; 32]))
                .await
                .expect("seed key");
            rig.user_secrets
                .save_latest(
                    SECRET_ID,
                    UserSecrets {
                        version: 4,
                        secrets: Vec::new(),
                        description: None,
                        author_replica_id: None,
                        threshold: None,
                    },
                )
                .await
                .expect("seed snapshot");

            super::tear_down(&mut rig.stores(), &lf.local())
                .await
                .expect("tear down");

            assert!(
                rig.channels
                    .replicas(SECRET_ID, ReplicaFilter::default())
                    .await
                    .expect("roster")
                    .is_empty()
            );
            assert!(
                rig.channels
                    .helpers(SECRET_ID, HelperFilter::default())
                    .await
                    .expect("helpers")
                    .is_empty()
            );
            assert!(
                rig.secrets
                    .load(SECRET_ID, GROUP, SecretKind::SharedKey)
                    .await
                    .expect("load")
                    .is_none(),
                "the group key goes with everything else"
            );
            assert!(
                rig.user_secrets
                    .load_latest(SECRET_ID)
                    .await
                    .expect("load")
                    .is_none(),
                "a departing device keeps no copy of the secret"
            );
        });
    }

    async fn seed_group_key(secrets: &mut InMemSecretStore) {
        secrets
            .save(SECRET_ID, GROUP, SecretValue::SharedKey([7u8; 32]))
            .await
            .expect("seed group key");
    }

    async fn role_of(channels: &InMemChannelStore, id: u64) -> ReplicaRole {
        channels
            .replicas(SECRET_ID, ReplicaFilter::default())
            .await
            .expect("roster")
            .into_iter()
            .find(|m| m.replica_id.0 == id)
            .expect("member present")
            .role
    }

    /// R1 — removing the source promotes a remaining member, and the departing
    /// source is never its own successor.
    #[test]
    fn removing_the_source_promotes_a_remaining_member() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1002);
            let mut rig = StoreRig::with_transport(NoopTransport);
            seed_group_key(&mut rig.secrets).await;
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Paired,
            )
            .await;

            let events = super::start(&mut rig.stores(), &lf.local(), 1001, None, TRACE_ID)
                .await
                .expect("removing the source succeeds once a successor is chosen");

            assert!(
                events.iter().any(|e| matches!(
                    e,
                    DeRecEvent::ReplicaSourceChanged { replica_id } if *replica_id == 1002
                )),
                "the chosen successor is reported to the application"
            );
            assert_eq!(role_of(&rig.channels, 1002).await, ReplicaRole::Source);
            assert!(
                events.iter().any(|e| matches!(
                    e,
                    DeRecEvent::ReplicaRemoved { replica_id } if *replica_id == 1001
                )),
                "the departing source is removed at once"
            );
            assert!(
                rig.channels
                    .replicas(SECRET_ID, ReplicaFilter::default())
                    .await
                    .expect("roster")
                    .iter()
                    .all(|m| m.replica_id.0 != 1001)
            );
        });
    }

    /// R1 — a member already told to leave cannot be crowned on its way out.
    #[test]
    fn a_departing_member_is_not_eligible_to_succeed() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1003);
            let mut rig = StoreRig::with_transport(NoopTransport);
            seed_group_key(&mut rig.secrets).await;
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Unpairing,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1003,
                ReplicaRole::Destination,
                ChannelStatus::Paired,
            )
            .await;

            super::start(&mut rig.stores(), &lf.local(), 1001, None, TRACE_ID)
                .await
                .expect("start");

            assert_eq!(role_of(&rig.channels, 1003).await, ReplicaRole::Source);
            assert_eq!(role_of(&rig.channels, 1002).await, ReplicaRole::Destination);
        });
    }

    /// R1 — a member whose pairing is unconfirmed is not in the published
    /// roster, so it cannot be the source that roster names.
    #[test]
    fn an_unconfirmed_member_is_not_eligible_to_succeed() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1003);
            let mut rig = StoreRig::with_transport(NoopTransport);
            seed_group_key(&mut rig.secrets).await;
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Pending,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1003,
                ReplicaRole::Destination,
                ChannelStatus::Paired,
            )
            .await;

            super::start(&mut rig.stores(), &lf.local(), 1001, None, TRACE_ID)
                .await
                .expect("start");

            assert_eq!(role_of(&rig.channels, 1003).await, ReplicaRole::Source);
            assert_eq!(role_of(&rig.channels, 1002).await, ReplicaRole::Destination);
        });
    }

    /// R1 — a sole source leaves no successor. The group dissolves with it
    /// rather than the removal failing.
    #[test]
    fn a_sole_source_leaves_no_successor() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1001);
            let mut rig = StoreRig::with_transport(NoopTransport);
            seed_group_key(&mut rig.secrets).await;
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;

            let events = super::start(&mut rig.stores(), &lf.local(), 1001, None, TRACE_ID)
                .await
                .expect("a sole source may still leave");

            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::ReplicaSourceChanged { .. })),
                "no successor exists to report"
            );
        });
    }

    /// R1 — removing a destination changes nobody's role.
    #[test]
    fn removing_a_destination_promotes_nobody() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1001);
            let mut rig = StoreRig::with_transport(NoopTransport);
            seed_group_key(&mut rig.secrets).await;
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                ChannelStatus::Paired,
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                ChannelStatus::Paired,
            )
            .await;

            let events = super::start(&mut rig.stores(), &lf.local(), 1002, None, TRACE_ID)
                .await
                .expect("start");

            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::ReplicaSourceChanged { .. })),
                "the source is unaffected by a destination leaving"
            );
            assert_eq!(role_of(&rig.channels, 1001).await, ReplicaRole::Source);
        });
    }

    /// A member that has just joined still talks on its pairing channel,
    /// under that channel's key, until it is handed the group channel. Each
    /// notice is sealed under the key of the channel it travels on, whichever
    /// member is leaving, so every remaining member can read its own.
    #[test]
    fn each_notice_is_sealed_under_its_own_channel_key() {
        const PAIRING: ChannelId = ChannelId(5002);
        const GROUP_KEY: SharedKey = [7u8; 32];
        const PAIRING_KEY: SharedKey = [0x22; 32];

        for leaving in [1002, 1003] {
            run_async(async {
                let lf = LocalFixture::with_replica(SECRET_ID, 1001);
                let mut rig = StoreRig::new();
                seed_group_key(&mut rig.secrets).await;
                rig.secrets
                    .save(SECRET_ID, PAIRING, SecretValue::SharedKey(PAIRING_KEY))
                    .await
                    .expect("seed pairing key");
                seed_member(
                    &mut rig.channels,
                    1001,
                    ReplicaRole::Source,
                    ChannelStatus::Paired,
                )
                .await;
                seed_member(
                    &mut rig.channels,
                    1002,
                    ReplicaRole::Destination,
                    ChannelStatus::Paired,
                )
                .await;
                rig.channels
                    .save(
                        SECRET_ID,
                        ChannelRecord::Replica(ReplicaMember {
                            channel_id: PAIRING,
                            replica_id: ReplicaId(1003),
                            transports: vec![endpoint("https://joiner.example")],
                            communication_info: HashMap::new(),
                            role: ReplicaRole::Destination,
                            status: ChannelStatus::Paired,
                            created_at: 0,
                            handover_channel: None,
                        }),
                    )
                    .await
                    .expect("seed joiner");

                super::start(&mut rig.stores(), &lf.local(), leaving, None, TRACE_ID)
                    .await
                    .expect("start");

                let mut noticed = Vec::new();
                for bytes in rig.transport.sent_envelopes() {
                    let envelope =
                        DeRecMessage::decode(bytes.as_slice()).expect("envelope decodes");
                    let key = if envelope.channel_id == PAIRING.0 {
                        PAIRING_KEY
                    } else {
                        GROUP_KEY
                    };
                    match extract_inner_message(&envelope.message, &key) {
                        Ok(MessageBody::UnpairRequest(_)) => noticed.push(envelope.channel_id),
                        Ok(_) => {}
                        Err(e) => panic!(
                            "removing {leaving}: the message on channel {} must open under that channel's key: {e}",
                            envelope.channel_id
                        ),
                    }
                }
                noticed.sort_unstable();
                assert_eq!(
                    noticed,
                    vec![GROUP.0, PAIRING.0],
                    "removing {leaving}: both other members are told"
                );
            });
        }
    }

    /// The device running a removal drops the member at once, with the key
    /// only it used; the group key stays for the members that remain.
    #[test]
    fn removing_another_member_drops_its_row_and_its_own_key() {
        const PAIRING: ChannelId = ChannelId(5002);
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1001);
            let mut rig = StoreRig::with_transport(NoopTransport);
            seed_group_key(&mut rig.secrets).await;
            rig.secrets
                .save(SECRET_ID, PAIRING, SecretValue::SharedKey([0x22; 32]))
                .await
                .expect("seed pairing key");
            for id in [1001, 1002] {
                seed_member(
                    &mut rig.channels,
                    id,
                    ReplicaRole::Destination,
                    ChannelStatus::Paired,
                )
                .await;
            }
            rig.channels
                .save(
                    SECRET_ID,
                    ChannelRecord::Replica(ReplicaMember {
                        channel_id: PAIRING,
                        replica_id: ReplicaId(1003),
                        transports: vec![endpoint("https://joiner.example")],
                        communication_info: HashMap::new(),
                        role: ReplicaRole::Destination,
                        status: ChannelStatus::Paired,
                        created_at: 0,
                        handover_channel: None,
                    }),
                )
                .await
                .expect("seed joiner");

            let events = super::start(&mut rig.stores(), &lf.local(), 1003, None, TRACE_ID)
                .await
                .expect("start");

            assert!(
                events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::ReplicaRemoved { replica_id: 1003 })),
                "{events:?}"
            );
            let mut ids: Vec<u64> = rig
                .channels
                .replicas(SECRET_ID, ReplicaFilter::default())
                .await
                .expect("roster")
                .iter()
                .map(|m| m.replica_id.0)
                .collect();
            ids.sort_unstable();
            assert_eq!(ids, vec![1001, 1002]);
            assert!(
                rig.secrets
                    .load(SECRET_ID, PAIRING, SecretKind::SharedKey)
                    .await
                    .expect("load")
                    .is_none(),
                "the key only the removed member used is dropped"
            );
            assert!(
                rig.secrets
                    .load(SECRET_ID, GROUP, SecretKind::SharedKey)
                    .await
                    .expect("load")
                    .is_some(),
                "the group key stays"
            );
        });
    }

    /// The removed member drops everything as soon as it is told: nothing
    /// more will be sent to it.
    #[test]
    fn a_member_told_to_leave_drops_everything_at_once() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1002);
            let mut rig = StoreRig::new();
            seed_group_key(&mut rig.secrets).await;
            for id in [1001, 1002] {
                seed_member(
                    &mut rig.channels,
                    id,
                    ReplicaRole::Destination,
                    ChannelStatus::Paired,
                )
                .await;
            }
            rig.user_secrets
                .save_latest(
                    SECRET_ID,
                    UserSecrets {
                        version: 4,
                        secrets: Vec::new(),
                        description: None,
                        author_replica_id: None,
                        threshold: None,
                    },
                )
                .await
                .expect("seed snapshot");

            let events = super::handle(
                &mut rig.stores(),
                &lf.local(),
                1002,
                MessageBody::UnpairRequest(UnpairRequestMessage::default()),
            )
            .await
            .expect("handled");

            assert!(
                matches!(
                    events.as_slice(),
                    [DeRecEvent::SelfRemovedFromGroup { version: 4 }]
                ),
                "{events:?}"
            );
            assert!(
                rig.channels
                    .replicas(SECRET_ID, ReplicaFilter::default())
                    .await
                    .expect("roster")
                    .is_empty()
            );
            assert!(
                rig.secrets
                    .load(SECRET_ID, GROUP, SecretKind::SharedKey)
                    .await
                    .expect("load")
                    .is_none()
            );
            assert!(
                rig.user_secrets
                    .load_latest(SECRET_ID)
                    .await
                    .expect("load")
                    .is_none()
            );
        });
    }

    /// Every other member only flags the departing one; the roster without it
    /// completes the removal there.
    #[test]
    fn another_member_told_of_a_removal_only_flags_it() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1001);
            let mut rig = StoreRig::new();
            seed_group_key(&mut rig.secrets).await;
            for id in [1001, 1002] {
                seed_member(
                    &mut rig.channels,
                    id,
                    ReplicaRole::Destination,
                    ChannelStatus::Paired,
                )
                .await;
            }

            let events = super::handle(
                &mut rig.stores(),
                &lf.local(),
                1002,
                MessageBody::UnpairRequest(UnpairRequestMessage::default()),
            )
            .await
            .expect("handled");

            assert!(
                matches!(events.as_slice(), [DeRecEvent::NoOp]),
                "{events:?}"
            );
            let departing = rig
                .channels
                .replicas(SECRET_ID, ReplicaFilter::default())
                .await
                .expect("roster")
                .into_iter()
                .find(|m| m.replica_id.0 == 1002)
                .expect("still recorded");
            assert_eq!(departing.status, ChannelStatus::Unpairing);
        });
    }
}