Skip to main content

zaun_client/voice/
stay.rs

1//! One stay in a voice channel without its transport: the roster and its keys, who offers a
2//! connection to whom, a peer's signals that come before it, rekeying and the wait before a
3//! new key seals, mute and deafen, and sealing and opening frames.
4//!
5//! A new epoch seals only once every peer it was made for said it installed the keys
6//! ([`Signal::Keyed`]), or after [`ACTIVATE_WITHIN_MS`]: the host relays keys in a few hundred
7//! milliseconds, and a frame sealed before they arrive cannot be opened. Frames go only to the
8//! peers the sealing epoch was made for, so a newcomer gets nothing it cannot open.
9//!
10//! A peer keeps only two of a sender's epochs. A leave while an epoch is pending forces a third
11//! at once, and a peer that installs both drops the one still sealing; so the pending epoch
12//! seals first when the leaver had what seals and every peer that hears has it, and a forced
13//! epoch seals once the peers that hear have it, a newcomer hearing once it says so too.
14//!
15//! It answers each input with [`Act`]s for the transport to carry out: str0m over UDP in the
16//! native build, the browser's WebRTC in WebAssembly. Time is wall milliseconds, given in.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use zaun_community_protocol::command::object::VoiceParticipant;
21use zaun_community_protocol::command::voice::{Joined, Keys as KeysBody};
22use zaun_community_protocol::event::{VoiceKeys, VoiceLeft, VoiceLeftReason, VoiceSignal};
23use zaun_community_protocol::ids::{ChannelId, MemberId, VoiceSessionId};
24
25use super::keys::{AddError, StayKeys};
26use super::signal::Signal;
27
28/// The longest a new epoch waits for its peers to say they installed it (RFC 9605 ยง4.4.1)
29/// before it seals anyway: a peer that never says so (an older client) still has the keys.
30pub(crate) const ACTIVATE_WITHIN_MS: u64 = 3_000;
31/// Signals kept for a voice session not yet known (it joins in the same breath).
32const EARLY_SIGNALS: usize = 8;
33/// Voice sessions whose early signals are kept.
34const EARLY_SESSIONS: usize = 16;
35
36/// What happens in a voice session.
37#[cfg_attr(
38    target_arch = "wasm32",
39    allow(
40        dead_code,
41        reason = "the browser decodes frames itself and says when it connects"
42    )
43)]
44#[derive(Debug, Clone)]
45pub enum VoiceEvent {
46    /// Someone joined the channel (no key package: that stays inside the session).
47    Joined(VoiceParticipant),
48    /// Someone changed mute or deafen, or a moderator did.
49    Updated(VoiceParticipant),
50    /// Someone left the channel.
51    Left {
52        /// The member.
53        member: MemberId,
54        /// Why.
55        reason: VoiceLeftReason,
56    },
57    /// The media connection to a participant is up.
58    Connected(MemberId),
59    /// An Opus frame from a participant, decrypted.
60    Audio {
61        /// Who spoke.
62        member: MemberId,
63        /// The Opus frame.
64        frame: Vec<u8>,
65    },
66    /// This member's keys moved to a new epoch (someone joined or left).
67    Rekeyed(u32),
68    /// The host listed another key for `member` than the one this client saw first, so the
69    /// participant was skipped: no media and no keys go to it. Either the member replaced its
70    /// key, or the host is putting itself in the member's place; compare
71    /// [`Member::fingerprint`](crate::Member::fingerprint) with the member out of band.
72    KeyChanged {
73        /// The member whose key changed.
74        member: MemberId,
75    },
76    /// The session ended: left, moved or disconnected by a moderator, the host went away, or
77    /// the media relay ended the allocation (never replaced by a direct path).
78    /// When moved, rejoin in `moved_to` with [`Channel::join`](crate::Channel::join).
79    Ended {
80        /// Why, when the host said.
81        reason: Option<VoiceLeftReason>,
82        /// The channel a moderator moved this member to.
83        moved_to: Option<ChannelId>,
84    },
85    /// Something was skipped safely (a peer whose key package did not verify, a refused
86    /// signal); the text names no key or address.
87    Warning(String),
88}
89
90/// What the host says about the channel, for the stay.
91#[derive(Debug, Clone)]
92pub(crate) enum HostInput {
93    Joined(VoiceParticipant),
94    Updated(VoiceParticipant),
95    Left(VoiceLeft),
96    Signal(VoiceSignal),
97    Keys(VoiceKeys),
98    /// The host connection closed, or this member was removed.
99    Gone,
100}
101
102/// What the transport does next.
103#[cfg_attr(
104    target_arch = "wasm32",
105    allow(dead_code, reason = "the browser transport looks the member up itself")
106)]
107#[derive(Debug)]
108pub(crate) enum Act {
109    /// Make a connection for `session`; `offer` when this side makes the offer.
110    Open {
111        session: VoiceSessionId,
112        member: MemberId,
113        offer: bool,
114    },
115    /// Drop the connection for `session`.
116    Close(VoiceSessionId),
117    /// A peer's signal, for the connection that `Open` made.
118    Signal(VoiceSessionId, Signal),
119    /// Send `signal` to a peer through the host (`voice.signal`).
120    Tell {
121        session: VoiceSessionId,
122        member: MemberId,
123        signal: Signal,
124    },
125    /// Publish this member's new keys (`voice.keys`).
126    Keys(KeysBody),
127    /// Tell the application.
128    Event(VoiceEvent),
129    /// The stay is over; tell the application and stop.
130    End(VoiceEvent),
131}
132
133pub(crate) struct Stay {
134    me: MemberId,
135    my_session: VoiceSessionId,
136    keys: StayKeys,
137    peers: BTreeMap<VoiceSessionId, MemberId>,
138    early: BTreeMap<VoiceSessionId, Vec<Signal>>,
139    self_mute: bool,
140    self_deaf: bool,
141    server_mute: bool,
142    server_deaf: bool,
143    can_speak: bool,
144    /// The newest epoch, waiting for its peers before it seals.
145    pending: Option<Pending>,
146    /// Another rekey is due once the pending epoch seals (someone joined meanwhile).
147    deferred: bool,
148    /// The peers the sealing epoch was made for that have it (or whose wait is over): the only
149    /// ones frames go to.
150    hears: BTreeSet<VoiceSessionId>,
151    /// The sealing epoch's peers that have not said they installed it (newcomers when a forced
152    /// epoch sealed early): each hears once it says so, all of them at its deadline.
153    late: Option<Pending>,
154}
155
156/// An epoch made and sent, not yet sealing.
157struct Pending {
158    epoch: u32,
159    /// The peers it was made for.
160    recipients: BTreeSet<VoiceSessionId>,
161    /// Those that have not said they installed it.
162    waiting: BTreeSet<VoiceSessionId>,
163    /// Wall ms at which it seals anyway.
164    deadline: u64,
165    /// Made for a leave: it seals once the peers that hear have it.
166    forced: bool,
167}
168
169impl Pending {
170    /// Whether every peer in `hears` said it installed it.
171    fn heard_by(&self, hears: &BTreeSet<VoiceSessionId>) -> bool {
172        self.waiting.is_disjoint(hears)
173    }
174}
175
176impl Stay {
177    pub(crate) fn new(
178        me: MemberId,
179        joined: &Joined,
180        keys: StayKeys,
181        self_mute: bool,
182        self_deaf: bool,
183    ) -> Self {
184        let mine = joined.participants.iter().find(|p| p.member_id == me);
185        Self {
186            me,
187            my_session: joined.voice_session,
188            keys,
189            peers: BTreeMap::new(),
190            early: BTreeMap::new(),
191            self_mute,
192            self_deaf,
193            server_mute: mine.is_some_and(|p| p.server_mute),
194            server_deaf: mine.is_some_and(|p| p.server_deaf),
195            can_speak: mine.is_none_or(|p| p.can_speak),
196            pending: None,
197            deferred: false,
198            hears: BTreeSet::new(),
199            late: None,
200        }
201    }
202
203    /// Whether frames go out: not muted by this member or a moderator, and allowed to speak.
204    pub(crate) const fn can_send(&self) -> bool {
205        !self.self_mute && !self.server_mute && self.can_speak
206    }
207
208    pub(crate) const fn deafened(&self) -> bool {
209        self.self_deaf || self.server_deaf
210    }
211
212    /// The participants already in the channel: verify each and offer it a connection.
213    pub(crate) fn begin(&mut self, joined: &Joined, wall: u64) -> Vec<Act> {
214        let mut acts = Vec::new();
215        for p in &joined.participants {
216            if p.voice_session == self.my_session || p.member_id == self.me {
217                continue;
218            }
219            if self.add_peer(p, &mut acts) {
220                acts.push(Act::Open {
221                    session: p.voice_session,
222                    member: p.member_id,
223                    offer: true,
224                });
225            }
226        }
227        self.rekey(wall, false, &mut acts);
228        acts
229    }
230
231    pub(crate) fn on_host(&mut self, input: HostInput, wall: u64) -> Vec<Act> {
232        let mut acts = Vec::new();
233        match input {
234            HostInput::Gone => acts.push(Act::End(VoiceEvent::Ended {
235                reason: None,
236                moved_to: None,
237            })),
238            // Only this stay's own end: leaving another channel to join this one names the old one.
239            HostInput::Left(l) if l.voice_session == self.my_session => {
240                acts.push(Act::End(VoiceEvent::Ended {
241                    reason: Some(l.reason),
242                    moved_to: l.moved_to,
243                }));
244            }
245            HostInput::Joined(p) => {
246                if p.member_id != self.me && self.add_peer(&p, &mut acts) {
247                    acts.push(Act::Open {
248                        session: p.voice_session,
249                        member: p.member_id,
250                        offer: false,
251                    });
252                    for s in self.early.remove(&p.voice_session).unwrap_or_default() {
253                        acts.push(Act::Signal(p.voice_session, s));
254                    }
255                    self.rekey(wall, false, &mut acts);
256                }
257                acts.push(Act::Event(VoiceEvent::Joined(public(p))));
258            }
259            HostInput::Updated(p) => {
260                if p.member_id == self.me {
261                    self.server_mute = p.server_mute;
262                    self.server_deaf = p.server_deaf;
263                    self.can_speak = p.can_speak;
264                }
265                acts.push(Act::Event(VoiceEvent::Updated(public(p))));
266            }
267            HostInput::Left(l) => {
268                if self.peers.remove(&l.voice_session).is_some() {
269                    acts.push(Act::Close(l.voice_session));
270                }
271                self.early.remove(&l.voice_session);
272                // Whether the leaver had the sealing epoch.
273                let mut had = self.hears.remove(&l.voice_session);
274                if let Some(late) = self.late.as_mut() {
275                    had |= late.waiting.remove(&l.voice_session);
276                    if late.waiting.is_empty() {
277                        self.late = None;
278                    }
279                }
280                if let Some(p) = self.pending.as_mut() {
281                    p.recipients.remove(&l.voice_session);
282                    p.waiting.remove(&l.voice_session);
283                }
284                if self.keys.remove(&l.voice_session).is_some() {
285                    // The leaver must not open what comes next: rekey now, even over a
286                    // pending epoch (which it had). The peers that hear would then drop the
287                    // sealing epoch for the two newer ones, so the pending one seals first
288                    // when they all have it and the leaver had nothing less.
289                    if had
290                        && self
291                            .pending
292                            .as_ref()
293                            .is_some_and(|p| p.heard_by(&self.hears))
294                    {
295                        self.deferred = false;
296                        self.activate(wall, &mut acts);
297                    }
298                    self.rekey(wall, true, &mut acts);
299                }
300                self.activate_if_ready(wall, &mut acts);
301                acts.push(Act::Event(VoiceEvent::Left {
302                    member: l.member_id,
303                    reason: l.reason,
304                }));
305            }
306            HostInput::Signal(s) => match Signal::decode(s.data.as_bytes()) {
307                Some(Signal::Keyed { epoch }) => {
308                    if let Some(p) = self.pending.as_mut()
309                        && p.epoch == epoch
310                    {
311                        p.waiting.remove(&s.voice_session);
312                    }
313                    if let Some(late) = self.late.as_mut()
314                        && late.epoch == epoch
315                        && late.waiting.remove(&s.voice_session)
316                    {
317                        self.hears.insert(s.voice_session);
318                        if late.waiting.is_empty() {
319                            self.late = None;
320                        }
321                    }
322                    self.activate_if_ready(wall, &mut acts);
323                }
324                Some(signal) if self.peers.contains_key(&s.voice_session) => {
325                    acts.push(Act::Signal(s.voice_session, signal));
326                }
327                Some(signal) => self.keep_early(s.voice_session, signal),
328                None => acts.push(warning("a signal did not decode")),
329            },
330            HostInput::Keys(k) => {
331                match self.keys.accept(
332                    &k.voice_session,
333                    k.sender_keys.as_bytes(),
334                    k.wrapped.as_bytes(),
335                ) {
336                    Ok(epoch) => {
337                        if let Some(member) = self.peers.get(&k.voice_session) {
338                            acts.push(Act::Tell {
339                                session: k.voice_session,
340                                member: *member,
341                                signal: Signal::Keyed { epoch },
342                            });
343                        }
344                    }
345                    Err(e) => acts.push(Act::Event(VoiceEvent::Warning(format!(
346                        "a participant's keys were refused ({e})"
347                    )))),
348                }
349            }
350        }
351        acts
352    }
353
354    /// A pending epoch seals once its wait is over, whoever said they have it, and the sealing
355    /// epoch's late peers hear.
356    pub(crate) fn on_time(&mut self, wall: u64) -> Vec<Act> {
357        let mut acts = Vec::new();
358        if self.late.as_ref().is_some_and(|l| l.deadline <= wall)
359            && let Some(late) = self.late.take()
360        {
361            self.hears.extend(late.waiting);
362        }
363        if self.pending.as_ref().is_some_and(|p| p.deadline <= wall) {
364            self.activate(wall, &mut acts);
365        }
366        acts
367    }
368
369    /// The pending epoch seals once every peer it was made for has it; a forced one once the
370    /// peers that hear have it.
371    fn activate_if_ready(&mut self, wall: u64, acts: &mut Vec<Act>) {
372        if self
373            .pending
374            .as_ref()
375            .is_some_and(|p| p.waiting.is_empty() || (p.forced && p.heard_by(&self.hears)))
376        {
377            self.activate(wall, acts);
378        }
379    }
380
381    /// The pending epoch seals, for the peers it was made for that have it (all of them once
382    /// its wait is over; the others hear once they say so); a deferred rekey follows.
383    fn activate(&mut self, wall: u64, acts: &mut Vec<Act>) {
384        let Some(mut p) = self.pending.take() else {
385            return;
386        };
387        self.keys.activate();
388        if p.deadline <= wall {
389            p.waiting.clear();
390        }
391        self.hears = p.recipients.difference(&p.waiting).copied().collect();
392        self.late = (!p.waiting.is_empty()).then_some(p);
393        if std::mem::take(&mut self.deferred) {
394            self.rekey(wall, false, acts);
395        }
396    }
397
398    /// Whether frames go to `session`: the sealing epoch was made for it.
399    pub(crate) fn sends_to(&self, session: &VoiceSessionId) -> bool {
400        self.hears.contains(session)
401    }
402
403    /// When [`on_time`](Self::on_time) has something to do.
404    #[cfg_attr(
405        target_arch = "wasm32",
406        allow(dead_code, reason = "the browser stay runs on the client's tick")
407    )]
408    pub(crate) fn next_deadline(&self) -> Option<u64> {
409        [self.pending.as_ref(), self.late.as_ref()]
410            .into_iter()
411            .flatten()
412            .map(|p| p.deadline)
413            .min()
414    }
415
416    pub(crate) fn set_self(&mut self, mute: Option<bool>, deaf: Option<bool>) {
417        self.self_mute = mute.unwrap_or(self.self_mute);
418        self.self_deaf = deaf.unwrap_or(self.self_deaf);
419    }
420
421    /// `frame` sealed for every peer; `None` while muted or before the first epoch is active.
422    pub(crate) fn seal(&mut self, frame: &[u8]) -> Option<Vec<u8>> {
423        if !self.can_send() {
424            return None;
425        }
426        self.keys.seal(frame).ok()
427    }
428
429    /// A frame from `session`, opened, and who sent it; `None` while deafened, or for a frame
430    /// that does not open.
431    pub(crate) fn open(
432        &mut self,
433        session: &VoiceSessionId,
434        data: &[u8],
435    ) -> Option<(MemberId, Vec<u8>)> {
436        if self.deafened() {
437            return None;
438        }
439        let member = *self.peers.get(session)?;
440        self.keys.open(session, data).ok().map(|f| (member, f))
441    }
442
443    /// Whom `session` belongs to, while it is a peer.
444    #[cfg_attr(
445        not(target_arch = "wasm32"),
446        allow(dead_code, reason = "the browser transport's; str0m keeps its own")
447    )]
448    pub(crate) fn member(&self, session: &VoiceSessionId) -> Option<MemberId> {
449        self.peers.get(session).copied()
450    }
451
452    fn add_peer(&mut self, p: &VoiceParticipant, acts: &mut Vec<Act>) -> bool {
453        match self.keys.add(p) {
454            Ok(true) => {
455                self.peers.insert(p.voice_session, p.member_id);
456                true
457            }
458            Ok(false) => false,
459            Err(e) => {
460                acts.push(Act::Event(refusal(p.member_id, e)));
461                false
462            }
463        }
464    }
465
466    fn keep_early(&mut self, session: VoiceSessionId, signal: Signal) {
467        if !self.early.contains_key(&session) && self.early.len() >= EARLY_SESSIONS {
468            return;
469        }
470        let list = self.early.entry(session).or_default();
471        if list.len() < EARLY_SIGNALS {
472            list.push(signal);
473        }
474    }
475
476    /// Makes the next epoch if the peers changed. While one is pending, a join waits for it
477    /// (`urgent` false); a leave does not.
478    fn rekey(&mut self, wall: u64, urgent: bool, acts: &mut Vec<Act>) {
479        if !self.keys.needs_rekey() {
480            return;
481        }
482        if self.pending.is_some() && !urgent {
483            self.deferred = true;
484            return;
485        }
486        self.deferred = false;
487        match self.keys.rekey(wall) {
488            Ok((epoch, body)) => {
489                match body {
490                    Some(body) => {
491                        acts.push(Act::Keys(body));
492                        let recipients: BTreeSet<VoiceSessionId> =
493                            self.peers.keys().copied().collect();
494                        self.pending = Some(Pending {
495                            epoch,
496                            waiting: recipients.clone(),
497                            recipients,
498                            deadline: wall + ACTIVATE_WITHIN_MS,
499                            forced: urgent,
500                        });
501                    }
502                    None => {
503                        self.keys.activate();
504                        self.pending = None;
505                        self.hears.clear();
506                        self.late = None;
507                    }
508                }
509                acts.push(Act::Event(VoiceEvent::Rekeyed(epoch)));
510            }
511            Err(e) => acts.push(Act::Event(VoiceEvent::Warning(format!(
512                "rekey failed: {e}"
513            )))),
514        }
515    }
516}
517
518fn warning(text: &str) -> Act {
519    Act::Event(VoiceEvent::Warning(text.into()))
520}
521
522/// What the application hears about a participant that was skipped.
523pub(crate) fn refusal(member: MemberId, e: AddError) -> VoiceEvent {
524    match e {
525        AddError::Missing => VoiceEvent::Warning(
526            "a participant came without a key package or member key; skipped".into(),
527        ),
528        AddError::Refused(e) => VoiceEvent::Warning(format!(
529            "a participant's key package was refused ({e}); skipped"
530        )),
531        AddError::KeyChanged => VoiceEvent::KeyChanged { member },
532        AddError::Unpinned(e) => VoiceEvent::Warning(format!(
533            "a participant's key could not be pinned ({e}); skipped"
534        )),
535    }
536}
537
538/// A participant as the application sees it: the key material stays in the session.
539pub(crate) fn public(mut p: VoiceParticipant) -> VoiceParticipant {
540    p.key_package = None;
541    p.member_public_key = None;
542    p
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548    use crate::pins::tests::Memory;
549    use zaun_community_protocol::command::object::{IcePolicy, Opaque};
550    use zaun_community_protocol::crypto::SecretKey;
551    use zaun_community_protocol::ids::CommunityId;
552
553    const C: CommunityId = CommunityId::from_bytes([1; 32]);
554    const CH: ChannelId = ChannelId::from_bytes([2; 16]);
555
556    struct Who {
557        key: SecretKey,
558        id: MemberId,
559        session: VoiceSessionId,
560        package: Vec<u8>,
561    }
562
563    /// A participant with its stay's keys, which go into the stay `stay` makes.
564    fn who(n: u8) -> (Who, StayKeys) {
565        let key = SecretKey::generate().unwrap();
566        let id = MemberId::from_bytes([n; 16]);
567        let keys = StayKeys::new(key.clone(), C, CH, id, 0, Box::new(Memory::default())).unwrap();
568        let w = Who {
569            key,
570            id,
571            session: VoiceSessionId::from_bytes([n; 16]),
572            package: keys.key_package(),
573        };
574        (w, keys)
575    }
576
577    fn participant(w: &Who) -> VoiceParticipant {
578        VoiceParticipant {
579            member_id: w.id,
580            voice_session: w.session,
581            key_package: Some(Opaque(w.package.clone())),
582            member_public_key: Some(w.key.public_key()),
583            self_mute: false,
584            self_deaf: false,
585            server_mute: false,
586            server_deaf: false,
587            can_speak: true,
588        }
589    }
590
591    /// `w` joins with everyone in `there` already in the channel.
592    fn join(w: &Who, keys: StayKeys, there: &[&Who], wall: u64) -> (Stay, Vec<Act>) {
593        let mut participants: Vec<VoiceParticipant> =
594            there.iter().map(|o| participant(o)).collect();
595        participants.push(participant(w));
596        let joined = Joined {
597            channel_id: CH,
598            voice_session: w.session,
599            participants,
600            ice_servers: Vec::new(),
601            ice_policy: IcePolicy::Relay,
602            mesh_max: 8,
603        };
604        let mut stay = Stay::new(w.id, &joined, keys, false, false);
605        let acts = stay.begin(&joined, wall);
606        (stay, acts)
607    }
608
609    fn keys_in(acts: &[Act]) -> Option<&KeysBody> {
610        acts.iter().find_map(|a| match a {
611            Act::Keys(k) => Some(k),
612            _ => None,
613        })
614    }
615
616    /// `from`'s `voice.keys` as the host hands it to `to`.
617    fn deliver(body: &KeysBody, from: &Who, to: &Who) -> HostInput {
618        let mine = body.keys.iter().find(|k| k.to == to.id).unwrap();
619        HostInput::Keys(VoiceKeys {
620            from: from.id,
621            voice_session: from.session,
622            epoch: body.epoch,
623            sender_keys: body.sender_keys.clone(),
624            wrapped: mine.wrapped.clone(),
625        })
626    }
627
628    /// The `Keyed` a stay told `to`, as the host relays it from `from`.
629    fn told(acts: &[Act], from: &Who, to: &Who) -> HostInput {
630        let signal = acts
631            .iter()
632            .find_map(|a| match a {
633                Act::Tell {
634                    session, signal, ..
635                } if *session == to.session => Some(signal.clone()),
636                _ => None,
637            })
638            .expect("a Keyed was told");
639        assert!(matches!(signal, Signal::Keyed { .. }));
640        HostInput::Signal(VoiceSignal {
641            from: from.id,
642            voice_session: from.session,
643            data: Opaque(signal.encode().unwrap()),
644        })
645    }
646
647    #[test]
648    fn a_new_epoch_seals_only_once_its_peer_said_it_has_the_keys() {
649        let ((a, ka), (b, kb)) = (who(1), who(2));
650        let (mut sa, acts) = join(&a, ka, &[], 0);
651        assert!(keys_in(&acts).is_none(), "alone, nothing is sent");
652        assert!(
653            sa.seal(b"to nobody").is_some(),
654            "alone, the epoch seals at once"
655        );
656
657        // b joins: each makes an epoch for the other and waits for it to be installed.
658        let (mut sb, b_acts) = join(&b, kb, &[&a], 10);
659        let a_acts = sa.on_host(HostInput::Joined(participant(&b)), 20);
660        let (body_a, body_b) = (keys_in(&a_acts).unwrap(), keys_in(&b_acts).unwrap());
661        assert!(!sa.sends_to(&b.session) && !sb.sends_to(&a.session));
662
663        // a installs b's keys and says so; b seals for a from then on, and a opens it.
664        let a_got = sa.on_host(deliver(body_b, &b, &a), 400);
665        assert!(
666            !sb.sends_to(&a.session),
667            "nothing before a said it has the keys"
668        );
669        assert!(sb.on_host(told(&a_got, &a, &b), 900).is_empty());
670        assert!(sb.sends_to(&a.session));
671        let frame = sb.seal(b"from b").unwrap();
672        assert_eq!(sa.open(&b.session, &frame).unwrap().1, b"from b");
673
674        // The other way round: a's epoch waits for b's word, its old one never reached b.
675        let b_got = sb.on_host(deliver(body_a, &a, &b), 1_000);
676        assert!(!sa.sends_to(&b.session));
677        sa.on_host(told(&b_got, &b, &a), 1_500);
678        assert!(sa.sends_to(&b.session));
679        let frame = sa.seal(b"from a").unwrap();
680        assert_eq!(sb.open(&a.session, &frame).unwrap().1, b"from a");
681    }
682
683    #[test]
684    fn an_epoch_nobody_acknowledges_seals_after_the_wait() {
685        let ((a, ka), (b, _)) = (who(1), who(2));
686        let (mut sa, _) = join(&a, ka, &[], 0);
687        sa.on_host(HostInput::Joined(participant(&b)), 100);
688        assert_eq!(sa.next_deadline(), Some(100 + ACTIVATE_WITHIN_MS));
689        assert!(sa.on_time(99 + ACTIVATE_WITHIN_MS).is_empty());
690        assert!(!sa.sends_to(&b.session));
691        sa.on_time(100 + ACTIVATE_WITHIN_MS);
692        assert!(
693            sa.sends_to(&b.session),
694            "an older peer that never says so has the keys"
695        );
696        assert_eq!(sa.next_deadline(), None);
697    }
698
699    #[test]
700    fn a_join_waits_for_the_pending_epoch_and_a_leave_does_not() {
701        let ((a, ka), (b, kb), (c, _)) = (who(1), who(2), who(3));
702        let (mut sa, _) = join(&a, ka, &[], 0);
703        let (mut sb, _) = join(&b, kb, &[&a], 0);
704        let first = sa.on_host(HostInput::Joined(participant(&b)), 10);
705        // c joins before b has a's keys: no second epoch yet.
706        let later = sa.on_host(HostInput::Joined(participant(&c)), 20);
707        assert!(keys_in(&later).is_none());
708        // b's word seals the first epoch (for b only) and makes the next one, for b and c.
709        let b_got = sb.on_host(deliver(keys_in(&first).unwrap(), &a, &b), 30);
710        let next = sa.on_host(told(&b_got, &b, &a), 40);
711        assert!(sa.sends_to(&b.session) && !sa.sends_to(&c.session));
712        let to: Vec<MemberId> = keys_in(&next).unwrap().keys.iter().map(|k| k.to).collect();
713        assert_eq!(to.len(), 2);
714        // c leaves while that epoch is pending: the rekey without it does not wait.
715        let left = sa.on_host(
716            HostInput::Left(VoiceLeft {
717                channel_id: CH,
718                member_id: c.id,
719                voice_session: c.session,
720                reason: VoiceLeftReason::Left,
721                moved_to: None,
722            }),
723            50,
724        );
725        let to: Vec<MemberId> = keys_in(&left).unwrap().keys.iter().map(|k| k.to).collect();
726        assert_eq!(to, vec![b.id]);
727    }
728
729    fn left(w: &Who) -> HostInput {
730        HostInput::Left(VoiceLeft {
731            channel_id: CH,
732            member_id: w.id,
733            voice_session: w.session,
734            reason: VoiceLeftReason::Left,
735            moved_to: None,
736        })
737    }
738
739    fn opens(stay: &mut Stay, from: &Who, frame: &[u8]) -> Option<Vec<u8>> {
740        stay.open(&from.session, frame).map(|(_, f)| f)
741    }
742
743    /// a, b and d in the channel with a's first epoch sealing; c joins and a makes the next
744    /// epoch for b, c and d, which b and d install. Returns the stays and that epoch.
745    fn three_hear_and_c_joins() -> (Vec<Who>, Stay, Stay, Stay, Stay, KeysBody) {
746        let ((a, ka), (b, kb), (c, kc), (d, kd)) = (who(1), who(2), who(3), who(4));
747        let (mut sa, first) = join(&a, ka, &[&b, &d], 0);
748        let (mut sb, _) = join(&b, kb, &[&a, &d], 0);
749        let (mut sd, _) = join(&d, kd, &[&a, &b], 0);
750        let first = keys_in(&first).unwrap();
751        for (s, w) in [(&mut sb, &b), (&mut sd, &d)] {
752            let got = s.on_host(deliver(first, &a, w), 10);
753            sa.on_host(told(&got, w, &a), 20);
754        }
755        assert!(sa.sends_to(&b.session) && sa.sends_to(&d.session));
756        let frame = sa.seal(b"first").unwrap();
757        assert_eq!(opens(&mut sb, &a, &frame).unwrap(), b"first");
758
759        let (sc, _) = join(&c, kc, &[&a, &b, &d], 100);
760        let joined = sa.on_host(HostInput::Joined(participant(&c)), 100);
761        let next = keys_in(&joined).unwrap().clone();
762        sd.on_host(deliver(&next, &a, &d), 200);
763        (vec![a, b, c, d], sa, sb, sc, sd, next)
764    }
765
766    #[test]
767    fn a_leave_over_a_pending_epoch_its_hearers_have_does_not_cut_them_off() {
768        let (w, mut sa, mut sb, mut sc, mut sd, next) = three_hear_and_c_joins();
769        let (a, b, c, d) = (&w[0], &w[1], &w[2], &w[3]);
770        let got = sb.on_host(deliver(&next, a, b), 200);
771        sa.on_host(told(&got, b, a), 300);
772
773        // d leaves before c said it has the pending epoch: a rekeys for b and c at once.
774        let forced = sa.on_host(left(d), 400);
775        let forced = keys_in(&forced).unwrap();
776        assert!(!sa.sends_to(&d.session));
777        // b installs it, its word still on the way: b keeps two of a's epochs, and the one a
778        // seals with must be one of them.
779        let got = sb.on_host(deliver(forced, a, b), 500);
780        let frame = sa.seal(b"while b's word travels").unwrap();
781        assert_eq!(
782            opens(&mut sb, a, &frame).unwrap(),
783            b"while b's word travels"
784        );
785
786        // b's word seals the new epoch: b hears it, the leaver opens nothing from then on,
787        // and c, not yet keyed, gets nothing.
788        sa.on_host(told(&got, b, a), 600);
789        assert!(sa.sends_to(&b.session) && !sa.sends_to(&c.session));
790        let frame = sa.seal(b"after d left").unwrap();
791        assert_eq!(opens(&mut sb, a, &frame).unwrap(), b"after d left");
792        assert!(
793            opens(&mut sd, a, &frame).is_none(),
794            "the leaver opens nothing"
795        );
796
797        // c says it has the keys and hears from then on.
798        let got = sc.on_host(deliver(forced, a, c), 700);
799        sa.on_host(told(&got, c, a), 800);
800        assert!(sa.sends_to(&c.session));
801        let frame = sa.seal(b"to b and c").unwrap();
802        assert_eq!(opens(&mut sc, a, &frame).unwrap(), b"to b and c");
803        assert_eq!(opens(&mut sb, a, &frame).unwrap(), b"to b and c");
804        assert!(opens(&mut sd, a, &frame).is_none());
805        assert_eq!(sa.next_deadline(), None);
806    }
807
808    #[test]
809    fn a_leave_over_a_pending_epoch_not_all_hearers_have_seals_on_their_word_alone() {
810        let (w, mut sa, mut sb, mut sc, mut sd, next) = three_hear_and_c_joins();
811        let (a, b, c, d) = (&w[0], &w[1], &w[2], &w[3]);
812        // b installs the pending epoch, but d leaves before b's word reaches a.
813        let late_word = sb.on_host(deliver(&next, a, b), 200);
814        let forced = sa.on_host(left(d), 400);
815        let forced = keys_in(&forced).unwrap();
816        sa.on_host(told(&late_word, b, a), 450);
817        let got = sb.on_host(deliver(forced, a, b), 500);
818
819        // b's word on the forced epoch is enough: a does not wait for c, nor for the deadline.
820        sa.on_host(told(&got, b, a), 600);
821        assert!(sa.sends_to(&b.session) && !sa.sends_to(&c.session));
822        let frame = sa.seal(b"after d left").unwrap();
823        assert_eq!(opens(&mut sb, a, &frame).unwrap(), b"after d left");
824        assert!(
825            opens(&mut sd, a, &frame).is_none(),
826            "the leaver opens nothing"
827        );
828
829        // c never says it has the keys (an older client): it hears after the wait.
830        assert_eq!(sa.next_deadline(), Some(400 + ACTIVATE_WITHIN_MS));
831        sc.on_host(deliver(forced, a, c), 700);
832        assert!(sa.on_time(399 + ACTIVATE_WITHIN_MS).is_empty());
833        assert!(!sa.sends_to(&c.session));
834        sa.on_time(400 + ACTIVATE_WITHIN_MS);
835        assert!(sa.sends_to(&c.session));
836        assert_eq!(sa.next_deadline(), None);
837        let frame = sa.seal(b"to c").unwrap();
838        assert_eq!(opens(&mut sc, a, &frame).unwrap(), b"to c");
839    }
840
841    #[test]
842    fn a_joiner_that_leaves_before_its_epoch_seals_opens_nothing_after() {
843        let ((a, ka), (b, kb), (c, kc)) = (who(1), who(2), who(3));
844        let (mut sa, first) = join(&a, ka, &[&b], 0);
845        let (mut sb, _) = join(&b, kb, &[&a], 0);
846        let got = sb.on_host(deliver(keys_in(&first).unwrap(), &a, &b), 10);
847        sa.on_host(told(&got, &b, &a), 20);
848        // c joins, installs a's next epoch, and leaves before it seals; b had it too.
849        let (mut sc, _) = join(&c, kc, &[&a, &b], 100);
850        let joined = sa.on_host(HostInput::Joined(participant(&c)), 100);
851        let next = keys_in(&joined).unwrap();
852        let got = sb.on_host(deliver(next, &a, &b), 200);
853        sa.on_host(told(&got, &b, &a), 300);
854        sc.on_host(deliver(next, &a, &c), 200);
855        let forced = sa.on_host(left(&c), 400);
856        let forced = keys_in(&forced).unwrap();
857        // The epoch c had never seals: what a seals now and later is closed to c.
858        let frame = sa.seal(b"after c left").unwrap();
859        assert!(
860            opens(&mut sc, &a, &frame).is_none(),
861            "the leaver opens nothing"
862        );
863        let got = sb.on_host(deliver(forced, &a, &b), 500);
864        sa.on_host(told(&got, &b, &a), 600);
865        let frame = sa.seal(b"to b").unwrap();
866        assert_eq!(opens(&mut sb, &a, &frame).unwrap(), b"to b");
867        assert!(opens(&mut sc, &a, &frame).is_none());
868    }
869
870    #[test]
871    fn a_changed_key_is_reported_with_its_member_and_nothing_else_names_one() {
872        let member = MemberId::from_bytes([2; 16]);
873        assert!(matches!(
874            refusal(member, AddError::KeyChanged),
875            VoiceEvent::KeyChanged { member: m } if m == member
876        ));
877        for e in [
878            AddError::Missing,
879            AddError::Refused(zaun_community_protocol::crypto::voice::VoiceError::Replay),
880            AddError::Unpinned("disk full".into()),
881        ] {
882            assert!(matches!(refusal(member, e), VoiceEvent::Warning(_)));
883        }
884    }
885}