From 2a29c458ce31ef539bfa7dbcf0f643bd8a1fd695 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 20:49:28 +0100 Subject: [PATCH 1/7] Render the packet filter's allowances beside the derived ports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The operator, 2026-11-21: a firewall module has tools to open a port by hand beside the ports derived from the modules' listens, and the node-engine stays the one renderer of the filter file. AsNftablesAllowing renders each allowance the holder answered as one accept rule in the input chain after the derived ones: its interface by name or a negated match on the private network's interface, its source by its family, an until as the one element of a timeout set so the kernel closes the port, and the comment allowance . With no allowance the file is today's, byte for byte. Builds: design 08 control-verbs §2, §8; ADR 0683; H-A-305, H-A-308 (1), H-A-315 (4), (5) --- cmd/mesh-compose/main_test.go | 4 +- go.mod | 1 + internal/compose/resolution/filtering.go | 81 ++++++++++++++++++- internal/compose/resolution/filtering_test.go | 66 +++++++++++++++ 4 files changed, 147 insertions(+), 5 deletions(-) diff --git a/cmd/mesh-compose/main_test.go b/cmd/mesh-compose/main_test.go index 12e43dbe..e425a9e4 100644 --- a/cmd/mesh-compose/main_test.go +++ b/cmd/mesh-compose/main_test.go @@ -441,7 +441,7 @@ func ownPackages(t *testing.T) map[string][]string { } // 1621/AC2 and AC4: the command imports, through every package of this repository it reaches, only the standard -// library, mesh-sdk, the contracts modules' pure packages (seats' types, clients' codecs), the delivery SDK's composer (the command's own request and verdict types) and catalog key codec (a catalog entry's key, design 47 G A-144), the builder's builds package (a build's value and its keys), the private network's overlay package (mesh-wireguard's own pure package: names, graph and +// library, mesh-sdk, the contracts modules' pure packages (seats' types, clients' codecs; the Connectivity domain's seats' types, the packet filter's allowances among them), the delivery SDK's composer (the command's own request and verdict types) and catalog key codec (a catalog entry's key, design 47 G A-144), the builder's builds package (a build's value and its keys), the private network's overlay package (mesh-wireguard's own pure package: names, graph and // generator, no bus) and this repository's own packages, and none that reaches a bus, a store, a network service or // another process. func TestTheCommandImportsNoBusStoreNetworkOrProcess(t *testing.T) { @@ -453,7 +453,7 @@ func TestTheCommandImportsNoBusStoreNetworkOrProcess(t *testing.T) { for path, imports := range own { for _, imp := range imports { std := !strings.Contains(strings.SplitN(imp, "/", 2)[0], ".") - if !std && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-sdk/go") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-contracts/") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer") && imp != "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey" && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds") && !strings.HasPrefix(imp, "github.com/novox/mesh-host/") { + if !std && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-sdk/go") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-contracts/") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/") && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer") && imp != "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey" && !strings.HasPrefix(imp, "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds") && !strings.HasPrefix(imp, "github.com/novox/mesh-host/") { t.Errorf("%s imports %s, which is neither the standard library, mesh-sdk nor this repository", path, imp) } for _, f := range forbidden { diff --git a/go.mod b/go.mod index 79b949ab..2fb3aa01 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-grants/grantsstate v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 github.com/nats-io/nats-server/v2 v2.11.17 diff --git a/internal/compose/resolution/filtering.go b/internal/compose/resolution/filtering.go index 4d99f256..fb9639e2 100644 --- a/internal/compose/resolution/filtering.go +++ b/internal/compose/resolution/filtering.go @@ -2,20 +2,25 @@ package resolution import ( "fmt" + "math" "slices" "sort" "strconv" "strings" + "time" + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter" mcat "git.novox.be/novox/mesh-sdk/go/catalogue" ) // Filtering is the whole rule set for the node this resolved for. // // **Derived from what is assigned here, and from the overlay's shape** — a node's open ports are -// a consequence of what runs on it, not a second list kept in step by hand. Nothing else opens a -// port: **what is not declared is closed**, which is the property that makes the derivation worth -// having rather than merely tidy. +// a consequence of what runs on it, not a second list kept in step by hand. Beside them only the +// allowances are rendered, the ports opened by hand through the seat node-packet-filter: nothing else +// writes the chain; the allowances come from the holder (Allowing; design 08 control-verbs §1, §2). +// **What is neither declared nor allowed is closed**, which is the property that makes the derivation +// worth having rather than merely tidy. func Filtering(r mcat.Resolution, computed map[string]mcat.Generator, ports map[string]map[int]int, exposure map[string]map[int]string) ([]mcat.Rule, error) { // Keyed by what actually distinguishes an opening. Two modules wanting :443 from the mesh is // one rule with two sources; one wanting it from the mesh and another from anywhere is two, @@ -183,6 +188,28 @@ func widest(rules []mcat.Rule) []mcat.Rule { // anywhere and not dropped silently: the rule set says the port wanted the local network and found none. func AsNftablesWithLocal(rules []mcat.Rule, mesh []string, outward bool, foundation []int, outwardLinks []string, tunnel string, local []string) string { + return AsNftablesAllowing(rules, mesh, outward, foundation, outwardLinks, tunnel, local, Allowing{}) +} + +// Allowing is what the holder of the seat node-packet-filter answered its verb allowed at a compose of the filter, and the +// time of that compose (design 08 control-verbs §1, §2): the allowances rendered beside the derived ports. +type Allowing struct { + Allowances []nodepacketfilter.Allowance + At time.Time +} + +// AsNftablesAllowing is AsNftablesWithLocal with the allowances the holder answered (design 08 control-verbs §2): one accept +// rule per allowance in the input chain, after the derived ports' rules and before the chain's drop policy, each with the +// comment `allowance `. Its interface by name, or for the default set a negated match on the private network's +// interface (tunnel), so an interface that comes up later is covered and the tunnel never is; its source when it has one, +// for the family of its CIDR. An allowance with an until matches its port as the one element of a set of the table with +// the timeout flag, the element's timeout the time left to its until at allowing.At, at least 1 s, so the kernel closes the +// port at its until even while the holder is away (H-A-315 (4)). The forward chain takes none: an allowance opens the input +// path only. With no allowance the file is AsNftablesWithLocal's, byte for byte. +func AsNftablesAllowing(rules []mcat.Rule, mesh []string, outward bool, foundation []int, + outwardLinks []string, tunnel string, local []string, allowing Allowing) string { + allowances := slices.Clone(allowing.Allowances) + sort.Slice(allowances, func(a, b int) bool { return allowances[a].Key < allowances[b].Key }) // The links that are not this machine's own: the ones facing outside, and the mesh's tunnel. // Traffic arriving on any of them is admitted only by a rule below; traffic arriving anywhere // else is this machine's own guest and is not something the mesh has a position on. @@ -207,6 +234,14 @@ func AsNftablesWithLocal(rules []mcat.Rule, mesh []string, outward bool, foundat // runtime writes for its bridges. Reloading the mesh's rules must not stop every container. b.WriteString("table inet mesh {}\ndelete table inet mesh\n\n") b.WriteString("table inet mesh {\n") + // The sets of the allowances with an until, declared before the chain that matches them. + for i, a := range allowances { + if a.Until == "" { + continue + } + b.WriteString(fmt.Sprintf("\tset %s {\n\t\ttype inet_service\n\t\tflags timeout\n", allowanceSet(i))) + b.WriteString(fmt.Sprintf("\t\telements = { %d timeout %ds }\n\t}\n", a.Port, timeLeft(a.Until, allowing.At))) + } b.WriteString("\tchain input {\n") // Dropping by default is the whole point, and the three lines under it are what keep dropping // by default from meaning "unreachable": a reply to something this node started, its own @@ -375,6 +410,33 @@ func AsNftablesWithLocal(rules []mcat.Rule, mesh []string, outward bool, foundat } } + // The allowances, set by hand through the seat node-packet-filter and answered by its holder (design 08 control-verbs §2). + if len(allowances) > 0 { + b.WriteString("\n\t\t# allowances, opened by hand through the seat node-packet-filter\n") + } + for i, a := range allowances { + var match []string + switch { + case a.Interface != "": + match = append(match, fmt.Sprintf("iifname %q", a.Interface)) + case tunnel != "": + match = append(match, fmt.Sprintf("iifname != %q", tunnel)) + } + if a.Source != "" { + family := "ip" + if strings.Contains(a.Source, ":") { + family = "ip6" + } + match = append(match, fmt.Sprintf("%s saddr %s", family, a.Source)) + } + port := strconv.FormatInt(a.Port, 10) + if a.Until != "" { + port = "@" + allowanceSet(i) + } + match = append(match, fmt.Sprintf("%s dport %s", a.Protocol, port)) + b.WriteString(fmt.Sprintf("\t\t%s accept comment %q\n", strings.Join(match, " "), "allowance "+a.Key+" "+a.At)) + } + b.WriteString("\t}\n") // Nothing this node sends is filtered, and it is stated rather than left to nftables' default // so that reading this file answers the question instead of requiring the reader to know it. @@ -499,6 +561,19 @@ func AsNftablesWithLocal(rules []mcat.Rule, mesh []string, outward bool, foundat return b.String() } +// allowanceSet is the name of the set of the i-th allowance (by key) with an until. +func allowanceSet(i int) string { return fmt.Sprintf("allowance_%d", i+1) } + +// timeLeft is the whole seconds from at to until, at least 1 (design 08 control-verbs §2): an until already passed, or one +// that does not read as RFC 3339 (the ask refuses such an answer before a compose renders it), closes the port at once. +func timeLeft(until string, at time.Time) int64 { + u, err := time.Parse(time.RFC3339, until) + if err != nil { + return 1 + } + return max(int64(math.Ceil(u.Sub(at).Seconds())), 1) +} + // byFamily splits addresses into the two nftables understands separately. // // `ip saddr` and `ip6 saddr` are different matches, and one set holding both families is a syntax diff --git a/internal/compose/resolution/filtering_test.go b/internal/compose/resolution/filtering_test.go index 79e4e537..44ee2970 100644 --- a/internal/compose/resolution/filtering_test.go +++ b/internal/compose/resolution/filtering_test.go @@ -5,7 +5,9 @@ import ( "fmt" "strings" "testing" + "time" + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter" mcat "git.novox.be/novox/mesh-sdk/go/catalogue" ) @@ -113,6 +115,70 @@ func TestTheModuleAskingForTheRuleSetGetsEveryModulesPorts(t *testing.T) { t.Errorf("expose %v: the left-out module's 5100 opens from %v, want %s", row.expose, from, row.from) } } + + // The allowances the holder of node-packet-filter answered, rendered beside the derived ports (design 08 control-verbs §2, + // §8; H-A-315 (4), (5)). + t.Run("allowances", func(t *testing.T) { + derived := []mcat.Rule{{Port: 443, Protocol: "tcp", From: mcat.FromEverywhere, Because: []string{"web"}}} + at := time.Date(2026, 11, 21, 20, 0, 0, 0, time.UTC) + render := func(allowances ...nodepacketfilter.Allowance) string { + return AsNftablesAllowing(derived, []string{"10.10.0.1"}, false, nil, []string{"eth0"}, "mesh0", nil, + Allowing{Allowances: allowances, At: at}) + } + inputOf := func(out string) string { + in, _, _ := strings.Cut(out, "\tchain output") + return in + } + // 08 control-verbs §8: with no allowance the file is byte for byte today's derived file. + if none, today := render(), AsNftablesWithLocal(derived, []string{"10.10.0.1"}, false, nil, []string{"eth0"}, "mesh0", nil); none != today { + t.Errorf("no allowance changed the file:\n%s\nwant\n%s", none, today) + } + // 08 control-verbs §8: one of the default set, a negated match on the private network's interface and no positive one. + one := render(nodepacketfilter.Allowance{Key: "allow.tcp.8000", Port: 8000, Protocol: "tcp", At: "2026-11-21T19:00:00Z"}) + if want := "\t\tiifname != \"mesh0\" tcp dport 8000 accept comment \"allowance allow.tcp.8000 2026-11-21T19:00:00Z\"\n"; !strings.Contains(inputOf(one), want) { + t.Errorf("the default set's allowance is not rendered as %q:\n%s", want, one) + } + if strings.Contains(one, "iifname \"mesh0\" tcp dport 8000") || strings.Contains(one, "proto-dst 8000") { + t.Errorf("the allowance opens the tunnel or the forward path:\n%s", one) + } + // 08 control-verbs §8: three, one interface named, one with an IPv4 source, one udp, after the derived ones. + three := inputOf(render( + nodepacketfilter.Allowance{Key: "allow.udp.5353", Port: 5353, Protocol: "udp", At: "a3"}, + nodepacketfilter.Allowance{Key: "allow.tcp.8000.enp3s0", Port: 8000, Protocol: "tcp", Interface: "enp3s0", At: "a1"}, + nodepacketfilter.Allowance{Key: "allow.tcp.9000", Port: 9000, Protocol: "tcp", Source: "192.168.1.0/24", At: "a2"}, + )) + derivedAt := strings.Index(three, "tcp dport 443 accept") + last := derivedAt + for _, want := range []string{ + "\t\tiifname \"enp3s0\" tcp dport 8000 accept comment \"allowance allow.tcp.8000.enp3s0 a1\"\n", + "\t\tiifname != \"mesh0\" ip saddr 192.168.1.0/24 tcp dport 9000 accept comment \"allowance allow.tcp.9000 a2\"\n", + "\t\tiifname != \"mesh0\" udp dport 5353 accept comment \"allowance allow.udp.5353 a3\"\n", + } { + at := strings.Index(three, want) + if at < 0 || at < last { + t.Errorf("the input chain lacks %q after the derived rules and the one before it:\n%s", want, three) + } + last = at + } + // 08 control-verbs §2, §8: an allowance with an until matches its port as the one element of a timeout set, its timeout + // the time left; one past its until is rendered as answered, at least 1 s. + until := render( + nodepacketfilter.Allowance{Key: "allow.tcp.8000", Port: 8000, Protocol: "tcp", At: "a1", Until: "2026-11-21T21:00:00Z"}, + nodepacketfilter.Allowance{Key: "allow.tcp.8001", Port: 8001, Protocol: "tcp", At: "a2", Until: "2026-11-21T19:00:00Z"}, + nodepacketfilter.Allowance{Key: "allow.tcp.8002", Port: 8002, Protocol: "tcp", Source: "2001:db8::/32", At: "a3"}, + ) + for _, want := range []string{ + "\tset allowance_1 {\n\t\ttype inet_service\n\t\tflags timeout\n\t\telements = { 8000 timeout 3600s }\n\t}\n", + "\tset allowance_2 {\n\t\ttype inet_service\n\t\tflags timeout\n\t\telements = { 8001 timeout 1s }\n\t}\n", + "\t\tiifname != \"mesh0\" tcp dport @allowance_1 accept comment \"allowance allow.tcp.8000 a1\"\n", + "\t\tiifname != \"mesh0\" tcp dport @allowance_2 accept comment \"allowance allow.tcp.8001 a2\"\n", + "\t\tiifname != \"mesh0\" ip6 saddr 2001:db8::/32 tcp dport 8002 accept comment \"allowance allow.tcp.8002 a3\"\n", + } { + if !strings.Contains(until, want) { + t.Errorf("the rule set lacks %q:\n%s", want, until) + } + } + }) } // The host does not sort, so the order the mesh writes is the order a machine applies. From dc3765bb7cf4ec126409f4aa538313a948bb938e Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 21:01:07 +0100 Subject: [PATCH 2/7] Ask the packet filter's holder allowed at every compose of the filter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The node-engine stays the one renderer of the filter file: at each compose of a converged node's filter it asks the holder of node-packet-filter its verb allowed within the setting compose-ask-bound (10 s) and renders the answer. When allowed does not answer, or answers what is not its answer, no filter file is composed: the one loaded is kept as it runs, the holder's module is not held (an old holder must stay replaceable), and the part withheld is said once in the journal until an answer comes between. The node hears allowances-changed on its own node's subject and composes again. The manifest invokes seat:node-packet-filter.allowed and consumes node-packet-filter.allowances-changed. Builds: design 08 control-verbs §1, §3, §4, §5, §7, §8; ADR 0683; H-A-305, H-A-307 (1), (2), H-A-314 (3), (5), (7), H-A-315 (2), (6), H-A-321 --- cmd/mesh-host/nodeagent.go | 7 ++ cmd/mesh-host/ownname_test.go | 17 +++ cmd/mesh-host/seatlist.go | 18 +++ internal/compose/composed.go | 27 ++++ internal/compose/frombus/answer_rows_test.go | 47 +++++++ internal/compose/frombus/frombus.go | 10 ++ internal/compose/input.go | 5 + internal/compose/node.go | 6 +- internal/compose/resolution/declaration.go | 50 ++++++-- internal/nodegrant/testdata/node.json | 2 + internal/selfcompose/candidate.go | 2 +- internal/selfcompose/filter.go | 124 +++++++++++++++++++ internal/selfcompose/selfcompose.go | 59 ++++++--- internal/selfcompose/selfcompose_test.go | 3 +- internal/selfcompose/shadow.go | 2 +- internal/selfcompose/versions_test.go | 115 +++++++++++++++++ module.json | 15 +++ packaging/operator_keys_test.go | 7 +- 18 files changed, 486 insertions(+), 30 deletions(-) create mode 100644 internal/selfcompose/filter.go diff --git a/cmd/mesh-host/nodeagent.go b/cmd/mesh-host/nodeagent.go index 96605260..92c0b224 100644 --- a/cmd/mesh-host/nodeagent.go +++ b/cmd/mesh-host/nodeagent.go @@ -18,6 +18,7 @@ import ( "sync/atomic" "time" + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter" "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay" "git.novox.be/novox/mesh-sdk/go/declaration" "github.com/novox/mesh-host/internal/agent" @@ -1234,6 +1235,12 @@ func composerEnv(session *link.Session, node string, say func(string), hooks com env.Entry = selfcompose.EntryCall(session.AskMeshSeat) // And the registry seats' verb versions, to resolve a want that names its version to its artifacts' digests (A-430a). env.Registry = selfcompose.EntryCall(session.AskMeshSeat) + // And the holder of node-packet-filter's verb allowed of this node, at every compose of the filter, within the setting + // compose-ask-bound (design 08 control-verbs §1). + env.Allowed = func(ctx context.Context, within time.Duration) (json.RawMessage, error) { + return session.AskSeat(ctx, nodepacketfilter.Seat, nodepacketfilter.VerbAllowed, nodepacketfilter.AllowedInput{}, within) + } + env.ComposeAskBound = composeAskBound() return env } diff --git a/cmd/mesh-host/ownname_test.go b/cmd/mesh-host/ownname_test.go index d82ab278..4f23a005 100644 --- a/cmd/mesh-host/ownname_test.go +++ b/cmd/mesh-host/ownname_test.go @@ -111,4 +111,21 @@ func TestTheViewWaitsBoundIsTheManifestsSetting(t *testing.T) { if got := resolveAgainBound(); got != time.Minute { t.Errorf("no file gives %v", got) } + // Design 08 control-verbs §1, H-A-314 (5): the compose-ask bound is the file `compose-ask-bound` feeds, in seconds, ten when + // it holds nothing usable. + wasAsk := composeAskBoundFile + defer func() { composeAskBoundFile = wasAsk }() + for content, want := range map[string]time.Duration{"3\n": 3 * time.Second, "": 10 * time.Second, "0": 10 * time.Second, "x": 10 * time.Second} { + composeAskBoundFile = filepath.Join(t.TempDir(), "a") + if err := os.WriteFile(composeAskBoundFile, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + if got := composeAskBound(); got != want { + t.Errorf("the file %q gives %v, want %v", content, got, want) + } + } + composeAskBoundFile = filepath.Join(t.TempDir(), "missing") + if got := composeAskBound(); got != 10*time.Second { + t.Errorf("no file gives %v", got) + } } diff --git a/cmd/mesh-host/seatlist.go b/cmd/mesh-host/seatlist.go index 5a390443..f5bae1eb 100644 --- a/cmd/mesh-host/seatlist.go +++ b/cmd/mesh-host/seatlist.go @@ -300,6 +300,24 @@ func resolveAgainBound() time.Duration { return time.Duration(n) * time.Minute } +// composeAskBoundFile is the file the manifest declares with the content ${config:compose-ask-bound} (design 08 control-verbs +// §1, H-A-314 (5)), read at the engine's start as resolveAgainFile is. +var composeAskBoundFile = "/var/lib/mesh-host/compose-ask-bound" + +// composeAskBound is how long a compose waits for an input it asks (the packet filter's allowed): the file's seconds, the +// design's ten (selfcompose.DefaultComposeAskBound) when the file is missing, empty or not a positive number. +func composeAskBound() time.Duration { + raw, err := os.ReadFile(composeAskBoundFile) + if err != nil { + return selfcompose.DefaultComposeAskBound + } + n, err := strconv.Atoi(strings.TrimSpace(string(raw))) + if err != nil || n < 1 { + return selfcompose.DefaultComposeAskBound + } + return time.Duration(n) * time.Second +} + // entryAsksFile is the file the manifest declares with the content ${config:entry-asks} (design 47 H, H-A-60), read at the // engine's start as recoveryWaitFile is. var entryAsksFile = "/var/lib/mesh-host/entry-asks" diff --git a/internal/compose/composed.go b/internal/compose/composed.go index d3eb61af..9ba9dc16 100644 --- a/internal/compose/composed.go +++ b/internal/compose/composed.go @@ -364,6 +364,33 @@ func RunsAnyOf(runs *engcomp.Composed, module string) bool { return false } +// FilterRunning is the content of the packet filter's file as it runs (the resource `.filtering` of the module that +// loads the filter), nil where none runs: kept as it runs when the holder's allowed does not answer (design 08 +// control-verbs §4). +func FilterRunning(running []engcomp.Composed) *string { + for _, c := range running { + for _, raw := range c.Resources { + var r struct { + ID string `json:"id"` + Module string `json:"module"` + Type string `json:"type"` + Content *string `json:"content"` + } + if json.Unmarshal(raw, &r) != nil || r.Type != "file" || r.Content == nil { + continue + } + owner := r.Module + if owner == "" { + owner, _ = declaration.ModuleGuess(r.ID) + } + if owner != "" && r.ID == owner+"."+catalogue.FilteringID() { + return r.Content + } + } + } + return nil +} + // ToolsRunning is, by module, the tools bundles that run on the node (Node.RunsTools): each bundle archive a module's // resource unpacks at its BundlePath, with what the runtime's own process loads of it and the words it hands it // (catalogue.RuntimeToolModules, catalogue.RuntimeToolEnv, the mesh's own words left out). A bundle the runtime loads diff --git a/internal/compose/frombus/answer_rows_test.go b/internal/compose/frombus/answer_rows_test.go index 5a4011b1..ff6308c7 100644 --- a/internal/compose/frombus/answer_rows_test.go +++ b/internal/compose/frombus/answer_rows_test.go @@ -19,6 +19,7 @@ import ( "strings" "testing" + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter" "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay" "git.novox.be/novox/mesh-sdk/go/catalogue" "github.com/novox/mesh-host/internal/compose" @@ -349,6 +350,52 @@ func answerNamesEveryRefusalAndLeavesAnOldBuildToTheNode(t *testing.T) { if !strings.Contains(rules, "# spiegel — the site") || !strings.Contains(rules, "dport 20005 accept") || strings.Contains(rules, "dport 8080") { t.Errorf("the filter does not open the machine port spiegel runs at:\n%s", rules) } + // Design 08 control-verbs §1, §2, §4 (H-A-321): the compose of the filter renders the allowances the holder answered; + // where allowed did not answer it composes no filter file and keeps the one loaded, as it runs, and the rest composes. + filterOf := func(f resolution.Filter, running []engcomp.Composed) (string, bool) { + t.Helper() + got, _, held, err := Compose(ctx, b, Mesh{}, Scope{Node: "n1", InOwn: []string{"spiegel"}, Running: running, Filter: f}, fps) + if _, nftHeld := held["nft"]; err != nil || nftHeld { + t.Fatalf("the node does not compose itself with the filter given %+v: %v, held %v", f, err, held) + } + for _, c := range got { + for _, raw := range c.Resources { + var r struct { + ID string `json:"id"` + Content string `json:"content"` + } + if json.Unmarshal(raw, &r) == nil && r.ID == "nft."+catalogue.FilteringID() { + return r.Content, true + } + } + } + return "", false + } + allowance := nodepacketfilter.Allowance{Key: "allow.tcp.8000", Port: 8000, Protocol: "tcp", At: "2026-11-21T19:00:00Z"} + if got, _ := filterOf(resolution.Filter{Allowing: resolution.Allowing{Allowances: []nodepacketfilter.Allowance{allowance}}}, running); !strings.Contains(got, + `tcp dport 8000 accept comment "allowance allow.tcp.8000 2026-11-21T19:00:00Z"`) || !strings.Contains(got, "dport 20005 accept") { + t.Errorf("the filter does not render the allowance beside the derived ports:\n%s", got) + } + kept := slices.Clone(running) + for i, c := range kept { + if c.Module != "nft" { + continue + } + c.Resources = slices.Clone(c.Resources) + for j, raw := range c.Resources { + if strings.Contains(string(raw), `"nft.`+catalogue.FilteringID()+`"`) { + c.Resources[j] = json.RawMessage(`{"id":"nft.filtering","module":"nft","type":"file","path":"/etc/nftables.conf","mode":"0600","content":"the filter loaded\n"}`) + } + } + kept[i] = c + } + withheld := resolution.Filter{Withheld: "asked of the seat node-packet-filter's verb allowed on n1, which did not answer"} + if got, ok := filterOf(withheld, kept); !ok || got != "the filter loaded\n" { + t.Errorf("an unanswered allowed composes the filter %q (%v), want the one loaded kept as it runs", got, ok) + } + if got, ok := filterOf(withheld, nil); ok { + t.Errorf("an unanswered allowed where no filter runs composes one:\n%s", got) + } // The paths a carried module owns are its manifest's, as the controller composes them, never what runs of it (issue // 1126, seed-8 #542: on ace, the folded f1-circuits, snake and txt-game, whose manifests leave their directories and // files to ${dir:…}, owned their /var/lib paths on the node and none on the controller, shifting node-tools' diff --git a/internal/compose/frombus/frombus.go b/internal/compose/frombus/frombus.go index 2d00c72b..e5a59254 100644 --- a/internal/compose/frombus/frombus.go +++ b/internal/compose/frombus/frombus.go @@ -201,6 +201,10 @@ type Scope struct { // keeps offering the others (what it provides, contributes and listens on), since it keeps running what it runs. False // where nothing is read; the manifest it is composed from is its offer then. Nil: none is read. RunningManifest func(module string) (catalogue.Manifest, bool) + // Filter is, for the node composing itself, what the compose of its packet filter is given beside the derived ports + // (compose.Node.Filter): the allowances the holder of node-packet-filter answered its verb allowed, or why it did not + // answer, and then the filter file is kept as it runs in Running (design 08 control-verbs §1, §4). Empty renders none. + Filter resolution.Filter } // InOwn is, of the modules p places on its node, those whose resources the node's own composition it runs @@ -479,6 +483,12 @@ func readBase(ctx context.Context, r Reader, mesh Mesh, s Scope) (base, error) { n.RunsRuntime = compose.RuntimeRunning(s.Running) // And every runtime process as it runs, whose words give each held module's share of a holder's (H-A-335). n.RunsRuntimes = compose.RuntimesRunning(s.Running) + // And its packet filter's allowances, or the filter file as it runs where allowed did not answer (design 08 + // control-verbs §4). + n.Filter = s.Filter + if n.Filter.Withheld != "" { + n.Filter.Running = compose.FilterRunning(s.Running) + } for _, module := range s.InOwn { if n.InOwn == nil { n.InOwn = map[string]bool{} diff --git a/internal/compose/input.go b/internal/compose/input.go index dae6f2c9..1eb57312 100644 --- a/internal/compose/input.go +++ b/internal/compose/input.go @@ -22,6 +22,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/novox/mesh-host/internal/compose/resolution" engcomp "github.com/novox/mesh-host/internal/compositions" "sort" "strings" @@ -283,6 +284,10 @@ type Node struct { // (`.own-runtime`); nil when none runs. A held module's share of a holder's words that every module gives a // share of (the secret places, the owned paths) is taken from them (resolution.Holding; design 47 H, H-A-335, H-A-337). RunsRuntimes map[string]map[string]string + // Filter is, of the node composing itself, what the compose of its packet filter is given beside the derived ports: the + // allowances the holder of node-packet-filter answered its verb allowed, or why it did not answer and the filter file as + // it runs, which is then kept (design 08 control-verbs §1, §4). Empty renders no allowance, as for every other node. + Filter resolution.Filter } // ComposedHow is how a node-engine composes its node from an Input (Input.ComposedHow). diff --git a/internal/compose/node.go b/internal/compose/node.go index 43c7c8e8..cbbaf668 100644 --- a/internal/compose/node.go +++ b/internal/compose/node.go @@ -176,10 +176,10 @@ func ComposeIn(in Input, node string, mode Mode) (Declared, []string, error) { // none (resolution.NoStoreError, whatever the shape: an image, a source, a tools bundle, a runtime program, a templates // archive) is left out of the declaration with its words and the rest composes again; the node is never refused whole for it // (design 47 G A-461, A-452). The rendering returned carries the modules so left out, for the filter and the rest to read. -func composeWithoutStoreFetchers(plan catalogue.Resolution, with catalogue.Rendering, holding resolution.Holding) (catalogue.Composed, catalogue.Rendering, map[string]string, error) { +func composeWithoutStoreFetchers(plan catalogue.Resolution, with catalogue.Rendering, holding resolution.Holding, filter resolution.Filter) (catalogue.Composed, catalogue.Rendering, map[string]string, error) { var held map[string]string for { - composed, err := resolution.ComposeHolding(plan, with, holding) + composed, err := resolution.ComposeHoldingFiltered(plan, with, holding, filter) var none *resolution.NoStoreError if !errors.As(err, &none) { return composed, with, held, err @@ -223,7 +223,7 @@ func (c *composer) declaration(nodeName string, mode Mode) (Declared, error) { } // A held module's share of a holder's words is what runs of each runtime process (design 47 H, H-A-335, H-A-337). holding := resolution.Holding{Held: node.Held, Runs: node.RunsRuntimes} - composed, with, storeHeld, err := composeWithoutStoreFetchers(plan, with, holding) + composed, with, storeHeld, err := composeWithoutStoreFetchers(plan, with, holding, node.Filter) if err != nil { return Declared{}, err } diff --git a/internal/compose/resolution/declaration.go b/internal/compose/resolution/declaration.go index 3647fcbc..cc071c50 100644 --- a/internal/compose/resolution/declaration.go +++ b/internal/compose/resolution/declaration.go @@ -105,18 +105,40 @@ func (e *UnreadManifestError) Error() string { return e.said } // Compose is Declaration with the owner of every resource said. func Compose(r mcat.Resolution, with mcat.Rendering) (mcat.Composed, error) { - return ComposeHolding(r, with, Holding{}) + return ComposeHoldingFiltered(r, with, Holding{}, Filter{}) } // ComposeHolding is Compose for a node that holds modules this pass (Holding): a held module's share of a holder's words // is what runs (design 47 H, H-A-335, H-A-337). func ComposeHolding(r mcat.Resolution, with mcat.Rendering, h Holding) (mcat.Composed, error) { + return ComposeHoldingFiltered(r, with, h, Filter{}) +} + +// Filter is what a compose of the node's packet filter is given beside the derived ports (design 08 control-verbs §1, §4): +// the allowances the holder of node-packet-filter answered its verb allowed, or, when allowed did not answer, why +// (Withheld) and the filter file as it runs (Running, nil when none runs). A withheld allowed composes no filter file: the +// one loaded is kept, its content as it runs, and none is composed where none runs, never one read as "nothing opened" +// (H-A-307 (1)). +type Filter struct { + Allowing Allowing + Withheld string + Running *string +} + +// ComposeFiltered is Compose with the filter's allowances, or the filter kept as it runs (Filter). +func ComposeFiltered(r mcat.Resolution, with mcat.Rendering, filter Filter) (mcat.Composed, error) { + return ComposeHoldingFiltered(r, with, Holding{}, filter) +} + +// ComposeHoldingFiltered is Compose for a node that holds modules this pass (Holding) and composes its packet filter with +// the allowances or keeps it as it runs (Filter): ComposeHolding and ComposeFiltered at once. +func ComposeHoldingFiltered(r mcat.Resolution, with mcat.Rendering, h Holding, filter Filter) (mcat.Composed, error) { owner := map[string]string{} received := map[string]map[string][]mcat.Contribution{} leftOut := map[string]string{} var foreseen, unplaced, handedOnly []string handed := &handedFiles{plans: map[string]mcat.Plan{}} - resources, err := resolutionCompose(r, with, h, owner, received, leftOut, &foreseen, &unplaced, &handedOnly, handed) + resources, err := resolutionCompose(r, with, h, filter, owner, received, leftOut, &foreseen, &unplaced, &handedOnly, handed) if err != nil { return mcat.Composed{}, err } @@ -143,7 +165,7 @@ func ComposeHolding(r mcat.Resolution, with mcat.Rendering, h Holding) (mcat.Com // BusMembershipPath is where the host reads it — the same constant on both sides. func BusMembershipID() string { return "bus-membership" } -func resolutionCompose(r mcat.Resolution, with mcat.Rendering, h Holding, owner map[string]string, +func resolutionCompose(r mcat.Resolution, with mcat.Rendering, h Holding, filter Filter, owner map[string]string, received map[string]map[string][]mcat.Contribution, leftOut map[string]string, foreseen, unplaced, handedOnly *[]string, handed *handedFiles) ([]map[string]any, error) { // **A setting is judged where it is stored, and an impossible one costs a module, not a @@ -284,8 +306,8 @@ func resolutionCompose(r mcat.Resolution, with mcat.Rendering, h Holding, owner "`node show %s` says whether it has. Until then %s is not sent, and the machine "+ "keeps the filter it has", r.Node, r.Node, filters) } - filtering := AsNftablesWithLocal(rules, with.Mesh, r.PublicDomain != "", with.Foundation, - with.OutwardLinks, with.TunnelInterface, with.LocalNetworks) + filtering := AsNftablesAllowing(rules, with.Mesh, r.PublicDomain != "", with.Foundation, + with.OutwardLinks, with.TunnelInterface, with.LocalNetworks, filter.Allowing) // **A variable two modules set is refused whether or not anything places it** (novox/hq ADR // 0203 §5): the account has one environment, and a machine whose holder arrives later should not @@ -323,10 +345,20 @@ func resolutionCompose(r mcat.Resolution, with mcat.Rendering, h Holding, owner // that does not, because what gets remembered is that it works. var first []map[string]any if f := m.Filtering; f != nil { - first = append(first, map[string]any{ - "id": mcat.FilteringID(), "type": "file", "path": f.Into, - "content": filtering, "mode": "0600", - }) + // **An unanswered allowed composes no filter file** (design 08 control-verbs §4): the one loaded is kept as it + // runs, and none is composed where none runs. + switch { + case filter.Withheld == "": + first = append(first, map[string]any{ + "id": mcat.FilteringID(), "type": "file", "path": f.Into, + "content": filtering, "mode": "0600", + }) + case filter.Running != nil: + first = append(first, map[string]any{ + "id": mcat.FilteringID(), "type": "file", "path": f.Into, + "content": *filter.Running, "mode": "0600", + }) + } } // The node's fail2ban jails, composed from every module it runs (novox/hq to-be 31), written // where the intrusion-prevention holder owns them. Like the rule set above: gathered from all diff --git a/internal/nodegrant/testdata/node.json b/internal/nodegrant/testdata/node.json index 46b12cd7..d6b315e8 100644 --- a/internal/nodegrant/testdata/node.json +++ b/internal/nodegrant/testdata/node.json @@ -130,6 +130,8 @@ "mesh.seat.node-backup.call.now.NODE.node~NODE", "mesh.seat.node-backup.tool.backed-up.NODE", "mesh.seat.node-backup.tool.now.NODE", + "mesh.seat.node-packet-filter.call.allowed.NODE.node~NODE", + "mesh.seat.node-packet-filter.tool.allowed.NODE", "mesh.seat.node-engine.event.*.NODE", "mesh.stream.mesh-host.event.*.NODE" ], diff --git a/internal/selfcompose/candidate.go b/internal/selfcompose/candidate.go index 34411a5c..c03ba799 100644 --- a/internal/selfcompose/candidate.go +++ b/internal/selfcompose/candidate.go @@ -473,7 +473,7 @@ func (c *Composer) composeShadow(ctx context.Context, running []engcomp.Composed c.mu.Lock() c.wants = wants c.mu.Unlock() - scope := frombus.Scope{Node: node, KeptAt: kept, InOwn: inOwn, Running: running, SameValue: c.sameValue, Heard: c.heardNow(), RunningManifest: c.runningFor(node)} + scope := frombus.Scope{Node: node, KeptAt: kept, InOwn: inOwn, Running: running, SameValue: c.sameValue, Heard: c.heardNow(), RunningManifest: c.runningFor(node), Filter: c.lastFilter(node)} if input != nil { input(scope, fps) } diff --git a/internal/selfcompose/filter.go b/internal/selfcompose/filter.go new file mode 100644 index 00000000..71b8e6ca --- /dev/null +++ b/internal/selfcompose/filter.go @@ -0,0 +1,124 @@ +package selfcompose + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter" + "github.com/novox/mesh-host/internal/compose/resolution" +) + +// The compose of the node's packet filter asks the holder of the seat node-packet-filter its verb allowed, of its own node, +// within the compose-ask bound, and renders the answer's allowances beside the derived ports (design 08 control-verbs §1, +// §2; ADR 0683). An unanswered allowed is a part withheld (H-A-306): no filter file is composed and the one loaded is kept, +// said once in the journal and in the composition read (§4, H-A-321). + +// DefaultComposeAskBound is how long a compose waits for an input it asks (allowed) when the setting `compose-ask-bound` +// gives nothing (Env.ComposeAskBound 0; design 08 control-verbs §1, H-A-314 (5); principle 11). +const DefaultComposeAskBound = 10 * time.Second + +// AllowedPart is the part a compose of the filter asks: the seat node-packet-filter's verb allowed (H-A-321). +const AllowedPart = nodepacketfilter.Seat + "." + nodepacketfilter.VerbAllowed + +// composeAskBound is the setting, or DefaultComposeAskBound. +func (c *Composer) composeAskBound() time.Duration { + if c.env.ComposeAskBound > 0 { + return c.env.ComposeAskBound + } + return DefaultComposeAskBound +} + +// filterOf is what this pass's compose of the node's packet filter is given: on a converged node whose placed modules hold +// the seat node-packet-filter, the allowances allowed answered, or why it did not answer (the filter then kept as it runs). +// An adopted node renders none (§5), and a node with no holder placed composes no filter to give them to. +func (c *Composer) filterOf(ctx context.Context, own meshmoduleassigner.Assignments) resolution.Filter { + if c.env.Allowed == nil || own.Decided.Adopted || !c.holdsFilter(ctx, own) { + return resolution.Filter{} + } + at := c.now() + bound := c.composeAskBound() + raw, err := c.env.Allowed(ctx, bound) + why := "" + var answer nodepacketfilter.AllowedAnswer + switch { + case err != nil: + why = fmt.Sprintf("asked of the seat %s's verb %s on %s, which did not answer within %s: %v", + nodepacketfilter.Seat, nodepacketfilter.VerbAllowed, c.env.Node, bound, err) + case json.Unmarshal(raw, &answer) != nil: + why = fmt.Sprintf("asked of the seat %s's verb %s on %s, which answered what is not its answer", + nodepacketfilter.Seat, nodepacketfilter.VerbAllowed, c.env.Node) + default: + if bad := notAnAllowance(answer.Allowances); bad != "" { + why = fmt.Sprintf("asked of the seat %s's verb %s on %s, which answered what is not its answer: %s", + nodepacketfilter.Seat, nodepacketfilter.VerbAllowed, c.env.Node, bad) + } + } + c.mu.Lock() + said := c.allowedSaid + c.allowedSaid = why != "" + c.mu.Unlock() + if why != "" { + // Said once, and again only after a compose with an answer in between (§4). + if !said { + c.env.Say("the node composes no filter file and keeps the one loaded: the part " + AllowedPart + " is withheld, " + why) + } + return resolution.Filter{Withheld: why} + } + return resolution.Filter{Allowing: resolution.Allowing{Allowances: answer.Allowances, At: at}} +} + +// holdsFilter says a module placed on the node claims the seat node-packet-filter, as the manifest of its want's build says. +func (c *Composer) holdsFilter(ctx context.Context, own meshmoduleassigner.Assignments) bool { + for _, m := range own.Modules { + if claims, known := c.Claims(ctx, m.Module, nodepacketfilter.Seat); claims && known { + return true + } + } + return false +} + +// notAnAllowance names the first allowance the renderer cannot render as the seat's form says it (a key, tcp or udp, a +// port 1-65535, an until in RFC 3339); "" when every one reads. +func notAnAllowance(allowances []nodepacketfilter.Allowance) string { + for _, a := range allowances { + switch { + case a.Key == "": + return "an allowance with no key" + case a.Protocol != nodepacketfilter.AllowanceProtocolTcp && a.Protocol != nodepacketfilter.AllowanceProtocolUdp: + return fmt.Sprintf("%s has the protocol %q", a.Key, a.Protocol) + case a.Port < 1 || a.Port > 65535: + return fmt.Sprintf("%s has the port %d", a.Key, a.Port) + } + if a.Until != "" { + if _, err := time.Parse(time.RFC3339, a.Until); err != nil { + return fmt.Sprintf("%s has the until %q", a.Key, a.Until) + } + } + } + return "" +} + +// LastWithheldParts is each part the last pass kept because its read did not answer, with why (H-A-321): the filter's +// allowed, named AllowedPart. Nil when none. +func (c *Composer) LastWithheldParts() map[string]string { + c.mu.Lock() + defer c.mu.Unlock() + if c.filter.Withheld == "" { + return nil + } + return map[string]string{AllowedPart: c.filter.Withheld} +} + +// lastFilter is what the last pass's compose of this node's filter was given, for a candidate composed in shadow on node +// (so a candidate's filter is what the node composes); empty for another node. +func (c *Composer) lastFilter(node string) resolution.Filter { + if node != c.env.Node { + return resolution.Filter{} + } + c.mu.Lock() + defer c.mu.Unlock() + return c.filter +} diff --git a/internal/selfcompose/selfcompose.go b/internal/selfcompose/selfcompose.go index d35cd5c9..8ac1fbce 100644 --- a/internal/selfcompose/selfcompose.go +++ b/internal/selfcompose/selfcompose.go @@ -28,6 +28,7 @@ import ( "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter" "git.novox.be/novox/mesh-sdk/go/declaration" "github.com/novox/mesh-host/internal/buckets" "github.com/novox/mesh-host/internal/compositions" @@ -145,6 +146,13 @@ type Env struct { // Set, the composer reads the catalog half by the fingerprints its wants and the runnings it heard name and nothing else of // the indexer's or the builder's states (design 47 G §421, §628); a composer is made with it. Entry meshcatalogclient.Call + // Allowed asks the holder of the seat node-packet-filter on this node its verb allowed, within the bound given, in the + // engine's own name: the allowances a compose of the filter renders (design 08 control-verbs §1). Nil asks nothing, and + // the filter renders none. + Allowed func(ctx context.Context, within time.Duration) (json.RawMessage, error) + // ComposeAskBound is the setting `compose-ask-bound`: how long a compose waits for allowed; DefaultComposeAskBound when 0 + // (design 08 control-verbs §1, H-A-314 (5)). + ComposeAskBound time.Duration // Registry asks the registry seats' verb versions (oci-artifact-registry, container-image-registry) in the engine's own // name: a want naming its version is resolved to its artifacts' digests through it (design 47 G A-430a). Registry meshcatalogclient.Call @@ -328,6 +336,11 @@ type Composer struct { pubSaid string pubWrite sync.Mutex pubKept map[string]ComposedEntry + // filter is what the last pass's compose of the packet filter was given (filterOf), which a candidate composed in shadow + // is given too; allowedSaid says its withheld allowed was said in the journal, until it answers (design 08 + // control-verbs §4). Guarded by mu. + filter resolution.Filter + allowedSaid bool } // Pass is how one pass went, as the node-engine's verb compose answers it. @@ -574,24 +587,37 @@ func (c *Composer) Watch(ctx context.Context, _ string) (<-chan agent.Update, er if err != nil { return nil, fmt.Errorf("the node composes again when a secret changes, and cannot hear the vault say so: %w", err) } - go func() { - defer stop() - for { - select { - case <-ctx.Done(): - return - case _, ok := <-heard: - if !ok { - return - } + // And the packet filter's holder saying its allowances changed on this node: the filter is composed again, asking + // allowed; the event's body is not rendered (design 08 control-verbs §3). + changed, stopChanged, err := c.env.Hear(nodepacketfilter.SubjectAllowancesChanged(c.env.Node)) + if err != nil { + stop() + return nil, fmt.Errorf("the node composes its filter again when its allowances change, and cannot hear the holder of %s say so: %w", + nodepacketfilter.Seat, err) + } + for _, h := range []struct { + heard <-chan []byte + stop func() + }{{heard, stop}, {changed, stopChanged}} { + go func() { + defer h.stop() + for { select { - case merged <- tagged{in: -1, ok: true}: case <-ctx.Done(): return + case _, ok := <-h.heard: + if !ok { + return + } + select { + case merged <- tagged{in: -1, ok: true}: + case <-ctx.Done(): + return + } } } - } - }() + }() + } } if c.env.SeatListChanged != nil { go func() { @@ -662,7 +688,7 @@ func (c *Composer) Watch(ctx context.Context, _ string) (<-chan agent.Update, er } switch { case t.in < 0: - dirty = true // a secret changed: its new generation is asked of the vault at the compose + dirty = true // a secret or the allowances changed: asked again at the compose case t.u.Caught: caught[t.in] = true if ins[t.in].bucket == buckets.Assignments { @@ -1138,6 +1164,11 @@ func (c *Composer) compose(ctx context.Context) []agent.Update { // (ADR 0636 §1): the module is held as it runs before anything of its build is read, so no take-in or artifact // reference of it (the artifact store's seat is not bootstrapped) can refuse the pass (issue 1966). scope.Held = c.heldUntilListed(ctx, r, own) + // The packet filter's allowances, asked of its holder at every compose of the filter (design 08 control-verbs §1, §4). + scope.Filter = c.filterOf(ctx, own) + c.mu.Lock() + c.filter = scope.Filter + c.mu.Unlock() // A want whose entry the catalog half has not answered, or holds none of, is held with what runs of it (§421). if holds := c.entryHolds(); len(holds) > 0 { if scope.Held == nil { diff --git a/internal/selfcompose/selfcompose_test.go b/internal/selfcompose/selfcompose_test.go index 32736a8f..3f262b55 100644 --- a/internal/selfcompose/selfcompose_test.go +++ b/internal/selfcompose/selfcompose_test.go @@ -31,6 +31,7 @@ import ( "testing" "time" + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter" "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay" "git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/seatlist" @@ -250,7 +251,7 @@ func TestTheNodeComposesItsWantsFromTheBus(t *testing.T) { } secretChanged := make(chan []byte, 1) env.Hear = func(subject string) (<-chan []byte, func(), error) { - if subject == meshcatalog.SubjectCatalogRevisionAll { + if subject == meshcatalog.SubjectCatalogRevisionAll || subject == nodepacketfilter.SubjectAllowancesChanged("n1") { return make(chan []byte), func() {}, nil } if subject != VaultSecretChanged { diff --git a/internal/selfcompose/shadow.go b/internal/selfcompose/shadow.go index 8a6ab8aa..c4ebd49d 100644 --- a/internal/selfcompose/shadow.go +++ b/internal/selfcompose/shadow.go @@ -682,7 +682,7 @@ func (s *Shadow) answerProposal(ctx context.Context, proposal string) (nodeengin given[node] = &without } a := frombus.Answer(ctx, reader{c: c}, c.env.Mesh, frombus.Scope{Node: node, KeptAt: kept, Assignments: given, InOwn: inOwn, - SameValue: c.sameValue, HeldToday: s.heldToday(heldAdded), RunningManifest: c.runningFor(node)}, fps, running, proposal, rev) + SameValue: c.sameValue, HeldToday: s.heldToday(heldAdded), RunningManifest: c.runningFor(node), Filter: c.lastFilter(node)}, fps, running, proposal, rev) for _, module := range slices.Sorted(maps.Keys(heldAdded)) { a.Held = append(a.Held, nodeengine.CandidateRefusal{Module: module, Why: heldAdded[module]}) } diff --git a/internal/selfcompose/versions_test.go b/internal/selfcompose/versions_test.go index f06cdc6e..26b4cbed 100644 --- a/internal/selfcompose/versions_test.go +++ b/internal/selfcompose/versions_test.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "runtime" "strings" "sync" "testing" @@ -13,9 +14,11 @@ import ( "github.com/novox/mesh-host/internal/agent" + "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" + "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodepacketfilter" ) // Design 47 G A-430, A-430a (the lead's answer A-430b): a want naming its version is resolved to its artifacts' @@ -134,6 +137,118 @@ func TestAModulesClaimsAreReadFromTheEntryOfItsWantsBuild(t *testing.T) { if claims, known := c.Claims(context.Background(), "ghost", "mesh-broker"); claims || known { t.Errorf("a module with no want has no manifest read: claims %v, known %v", claims, known) } + + // Design 08 control-verbs §1, §4, §5: the compose of the filter asks the holder of node-packet-filter its verb allowed + // within the compose-ask bound; an unanswered allowed is a part withheld, said once until an answer comes between. + t.Run("the filter asks allowed of its holder", func(t *testing.T) { + now := time.Date(2026, 11, 21, 20, 0, 0, 0, time.UTC) + var said []string + var asked []time.Duration + answer, failure := json.RawMessage(`{"allowances":[{"key":"allow.tcp.8000","port":8000,"protocol":"tcp","at":"a1","by":"op","why":"w"}]}`), error(nil) + env := Env{Node: "desk", Say: func(line string) { said = append(said, line) }, Now: func() time.Time { return now }, + Allowed: func(_ context.Context, within time.Duration) (json.RawMessage, error) { + asked = append(asked, within) + return answer, failure + }} + c := New(env) + c.keptEnt = map[string]keptEntry{} + c.wants["nft"] = meshwants.WantsByWantNodeModuleValue{Fp: fp} + c.keptEnt[fp] = keptEntry{entry: meshcatalog.CatalogEntry{Module: "nft", Fp: fp, + Manifest: map[string]any{"module": "nft", "version": "1", "claims": []any{map[string]any{"name": "node-packet-filter"}}}}} + own := meshmoduleassigner.Assignments{Node: "desk", Modules: []meshmoduleassigner.PlacedModule{{Module: "nft"}}} + got := c.filterOf(context.Background(), own) + if len(asked) != 1 || asked[0] != DefaultComposeAskBound || got.Withheld != "" || len(got.Allowing.Allowances) != 1 || + got.Allowing.Allowances[0].Key != "allow.tcp.8000" || !got.Allowing.At.Equal(now) { + t.Errorf("asked %v, given %+v; want allowed asked once within 10s and its allowance given at the compose's time", asked, got) + } + failure = errors.New("nats: no responders available for request") + for range 2 { + if got = c.filterOf(context.Background(), own); !strings.Contains(got.Withheld, "node-packet-filter's verb allowed on desk, which did not answer within 10s: nats: no responders") { + t.Errorf("an unanswered allowed gives %+v, want the part withheld naming the holder asked", got) + } + } + answer, failure = json.RawMessage(`{"allowances":[{"key":"allow.tcp.8000","port":8000,"protocol":"tcp","until":"tomorrow"}]}`), nil + if got = c.filterOf(context.Background(), own); !strings.Contains(got.Withheld, `answered what is not its answer: allow.tcp.8000 has the until "tomorrow"`) { + t.Errorf("an answer that is not allowed's gives %+v, want the part withheld", got) + } + if n := strings.Count(strings.Join(said, "\n"), "is withheld"); n != 1 { + t.Errorf("the withheld part is said %d times over three unanswered composes, want once:\n%s", n, strings.Join(said, "\n")) + } + answer = json.RawMessage(`{"allowances":[]}`) + c.filterOf(context.Background(), own) + failure = errors.New("nats: timeout") + c.filterOf(context.Background(), own) + if n := strings.Count(strings.Join(said, "\n"), "is withheld"); n != 2 { + t.Errorf("the withheld part is said %d times, want again after a compose with an answer between", n) + } + asked = nil + c.env.ComposeAskBound = 3 * time.Second + if c.filterOf(context.Background(), own); len(asked) != 1 || asked[0] != 3*time.Second { + t.Errorf("asked within %v, want the setting compose-ask-bound", asked) + } + asked = nil + own.Decided.Adopted = true + if got = c.filterOf(context.Background(), own); len(asked) != 0 || got.Withheld != "" || len(got.Allowing.Allowances) != 0 { + t.Errorf("an adopted node asked %d times and is given %+v, want none asked and none rendered", len(asked), got) + } + own.Decided.Adopted = false + own.Modules = []meshmoduleassigner.PlacedModule{{Module: "ghost"}} + if c.filterOf(context.Background(), own); len(asked) != 0 { + t.Errorf("a node with no holder of node-packet-filter placed asked allowed %d times", len(asked)) + } + }) + + // Design 08 control-verbs §3, §8: the node hears allowances-changed on its own node's subject, never another's, and + // composes again on it. + t.Run("an allowances-changed of its node composes again", func(t *testing.T) { + b := newFakeBus() + env := b.env() + var mu sync.Mutex + heard := map[string]chan []byte{} + env.Hear = func(subject string) (<-chan []byte, func(), error) { + mu.Lock() + defer mu.Unlock() + heard[subject] = make(chan []byte) + return heard[subject], func() {}, nil + } + c := New(env) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + out, err := c.Watch(ctx, "n1.>") + if err != nil { + t.Fatal(err) + } + go func() { + for range out { + } + }() + for _, in := range c.inputs() { + b.send(in.bucket, agent.Update{Caught: true}) + } + passAt := func() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.last.At } + for deadline := time.Now().Add(10 * time.Second); passAt().IsZero(); runtime.Gosched() { + if time.Now().After(deadline) { + t.Fatal("no first pass") + } + } + first := passAt() + mu.Lock() + own, other := heard[nodepacketfilter.SubjectAllowancesChanged("n1")], heard[nodepacketfilter.SubjectAllowancesChanged("n2")] + mu.Unlock() + if own == nil || other != nil { + t.Fatalf("heard %v, want the own node's allowances-changed and no other's", heard) + } + select { + case own <- []byte(`{"node":"n1","change":"allowed"}`): + case <-time.After(10 * time.Second): + t.Fatal("nothing hears the node's allowances-changed") + } + for deadline := time.Now().Add(10 * time.Second); passAt().Equal(first); runtime.Gosched() { + if time.Now().After(deadline) { + t.Fatal("an allowances-changed of the node composed nothing again") + } + } + }) } // Design 47 H, the lead's answer H-A-146 (A-430a: the bytes are fetched by the digest the versions answer gives): a resolution diff --git a/module.json b/module.json index a3ce2934..aeef6d1d 100644 --- a/module.json +++ b/module.json @@ -51,6 +51,7 @@ "seat:mesh-recovery.kept-points", "seat:mesh-recovery.restore-kept", "seat:mesh-recovery.snapshot-kept", + "seat:node-packet-filter.allowed", "seat:oci-artifact-registry.versions" ], "consumes": [ @@ -63,6 +64,7 @@ "mesh-recovery.ended", "mesh-recovery.restored", "node-engine.running", + "node-packet-filter.allowances-changed", "restic.backed-up" ], "streams": [ @@ -105,6 +107,12 @@ "minimum": 1, "default": 5 }, + "compose-ask-bound": { + "type": "number", + "description": "How long a compose of the node's packet filter waits for the holder of node-packet-filter to answer its verb allowed before it keeps the filter loaded and says the part withheld, in seconds (design 08 control-verbs §1, §4).", + "minimum": 1, + "default": 10 + }, "resolve-again-minutes": { "type": "number", "description": "How long the node-engine holds a module whose want's version it could not resolve to its artifacts' digests, or whose resolution it forgot after a failed fetch, before it asks the registry seats' verb versions again, in minutes (design 47 H, H-A-146).", @@ -167,6 +175,13 @@ "mode": "0644", "content": "${config:entry-asks}\n" }, + { + "id": "compose-ask-bound", + "type": "file", + "path": "/var/lib/mesh-host/compose-ask-bound", + "mode": "0644", + "content": "${config:compose-ask-bound}\n" + }, { "id": "resolve-again", "type": "file", diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index 99eb01b6..b29841a8 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -95,11 +95,16 @@ func TestTheManifestConsumesTheBackupEvent(t *testing.T) { if !strings.Contains(string(raw), `"content": "${config:resolve-again-minutes}\n"`) || m.Config["resolve-again-minutes"].Default != float64(1) { t.Errorf("module.json declares no file with the content ${config:resolve-again-minutes} or its default is not 1 (design 47 H, H-A-146)") } + // Design 08 control-verbs §1, H-A-314 (3), (5): the compose-ask bound, ten seconds by default, fed into its file; allowed invoked. + if !strings.Contains(string(raw), `"content": "${config:compose-ask-bound}\n"`) || m.Config["compose-ask-bound"].Default != float64(10) || + !strings.Contains(string(raw), `"seat:node-packet-filter.allowed"`) { + t.Errorf("module.json declares no file with the content ${config:compose-ask-bound}, its default is not 10, or it invokes no seat:node-packet-filter.allowed") + } if m.Config["recovery-wait-minutes"].Default != float64(90) { t.Errorf("config recovery-wait-minutes is %+v, want default 90", m.Config["recovery-wait-minutes"]) } // The backup event, the status view's settled, and the two events of the seat that serves the seat list (ADR 0636 §4), the keeper's ask (design 47 G §387), the seat's running (§199) and the builder's build ends (A-293). - if want := []string{"mesh-catalog.catalog-revision", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", "mesh-conditions.findings-asked", "mesh-delivery-builder.build.ended.**", "mesh-delivery-view.settled", "mesh-recovery.ended", "mesh-recovery.restored", "node-engine.running", "restic.backed-up"}; !slices.Equal(m.Consumes, want) { + if want := []string{"mesh-catalog.catalog-revision", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", "mesh-conditions.findings-asked", "mesh-delivery-builder.build.ended.**", "mesh-delivery-view.settled", "mesh-recovery.ended", "mesh-recovery.restored", "node-engine.running", "node-packet-filter.allowances-changed", "restic.backed-up"}; !slices.Equal(m.Consumes, want) { t.Fatalf("consumes %v, want %v", m.Consumes, want) } // 774: the acts bucket mesh-host_acts is not declared as state for now: a declared state of a module with no account From 546e535375255c7991571e088418dd8ede9698df Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 21:06:29 +0100 Subject: [PATCH 3/7] Serve the node-engine seat's converged, and name a part a compose kept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The holder of node-packet-filter asks the node's convergence state before it allows a port, and never assumes converged: the engine answers it from its record, adopted or converged, since the mode last changed (now recorded with its time), and the found firewall's kind when adopted; a record with no mode is refused. The composition read of the filter's holder names, under withheld-parts, the part node-packet-filter.allowed with why when the last compose kept the filter file because allowed did not answer. Builds: design 33 control-verbs §10, §14; design 08 control-verbs §4, §8; ADR 0683, ADR 0168; H-A-316, H-A-321 --- cmd/mesh-host/engineseat.go | 22 +++++++++++++++++- cmd/mesh-host/main.go | 9 ++++---- cmd/mesh-host/ownname_test.go | 33 +++++++++++++++++++++++++++ cmd/mesh-host/seatlist.go | 23 +++++++++++++++++++ internal/agent/composition.go | 9 ++++++++ internal/bootstrap/apply.go | 5 ++-- internal/link/handacts.go | 10 ++++++++ internal/selfcompose/filter.go | 11 +++++---- internal/selfcompose/selfcompose.go | 5 ++-- internal/selfcompose/versions_test.go | 10 ++++++++ internal/store/store.go | 14 ++++++++++++ module.json | 3 ++- 12 files changed, 140 insertions(+), 14 deletions(-) diff --git a/cmd/mesh-host/engineseat.go b/cmd/mesh-host/engineseat.go index e0decefb..81914329 100644 --- a/cmd/mesh-host/engineseat.go +++ b/cmd/mesh-host/engineseat.go @@ -7,8 +7,10 @@ import ( "errors" "fmt" "log" + "maps" "os" "path/filepath" + "slices" "strings" "sync/atomic" "syscall" @@ -287,7 +289,8 @@ const compositionReadFor = 20 * time.Second // compositionFrom answers the verb composition from the node agent that runs now (issue 774); refused in words while // none does. -func compositionFrom(current *agentNow, withheld func(ctx context.Context, module string) ([]link.WithheldSubject, string)) func(module, digest string, diff bool) (any, error) { +func compositionFrom(current *agentNow, withheld func(ctx context.Context, module string) ([]link.WithheldSubject, string), + parts func(module string) map[string]string) func(module, digest string, diff bool) (any, error) { return func(module, digest string, diff bool) (any, error) { ag := current.get() if ag == nil { @@ -305,10 +308,27 @@ func compositionFrom(current *agentNow, withheld func(ctx context.Context, modul view.Withheld = append(view.Withheld, agent.WithheldView{Subject: s.Subject, Why: s.Why}) } view.WithheldUnknown = unknown + // And each part the last compose kept because its read did not answer (design 08 control-verbs §4, H-A-321). + if parts != nil { + kept := parts(module) + for _, part := range slices.Sorted(maps.Keys(kept)) { + view.WithheldParts = append(view.WithheldParts, agent.WithheldPartView{Part: part, Why: kept[part]}) + } + } return view, nil } } +// withheldPartsOf is, of the composer that runs now, each part its last pass kept for module because its read did not answer. +func withheldPartsOf(composer *atomic.Pointer[selfcompose.Composer]) func(module string) map[string]string { + return func(module string) map[string]string { + if c := composer.Load(); c != nil { + return c.LastWithheldParts(module) + } + return nil + } +} + // applyOrderFrom answers the verb apply-order from the node agent that runs now (design 47 H §771): the order it applies its changed // wants in, with why; refused in words while none does. func applyOrderFrom(current *agentNow) func() (any, error) { diff --git a/cmd/mesh-host/main.go b/cmd/mesh-host/main.go index fb0749f4..b04587d4 100644 --- a/cmd/mesh-host/main.go +++ b/cmd/mesh-host/main.go @@ -593,7 +593,7 @@ func runApply(ctx context.Context, opts options, d *declaration.Declaration, raw // What this apply settles about the node, whichever way it went. The mode is what the // declaration said and the check above agreed with; the bundle, once applied, is consumed. - updated.Mode = apply.ModeOf(d) + updated.SetMode(apply.ModeOf(d), time.Now()) if from == fromBundle { updated.Genesis = &store.Genesis{Digest: digest, At: time.Now().UTC()} } @@ -1027,7 +1027,7 @@ func runLink(ctx context.Context, opts options) error { queue.Acts = engineActs(opts, mine.Node, queue, setuidSearch) go reconcileActs(ctx, queue.Acts) current := &agentNow{} - queue.Acts.Composition = compositionFrom(current, queue.WithheldOf) + queue.Acts.Composition = compositionFrom(current, queue.WithheldOf, withheldPartsOf(&composerNow)) queue.Acts.Compose = composeFrom(current, &composerNow) queue.Acts.ApplyOrder = applyOrderFrom(current) queue.Acts.Packages = packagesFrom(mine.Node, queue, &composerNow) @@ -1045,6 +1045,7 @@ func runLink(ctx context.Context, opts options) error { defer cancel() return processbuilds.Reader{Node: mine.Node, Run: processbuilds.Runner(opts.run())}.Read(ctx, d, module), nil } + queue.Acts.Converged = func() (any, error) { return convergedOf(opts.state) } queue.Acts.ComposeCandidate = composeCandidateFrom(mine.Node, &shadowNow) setRunsHere(runsFromAgent(current)) factsOfNow := func(ctx context.Context, ag *agent.Agent) { @@ -1680,7 +1681,7 @@ func applyModuleHeld(ctx context.Context, opts options, declared *declaration.De if node && known.Mode != "" && known.Mode != apply.ModeOf(declared) { announceOr(say)(fmt.Sprintf("this node's record said %s; what the mesh last said, signed, says %s — the record is repaired", known.Mode, apply.ModeOf(declared))) - known.Mode = apply.ModeOf(declared) + known.SetMode(apply.ModeOf(declared), time.Now()) } // **A file given by digest is fetched and verified before anything of the composition is applied** (novox/hq ADR @@ -1721,7 +1722,7 @@ func applyModuleHeld(ctx context.Context, opts options, declared *declaration.De }, announceOr(say)) if node { - updated.Mode = apply.ModeOf(declared) + updated.SetMode(apply.ModeOf(declared), time.Now()) } // Root acted on what an agent account's judgement reads — an account, a package, an action, sudo's rules: the search diff --git a/cmd/mesh-host/ownname_test.go b/cmd/mesh-host/ownname_test.go index 4f23a005..bbbfd5a0 100644 --- a/cmd/mesh-host/ownname_test.go +++ b/cmd/mesh-host/ownname_test.go @@ -8,8 +8,10 @@ import ( "testing" "time" + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" "github.com/novox/mesh-host/internal/link" + "github.com/novox/mesh-host/internal/store" ) // Design 47 G §527, §634, A-149: the node-engine's own module is the module of its applied record at its own fingerprint, @@ -54,6 +56,37 @@ func TestTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testi case <-time.After(5 * time.Second): t.Fatal("the writer was never made after the name was known") } + + // Design 33 control-verbs §10, §14: the seat's verb converged answers the node's convergence state as the record keeps + // it, adopted with its found firewall's kind or converged, since its mode last changed; a record with no mode is refused. + t.Run("converged answers the record's convergence state", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + found := time.Date(2026, 10, 2, 9, 0, 0, 0, time.UTC) + st := store.State{Firewall: &store.FoundFirewall{Kind: "ufw", FoundAt: found}} + if err := store.Save(path, st); err != nil { + t.Fatal(err) + } + if got, err := convergedOf(path); err == nil { + t.Errorf("a record with no mode answers %+v, want refused", got) + } + st.SetMode(store.ModeAdopted, found) + st.SetMode(store.ModeAdopted, found.Add(time.Hour)) // said again: its time is kept + if err := store.Save(path, st); err != nil { + t.Fatal(err) + } + acts := &link.HandActs{Converged: func() (any, error) { return convergedOf(path) }} + if got, err := acts.Call(link.EngineCall{Verb: link.ActConverged}); err != nil || + got != (nodeengine.ConvergedAnswer{State: "adopted", Since: "2026-10-02T09:00:00Z", Found: "ufw"}) { + t.Errorf("an adopted node answers %+v, %v; want adopted since its adoption, found ufw", got, err) + } + st.SetMode(store.ModeConverged, found.Add(48*time.Hour)) + if err := store.Save(path, st); err != nil { + t.Fatal(err) + } + if got, err := convergedOf(path); err != nil || got != (nodeengine.ConvergedAnswer{State: "converged", Since: "2026-10-04T09:00:00Z"}) { + t.Errorf("a converged node answers %+v, %v; want converged since it converged, no found firewall", got, err) + } + }) } // Design 47 H, H-A-60: how often an entry whose ask failed is asked again is the file the manifest's `entry-asks` feeds, five when it diff --git a/cmd/mesh-host/seatlist.go b/cmd/mesh-host/seatlist.go index f5bae1eb..136aa5c6 100644 --- a/cmd/mesh-host/seatlist.go +++ b/cmd/mesh-host/seatlist.go @@ -13,6 +13,7 @@ import ( "sync/atomic" "time" + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" "git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/seatdef" @@ -21,6 +22,7 @@ import ( "github.com/novox/mesh-host/internal/link" "github.com/novox/mesh-host/internal/seatwait" "github.com/novox/mesh-host/internal/selfcompose" + "github.com/novox/mesh-host/internal/store" ) // The node-engine reads the seat list as every part does (novox/hq ADR 0635 §1, ADR 0636): through the seat mesh-catalog, @@ -335,3 +337,24 @@ func entryAsks() int { } return n } + +// convergedOf is the node's convergence state as this engine keeps it in its record at path (ADR 0168): the answer of the +// seat node-engine's verb converged (design 33 control-verbs §10). A record that says no mode yet is refused, so its asker +// never takes it for converged. +func convergedOf(path string) (nodeengine.ConvergedAnswer, error) { + st, err := store.Load(path) + if err != nil { + return nodeengine.ConvergedAnswer{}, err + } + if st.Mode != store.ModeAdopted && st.Mode != store.ModeConverged { + return nodeengine.ConvergedAnswer{}, errors.New("this node's record says no mode yet: no declaration has said it adopted or converged") + } + out := nodeengine.ConvergedAnswer{State: st.Mode} + if st.ModeSince != nil { + out.Since = st.ModeSince.UTC().Format(time.RFC3339) + } + if st.Mode == store.ModeAdopted && st.Firewall != nil { + out.Found = st.Firewall.Kind + } + return out, nil +} diff --git a/internal/agent/composition.go b/internal/agent/composition.go index 16c78b3f..b80a2891 100644 --- a/internal/agent/composition.go +++ b/internal/agent/composition.go @@ -52,6 +52,15 @@ type CompositionView struct { // mark §6, lead answer A-239). Withheld []WithheldView `json:"withheld,omitempty"` WithheldUnknown string `json:"withheld-unknown,omitempty"` + // WithheldParts are the parts a compose kept because its read did not answer, each with why (design 08 control-verbs §4, + // H-A-321): for the packet filter's holder the part node-packet-filter.allowed, its filter file kept as it runs. + WithheldParts []WithheldPartView `json:"withheld-parts,omitempty"` +} + +// WithheldPartView is one part a compose kept because its read did not answer, and why. +type WithheldPartView struct { + Part string `json:"part"` + Why string `json:"why"` } // WithheldView is one marked subject withheld, and why. diff --git a/internal/bootstrap/apply.go b/internal/bootstrap/apply.go index f056c6d2..b9c1c218 100644 --- a/internal/bootstrap/apply.go +++ b/internal/bootstrap/apply.go @@ -81,10 +81,11 @@ func ApplyBundle(ctx context.Context, o Options, sys system.System, d *declarati // been flipped. updated.Genesis = &store.Genesis{Digest: apply.DigestOf(raw), At: time.Now().UTC(), Rewritten: true} if updated.Mode == "" { - updated.Mode = store.ModeConverged + mode := store.ModeConverged if o.Adopted { - updated.Mode = store.ModeAdopted + mode = store.ModeAdopted } + updated.SetMode(mode, time.Now()) } // Saved whichever way it went, for the reason `mesh-host` gives: what was applied before a diff --git a/internal/link/handacts.go b/internal/link/handacts.go index 3e0f0706..d902eb3f 100644 --- a/internal/link/handacts.go +++ b/internal/link/handacts.go @@ -68,6 +68,9 @@ const ( // ActProcessBuilds reads the build each process on this node was started with (design 47, *The fingerprint handover*); // it reads only; who may call it is the seat definition's (design 47 G §440, §447). ActProcessBuilds = nodeengine.VerbProcessBuilds + // ActConverged reads the node's convergence state: adopted or converged, since when, the found firewall's kind when + // adopted (design 33 control-verbs §10); read-only. + ActConverged = nodeengine.VerbConverged ) // The states of an act: asked, done and refused are also the seat's events. @@ -177,6 +180,8 @@ type HandActs struct { ApplyOrder func() (any, error) // ProcessBuilds answers the build each process of the node was started with, narrowed to a module when one is given. ProcessBuilds func(module string) (any, error) + // Converged answers the verb converged: the node's convergence state as the engine keeps it (design 33 control-verbs §10). + Converged func() (any, error) // ComposeCandidate composes a check's candidate (the indexer's candidate key) on this node in shadow and answers per // module, applying and writing nothing; with input, also the composition input it composed from (the verb // compose-candidate, ADR 0593 §7). @@ -278,6 +283,11 @@ func (h *HandActs) Call(c EngineCall) (any, error) { return nil, errors.New("this engine reads no process yet: its node agent has not started") } return h.ProcessBuilds(arg("module")) + case ActConverged: + if h.Converged == nil { + return nil, errors.New("this engine reads no convergence state yet: its node agent has not started") + } + return h.Converged() case ActSeatListAgain: if h.SeatListAgain == nil { return nil, errors.New("this engine reads no seat list yet: its node agent has not started") diff --git a/internal/selfcompose/filter.go b/internal/selfcompose/filter.go index 71b8e6ca..d24a5d24 100644 --- a/internal/selfcompose/filter.go +++ b/internal/selfcompose/filter.go @@ -74,6 +74,9 @@ func (c *Composer) filterOf(ctx context.Context, own meshmoduleassigner.Assignme func (c *Composer) holdsFilter(ctx context.Context, own meshmoduleassigner.Assignments) bool { for _, m := range own.Modules { if claims, known := c.Claims(ctx, m.Module, nodepacketfilter.Seat); claims && known { + c.mu.Lock() + c.filterHolder = m.Module + c.mu.Unlock() return true } } @@ -101,12 +104,12 @@ func notAnAllowance(allowances []nodepacketfilter.Allowance) string { return "" } -// LastWithheldParts is each part the last pass kept because its read did not answer, with why (H-A-321): the filter's -// allowed, named AllowedPart. Nil when none. -func (c *Composer) LastWithheldParts() map[string]string { +// LastWithheldParts is each part the last pass kept of module because its read did not answer, with why (H-A-321): of the +// holder of node-packet-filter, the filter's allowed, named AllowedPart. Nil when none. +func (c *Composer) LastWithheldParts(module string) map[string]string { c.mu.Lock() defer c.mu.Unlock() - if c.filter.Withheld == "" { + if c.filter.Withheld == "" || module != c.filterHolder { return nil } return map[string]string{AllowedPart: c.filter.Withheld} diff --git a/internal/selfcompose/selfcompose.go b/internal/selfcompose/selfcompose.go index 8ac1fbce..f177fd83 100644 --- a/internal/selfcompose/selfcompose.go +++ b/internal/selfcompose/selfcompose.go @@ -339,8 +339,9 @@ type Composer struct { // filter is what the last pass's compose of the packet filter was given (filterOf), which a candidate composed in shadow // is given too; allowedSaid says its withheld allowed was said in the journal, until it answers (design 08 // control-verbs §4). Guarded by mu. - filter resolution.Filter - allowedSaid bool + filter resolution.Filter + filterHolder string + allowedSaid bool } // Pass is how one pass went, as the node-engine's verb compose answers it. diff --git a/internal/selfcompose/versions_test.go b/internal/selfcompose/versions_test.go index 26b4cbed..76cf4bf8 100644 --- a/internal/selfcompose/versions_test.go +++ b/internal/selfcompose/versions_test.go @@ -171,6 +171,16 @@ func TestAModulesClaimsAreReadFromTheEntryOfItsWantsBuild(t *testing.T) { if got = c.filterOf(context.Background(), own); !strings.Contains(got.Withheld, `answered what is not its answer: allow.tcp.8000 has the until "tomorrow"`) { t.Errorf("an answer that is not allowed's gives %+v, want the part withheld", got) } + // H-A-321: the composition read of the holder names the part kept, and of another module none. + c.mu.Lock() + c.filter = got + c.mu.Unlock() + if parts := c.LastWithheldParts("nft"); len(parts) != 1 || parts[AllowedPart] != got.Withheld || AllowedPart != "node-packet-filter.allowed" { + t.Errorf("the holder's withheld parts are %v, want node-packet-filter.allowed with its why", parts) + } + if parts := c.LastWithheldParts("web"); parts != nil { + t.Errorf("another module's withheld parts are %v, want none", parts) + } if n := strings.Count(strings.Join(said, "\n"), "is withheld"); n != 1 { t.Errorf("the withheld part is said %d times over three unanswered composes, want once:\n%s", n, strings.Join(said, "\n")) } diff --git a/internal/store/store.go b/internal/store/store.go index 892f5c04..105c86c5 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -221,6 +221,9 @@ type State struct { // the mesh sends and at genesis from what the operator said, so a declaration that says the // other mode can be refused before it is applied (novox/hq issue 104). Mode string `json:"mode,omitempty"` + // ModeSince is when Mode last became what it is (SetMode): the node's convergence state the seat node-engine's verb + // converged answers (ADR 0168, design 33 control-verbs §10). Nil where no change of mode was recorded with its time. + ModeSince *time.Time `json:"mode_since,omitempty"` // FoundFirst is, by resource id, what a service's unit was found as by an apply of it that did // not finish — kept apart from Resources, because a record follows the fact and this apply's @@ -319,6 +322,17 @@ type Retired struct { Again int `json:"again,omitempty"` } +// SetMode records the node's mode, and when it became so when it changes (design 33 control-verbs §10); a mode said again +// keeps its time. +func (s *State) SetMode(mode string, at time.Time) { + if s.Mode == mode { + return + } + s.Mode = mode + at = at.UTC() + s.ModeSince = &at +} + // Modes a node can be in (novox/hq ADR 0100). const ( ModeAdopted = "adopted" diff --git a/module.json b/module.json index aeef6d1d..8f6929b1 100644 --- a/module.json +++ b/module.json @@ -36,7 +36,8 @@ "first-views", "first-view-again", "entry-again", - "process-builds" + "process-builds", + "converged" ] } ], From f642077720dccf149d49b7f478d9868b20e03cca Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 21:12:52 +0100 Subject: [PATCH 4/7] Keep an allowance with no interface off the outward links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An allowance of the default set opened every link but the tunnel, so a node's internet-facing link took it too. It now negates the tunnel and every outward link, the same links the derived rules count as outside; an outward link opens only when an allowance names it. Builds: design 08 control-verbs §2, §8; design 47 H lead answer H-A-324 --- internal/compose/resolution/filtering.go | 9 +++++--- internal/compose/resolution/filtering_test.go | 23 +++++++++++++------ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/internal/compose/resolution/filtering.go b/internal/compose/resolution/filtering.go index fb9639e2..7d244245 100644 --- a/internal/compose/resolution/filtering.go +++ b/internal/compose/resolution/filtering.go @@ -201,7 +201,8 @@ type Allowing struct { // AsNftablesAllowing is AsNftablesWithLocal with the allowances the holder answered (design 08 control-verbs §2): one accept // rule per allowance in the input chain, after the derived ports' rules and before the chain's drop policy, each with the // comment `allowance `. Its interface by name, or for the default set a negated match on the private network's -// interface (tunnel), so an interface that comes up later is covered and the tunnel never is; its source when it has one, +// interface (tunnel) and the outward links (H-A-324), so an interface that comes up later is covered and neither the tunnel +// nor an outward link ever is; an outward link is opened only when named; its source when it has one, // for the family of its CIDR. An allowance with an until matches its port as the one element of a set of the table with // the timeout flag, the element's timeout the time left to its until at allowing.At, at least 1 s, so the kernel closes the // port at its until even while the holder is away (H-A-315 (4)). The forward chain takes none: an allowance opens the input @@ -419,8 +420,10 @@ func AsNftablesAllowing(rules []mcat.Rule, mesh []string, outward bool, foundati switch { case a.Interface != "": match = append(match, fmt.Sprintf("iifname %q", a.Interface)) - case tunnel != "": - match = append(match, fmt.Sprintf("iifname != %q", tunnel)) + case inward != "": + // No interface: every input interface that is neither the private network's tunnel nor an outward link, the + // links the derived rules count as outside (H-A-324); an outward link is opened only when named. + match = append(match, fmt.Sprintf("iifname != { %s }", inward)) } if a.Source != "" { family := "ip" diff --git a/internal/compose/resolution/filtering_test.go b/internal/compose/resolution/filtering_test.go index 44ee2970..8450a0b4 100644 --- a/internal/compose/resolution/filtering_test.go +++ b/internal/compose/resolution/filtering_test.go @@ -133,14 +133,23 @@ func TestTheModuleAskingForTheRuleSetGetsEveryModulesPorts(t *testing.T) { if none, today := render(), AsNftablesWithLocal(derived, []string{"10.10.0.1"}, false, nil, []string{"eth0"}, "mesh0", nil); none != today { t.Errorf("no allowance changed the file:\n%s\nwant\n%s", none, today) } - // 08 control-verbs §8: one of the default set, a negated match on the private network's interface and no positive one. + // 08 control-verbs §8, H-A-324: one of the default set, a negated match on the private network's interface and the outward + // links, and no positive one. one := render(nodepacketfilter.Allowance{Key: "allow.tcp.8000", Port: 8000, Protocol: "tcp", At: "2026-11-21T19:00:00Z"}) - if want := "\t\tiifname != \"mesh0\" tcp dport 8000 accept comment \"allowance allow.tcp.8000 2026-11-21T19:00:00Z\"\n"; !strings.Contains(inputOf(one), want) { + if want := "\t\tiifname != { \"eth0\", \"mesh0\" } tcp dport 8000 accept comment \"allowance allow.tcp.8000 2026-11-21T19:00:00Z\"\n"; !strings.Contains(inputOf(one), want) { t.Errorf("the default set's allowance is not rendered as %q:\n%s", want, one) } if strings.Contains(one, "iifname \"mesh0\" tcp dport 8000") || strings.Contains(one, "proto-dst 8000") { t.Errorf("the allowance opens the tunnel or the forward path:\n%s", one) } + // H-A-324: an allowance with no interface never opens an outward link; one named in interfaces does. + if strings.Contains(inputOf(one), "iifname \"eth0\" tcp dport 8000") { + t.Errorf("the default set's allowance opens the outward link:\n%s", one) + } + named := render(nodepacketfilter.Allowance{Key: "allow.tcp.8000.eth0", Port: 8000, Protocol: "tcp", Interface: "eth0", At: "a1"}) + if want := "\t\tiifname \"eth0\" tcp dport 8000 accept comment \"allowance allow.tcp.8000.eth0 a1\"\n"; !strings.Contains(inputOf(named), want) { + t.Errorf("the named outward link's allowance is not rendered as %q:\n%s", want, named) + } // 08 control-verbs §8: three, one interface named, one with an IPv4 source, one udp, after the derived ones. three := inputOf(render( nodepacketfilter.Allowance{Key: "allow.udp.5353", Port: 5353, Protocol: "udp", At: "a3"}, @@ -151,8 +160,8 @@ func TestTheModuleAskingForTheRuleSetGetsEveryModulesPorts(t *testing.T) { last := derivedAt for _, want := range []string{ "\t\tiifname \"enp3s0\" tcp dport 8000 accept comment \"allowance allow.tcp.8000.enp3s0 a1\"\n", - "\t\tiifname != \"mesh0\" ip saddr 192.168.1.0/24 tcp dport 9000 accept comment \"allowance allow.tcp.9000 a2\"\n", - "\t\tiifname != \"mesh0\" udp dport 5353 accept comment \"allowance allow.udp.5353 a3\"\n", + "\t\tiifname != { \"eth0\", \"mesh0\" } ip saddr 192.168.1.0/24 tcp dport 9000 accept comment \"allowance allow.tcp.9000 a2\"\n", + "\t\tiifname != { \"eth0\", \"mesh0\" } udp dport 5353 accept comment \"allowance allow.udp.5353 a3\"\n", } { at := strings.Index(three, want) if at < 0 || at < last { @@ -170,9 +179,9 @@ func TestTheModuleAskingForTheRuleSetGetsEveryModulesPorts(t *testing.T) { for _, want := range []string{ "\tset allowance_1 {\n\t\ttype inet_service\n\t\tflags timeout\n\t\telements = { 8000 timeout 3600s }\n\t}\n", "\tset allowance_2 {\n\t\ttype inet_service\n\t\tflags timeout\n\t\telements = { 8001 timeout 1s }\n\t}\n", - "\t\tiifname != \"mesh0\" tcp dport @allowance_1 accept comment \"allowance allow.tcp.8000 a1\"\n", - "\t\tiifname != \"mesh0\" tcp dport @allowance_2 accept comment \"allowance allow.tcp.8001 a2\"\n", - "\t\tiifname != \"mesh0\" ip6 saddr 2001:db8::/32 tcp dport 8002 accept comment \"allowance allow.tcp.8002 a3\"\n", + "\t\tiifname != { \"eth0\", \"mesh0\" } tcp dport @allowance_1 accept comment \"allowance allow.tcp.8000 a1\"\n", + "\t\tiifname != { \"eth0\", \"mesh0\" } tcp dport @allowance_2 accept comment \"allowance allow.tcp.8001 a2\"\n", + "\t\tiifname != { \"eth0\", \"mesh0\" } ip6 saddr 2001:db8::/32 tcp dport 8002 accept comment \"allowance allow.tcp.8002 a3\"\n", } { if !strings.Contains(until, want) { t.Errorf("the rule set lacks %q:\n%s", want, until) From f11be5d529e590797672513264ce0a478ed13922 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 21:16:52 +0100 Subject: [PATCH 5/7] Answer the node's links in the node-engine seat's converged MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The holder of node-packet-filter says when an allowance opens an outward link and reads no shape of the loaded table to know one, so converged answers the tunnel's interface and the outward links from the one classification the filter render uses; links it cannot read refuse it. Builds: design 33 control-verbs §10, §14; design 08 control-verbs §2; design 47 H H-A-325 --- cmd/mesh-host/main.go | 4 +++- cmd/mesh-host/ownname_test.go | 22 ++++++++++++++++++---- cmd/mesh-host/seatlist.go | 14 +++++++++++--- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/cmd/mesh-host/main.go b/cmd/mesh-host/main.go index b04587d4..0651e1e5 100644 --- a/cmd/mesh-host/main.go +++ b/cmd/mesh-host/main.go @@ -1045,7 +1045,9 @@ func runLink(ctx context.Context, opts options) error { defer cancel() return processbuilds.Reader{Node: mine.Node, Run: processbuilds.Runner(opts.run())}.Read(ctx, d, module), nil } - queue.Acts.Converged = func() (any, error) { return convergedOf(opts.state) } + queue.Acts.Converged = func() (any, error) { + return convergedOf(opts.state, func() ([]string, error) { return outward.Links("", "") }) + } queue.Acts.ComposeCandidate = composeCandidateFrom(mine.Node, &shadowNow) setRunsHere(runsFromAgent(current)) factsOfNow := func(ctx context.Context, ag *agent.Agent) { diff --git a/cmd/mesh-host/ownname_test.go b/cmd/mesh-host/ownname_test.go index bbbfd5a0..7f64d064 100644 --- a/cmd/mesh-host/ownname_test.go +++ b/cmd/mesh-host/ownname_test.go @@ -2,14 +2,17 @@ package main import ( "context" + "errors" "os" "path/filepath" + "reflect" "strings" "testing" "time" "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" + "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay" "github.com/novox/mesh-host/internal/link" "github.com/novox/mesh-host/internal/store" ) @@ -59,14 +62,17 @@ func TestTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testi // Design 33 control-verbs §10, §14: the seat's verb converged answers the node's convergence state as the record keeps // it, adopted with its found firewall's kind or converged, since its mode last changed; a record with no mode is refused. + // H-A-325: it answers too the tunnel and the outward links as the engine classifies them for its render; links it cannot + // read refuse it. t.Run("converged answers the record's convergence state", func(t *testing.T) { + links := func() ([]string, error) { return []string{"eth1"}, nil } path := filepath.Join(t.TempDir(), "state.json") found := time.Date(2026, 10, 2, 9, 0, 0, 0, time.UTC) st := store.State{Firewall: &store.FoundFirewall{Kind: "ufw", FoundAt: found}} if err := store.Save(path, st); err != nil { t.Fatal(err) } - if got, err := convergedOf(path); err == nil { + if got, err := convergedOf(path, links); err == nil { t.Errorf("a record with no mode answers %+v, want refused", got) } st.SetMode(store.ModeAdopted, found) @@ -74,18 +80,26 @@ func TestTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testi if err := store.Save(path, st); err != nil { t.Fatal(err) } - acts := &link.HandActs{Converged: func() (any, error) { return convergedOf(path) }} + acts := &link.HandActs{Converged: func() (any, error) { return convergedOf(path, links) }} if got, err := acts.Call(link.EngineCall{Verb: link.ActConverged}); err != nil || - got != (nodeengine.ConvergedAnswer{State: "adopted", Since: "2026-10-02T09:00:00Z", Found: "ufw"}) { + !reflect.DeepEqual(got, nodeengine.ConvergedAnswer{State: "adopted", Since: "2026-10-02T09:00:00Z", Found: "ufw", + Tunnel: overlay.Interface, Outward: []string{"eth1"}}) { t.Errorf("an adopted node answers %+v, %v; want adopted since its adoption, found ufw", got, err) } st.SetMode(store.ModeConverged, found.Add(48*time.Hour)) if err := store.Save(path, st); err != nil { t.Fatal(err) } - if got, err := convergedOf(path); err != nil || got != (nodeengine.ConvergedAnswer{State: "converged", Since: "2026-10-04T09:00:00Z"}) { + if got, err := convergedOf(path, links); err != nil || !reflect.DeepEqual(got, nodeengine.ConvergedAnswer{State: "converged", + Since: "2026-10-04T09:00:00Z", Tunnel: overlay.Interface, Outward: []string{"eth1"}}) { t.Errorf("a converged node answers %+v, %v; want converged since it converged, no found firewall", got, err) } + if got, err := convergedOf(path, func() ([]string, error) { return nil, nil }); err != nil || got.Outward == nil { + t.Errorf("a node with no outward link answers %+v, %v; want an empty list, never null", got, err) + } + if got, err := convergedOf(path, func() ([]string, error) { return nil, errors.New("no /proc") }); err == nil { + t.Errorf("links that cannot be read answer %+v, want refused", got) + } }) } diff --git a/cmd/mesh-host/seatlist.go b/cmd/mesh-host/seatlist.go index 136aa5c6..761ffb30 100644 --- a/cmd/mesh-host/seatlist.go +++ b/cmd/mesh-host/seatlist.go @@ -15,6 +15,7 @@ import ( "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" + "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay" "git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/seatdef" "git.novox.be/novox/mesh-sdk/go/seatlist" @@ -340,8 +341,11 @@ func entryAsks() int { // convergedOf is the node's convergence state as this engine keeps it in its record at path (ADR 0168): the answer of the // seat node-engine's verb converged (design 33 control-verbs §10). A record that says no mode yet is refused, so its asker -// never takes it for converged. -func convergedOf(path string) (nodeengine.ConvergedAnswer, error) { +// never takes it for converged. It answers too the node's links as this engine classifies them for its filter render +// (design 08 control-verbs §2, H-A-325): the private network's tunnel interface and the outward links that links reads, the +// same reading the engine reports for the render (outward.Links); a machine that cannot read them is refused, never +// answered with none. +func convergedOf(path string, links func() ([]string, error)) (nodeengine.ConvergedAnswer, error) { st, err := store.Load(path) if err != nil { return nodeengine.ConvergedAnswer{}, err @@ -349,7 +353,11 @@ func convergedOf(path string) (nodeengine.ConvergedAnswer, error) { if st.Mode != store.ModeAdopted && st.Mode != store.ModeConverged { return nodeengine.ConvergedAnswer{}, errors.New("this node's record says no mode yet: no declaration has said it adopted or converged") } - out := nodeengine.ConvergedAnswer{State: st.Mode} + outward, err := links() + if err != nil { + return nodeengine.ConvergedAnswer{}, fmt.Errorf("could not read which links face outside: %w", err) + } + out := nodeengine.ConvergedAnswer{State: st.Mode, Tunnel: overlay.Interface, Outward: append([]string{}, outward...)} if st.ModeSince != nil { out.Since = st.ModeSince.UTC().Format(time.RFC3339) } From d0129d08ae17b7397ea31d7f6522ea6ca53e8d31 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 21:38:20 +0100 Subject: [PATCH 6/7] Grant the node-engine the subscription to its allowances-changed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 1 (5): the node grant's stored copy had the allowed call subjects but not the event the engine consumes, which the grants part grants every machine's as a wildcard; the subtest of allowances-changed now checks the grant covers the node's subject. Builds: design 08 control-verbs §1, §3 --- internal/nodegrant/testdata/node.json | 3 ++- internal/selfcompose/versions_test.go | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/internal/nodegrant/testdata/node.json b/internal/nodegrant/testdata/node.json index d6b315e8..e31dcc1c 100644 --- a/internal/nodegrant/testdata/node.json +++ b/internal/nodegrant/testdata/node.json @@ -162,7 +162,8 @@ "mesh.seat.mesh-catalog.event.seat-definition-changed", "mesh.seat.mesh-catalog.event.seat-definition-removed", "mesh.seat.node-engine.call.*.NODE.*", - "mesh.seat.node-engine.tool.*.NODE" + "mesh.seat.node-engine.tool.*.NODE", + "mesh.seat.node-packet-filter.event.allowances-changed.*" ], "AllowResponses": true } diff --git a/internal/selfcompose/versions_test.go b/internal/selfcompose/versions_test.go index 76cf4bf8..9b2fa862 100644 --- a/internal/selfcompose/versions_test.go +++ b/internal/selfcompose/versions_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/novox/mesh-host/internal/agent" + "github.com/novox/mesh-host/internal/nodegrant" "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" @@ -248,6 +249,14 @@ func TestAModulesClaimsAreReadFromTheEntryOfItsWantsBuild(t *testing.T) { if own == nil || other != nil { t.Fatalf("heard %v, want the own node's allowances-changed and no other's", heard) } + // And the node's grant lets it subscribe there, as the grants part grants the consume (every machine's, as `*`). + granted := false + for _, f := range nodegrant.For("n1").Subscribe { + granted = granted || subjectCovers(f, nodepacketfilter.SubjectAllowancesChanged("n1")) + } + if !granted { + t.Errorf("the node's grant does not let it subscribe to %s", nodepacketfilter.SubjectAllowancesChanged("n1")) + } select { case own <- []byte(`{"node":"n1","change":"allowed"}`): case <-time.After(10 * time.Second): @@ -359,3 +368,17 @@ type storeAway struct{} func (storeAway) Error() string { return "artifact-store answered 503 Service Unavailable" } func (storeAway) StoreAnswered() bool { return false } + +// subjectCovers says whether the subject filter f matches the subject s, by NATS's wildcards (* one token, > the rest). +func subjectCovers(f, s string) bool { + ft, st := strings.Split(f, "."), strings.Split(s, ".") + for i, t := range ft { + if t == ">" { + return i < len(st) + } + if i >= len(st) || (t != "*" && t != st[i]) { + return false + } + } + return len(ft) == len(st) +} From 3991d531bff6596c582e0296cc9cb37b05099336 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 22:25:33 +0100 Subject: [PATCH 7/7] Order the ghost's entry case and end the first shadow before its setting changes Review round 2 (2), fix-a-bug-met-twice: the ghost's entry was answered at once, so a pass could read it entry-missing before the assertion read entry-asked; its answer now waits until the assertion has read. The 250 ms real sleep before compose now is gone: askedWithin is set to none, then to an hour for the ask made again at once. The first shadow ran on while notReadyAfter was set for the next step, a data race; it is ended first. Builds: design 47 H H-A-312 --- internal/selfcompose/selfcompose_test.go | 29 ++++++++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/internal/selfcompose/selfcompose_test.go b/internal/selfcompose/selfcompose_test.go index 3f262b55..ed6c9be8 100644 --- a/internal/selfcompose/selfcompose_test.go +++ b/internal/selfcompose/selfcompose_test.go @@ -237,7 +237,20 @@ func TestTheNodeComposesItsWantsFromTheBus(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() env := b.env() - env.Entry = half.call() + // The ghost's entry (issue 1966's step below) is answered only once that step has read it as asked: answered at once, + // a pass could read it as entry-missing before the assertion (review round 2; the race H-A-303's review saw too). + ghostFp := meshcatalogclient.SourcePrefix2 + strings.Repeat("8", 64) + ghostRead := make(chan struct{}) + var ghostOnce sync.Once + readGhost := func() { ghostOnce.Do(func() { close(ghostRead) }) } + defer readGhost() + entry := half.call() + env.Entry = func(key string, body any) (json.RawMessage, error) { + if in, ok := body.(meshcatalog.EntryInput); ok && in.Fingerprint == ghostFp { + <-ghostRead + } + return entry(key, body) + } // The vault's own: keeper's password sealed to n1's key, sealed again (other bytes) at every ask. var asks, generation int sealedAt := map[string]int{} // each box handed, by the generation it opens to @@ -339,9 +352,9 @@ func TestTheNodeComposesItsWantsFromTheBus(t *testing.T) { b.mu.Unlock() // Issue 774, 2026-10-31: the verb compose makes a pass now and says how it went; a composer that runs no watch // makes none, and says so rather than waiting. - // The pass made at the start is less than askedWithin old for a moment: the ask waits that out first. - setFor(t, &askedWithin, 200*time.Millisecond) - time.Sleep(250 * time.Millisecond) + // The pass made at the start is the answer while it is less than askedWithin old: with none counted recent, the ask + // makes a pass (no real wait for the start's pass to age, review round 2). + setFor(t, &askedWithin, 0) madeBefore := composed.Load() cctx, ccancel := context.WithTimeout(ctx, 5*time.Second) nowPass, err := c.ComposeNow(cctx) @@ -350,6 +363,7 @@ func TestTheNodeComposesItsWantsFromTheBus(t *testing.T) { t.Errorf("compose now: %+v (%v), %d pass(es) made; want one pass, composed", nowPass, err, composed.Load()-madeBefore) } // Asked again at once, the last pass is the answer: a caller in a loop drives no passes back to back (review round 1). + setFor(t, &askedWithin, time.Hour) madeBefore = composed.Load() if again, err := c.ComposeNow(ctx); err != nil || !again.Earlier || !again.At.Equal(nowPass.At) || composed.Load() != madeBefore { t.Errorf("compose now asked again at once: %+v (%v), %d pass(es) made; want the last pass, none made", again, err, composed.Load()-madeBefore) @@ -371,7 +385,7 @@ func TestTheNodeComposesItsWantsFromTheBus(t *testing.T) { // Issue 1966 (novox, 2026-11-09): every pass names each wanted module it composed nothing of, or composed from the indexer's // manifest for want of a done build, with why, and a want it did not take; said once; the agent's word that it waits // hands a composition the node believes handed again. - tfp, ghostFp := toolFp, meshcatalogclient.SourcePrefix2+strings.Repeat("8", 64) + tfp := toolFp c.holdEntry(t, "tool", tfp, toolBody) for module, w := range map[string]meshwants.WantsByWantNodeModuleValue{"tool": {Fp: tfp, Self: true}, "ghost": {Fp: ghostFp, Self: true}, "nofp": {Self: true}} { raw, _ := bucketstest.Want(w) @@ -399,6 +413,7 @@ func TestTheNodeComposesItsWantsFromTheBus(t *testing.T) { !strings.Contains(why["nofp"], "want not taken: its want names no fingerprint") || why["lemurs"] != "" { t.Errorf("the pass says it composed nothing of %q", why) } + readGhost() c.compose(ctx) if n := said("the node composes nothing of nofp"); n != saidOfNofp || n == 0 { t.Errorf("the journal says why nofp is not composed %d times after the second pass, %d after the first: want the same, not none", n, saidOfNofp) @@ -1432,6 +1447,10 @@ func TestTheNodeComposesItsWantsFromTheBus(t *testing.T) { return !ok && len(a) == 7 }) + // The shadow ends here: its tries read notReadyAfter, which the step below sets (review round 2, the race detector). + scancel() + <-kept + // Issue 1126, A7 AC1: a assignment that cannot be read composes nothing and says why; the node never applies a // composition made elsewhere instead. (A assignment read without the node's key composes nothing either: above.) {