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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Reading a channel, and answering on one.
//!
//! The queries here read as methods on the channel store because that is
//! what they are — resolving a target, checking a peer's role, finding the
//! endpoints a peer can be reached at. They are not part of
//! [`DeRecChannelStore`] itself: applications implement that trait, so a
//! method added there would have to be written by every implementor and
//! every SDK's store shim. An extension trait with a blanket impl gives
//! every store the same methods for free, and leaves the trait an
//! application must satisfy as small as it was.

use crate::protocol::obligation::{Obligation, deliver};
use crate::protocol::{DeRecChannelStore, DeRecTransport};
use crate::transport::TransportPolicy;
use crate::{
    Error, Result,
    derec_message::{DeRecMessageBuilder, current_timestamp},
    protocol::types::{
        ChannelQuery, ChannelStatus, HelperChannel, HelperFilter, ReplicaFilter, ReplicaMember,
        Target,
    },
    types::{ChannelId, ReplicaId, SharedKey},
};
use derec_proto::{MessageBody, SenderKind, StatusEnum, TransportProtocol};
use prost::Message;

/// Channel reads every flow needs, as methods on the store that holds them.
///
/// Blanket-implemented for every [`DeRecChannelStore`], so bringing the
/// trait into scope (`use crate::extensions::channel_store::ChannelStoreExt as _;`)
/// is all a caller does.
pub(crate) trait ChannelStoreExt: DeRecChannelStore {
    /// The helper channels that match `filter`, whatever the store returned.
    ///
    /// See [`Self::replicas_matching`] for why this exists. Use this, never the
    /// bare trait method: the protocol acts on these rows, and several call
    /// sites narrow to a single expected row.
    async fn helpers_matching(
        &self,
        secret_id: u64,
        filter: HelperFilter,
    ) -> Result<Vec<HelperChannel>> {
        let rows = self.helpers(secret_id, filter.clone()).await?;
        Ok(retain_matching(rows, "helpers", |c| {
            filter.matches(&c.channel_id, c.status, &c.peer_role)
        }))
    }

    /// The replica-group members that match `filter`, whatever the store
    /// returned.
    ///
    /// # Why this is not just [`DeRecChannelStore::replicas`]
    ///
    /// The filter is the store's to push into a query, and a store that does
    /// so transfers less — that is the whole point of
    /// [`ChannelFilter`](crate::protocol::types::ChannelFilter). But a store is
    /// **application-supplied code**, and the protocol acts on what comes back:
    /// it deletes rows the filter selected, and flags the member a by-id filter
    /// named. A store that ignored the filter would otherwise turn "evict
    /// member X" into evicting whichever member it listed first, and "sweep
    /// expired *pending* channels" into sweeping paired ones.
    ///
    /// That case is worth defending against because it needs no mistake to
    /// reach: TypeScript accepts a function of fewer parameters where more are
    /// declared, so a store written before the filter existed satisfies the
    /// current interface and compiles without a diagnostic. Ignoring the filter
    /// is the one wrong behaviour a binding cannot make impossible.
    ///
    /// # This is a one-way guarantee
    ///
    /// The check can only **drop** rows, so it enforces an upper bound: nothing
    /// the filter excluded reaches the caller. It cannot detect the opposite
    /// error. A store that returns *fewer* rows than the filter selects — one
    /// that over-filters, or simply answers `[]` — passes unchallenged, and the
    /// protocol then fails to act: a publish is skipped, a departure is never
    /// reconciled. That remains an application bug, and one nothing here can
    /// see.
    ///
    /// Nor does it police the `secret_id` partition: a
    /// [`ReplicaMember`](crate::protocol::types::ReplicaMember) does not carry
    /// its own `secret_id` — that is the key it is stored under — so a store
    /// that leaked rows across partitions would pass too.
    async fn replicas_matching(
        &self,
        secret_id: u64,
        filter: ReplicaFilter,
    ) -> Result<Vec<ReplicaMember>> {
        let rows = self.replicas(secret_id, filter.clone()).await?;
        Ok(retain_matching(rows, "replicas", |m| {
            filter.matches(&m.replica_id, m.status, &m.role)
        }))
    }

