Files
mesh-catalog/modules/mesh-vault/cmd/mesh-vault/licencebindings_test.go
T
jschoubben 51a83ed3a8 mesh-vault, claude-code: consume binding.changed.<consumer>, so binding moves are heard
The licence manager says each binding change as binding.changed.<consumer>
(mesh.mod.claude-licence-manager.event.binding.changed.<consumer>), but both
manifests consumed claude-licence-manager.binding.changed, which the grants part
composes into the exact filter mesh.mod.claude-licence-manager.event.binding.changed:
the bus consumer never handed either module one change, and the vault kept only its
first view (2026-11-20: g14 refused a switched licence's token until the first view
was asked again by hand). The consumed pattern now names the further part, `*`.

Builds: design 47 G A-134; design 39 bus-and-switch §17, §19, §22
2026-11-20 15:09:45 +01:00

245 lines
9.4 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"slices"
"sort"
"sync"
"testing"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/views"
)
// memLicenceBindings is the state licence-bindings in memory.
func memLicenceBindings() (LicenceBindings, map[string]LicenceBinding) {
held := map[string]LicenceBinding{}
return LicenceBindings{
Get: func(c string) (*LicenceBinding, error) {
if b, ok := held[c]; ok {
return &b, nil
}
return nil, nil
},
Put: func(c string, b LicenceBinding) error { held[c] = b; return nil },
Delete: func(c string) error { delete(held, c); return nil },
Keys: func() ([]string, error) {
var out []string
for c := range held {
out = append(out, c)
}
sort.Strings(out)
return out, nil
},
Log: func(string, ...any) {},
}, held
}
// design 39 bus-and-switch §17, B22, B25: the vault keeps a consumer's binding from binding.changed, decoded from a copy
// of the manager's form, with the licence's key; an older generation is passed over and a release deletes the key.
func TestALicenceBindingIsKeptFromBindingChanged(t *testing.T) {
lb, held := memLicenceBindings()
said, err := os.ReadFile("testdata/binding-changed.json")
if err != nil {
t.Fatal(err)
}
if err := lb.Heard(said); err != nil {
t.Fatal(err)
}
if b := held["laptop"]; b != (LicenceBinding{Licence: "api", Key: "api", Generation: 3}) {
t.Fatalf("laptop is kept as %+v", b)
}
for _, c := range []struct {
body string
want *LicenceBinding
}{
{`{"consumer":"laptop","licence":"other","key":"other","generation":2}`, &LicenceBinding{Licence: "api", Key: "api", Generation: 3}},
{`{"consumer":"laptop","licence":"other","key":"other","generation":4}`, &LicenceBinding{Licence: "other", Key: "other", Generation: 4}},
{`{"consumer":"laptop","licence":"","key":"","generation":4,"from":"other"}`, nil},
} {
if err := lb.Heard([]byte(c.body)); err != nil {
t.Fatal(err)
}
got, ok := held["laptop"]
if (c.want == nil) != !ok || (c.want != nil && got != *c.want) {
t.Fatalf("after %s laptop is kept as %+v (held %v), want %+v", c.body, got, ok, c.want)
}
}
if err := lb.Heard([]byte(`{"consumer":"server","licence":"api","generation":5}`)); err == nil {
t.Fatal("a binding without its licence's key was kept")
}
}
// design 39 bus-and-switch §17, B10, B25: the first view, the seat's answer to bindings, keeps every consumer's binding
// with its key and deletes a consumer it does not name; the vault invokes the verb and consumes the event its manifest
// names.
func TestTheFirstViewOfTheLicenceBindingsIsKept(t *testing.T) {
lb, held := memLicenceBindings()
held["gone"] = LicenceBinding{Licence: "api", Key: "api", Generation: 9}
raw, err := os.ReadFile("testdata/bindings-answer.json")
if err != nil {
t.Fatal(err)
}
a, err := licenceBindingsAnswer(raw)
if err != nil {
t.Fatal(err)
}
if err := lb.FirstView(a.Values, time.Time{}); err != nil {
t.Fatal(err)
}
want := map[string]LicenceBinding{"laptop": {Licence: "acct-1@example.org", Key: "acct-1_at_example.org", Generation: 1013},
"server": {Licence: "api", Key: "api", Generation: 1016}}
if len(held) != 2 || held["laptop"] != want["laptop"] || held["server"] != want["server"] {
t.Fatalf("the first view kept %v", held)
}
if _, err := licenceBindingsAnswer([]byte(`[{"consumer":"laptop","licence":"api","generation":1}]`)); err == nil {
t.Fatal("an answer without a licence's key was taken")
}
lb.Put = func(string, LicenceBinding) error { return errors.New("the bucket is full") }
held["laptop"] = LicenceBinding{Licence: "api", Key: "api", Generation: 1}
if err := lb.FirstView(a.Values, time.Time{}); err == nil {
t.Fatal("a first view not kept was not said")
}
// B43: a key an event wrote after the view was asked is kept though the view does not name it; one written before
// the ask and not named goes.
lb, held = memLicenceBindings()
asked := time.Date(2026, 11, 12, 1, 0, 0, 0, time.UTC)
written := map[string]time.Time{"late": asked.Add(time.Second), "gone": asked.Add(-time.Second)}
lb.WrittenAt = func(c string) (time.Time, error) { return written[c], nil }
held["late"] = LicenceBinding{Licence: "api", Key: "api", Generation: 2000}
held["gone"] = LicenceBinding{Licence: "api", Key: "api", Generation: 9}
if err := lb.FirstView(a.Values, asked); err != nil {
t.Fatal(err)
}
if _, ok := held["late"]; !ok {
t.Error("a key an event wrote after the first view was asked was removed by it")
}
if _, ok := held["gone"]; ok {
t.Error("a key written before the first view was asked, which it does not name, was kept")
}
manifest, _ := os.ReadFile("../../module.json")
var m struct {
Invokes, Consumes []string
State []json.RawMessage
}
_ = json.Unmarshal(manifest, &m)
kept := false
for _, st := range m.State {
kept = kept || string(st) == `"`+LicenceBindingsState+`"`
}
// The manager says each change as binding.changed.<consumer> (design 47 G A-134), and the bus consumer the vault's
// consumes is composed into hands it only what an entry names, so an entry naming binding.changed alone hears none.
hears := slices.ContainsFunc(m.Consumes, func(c string) bool { return stdio.TopicMatches(c, BindingChangedEvent+".g14") })
if !slices.Contains(m.Invokes, LicenceBindingsVerb) || !hears || !kept {
t.Fatalf("the manifest invokes %v, consumes %v, keeps %s", m.Invokes, m.Consumes, m.State)
}
}
// design 39 bus-and-switch B21, B42: vault_first_views lists the licence bindings' first view beside the assignments';
// vault_first_view_again asks the one its of names, and both when of is absent; an of it keeps no view of is refused.
func TestTheFirstViewToolsCoverTheLicenceBindings(t *testing.T) {
follower := func(owner, state string) *views.Follower {
return &views.Follower{Owner: owner, Tool: owner + ".read", State: state,
Ask: func(context.Context, string) (views.Answer, error) {
return views.Answer{Owner: owner, State: state, Values: map[string]json.RawMessage{}}, nil
}}
}
keptA, keptL := assignmentsView, licenceBindingsView
t.Cleanup(func() { assignmentsView, licenceBindingsView = keptA, keptL })
assignmentsView, licenceBindingsView = follower(assignerModule, "assignments"), follower("claude-licence-manager", "bindings")
run := map[string]toolDef{}
for _, d := range viewTools(nil) {
run[d.Name] = d
}
listed, err := run[FirstViewsTool].run("person.operator", nil)
if err != nil {
t.Fatal(err)
}
var states []string
for _, s := range listed.(map[string]any)["first-views"].([]views.Status) {
states = append(states, s.Owner+"."+s.State)
}
if !slices.Equal(states, []string{"claude-licence-manager.bindings", "mesh-delivery-assigner.assignments"}) {
t.Errorf("vault_first_views lists %v", states)
}
byHand := func() (int, int) { return assignmentsView.Status().ByHand, licenceBindingsView.Status().ByHand }
again := run[FirstViewAgainTool].run
for _, c := range []struct {
of string
assignments, bindings int
refused bool
}{
{of: "claude-licence-manager.bindings", bindings: 1},
{of: "", assignments: 1, bindings: 2},
{of: "mesh-delivery-assigner.assignments", assignments: 2, bindings: 2},
{of: "claude-licence-manager.licences", assignments: 2, bindings: 2, refused: true},
} {
_, err := again("person.operator", map[string]any{"why": "a test", "of": c.of})
if (err != nil) != c.refused {
t.Errorf("of %q: %v", c.of, err)
}
if a, b := byHand(); a != c.assignments || b != c.bindings {
t.Errorf("of %q: asked by hand %d and %d times, want %d and %d", c.of, a, b, c.assignments, c.bindings)
}
}
}
// The licence bindings' follower is adopted by a reader holding the vault's writer (design 47 G A-28, A-134): past its bound
// the reader writes its unanswered finding through that writer, the answer clears it, and the follower is the reader's.
func TestTheLicenceBindingsFollowerIsAdoptedAndItsFindingGoesThroughTheVaultsWriter(t *testing.T) {
var mu sync.Mutex
up := false
ask := func(string, any) (json.RawMessage, error) {
mu.Lock()
defer mu.Unlock()
if !up {
return nil, errors.New("nats: no responders available for request")
}
return json.RawMessage(`[]`), nil
}
written := make(chan string, 4)
lb, _ := memLicenceBindings()
f, r, err := newLicenceBindingsView(ask, lb, signalledFindings{written})
if err != nil {
t.Fatal(err)
}
if !r.Follows("claude-licence-manager.bindings") {
t.Fatal("the reader does not follow the licence bindings")
}
f.Bound, f.Wait = 30*time.Millisecond, 10*time.Millisecond
done := make(chan error, 1)
go func() { done <- f.Start(context.Background()) }()
if got := <-written; got != "write first-view-unanswered" {
t.Fatalf("past its bound the writer was told %q, want the unanswered finding written", got)
}
mu.Lock()
up = true
mu.Unlock()
if err := <-done; err != nil {
t.Fatal(err)
}
if got := <-written; got != "clear first-view-unanswered" {
t.Errorf("the answer told the writer %q, want the finding cleared", got)
}
}
// signalledFindings says each write and clear of a finding, by its kind.
type signalledFindings struct{ said chan<- string }
func (s signalledFindings) WriteWire(_ context.Context, f map[string]any) error {
s.said <- fmt.Sprint("write ", f["kind"])
return nil
}
func (s signalledFindings) Clear(_ context.Context, _, _, kind, _ string) error {
s.said <- "clear " + kind
return nil
}
func (s signalledFindings) ModuleNode() (string, string) { return Seat, "" }