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