    /// Refuse a message whose sender does not hold `expected` on every one
    /// of `channel_ids`.
    ///
    /// A channel absent from the store is a failure, not a skip: a message
    /// naming a channel this device never paired on has no role to check.
    async fn require_role(
        &self,
        secret_id: u64,
        channel_ids: &[ChannelId],
        expected: SenderKind,
    ) -> Result<()> {
        for channel_id in channel_ids {
            let channel = self
                .load(
                    secret_id,
                    ChannelQuery::Helper {
                        channel_id: *channel_id,
                    },
                )
                .await?
                .and_then(|r| r.as_helper().cloned())
                .ok_or(Error::InvalidInput(
                    "channel id not present in channel store",
                ))?;
            if channel.peer_role != expected {
                return Err(Error::RoleMismatch {
                    channel_id: *channel_id,
                    expected,
                    actual: channel.peer_role,
                });
            }
        }
        Ok(())
    }

    /// Narrow a caller-supplied [`Target`] to the paired channels this
    /// `secret_id` holds.
    ///
    /// Ids naming a channel that is unknown or not
    /// [`Paired`](ChannelStatus::Paired) are dropped rather than refused: a
    /// target is a request to reach whoever is reachable, and a stale id in a
    /// list should not fail the whole fan-out.
    async fn resolve_target(&self, secret_id: u64, target: Target) -> Result<Vec<ChannelId>> {
        let known: Vec<ChannelId> = self
            .helpers_matching(
                secret_id,
                HelperFilter {
                    ids: target.ids(),
                    status: vec![ChannelStatus::Paired],
                    ..Default::default()
                },
            )
            .await?
            .iter()
            .map(|c| c.channel_id)
            .collect();

        Ok(target.filter(&known))
    }

    /// Every endpoint recorded for a peer, in the order it advertised them.
    ///
    /// Handed to [`DeRecTransport::send`] as-is: the library does not rank
    /// them, and the application chooses which to dial and whether to fall
    /// back.
    async fn peer_endpoints(
        &self,
        secret_id: u64,
        channel_id: ChannelId,
    ) -> Result<Vec<TransportProtocol>> {
        let channel = self
            .load(secret_id, ChannelQuery::Helper { channel_id })
            .await?;
        channel
            .map(|ch| ch.transports().to_vec())
            .filter(|endpoints| !endpoints.is_empty())
            .ok_or(Error::InvalidInput("no transport endpoint for channel"))
    }

    /// Pick the endpoints to deliver a response to.
    ///
    /// A reply-to names the addresses the requester asked to be answered on,
    /// so they stand alone rather than joining the recorded set: the recorded
    /// endpoints may belong to a different peer entirely (a replica talking
    /// to a helper paired with a sibling), so falling back to them would
    /// misroute rather than fail over.
    ///
    /// `reply_to` is peer-supplied and is filtered through `policy` first —
    /// the same rule every other peer-supplied endpoint is held to. An entry
    /// the policy refuses is dropped rather than used, and if nothing
    /// survives, this falls back to the channel's recorded endpoints exactly
    /// as it would had `reply_to` been empty: a `reply_to` offering only
    /// refused endpoints has, for routing purposes, offered nothing. Without
    /// this, a peer could steer a response — including the failure response
    /// to its own refused request — to an endpoint this device's policy
    /// exists to keep it off.
    async fn resolve_response_endpoints(
        &self,
        secret_id: u64,
        channel_id: ChannelId,
        policy: TransportPolicy,
        reply_to: &[TransportProtocol],
    ) -> Result<Vec<TransportProtocol>> {
        let allowed = filter_reply_to(policy, reply_to);
        if !allowed.is_empty() {
            return Ok(allowed);
        }
        self.peer_endpoints(secret_id, channel_id).await
    }

