package main import ( "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "sync" "testing" "time" "github.com/godbus/dbus/v5" ) // The system bus stood in: the rating the test sets, each connection's signals on an unbuffered channel (a send // returns once the watcher's loop took it), and the system bus's socket fired by the test. type fakeSystem struct { mu sync.Mutex now Rating sessions []loginSession // refuse is how many dials, from the next, are refused. refuse int reads int dials int buses []*fakeBus socket chan struct{} } type fakeBus struct { sys *fakeSystem signals chan signal closed bool } func (s *fakeSystem) dial() (systemBus, error) { s.mu.Lock() defer s.mu.Unlock() s.dials++ if s.refuse > 0 { s.refuse-- return nil, errors.New("connection refused") } b := &fakeBus{sys: s, signals: make(chan signal)} s.buses = append(s.buses, b) return b, nil } func (s *fakeSystem) set(r Rating) { s.mu.Lock() s.now = r s.mu.Unlock() } func (s *fakeSystem) last() *fakeBus { s.mu.Lock() defer s.mu.Unlock() return s.buses[len(s.buses)-1] } func (s *fakeSystem) counts() (int, int) { s.mu.Lock() defer s.mu.Unlock() return s.reads, s.dials } func (b *fakeBus) listen() (<-chan signal, error) { return b.signals, nil } func (b *fakeBus) sessions(uid uint32) ([]loginSession, error) { b.sys.mu.Lock() defer b.sys.mu.Unlock() var out []loginSession for _, s := range b.sys.sessions { if s.UID == uid { out = append(out, s) } } return out, nil } func (b *fakeBus) session(path string) (loginSession, error) { b.sys.mu.Lock() defer b.sys.mu.Unlock() for _, s := range b.sys.sessions { if s.Path == path { return s, nil } } return loginSession{}, fmt.Errorf("no session %s", path) } func (b *fakeBus) close() { b.closed = true } func (b *fakeBus) rating() (Rating, error) { b.sys.mu.Lock() defer b.sys.mu.Unlock() b.sys.reads++ return b.sys.now, nil } // journalLines collects the journal for one test. func journalLines(t *testing.T) func() []string { t.Helper() var mu sync.Mutex var lines []string was := journal journal = func(format string, args ...any) { mu.Lock() lines = append(lines, fmt.Sprintf(format, args...)) mu.Unlock() } t.Cleanup(func() { journal = was }) return func() []string { mu.Lock() defer mu.Unlock() return append([]string(nil), lines...) } } var clockStart = time.Date(2026, 11, 24, 19, 0, 0, 0, time.UTC) // aWatcher is a watcher over the stood-in system bus, its clock one second on at each reading. func aWatcher(t *testing.T, sys *fakeSystem) *Watcher { t.Helper() tick := clockStart var mu sync.Mutex return &Watcher{Folder: aFolder(t), Dial: sys.dial, Now: func() time.Time { mu.Lock() defer mu.Unlock() tick = tick.Add(time.Second) return tick }, SocketThere: func(stop <-chan struct{}) <-chan struct{} { return sys.socket }, asks: make(chan asked), UID: 1000, Desk: &fakeDesk{}, Environment: func(string) ([]string, error) { return nil, nil }, FileEvents: func([]string, <-chan struct{}) <-chan struct{} { return nil }, After: func(time.Duration) <-chan time.Time { return nil }, Beside: func(work func() func()) { work()() }} } // The desktop stood in: each open it was asked, answered with outcome. type fakeDesk struct { mu sync.Mutex opens []string notes []note outcome openOutcome } func (d *fakeDesk) notify(s Session, n note) error { d.mu.Lock() defer d.mu.Unlock() d.notes = append(d.notes, n) return nil } // shown is every notification shown, as `[critical] summary: body`. func (d *fakeDesk) shown() []string { d.mu.Lock() defer d.mu.Unlock() var out []string for _, n := range d.notes { critical := "" if n.Critical { critical = "critical " } out = append(out, critical+n.Summary+": "+n.Body) } return out } func (d *fakeDesk) open(s Session, address string) openOutcome { d.mu.Lock() defer d.mu.Unlock() d.opens = append(d.opens, s.ID+" "+address) o := d.outcome if o.Outcome == "" { o = openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpened} } return o } func (d *fakeDesk) opened() []string { d.mu.Lock() defer d.mu.Unlock() return append([]string(nil), d.opens...) } // keptSaid is every kept event as ` `, in order. func keptSaid(t *testing.T, f Folder) []string { t.Helper() kept, err := f.pending() if err != nil { t.Fatal(err) } var out []string for _, k := range kept { var b struct{ Node, Link, Network, Address, At, Why string } if err := json.Unmarshal(k.Body, &b); err != nil { t.Fatal(err) } event := strings.Split(k.MessageID, ".")[1] if k.Subject != "mesh.seat.node-uplink.event."+event+".laptop" || b.Node != "laptop" || b.At == "" { t.Errorf("kept %+v %+v", k, b) } if event == eventAsked && b.Address != "http://check.example.net/" { t.Errorf("asked with the address %q", b.Address) } out = append(out, strings.Join(strings.Fields(fmt.Sprintf("%s %s %s %s", event, b.Why, b.Network, b.Link)), " ")) } return out } func guest(connectivity uint32) Rating { return Rating{Connectivity: connectivity, CheckEnabled: true, CheckAvailable: true, CheckURI: "http://check.example.net/", Connection: "/org/freedesktop/NetworkManager/ActiveConnection/1", Network: "guest-example", Link: "wlan0"} } func other(connectivity uint32) Rating { r := guest(connectivity) r.Connection, r.Network, r.Link = "/org/freedesktop/NetworkManager/ActiveConnection/2", "home-example", "eth0" return r } func with(r Rating, change func(*Rating)) Rating { change(&r) return r } // Each line of §21 keeps its event, and with the check off, or a check address that is not http or https, nothing is // kept (design 08 sign-in-page §21, §25). func TestEachLineOfTheRulesKeepsItsEvent(t *testing.T) { off := func(r *Rating) { r.CheckEnabled = false } unavailable := func(r *Rating) { r.CheckAvailable = false } none := func(r *Rating) { r.Connection, r.Network, r.Link = "/", "", "" } for _, c := range []struct { name string ratings []Rating kept []string }{ {"PORTAL at the start", []Rating{guest(ratingPortal)}, []string{"sign-in-asked guest-example wlan0"}}, {"FULL at the start", []Rating{guest(ratingFull)}, []string{"sign-in-ended no-longer-asked guest-example wlan0"}}, {"no connection at the start", []Rating{with(guest(ratingNone), none)}, []string{"sign-in-ended no-longer-asked"}}, {"PORTAL at a join", []Rating{guest(ratingFull), guest(ratingPortal)}, []string{"sign-in-ended no-longer-asked guest-example wlan0", "sign-in-asked guest-example wlan0"}}, {"staying PORTAL says it once", []Rating{guest(ratingPortal), guest(ratingPortal), guest(ratingPortal)}, []string{"sign-in-asked guest-example wlan0"}}, {"signed in", []Rating{guest(ratingPortal), guest(ratingFull), guest(ratingFull)}, []string{"sign-in-asked guest-example wlan0", "sign-in-ended signed-in guest-example wlan0"}}, {"the connection replaced, PORTAL again", []Rating{guest(ratingPortal), other(ratingPortal)}, []string{"sign-in-asked guest-example wlan0", "sign-in-ended left guest-example wlan0", "sign-in-asked home-example eth0"}}, {"the connection gone", []Rating{guest(ratingPortal), with(guest(ratingNone), none)}, []string{"sign-in-asked guest-example wlan0", "sign-in-ended left guest-example wlan0"}}, {"LIMITED", []Rating{guest(ratingPortal), guest(ratingLimited)}, []string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}}, {"UNKNOWN", []Rating{guest(ratingPortal), guest(ratingUnknown)}, []string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}}, {"the check switched off while asked", []Rating{guest(ratingPortal), with(guest(ratingPortal), off)}, []string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}}, {"the check off", []Rating{with(guest(ratingPortal), off), with(guest(ratingFull), off), with(guest(ratingPortal), off)}, nil}, {"the check not available", []Rating{with(guest(ratingPortal), unavailable), with(guest(ratingPortal), unavailable)}, nil}, {"a check address not http", []Rating{with(guest(ratingPortal), func(r *Rating) { r.CheckURI = "ftp://check.example.net/" })}, nil}, } { t.Run(c.name, func(t *testing.T) { journalLines(t) w := aWatcher(t, &fakeSystem{}) for i, r := range c.ratings { w.heard(r, i == 0) } if got := keptSaid(t, w.Folder); strings.Join(got, "|") != strings.Join(c.kept, "|") { t.Fatalf("kept %q, want %q", got, c.kept) } }) } } // Past 256 kept events the oldest goes, with a journal line naming it, and the state counts it (§20, §25). func TestPastTheBoundTheOldestKeptEventGoes(t *testing.T) { lines := journalLines(t) w := aWatcher(t, &fakeSystem{}) for range keptBound { if _, err := w.Folder.keep(eventEnded, eventSubject(eventEnded, "laptop"), map[string]string{}); err != nil { t.Fatal(err) } } w.heard(guest(ratingPortal), true) kept, _ := w.Folder.pending() if len(kept) != keptBound || kept[0].Sequence != 2 || kept[len(kept)-1].MessageID != "laptop.sign-in-asked.257" { t.Fatalf("kept %d, from %d", len(kept), kept[0].Sequence) } said := strings.Join(lines(), "\n") if !strings.Contains(said, "dropped the kept event laptop.sign-in-ended.1 past the bound of 256") || w.state.DroppedPastBound != 1 { t.Fatalf("the drop was not said: %s", said) } } // The system bus dropping and its socket coming back make the watcher subscribe again and act on the rating read then // as on a change; rating-again does the same at once; between them, nothing reads the rating but a signal (§14, §25). func TestTheWatcherSubscribesAgainAndRunsOnNoTimer(t *testing.T) { lines := journalLines(t) sys := &fakeSystem{socket: make(chan struct{})} sys.set(guest(ratingFull)) w := aWatcher(t, sys) stop := make(chan struct{}) done := make(chan struct{}) go func() { _ = w.run(stop); close(done) }() defer func() { close(stop); <-done }() state := func() watcherState { s, err := w.askLoop(askState) if err != nil { t.Fatal(err) } return s.(watcherState) } if s := state(); !s.Subscribed || s.Rating != "FULL" { t.Fatalf("at its start %+v", s) } for range 3 { state() } if reads, _ := sys.counts(); reads != 1 { t.Fatalf("the rating was read %d times with no signal: something reads it on a timer", reads) } sys.set(guest(ratingPortal)) sys.last().signals <- signal{Rating: true} if s := state(); s.Ask == nil || s.Ask.Network != "guest-example" { t.Fatalf("PORTAL heard as %+v", s) } close(sys.last().signals) if s := state(); s.Subscribed { t.Fatal("subscribed after the system bus dropped") } if !strings.Contains(strings.Join(lines(), "\n"), "the system bus connection dropped") { t.Fatal("the drop was not written to the journal") } sys.set(guest(ratingFull)) sys.socket <- struct{}{} if s := state(); !s.Subscribed || s.Ask != nil || s.Rating != "FULL" { t.Fatalf("after the socket came back %+v", s) } if got := keptSaid(t, w.Folder); got[len(got)-1] != "sign-in-ended signed-in guest-example wlan0" { t.Fatalf("the rating read on subscribing again was not acted on as a change: %q", got) } sys.set(guest(ratingPortal)) if _, err := w.askLoop(askRatingAgain); err != nil { t.Fatal(err) } if reads, dials := sys.counts(); dials != 3 || reads != 4 || !sys.buses[1].closed { t.Fatalf("rating-again: %d dials, %d reads", dials, reads) } if s := state(); !s.Subscribed || s.Ask == nil || s.AsksOpened != 2 || s.AsksEnded != 1 { t.Fatalf("after rating-again %+v", s) } } // The signals the watcher hears, as the system bus sends them (recorded with dbus-monitor): the network manager's // PropertiesChanged for a property of the rating, not for another, and logind's SessionNew (§14, §17). func TestTheWatcherHearsTheSystemBusSignals(t *testing.T) { changed := func(props map[string]dbus.Variant, invalidated []string) *dbus.Signal { return &dbus.Signal{Sender: ":1.5", Path: nmPath, Name: "org.freedesktop.DBus.Properties.PropertiesChanged", Body: []any{"org.freedesktop.NetworkManager", props, invalidated}} } for _, c := range []struct { name string s *dbus.Signal want signal ok bool }{ {"Connectivity", changed(map[string]dbus.Variant{"Connectivity": dbus.MakeVariant(uint32(2))}, []string{}), signal{Rating: true}, true}, {"PrimaryConnection", changed(map[string]dbus.Variant{"PrimaryConnection": dbus.MakeVariant(dbus.ObjectPath("/"))}, []string{}), signal{Rating: true}, true}, {"ConnectivityCheckUri invalidated", changed(map[string]dbus.Variant{}, []string{"ConnectivityCheckUri"}), signal{Rating: true}, true}, {"another property", changed(map[string]dbus.Variant{"Metered": dbus.MakeVariant(uint32(4))}, []string{}), signal{}, false}, {"another interface", &dbus.Signal{Path: nmPath, Name: "org.freedesktop.DBus.Properties.PropertiesChanged", Body: []any{"org.freedesktop.NetworkManager.Device", map[string]dbus.Variant{"Connectivity": dbus.MakeVariant(uint32(2))}, []string{}}}, signal{}, false}, {"SessionNew", &dbus.Signal{Sender: ":1.3", Path: login1Path, Name: "org.freedesktop.login1.Manager.SessionNew", Body: []any{"4", dbus.ObjectPath("/org/freedesktop/login1/session/_34")}}, signal{Session: "/org/freedesktop/login1/session/_34"}, true}, } { got, ok := readSignal(c.s) if ok != c.ok || got != c.want { t.Errorf("%s: heard %+v %v", c.name, got, ok) } } } // The watcher dials the system bus again only at the file event that makes its socket and at rating-again, never in a // loop (§14; note d); and when the bus came back and it cannot subscribe on it, it ends with an error, so its process // exits non-zero and its unit shows failing (§11; lead answer C-2c). func TestTheWatcherRedialsOnlyAtTheSocketsEventAndRatingAgain(t *testing.T) { journalLines(t) sys := &fakeSystem{socket: make(chan struct{}), refuse: 1} sys.set(guest(ratingFull)) w := aWatcher(t, sys) stop, done := make(chan struct{}), make(chan error, 1) go func() { done <- w.run(stop) }() state := func() watcherState { s, _ := w.askLoop(askState) return s.(watcherState) } dials := func() int { _, d := sys.counts(); return d } for range 3 { if s := state(); s.Subscribed { t.Fatal("subscribed through a refused dial") } } if d := dials(); d != 1 { t.Fatalf("a bus that refused the watcher at its start was dialled %d times with no event", d) } sys.socket <- struct{}{} if s := state(); !s.Subscribed || dials() != 2 { t.Fatalf("at the socket's event: %+v, %d dials", s, dials()) } close(sys.last().signals) state() state() if d := dials(); d != 2 { t.Fatalf("a dropped connection was dialled again before the socket's event: %d dials", d) } if _, err := w.askLoop(askRatingAgain); err != nil || dials() != 3 || !state().Subscribed { t.Fatalf("rating-again: %v, %d dials", err, dials()) } close(sys.last().signals) sys.mu.Lock() sys.refuse = 1 sys.mu.Unlock() sys.socket <- struct{}{} if err := <-done; err == nil || !strings.Contains(err.Error(), "could not subscribe") || dials() != 4 { t.Fatalf("the bus came back refusing: the watcher ended with %v after %d dials", err, dials()) } close(stop) } // When its first subscribe at its start fails while the system bus's socket is there, no file event will come: the // watcher writes the reason to its journal and ends with an error, so its process exits non-zero (§14; lead answer // C2-1). With no socket there it waits for the one that makes it, as above. func TestARefusedStartWithTheSocketThereEndsTheWatcher(t *testing.T) { lines := journalLines(t) sys := &fakeSystem{socket: make(chan struct{}), refuse: 1} w := aWatcher(t, sys) w.SocketExists = func() bool { return true } ended := make(chan error, 1) go func() { ended <- w.run(make(chan struct{})) }() answered := make(chan struct{}) go func() { w.askLoop(askState); close(answered) }() var err error select { case err = <-ended: case <-answered: t.Fatal("the watcher waits for a file event that will not come, its unit left active") } if _, dials := sys.counts(); err == nil || !strings.Contains(err.Error(), "at its start") || dials != 1 { t.Fatalf("the watcher ended with %v after %d dials", err, dials) } if !strings.Contains(strings.Join(lines(), "\n"), "could not subscribe on it at its start") { t.Fatalf("the reason is not in the journal: %q", lines()) } } // The real wait fires at the file event that makes the system bus's socket, not for one that is merely there (note d). func TestTheSocketsWaitFiresWhenTheSocketIsMade(t *testing.T) { journalLines(t) dir := t.TempDir() was := systemSocket systemSocket = filepath.Join(dir, "system_bus_socket") t.Cleanup(func() { systemSocket = was }) if err := os.WriteFile(systemSocket, nil, 0o600); err != nil { t.Fatal(err) } stop := make(chan struct{}) defer close(stop) there := systemSocketThere(stop) select { case <-there: t.Fatal("fired for a socket that was already there") default: } os.WriteFile(filepath.Join(dir, "other"), nil, 0o600) os.Remove(systemSocket) if err := os.WriteFile(systemSocket+".made", nil, 0o600); err != nil { t.Fatal(err) } if err := os.Rename(systemSocket+".made", systemSocket); err != nil { t.Fatal(err) } <-there }