package hub import ( "context" "encoding/json" "errors" "io" "log/slog" "testing" "time" ) // ringLen reads a participation's ring length under the hub's own lock, // the way every other reader of ring must (hub.go's lock discipline): // never through a pointer a caller holds unsynchronized. func ringLen(h *Hub, sqid, session string, peer PeerID) int { h.mu.Lock() defer h.mu.Unlock() p, ok := h.findLocked(sqid, session, peer) if !ok { return -1 } return len(p.ring) } func TestFanoutReachesEveryOtherAdmittedPeerAndNobodyElse(t *testing.T) { now := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC) h := testHub(&now) ctx := context.Background() a, _ := h.Open("r1", "sa", 1, "Ann", KindMember) h.Join(ctx, "r1", "sa", a.Peer) b, _ := h.Open("r1", "sb", 2, "Bob", KindMember) h.Join(ctx, "r1", "sb", b.Peer) g, _ := h.Open("r1", "sg", 100, "Gus", KindGuest) h.Join(ctx, "r1", "sg", g.Peer) // waiting drain(a.Sub) drain(b.Sub) drain(g.Sub) // Every field a forged or stale client could smuggle in: the // envelope the hub rebuilds must carry none of it through. in := Message{ Type: TypeChat, From: "forged", Name: "Admin", To: b.Peer, Seq: 99, Gen: 42, Payload: json.RawMessage(`{"text":"hi"}`), Reason: ReasonEnded, Roster: &Roster{}, Boot: "x", Peer: "y", Waiting: true, } if err := h.Fanout(ctx, "r1", "sa", a.Peer, in); err != nil { t.Fatal(err) } got := drain(b.Sub) if len(got) != 1 { t.Fatalf("Bob got %d events, want 1: %+v", len(got), got) } gm := got[0] if gm.Type != TypeChat || gm.From != a.Peer || gm.Name != "Ann" || string(gm.Payload) != `{"text":"hi"}` { t.Fatalf("Bob got %+v, want chat from Ann with the same payload", gm) } if gm.To != "" || gm.Seq != 0 || gm.Gen != 0 { t.Fatalf("Bob got %+v, want no To/Seq/Gen", gm) } if gm.Reason != "" || gm.Roster != nil || gm.Boot != "" || gm.Peer != "" || gm.Waiting { t.Fatalf("Bob got %+v, want none of the input's other fields carried through", gm) } if n := len(drain(a.Sub)); n != 0 { t.Fatalf("the sender must not receive its own chat, got %d", n) } if n := len(drain(g.Sub)); n != 0 { t.Fatalf("a waiting guest must receive nothing, got %d", n) } if n := ringLen(h, "r1", "sb", b.Peer); n != 0 { t.Fatalf("chat is never ringed, ring has %d", n) } } // TestFanoutIsNeverReplayedOnResume is §6's "gone with the tab" through // the resume path, not just through a direct ring read: a chat sent // while the recipient is detached must still be neither ringed nor // replayed when that recipient resumes, and must not manufacture a gap // either (a gap means the ring evicted something above the resuming // peer's last-seen, and nothing was ever added to evict). func TestFanoutIsNeverReplayedOnResume(t *testing.T) { now := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC) h := testHub(&now) ctx := context.Background() a, _ := h.Open("r1", "sa", 1, "Ann", KindMember) h.Join(ctx, "r1", "sa", a.Peer) b, _ := h.Open("r1", "sb", 2, "Bob", KindMember) h.Join(ctx, "r1", "sb", b.Peer) drain(a.Sub) drain(b.Sub) h.Detach("r1", b.Peer, b.Sub) msg := Message{Type: TypeChat, Payload: json.RawMessage(`{"text":"hi"}`)} if err := h.Fanout(ctx, "r1", "sa", a.Peer, msg); err != nil { t.Fatal(err) } if n := ringLen(h, "r1", "sb", b.Peer); n != 0 { t.Fatalf("chat sent to a detached peer must still not be ringed, ring has %d", n) } res, err := h.Resume(ctx, "r1", "sb", b.Peer, map[PeerID]uint64{}) if err != nil { t.Fatal(err) } if len(res.Replay) != 0 { t.Fatalf("chat must never be replayed on resume, got %d", len(res.Replay)) } if len(res.Gap) != 0 { t.Fatalf("nothing was ringed, so resume must report no gap either, got %d", len(res.Gap)) } } func TestFanoutNeedsAnAdmittedSenderBoundToThisSession(t *testing.T) { now := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC) h := testHub(&now) ctx := context.Background() a, _ := h.Open("r1", "sa", 1, "Ann", KindMember) msg := Message{Type: TypeChat, Payload: json.RawMessage(`{"text":"hi"}`)} if err := h.Fanout(ctx, "r1", "sa", a.Peer, msg); !errors.Is(err, ErrNotAdmitted) { t.Fatalf("unjoined: %v", err) } h.Join(ctx, "r1", "sa", a.Peer) if err := h.Fanout(ctx, "r1", "sb", a.Peer, msg); !errors.Is(err, ErrUnknownPeer) { t.Fatalf("another session: %v", err) } if err := h.Fanout(ctx, "r2", "sa", a.Peer, msg); !errors.Is(err, ErrUnknownPeer) { t.Fatalf("another room: %v", err) } g, _ := h.Open("r1", "sg", 100, "Gus", KindGuest) h.Join(ctx, "r1", "sg", g.Peer) if err := h.Fanout(ctx, "r1", "sg", g.Peer, msg); !errors.Is(err, ErrNotAdmitted) { t.Fatalf("waiting guest: %v", err) } // The guard is an allowlist of {chat, share}, not a denylist of the // targeted types: a server-raised type and the empty type must be // refused too, or a denylist that merely excludes offer/answer/ // candidate would pass this check by accident. for _, typ := range []string{TypeOffer, TypeRoster, TypeLost, TypeJoin, ""} { if err := h.Fanout(ctx, "r1", "sa", a.Peer, Message{Type: typ}); !errors.Is(err, ErrNotFanout) { t.Fatalf("type %q is not a fan-out: %v", typ, err) } } } // TestFanoutDropsAMemberWhoseStandingIsGoneAndKeepsAnAdmittedGuest mirrors // authorize_test.go's TestAuthorizeDropsAMemberWhoseStandingIsGoneAndKeepsAnAdmittedGuest: // the same mutable-standing fixture, moved without a tick running, so the // only thing that could refuse Ann is Fanout's own re-derivation (§15.12). // Carol, a second admitted member, is the witness that Bob's later chat // actually reaches somebody once Ann is gone; Bob himself, an admitted // guest whose grant has since "expired", never even asks standing // (ruling 14) and fans out anyway. func TestFanoutDropsAMemberWhoseStandingIsGoneAndKeepsAnAdmittedGuest(t *testing.T) { now := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC) standing := map[int64]bool{1: true, 3: true, 100: true} guestStandingCalls := 0 h := New(Config{ Now: func() time.Time { return now }, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), StandingFor: func(ctx context.Context, room string, id int64) (Kind, bool, error) { if id == 100 { guestStandingCalls++ return KindGuest, standing[id], nil } return KindMember, standing[id], nil }, }) ctx := context.Background() a, _ := h.Open("r1", "sa", 1, "Ann", KindMember) if err := h.Join(ctx, "r1", "sa", a.Peer); err != nil { t.Fatal(err) } c, _ := h.Open("r1", "sc", 3, "Carol", KindMember) if err := h.Join(ctx, "r1", "sc", c.Peer); err != nil { t.Fatal(err) } b, _ := h.Open("r1", "sb", 100, "Bob", KindGuest) if err := h.Join(ctx, "r1", "sb", b.Peer); err != nil { t.Fatal(err) } if err := h.Admit(ctx, "r1", "sa", a.Peer, b.Peer); err != nil { t.Fatal(err) } drain(a.Sub) drain(b.Sub) drain(c.Sub) standing[1] = false // Ann taken off the team, no tick has run msg := Message{Type: TypeChat, Payload: json.RawMessage(`{"text":"hi"}`)} if err := h.Fanout(ctx, "r1", "sa", a.Peer, msg); !errors.Is(err, ErrNotYours) { t.Fatalf("member whose standing is gone: want ErrNotYours, got %v", err) } if _, found := h.Find("r1", "sa", a.Peer); found { t.Fatal("Ann's participation should have ended") } bev := drain(b.Sub) if len(bev) != 1 || bev[0].Type != TypeGone || bev[0].From != a.Peer { t.Fatalf("Bob's stream got %v, want gone naming Ann and no chat", types(bev)) } drain(c.Sub) // Carol also saw the departure; not this test's point standing[100] = false // Bob's grant has "expired" before := guestStandingCalls if err := h.Fanout(ctx, "r1", "sb", b.Peer, msg); err != nil { t.Fatalf("admitted guest with a lapsed grant: %v", err) } if guestStandingCalls != before { t.Fatalf("Fanout asked StandingFor for a guest: %d calls during this Fanout, want 0", guestStandingCalls-before) } cev := drain(c.Sub) if len(cev) != 1 || cev[0].Type != TypeChat || cev[0].From != b.Peer { t.Fatalf("Carol should have received Bob's chat, got %v", types(cev)) } if n := len(drain(b.Sub)); n != 0 { t.Fatalf("Bob must not receive his own chat, got %d", n) } }