    /// Resolve one replica-group member by the identity the payload
    /// announced.
    ///
    /// Every member of a group answers on the same `channel_id`, so the
    /// channel alone cannot name the peer — the author does. A `0` is the
    /// wire's absent-value sentinel and never identifies a member.
    ///
    /// The author is sender-written, so it resolves only on the channel the
    /// member is recorded on. A member is stored by `(secret_id, replica_id)`
    /// and the store does not match `channel_id`; without this check, any peer
    /// holding a channel key could name a member and reach the replica path on
    /// its own channel.
    ///
    /// A member is also resolved on its
    /// [`handover_channel`](ReplicaMember::handover_channel), whose key only
    /// it and this device hold. The member is returned as reached there, with
    /// `channel_id` set to that channel, so an answer goes back on the channel
    /// and under the key the message arrived with.
    async fn load_replica_member(
        &self,
        secret_id: u64,
        channel_id: ChannelId,
        author: u64,
    ) -> Result<ReplicaMember> {
        let replica_id = ReplicaId::try_from(author)?;
        self.load(
            secret_id,
            ChannelQuery::Replica {
                channel_id,
                replica_id,
            },
        )
        .await?
        .and_then(|r| r.as_replica().cloned())
        .and_then(|member| {
            if member.channel_id == channel_id {
                Some(member)
            } else if member.handover_channel == Some(channel_id) {
                Some(ReplicaMember {
                    channel_id,
                    ..member
                })
            } else {
                None
            }
        })
        .ok_or(Error::InvalidInput(
            "replica sync names a member that is not in the group",
        ))
    }
}

impl<T: DeRecChannelStore> ChannelStoreExt for T {}

/// Narrow a peer-supplied `reply_to` to the entries `policy` accepts,
/// preserving order.
///
/// `reply_to` is used immediately rather than recorded, but it is still
/// peer-supplied input, so the rule is the same one
/// [`TransportPolicy::admit_peer_endpoints`](crate::transport::TransportPolicy::admit_peer_endpoints)
/// applies before an endpoint is stored: a refused entry is dropped, not
/// used. Shared by [`ChannelStoreExt::resolve_response_endpoints`] and the
/// replica-group answer paths, which address a [`ReplicaMember`] directly
/// rather than through a channel query and so cannot route through that
/// method.
pub(crate) fn filter_reply_to(
    policy: TransportPolicy,
    reply_to: &[TransportProtocol],
) -> Vec<TransportProtocol> {
    reply_to
        .iter()
        .filter(|endpoint| policy.check_peer(endpoint).is_ok())
        .cloned()
        .collect()
}

/// Build and dispatch an encrypted channel-mode response envelope.
///
/// `inbound_trace_id` is the `trace_id` read off the request envelope that
/// triggered this response. Echoed verbatim on the outbound envelope so the
/// requester can correlate (see the field doc on `DeRecMessage.traceId`).
/// Pass `0` when there is no inbound to echo from (e.g. unsolicited messages
/// that don't carry a meaningful correlation handle).
///
/// The envelope and `body` are stamped with one timestamp, read here: the
/// send time. Any timestamp `body` already carries is overwritten, so the
/// receiver's envelope-vs-inner check holds.
///
/// `body` answers the request `obligation` stands for, with `status` and
/// `memo`, the result `body` carries; it is
/// sent through [`deliver`](crate::protocol::obligation::deliver), so a
/// request is never answered twice.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn send_channel_message<Ch: DeRecChannelStore, T: DeRecTransport>(
    channel_store: &Ch,
    transport: &T,
    secret_id: u64,
    channel_id: ChannelId,
    mut body: MessageBody,
    shared_key: &SharedKey,
    inbound_trace_id: u64,
    policy: TransportPolicy,
    reply_to: &[TransportProtocol],
    obligation: Option<&Obligation>,
    status: StatusEnum,
    memo: &str,
) -> Result<()> {
    use crate::extensions::message_body::MessageBodyExt as _;

    let timestamp = current_timestamp();
    body.set_timestamp(timestamp);
    let envelope = DeRecMessageBuilder::channel()
        .channel_id(channel_id)
        .timestamp(timestamp)
        .message_body(body)
        .trace_id(inbound_trace_id)
        .encrypt(shared_key)?
        .build()?;

    let wire_bytes = envelope.encode_to_vec();
    let endpoint = channel_store
        .resolve_response_endpoints(secret_id, channel_id, policy, reply_to)
        .await?;
    deliver(obligation, transport, &endpoint, wire_bytes, status, memo).await
}

