diff --git a/modules/networkmanager/cmd/uplink-tools/whole_integration_test.go b/modules/networkmanager/cmd/uplink-tools/whole_integration_test.go new file mode 100644 index 000000000..fa0ecbeba --- /dev/null +++ b/modules/networkmanager/cmd/uplink-tools/whole_integration_test.go @@ -0,0 +1,347 @@ +//go:build integration + +package main + +// networkmanager whole (design 08 sign-in-page ยง25, R-M4, R2-1): its watcher, with the system bus, logind, the user +// manager and the desktop stood in, runs with no bus and opens the page; then the bundle, the built binary played over +// its real stdin and stdout as the node's tool runner plays it, meets a real bus holding node-uplink's events family and +// a stand-in holder of node-resolver: the kept events are published in order with the times of their changes, each +// matching the seat's definition, and uplink-names is called. + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/nats-io/nats.go" + "github.com/nats-io/nats.go/jetstream" + + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink" + "git.novox.be/novox/mesh-sdk/go/testbus" +) + +// clock is the watcher's clock, set by the test before each change. +type clock struct { + mu sync.Mutex + now time.Time +} + +func (c *clock) set(t time.Time) { c.mu.Lock(); c.now = t; c.mu.Unlock() } +func (c *clock) read() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now } + +// tellingDesk is the stood-in desktop, saying each notification on a channel. +type tellingDesk struct { + fakeDesk + told chan note +} + +func (d *tellingDesk) notify(s Session, n note) error { + d.fakeDesk.notify(s, n) + d.told <- n + return nil +} + +// runtime plays the node's tool runner for the bundle over a real bus: a kept event said on the seat is published on +// the stream with the module's prefix on its id, awaiting the acknowledgement; a seat verb is asked of its holder. +type runtime struct { + t *testing.T + ctx context.Context + nc *nats.Conn + js jetstream.JetStream + mu sync.Mutex + in io.Writer + next int + pending map[string]chan json.RawMessage +} + +func (r *runtime) send(m map[string]any) { + m["jsonrpc"] = "2.0" + raw, _ := json.Marshal(m) + r.mu.Lock() + defer r.mu.Unlock() + r.in.Write(append(raw, '\n')) +} + +func (r *runtime) answer(id json.RawMessage, result any, err error) { + if err != nil { + r.send(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": err.Error()}}) + return + } + r.send(map[string]any{"id": id, "result": result}) +} + +func (r *runtime) serve(out io.Reader) { + scanner := bufio.NewScanner(out) + scanner.Buffer(make([]byte, 1<<20), 1<<24) + for scanner.Scan() { + var m struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` + Result json.RawMessage `json:"result"` + } + if json.Unmarshal(scanner.Bytes(), &m) != nil { + continue + } + if m.Method == "" { + var id string + json.Unmarshal(m.ID, &id) + r.mu.Lock() + ch := r.pending[id] + r.mu.Unlock() + if ch != nil { + ch <- m.Result + } + continue + } + go r.handle(m.ID, m.Method, m.Params) + } +} + +func (r *runtime) handle(id json.RawMessage, method string, params json.RawMessage) { + switch method { + case "mesh/seat.publish": + var p struct { + Subject string `json:"subject"` + Body json.RawMessage `json:"body"` + ID string `json:"id"` + } + json.Unmarshal(params, &p) + _, err := r.js.Publish(r.ctx, p.Subject, p.Body, jetstream.WithMsgID(Module+"."+p.ID)) + r.answer(id, map[string]any{}, err) + case "mesh/ask": + var p struct { + Key string `json:"key"` + Body json.RawMessage `json:"body"` + } + json.Unmarshal(params, &p) + switch p.Key { + case "seat:mesh-module-assigner.assignments": + r.answer(id, json.RawMessage(`{"seats":[{"seat":"node-resolver","node":"home-server",`+ + `"holders":[{"module":"systemd-resolved","node":"home-server"}]}]}`), nil) + case "seat:node-resolver.uplink-names@home-server": + msg, err := r.nc.Request("stand-in.node-resolver.uplink-names", p.Body, testbus.SetupBound(r.t)) + if err != nil { + r.answer(id, nil, err) + return + } + r.answer(id, json.RawMessage(msg.Data), nil) + default: + r.answer(id, nil, errors.New("nats: no responders available for request")) + } + case "mesh/subscribe": + r.answer(id, map[string]any{}, nil) + default: + r.answer(id, nil, fmt.Errorf("%s is not played here", method)) + } +} + +// call calls one of the bundle's tools and answers its result's text. +func (r *runtime) call(name string) string { + r.t.Helper() + r.mu.Lock() + r.next++ + id := fmt.Sprintf("c-%d", r.next) + ch := make(chan json.RawMessage, 1) + r.pending[id] = ch + r.mu.Unlock() + r.send(map[string]any{"id": id, "method": "tools/call", "params": map[string]any{"name": name, "arguments": map[string]any{}}}) + select { + case raw := <-ch: + var res struct { + Content []struct { + Text string `json:"text"` + } `json:"content"` + IsError bool `json:"isError"` + } + json.Unmarshal(raw, &res) + if res.IsError || len(res.Content) == 0 { + r.t.Fatalf("%s answered %s", name, raw) + } + return res.Content[0].Text + case <-time.After(testbus.SetupBound(r.t)): + testbus.Starved(r.t, name+" was not answered") + } + return "" +} + +// Module is the module the runtime serves the bundle as. +const Module = "networkmanager" + +func TestNetworkManagerWhole(t *testing.T) { + home, err := os.MkdirTemp("", "nm") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(home) }) + f := Folder{Dir: filepath.Join(home, stateHome), Node: "home-server"} + if err := os.MkdirAll(f.Dir, 0o700); err != nil { + t.Fatal(err) + } + + // The watcher, with no bus: the rating FULL at its start, then PORTAL at 10:00, FULL at 10:05. + portal := Rating{Connectivity: ratingFull, CheckEnabled: true, CheckAvailable: true, + CheckURI: "http://example.net/portal", Connection: "/org/freedesktop/NetworkManager/ActiveConnection/1", + Network: "guest-example", Link: "wlan0"} + sys := &fakeSystem{socket: make(chan struct{}), sessions: []loginSession{personsSession()}} + sys.set(portal) + at := &clock{} + desk := &tellingDesk{told: make(chan note, 4)} + w := &Watcher{Folder: f, Dial: sys.dial, SocketThere: func(<-chan struct{}) <-chan struct{} { return sys.socket }, + Now: at.read, asks: make(chan asked), UID: 1000, Desk: desk, ends: make(chan func()), + Environment: func(string) ([]string, error) { return []string{"DISPLAY=:1", "XAUTHORITY=/x"}, nil }, + FileEvents: func([]string, <-chan struct{}) <-chan struct{} { return nil }, + After: func(time.Duration) <-chan time.Time { return nil }} + w.Beside = w.besideLoop + l, err := f.listen() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { l.Close() }) + go serveSocket(l, w.askLoop) + stop, stopped := make(chan struct{}), make(chan struct{}) + at.set(time.Date(2026, 11, 24, 9, 59, 0, 0, time.UTC)) + go func() { w.run(stop); close(stopped) }() + t.Cleanup(func() { close(stop); <-stopped }) + told := func(summary string) { + t.Helper() + select { + case n := <-desk.told: + if n.Summary != summary { + t.Fatalf("told %q, want %q", n.Summary, summary) + } + case <-time.After(testbus.SetupBound(t)): + testbus.Starved(t, "no notification "+summary) + } + } + w.askLoop(askState) + at.set(time.Date(2026, 11, 24, 10, 0, 0, 0, time.UTC)) + portal.Connectivity = ratingPortal + sys.set(portal) + sys.last().signals <- signal{Rating: true} + told("This network asks you to sign in") + if got := desk.opened(); len(got) != 1 || got[0] != "2 http://example.net/portal" { + t.Fatalf("with no bus the watcher opened %q", got) + } + at.set(time.Date(2026, 11, 24, 10, 5, 0, 0, time.UTC)) + portal.Connectivity = ratingFull + sys.set(portal) + sys.last().signals <- signal{Rating: true} + told("The network is open") + w.askLoop(askState) + kept, err := f.pending() + if err != nil || len(kept) != 3 { + t.Fatalf("kept %+v %v", kept, err) + } + + // The bus comes: node-uplink's family on the events stream, and a stand-in holder of node-resolver. + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + nc, err := nats.Connect(testbus.URL(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(nc.Close) + js, err := jetstream.New(nc) + if err != nil { + t.Fatal(err) + } + stream, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "EVENTS", + Subjects: []string{nodeuplink.SubjectSignInAskedAll, nodeuplink.SubjectSignInEndedAll}, + MaxAge: nodeuplink.FamilyMaxAgeDays * 24 * time.Hour, Duplicates: time.Hour}) + if err != nil { + t.Fatal(err) + } + given := make(chan string, 8) + if _, err := nc.Subscribe("stand-in.node-resolver.uplink-names", func(m *nats.Msg) { + given <- string(m.Data) + m.Respond([]byte(`{"names":["example.net"],"link":"wlan0","set_at":"2026-11-24T10:06:00Z"}`)) + }); err != nil { + t.Fatal(err) + } + + bin := filepath.Join(home, "uplink-tools") + if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil { + t.Fatalf("building uplink-tools: %v\n%s", err, out) + } + cmd := exec.CommandContext(ctx, bin) + cmd.Env = append(os.Environ(), "HOME="+home, "MESH_NODE=home-server", "MESH_MODULE="+Module, "MESH_SERVED_MODULE="+Module) + in, _ := cmd.StdinPipe() + out, _ := cmd.StdoutPipe() + cmd.Stderr = os.Stderr + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { in.Close(); cmd.Wait() }) + r := &runtime{t: t, ctx: ctx, nc: nc, js: js, in: in, pending: map[string]chan json.RawMessage{}} + go r.serve(out) + + select { + case body := <-given: + if body != `{"names":["example.net"]}` { + t.Fatalf("uplink-names was given %s", body) + } + case <-time.After(testbus.SetupBound(t)): + testbus.Starved(t, "uplink-names was not called") + } + consumer, err := stream.OrderedConsumer(ctx, jetstream.OrderedConsumerConfig{}) + if err != nil { + t.Fatal(err) + } + type published struct { + subject, id string + body []byte + } + var got []published + for len(got) < 3 { + msg, err := consumer.Next(jetstream.FetchMaxWait(testbus.SetupBound(t))) + if err != nil { + testbus.Starved(t, fmt.Sprintf("%d of the 3 kept events were published: %v", len(got), err)) + } + got = append(got, published{msg.Subject(), msg.Headers().Get(jetstream.MsgIDHeader), msg.Data()}) + } + for i, k := range kept { + if got[i].id != Module+"."+k.MessageID || string(got[i].body) != string(k.Body) || got[i].subject != k.Subject { + t.Errorf("published %d: %s %s %s, kept %s %s %s", i, got[i].subject, got[i].id, got[i].body, k.Subject, + k.MessageID, k.Body) + } + } + strict := func(raw []byte, into any) { + t.Helper() + dec := json.NewDecoder(strings.NewReader(string(raw))) + dec.DisallowUnknownFields() + if err := dec.Decode(into); err != nil { + t.Fatalf("%s does not match the seat's definition: %v", raw, err) + } + } + var asked nodeuplink.SignInAsked + strict(got[1].body, &asked) + if got[1].subject != nodeuplink.SubjectSignInAsked("home-server") || asked != (nodeuplink.SignInAsked{ + Node: "home-server", Link: "wlan0", Network: "guest-example", Address: "http://example.net/portal", + At: "2026-11-24T10:00:00Z"}) { + t.Errorf("sign-in-asked is %s on %s", got[1].body, got[1].subject) + } + var ended nodeuplink.SignInEnded + strict(got[2].body, &ended) + if got[2].subject != nodeuplink.SubjectSignInEnded("home-server") || ended != (nodeuplink.SignInEnded{ + Node: "home-server", Link: "wlan0", Network: "guest-example", At: "2026-11-24T10:05:00Z", + Why: nodeuplink.SignInEndedWhySignedIn}) { + t.Errorf("sign-in-ended is %s on %s", got[2].body, got[2].subject) + } + if text := r.call("uplink_publish_again"); text != `{"published":0,"waiting":0}` { + t.Fatalf("after the publishes uplink_publish_again answered %s", text) + } + if left, _ := f.pending(); len(left) != 0 { + t.Fatalf("left in pending/: %+v", left) + } +} diff --git a/modules/networkmanager/go.mod b/modules/networkmanager/go.mod index bdcbd251e..f0cccd811 100644 --- a/modules/networkmanager/go.mod +++ b/modules/networkmanager/go.mod @@ -7,13 +7,19 @@ require ( git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 github.com/godbus/dbus/v5 v5.1.0 + github.com/nats-io/nats.go v1.54.0 golang.org/x/sys v0.48.0 ) require ( + github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect + github.com/google/go-tpm v0.9.8 // indirect github.com/klauspost/compress v1.20.1 // indirect - github.com/nats-io/nats.go v1.54.0 // indirect + github.com/minio/highwayhash v1.0.4 // indirect + github.com/nats-io/jwt/v2 v2.8.1 // indirect + github.com/nats-io/nats-server/v2 v2.11.17 // indirect github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect golang.org/x/crypto v0.57.0 // indirect + golang.org/x/time v0.15.0 // indirect ) diff --git a/modules/networkmanager/go.sum b/modules/networkmanager/go.sum index c822b945f..fc2e54bf6 100644 --- a/modules/networkmanager/go.sum +++ b/modules/networkmanager/go.sum @@ -1,9 +1,19 @@ +github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI= +github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= +github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= +github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4= +github.com/nats-io/jwt/v2 v2.8.1/go.mod h1:nWnOEEiVMiKHQpnAy4eXlizVEtSfzacZ1Q43LIRavZg= +github.com/nats-io/jwt/v2 v2.8.1 h1:V0xpGuD/N8Mi+fQNDynXohVvp7ZztevW5io8CUWlPmU= github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k= github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA= +github.com/nats-io/nats-server/v2 v2.11.17/go.mod h1:B1sFVz4StNosQ903ak4N1G01Fl/9f8e06mXpFIE2K24= +github.com/nats-io/nats-server/v2 v2.11.17 h1:GKEghcFK6A+aFx11Yf1LjgLC3txAwvyhnYzhBIQZA8I= github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= @@ -12,3 +22,5 @@ golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZ golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=