/// Drop rows the store returned that the filter excluded.
///
/// A store that pushed the filter down loses nothing here — the predicate is
/// true for every row, and nothing is logged.
///
/// One that ignored it gets those rows dropped, and, under the `logging`
/// feature, a **warning** naming the listing and the count. The level is
/// deliberate: this only fires when a store is not honouring its contract, and
/// the sooner whoever wrote it sees that, the better. It is silent for a
/// correct store, so it cannot become routine noise.
fn retain_matching<T>(rows: Vec<T>, listing: &str, keep: impl Fn(&T) -> bool) -> Vec<T> {
    let before = rows.len();
    let kept: Vec<T> = rows.into_iter().filter(keep).collect();

    #[cfg(feature = "logging")]
    if kept.len() != before {
        tracing::warn!(
            listing,
            returned = before,
            kept = kept.len(),
            "channel store did not apply the filter it was given; the excluded \
             rows were dropped here, but the store is transferring rows the \
             protocol discards and must apply the filter in its query"
        );
    }
    #[cfg(not(feature = "logging"))]
    let _ = (before, listing);

    kept
}

#[cfg(test)]
mod defiant_store_tests {
    use super::*;
    use crate::protocol::tests::{InMemChannelStore, run_async};
    use crate::protocol::traits::{ChannelStoreFuture, DeRecChannelStore};
    use crate::protocol::types::{
        ChannelQuery, ChannelRecord, ChannelStatus, HelperChannel, ReplicaMember, ReplicaRole,
    };
    use crate::types::ReplicaId;
    use derec_proto::Protocol;
    use std::collections::HashMap;

    const SECRET_ID: u64 = 0xDEF1;
    const GROUP: ChannelId = ChannelId(500);

    /// A store that accepts a filter and ignores it — the shape a TypeScript
    /// store written against 0.0.2 still compiles into, and the shape any
    /// binding can produce by simply not implementing the restriction.
    #[derive(Default)]
    struct DefiantStore(InMemChannelStore);

    impl DeRecChannelStore for DefiantStore {
        fn load(
            &self,
            secret_id: u64,
            query: ChannelQuery,
        ) -> ChannelStoreFuture<'_, Option<ChannelRecord>> {
            self.0.load(secret_id, query)
        }
        fn save(&mut self, secret_id: u64, record: ChannelRecord) -> ChannelStoreFuture<'_, ()> {
            self.0.save(secret_id, record)
        }
        fn remove(&mut self, secret_id: u64, query: ChannelQuery) -> ChannelStoreFuture<'_, bool> {
            self.0.remove(secret_id, query)
        }
        fn helpers(
            &self,
            secret_id: u64,
            _filter: HelperFilter,
        ) -> ChannelStoreFuture<'_, Vec<HelperChannel>> {
            self.0.helpers(secret_id, HelperFilter::default())
        }
        fn replicas(
            &self,
            secret_id: u64,
            _filter: ReplicaFilter,
        ) -> ChannelStoreFuture<'_, Vec<ReplicaMember>> {
            self.0.replicas(secret_id, ReplicaFilter::default())
        }
        fn link_channel(
            &mut self,
            secret_id: u64,
            a: ChannelId,
            b: ChannelId,
        ) -> ChannelStoreFuture<'_, ()> {
            self.0.link_channel(secret_id, a, b)
        }
        fn linked_channels(
            &self,
            secret_id: u64,
            channel_id: ChannelId,
        ) -> ChannelStoreFuture<'_, Vec<ChannelId>> {
            self.0.linked_channels(secret_id, channel_id)
        }
    }

    async fn seed(store: &mut DefiantStore, replica_id: u64, status: ChannelStatus) {
        store
            .save(
                SECRET_ID,
                ChannelRecord::Replica(ReplicaMember {
                    channel_id: GROUP,
                    replica_id: ReplicaId(replica_id),
                    transports: vec![TransportProtocol {
                        uri: "https://peer.example".to_owned(),
                        protocol: Protocol::Https as i32,
                    }],
                    communication_info: HashMap::new(),
                    role: ReplicaRole::Destination,
                    status,
                    created_at: 0,
                    handover_channel: None,
                }),
            )
            .await
            .expect("seed");
    }

    /// The eviction case: a by-id filter must never hand back a different
    /// member. Without the re-check, `on_request` would flag whichever row this
    /// store listed first, and the completing roster would delete it — turning
    /// "evict member X" into evicting member Y, with no error anywhere.
    #[test]
    fn a_by_id_filter_yields_only_that_member_even_when_the_store_ignores_it() {
        run_async(async {
            let mut store = DefiantStore::default();
            for id in [7001u64, 7002, 7003] {
                seed(&mut store, id, ChannelStatus::Paired).await;
            }

            let rows = store
                .replicas_matching(
                    SECRET_ID,
                    ReplicaFilter {
                        ids: vec![ReplicaId(7002)],
                        ..Default::default()
                    },
                )
                .await
                .expect("listing");

            assert_eq!(
                rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
                vec![7002],
                "the defiant store returned the whole roster; only the named member may survive"
            );
        });
    }

    /// The destructive case: `remove_expired_channels` deletes what this
    /// listing returns, and only the filter says `Pending`. A store that
    /// ignores it would otherwise offer up paired channels for deletion.
    #[test]
    fn a_status_filter_holds_even_when_the_store_ignores_it() {
        run_async(async {
            let mut store = DefiantStore::default();
            seed(&mut store, 8001, ChannelStatus::Pending).await;
            seed(&mut store, 8002, ChannelStatus::Paired).await;
            seed(&mut store, 8003, ChannelStatus::Paired).await;

            let rows = store
                .replicas_matching(
                    SECRET_ID,
                    ReplicaFilter {
                        status: vec![ChannelStatus::Pending],
                        ..Default::default()
                    },
                )
                .await
                .expect("listing");

            assert_eq!(
                rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
                vec![8001],
                "a paired member must never reach a sweep that asked for pending ones"
            );
        });
    }

    /// `exclude` is what keeps a device from dispatching to itself and from
    /// counting its own row as a peer.
    #[test]
    fn exclude_holds_even_when_the_store_ignores_it() {
        run_async(async {
            let mut store = DefiantStore::default();
            for id in [9001u64, 9002] {
                seed(&mut store, id, ChannelStatus::Paired).await;
            }

            let rows = store
                .replicas_matching(
                    SECRET_ID,
                    ReplicaFilter {
                        exclude: vec![ReplicaId(9001)],
                        ..Default::default()
                    },
                )
                .await
                .expect("listing");

            assert_eq!(
                rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
                vec![9002]
            );
        });
    }

    /// A store that does push the filter down loses nothing: the re-check is a
    /// no-op over rows that already satisfy it.
    #[test]
    fn a_conforming_store_is_unaffected() {
        run_async(async {
            let mut store = InMemChannelStore::default();
            for (id, status) in [(1u64, ChannelStatus::Pending), (2, ChannelStatus::Paired)] {
                store
                    .save(
                        SECRET_ID,
                        ChannelRecord::Replica(ReplicaMember {
                            channel_id: GROUP,
                            replica_id: ReplicaId(id),
                            transports: Vec::new(),
                            communication_info: HashMap::new(),
                            role: ReplicaRole::Destination,
                            status,
                            created_at: 0,
                            handover_channel: None,
                        }),
                    )
                    .await
                    .expect("seed");
            }

            let rows = store
                .replicas_matching(
                    SECRET_ID,
                    ReplicaFilter {
                        status: vec![ChannelStatus::Paired],
                        ..Default::default()
                    },
                )
                .await
                .expect("listing");

            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0].replica_id.0, 2);
        });
    }
}

#[cfg(test)]
mod send_channel_message_tests {
    use super::*;
    use crate::derec_message::extract_inner_message;
    use crate::extensions::derec_result::DeRecResultExt as _;
    use crate::extensions::message_body::MessageBodyExt as _;
    use crate::protocol::tests::{InMemChannelStore, RecordingTransport, run_async};
    use crate::protocol::types::{ChannelRecord, HelperChannel};
    use derec_proto::{DeRecMessage, DeRecResult, Protocol, UpdateChannelInfoResponseMessage};
    use std::collections::HashMap;

    const SECRET_ID: u64 = 0x5E4D;
    const CHANNEL: ChannelId = ChannelId(77);
    const KEY: SharedKey = [3u8; 32];

    /// The body arrives here already carrying a timestamp of its own; the
    /// envelope and the body must leave with one value, the send time.
    #[test]
    fn send_channel_message_stamps_envelope_and_body_with_one_timestamp() {
        run_async(async {
            let mut channels = InMemChannelStore::default();
            channels
                .save(
                    SECRET_ID,
                    ChannelRecord::Helper(HelperChannel {
                        channel_id: CHANNEL,
                        transports: vec![TransportProtocol {
                            uri: "https://peer.example".to_owned(),
                            protocol: Protocol::Https as i32,
                        }],
                        communication_info: HashMap::new(),
                        peer_role: SenderKind::Owner,
                        status: ChannelStatus::Paired,
                        created_at: 0,
                        weight: 1,
                    }),
                )
                .await
                .expect("seed channel");
            let transport = RecordingTransport::default();

            let body = MessageBody::UpdateChannelInfoResponse(UpdateChannelInfoResponseMessage {
                result: Some(DeRecResult::ok()),
                timestamp: Some(prost_types::Timestamp {
                    seconds: 1,
                    nanos: 0,
                }),
            });

            send_channel_message(
                &channels,
                &transport,
                SECRET_ID,
                CHANNEL,
                body,
                &KEY,
                0,
                TransportPolicy::new(false),
                &[],
                None,
                StatusEnum::Ok,
                "",
            )
            .await
            .expect("send");

            let sent = transport.sent_envelopes();
            assert_eq!(sent.len(), 1);
            let envelope = DeRecMessage::decode(sent[0].as_slice()).expect("decode");
            let inner = extract_inner_message(&envelope.message, &KEY).expect("decrypt");
            assert!(envelope.timestamp.is_some());
            assert_eq!(envelope.timestamp.as_ref(), inner.timestamp());
        });
    }
}

/// A `reply_to` is peer-supplied, so [`ChannelStoreExt::resolve_response_endpoints`]
/// must apply the same transport policy to it that every other peer-supplied
/// endpoint is held to — including when it is standing in as the address for
/// a courtesy failure response.
#[cfg(test)]
mod resolve_response_endpoints_tests {
    use super::*;
    use crate::protocol::tests::{InMemChannelStore, run_async};
    use crate::protocol::types::{ChannelRecord, ChannelStatus, HelperChannel};
    use crate::transport::TransportPolicy;
    use derec_proto::Protocol;
    use std::collections::HashMap;

    const SECRET_ID: u64 = 0x1234;
    const CHANNEL: ChannelId = ChannelId(42);
    const STRICT: TransportPolicy = TransportPolicy::new(false);

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

    async fn seeded_store() -> InMemChannelStore {
        let mut store = InMemChannelStore::default();
        store
            .save(
                SECRET_ID,
                ChannelRecord::Helper(HelperChannel {
                    channel_id: CHANNEL,
                    transports: vec![endpoint("https://recorded.example")],
                    communication_info: HashMap::new(),
                    peer_role: SenderKind::Owner,
                    status: ChannelStatus::Paired,
                    created_at: 0,
                    weight: 1,
                }),
            )
            .await
            .expect("seed channel");
        store
    }

    /// A refused entry is dropped; an allowed sibling in the same `reply_to`
    /// still carries the response, and the recorded endpoint is never
    /// consulted.
    #[test]
    fn mixed_reply_to_keeps_only_the_allowed_entries() {
        run_async(async {
            let store = seeded_store().await;
            let reply_to = vec![
                endpoint("http://peer.example"),
                endpoint("https://peer.example"),
            ];

            let resolved = store
                .resolve_response_endpoints(SECRET_ID, CHANNEL, STRICT, &reply_to)
                .await
                .expect("resolve");

            assert_eq!(resolved, vec![endpoint("https://peer.example")]);
        });
    }

    /// Every `reply_to` entry refused is the same as a `reply_to` that was
    /// never supplied: the channel's recorded endpoints answer instead.
    #[test]
    fn all_refused_falls_back_to_recorded_endpoints() {
        run_async(async {
            let store = seeded_store().await;
            let reply_to = vec![endpoint("http://peer.example")];

            let resolved = store
                .resolve_response_endpoints(SECRET_ID, CHANNEL, STRICT, &reply_to)
                .await
                .expect("resolve");

            assert_eq!(resolved, vec![endpoint("https://recorded.example")]);
        });
    }

    /// Every `reply_to` entry allowed is used as-is, matching the
    /// unfiltered behaviour this policy-aware path must preserve.
    #[test]
    fn all_allowed_reply_to_is_used_unfiltered() {
        run_async(async {
            let store = seeded_store().await;
            let reply_to = vec![
                endpoint("https://peer-a.example"),
                endpoint("https://peer-b.example"),
            ];

            let resolved = store
                .resolve_response_endpoints(SECRET_ID, CHANNEL, STRICT, &reply_to)
                .await
                .expect("resolve");

            assert_eq!(resolved, reply_to);
        });
    }
}