Merge origin/main (licence manager on the bus, issue 1409) into feat/47-G-join9

claude-code's and mesh-vault's manifests take both sides' additions (G's seat reads and
findings-asked, main's licence seat verbs and events); claude-code's manifest test lists both.
mesh-vault's licence-bindings follower still uses the removed views.FindingWriter: fixed after.

Builds: design 47 G §610

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
This commit is contained in:
2026-11-12 01:48:43 +01:00
60 changed files with 7682 additions and 1150 deletions
@@ -126,25 +126,48 @@ func leaverKey(key string) (string, bool) {
return node, ok && node != ""
}
// viewTools are the read tool of the first view and its re-read, as every reader has them (design 25 § 12.2).
// firstViews are the vault's first views begun, by the owner's state each follows (`<owner>.<state>`): the assigner's
// assignments and the licence manager's bindings (design 39 bus-and-switch B21, B42).
func firstViews() ([]string, map[string]*views.Follower) {
all := map[string]*views.Follower{}
if assignmentsView != nil {
all[assignerModule+".assignments"] = assignmentsView
}
if licenceBindingsView != nil {
all["claude-licence-manager.bindings"] = licenceBindingsView
}
names := make([]string, 0, len(all))
for n := range all {
names = append(names, n)
}
sort.Strings(names)
return names, all
}
// viewTools are the read tool of the first views and their re-read, as every reader has them (design 25 § 12.2; design
// 39 bus-and-switch B21, B42).
func viewTools(env *Env) []toolDef {
return []toolDef{
{Name: FirstViewsTool,
Description: "The vault's first view of the assigner's assignments: the tool it asks, the revision its picture holds, when it " +
"asked and was answered, how many asks (and by hand), and whether it is waiting.",
Description: "The vault's first views, of the assigner's assignments and of the licence manager's bindings: for each, the tool " +
"it asks, the revision its picture holds, when it asked and was answered, how many asks (and by hand), and whether it is waiting.",
run: func(string, map[string]any) (any, error) {
if assignmentsView == nil {
return nil, fmt.Errorf("the vault reads the assigner's assignments only when it runs as the module")
names, all := firstViews()
if len(names) == 0 {
return nil, fmt.Errorf("the vault keeps its first views only when it runs as the module")
}
return map[string]any{"first-views": []views.Status{assignmentsView.Status()}}, nil
out := []views.Status{}
for _, n := range names {
out = append(out, all[n].Status())
}
return map[string]any{"first-views": out}, nil
}},
{Name: FirstViewAgainTool,
Description: "Ask the first view of the assigner's assignments once more by hand, with why, recorded in the vault's log.",
Input: map[string]any{"why": str("why the first view is asked again")},
Description: "Ask a first view once more by hand, with why, recorded in the vault's log: of names it by its owner's state " +
"(mesh-delivery-assigner.assignments or claude-licence-manager.bindings); absent, both are asked again.",
Input: map[string]any{"why": str("why the first view is asked again"),
"of": str("the first view, by its owner's state: mesh-delivery-assigner.assignments or claude-licence-manager.bindings; absent for both")},
run: func(caller string, a map[string]any) (any, error) {
if assignmentsView == nil {
return nil, fmt.Errorf("the vault reads the assigner's assignments only when it runs as the module")
}
why := strings.TrimSpace(arg(a, "why"))
if why == "" {
return nil, fmt.Errorf("say why: a first view asked by hand keeps its why")
@@ -152,8 +175,23 @@ func viewTools(env *Env) []toolDef {
if err := fromAGrantedCaller(caller, FirstViewAgainTool); err != nil {
return nil, err
}
say("the first view of the assigner's assignments is asked again by %s: %s", caller, why)
return map[string]any{"asked-again": true}, assignmentsView.Again(context.Background(), why)
names, all := firstViews()
if of := strings.TrimSpace(arg(a, "of")); of != "" {
if all[of] == nil {
return nil, fmt.Errorf("the vault keeps no first view of %q here; it keeps %v", of, names)
}
names = []string{of}
}
if len(names) == 0 {
return nil, fmt.Errorf("the vault keeps its first views only when it runs as the module")
}
for _, n := range names {
say("the first view of %s is asked again by %s: %s", n, caller, why)
if err := all[n].Again(context.Background(), why); err != nil {
return nil, err
}
}
return map[string]any{"asked-again": true}, nil
}},
}
}
+6 -4
View File
@@ -91,10 +91,12 @@ type callKey struct {
// move is what `move-in` takes: the row of the controller's store (move.go).
move *MoveOf
// why is what `move-in` with replace_running was asked for, in the caller's words (owntake.go).
why string
public [32]byte
private [32]byte
until time.Time
why string
// generation is the licence's generation `licence-put` keeps its value at (licences.go).
generation int
public [32]byte
private [32]byte
until time.Time
}
// Opened is a first step's answer: the call, and the key to seal its value to. Never a value.
@@ -0,0 +1,301 @@
package main
// The licence bindings the vault keeps (design 39 bus-and-switch §17, B2, B10, B25): which licence each consumer is
// bound to, so the vault hands a licence's access token only to a machine a binding names. Learned from the licence
// manager's `binding.changed`, which the vault consumes, and at its start from the seat's verb `bindings`, its first
// view, asked until it answers; kept in the vault's own state `licence-bindings`, one key per consumer with the
// licence, its key and the generation, deleted on a release. The vault never reads the manager's state (ADR 0596 §2).
import (
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"sync"
"time"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/views"
)
const (
// LicenceBindingsState is the vault's own state of the licence bindings (§17; B2: in the old section `state`).
LicenceBindingsState = "licence-bindings"
// BindingChangedEvent is the licence manager's event of a binding written or deleted (§21), which the vault consumes.
BindingChangedEvent = "claude-licence-manager.binding.changed"
// LicenceBindingsVerb is the seat's verb the vault asks for its first view (B10), declared in its invokes (B9).
LicenceBindingsVerb = "seat:anthropic-licence-manager.bindings"
)
// LicenceBinding is a consumer's key of `licence-bindings` (B25): the licence, its key and the binding's generation.
type LicenceBinding struct {
Licence string `json:"licence"`
Key string `json:"key"`
Generation int64 `json:"generation"`
}
// LicenceBindings is the state `licence-bindings`.
type LicenceBindings struct {
Get func(consumer string) (*LicenceBinding, error)
Put func(consumer string, b LicenceBinding) error
Delete func(consumer string) error
Keys func() ([]string, error)
Log func(string, ...any)
// WrittenAt is when the bus wrote a consumer's key, so a first view keeps a key an event wrote after it was asked
// (B43); nil writes no time, and every key a first view does not name goes.
WrittenAt func(consumer string) (time.Time, error)
// Answered is whether the first view of the bindings has been answered since the vault started; until it has, an
// access token is refused, saying why (B31). Nil is a vault that keeps no first view (its tests).
Answered func() bool
}
// busLicenceBindings is the state on the bus.
func busLicenceBindings() LicenceBindings {
st := stdio.State(LicenceBindingsState)
return LicenceBindings{
Get: func(consumer string) (*LicenceBinding, error) {
e, err := st.Get(consumer)
if err != nil || e == nil || len(e.Value) == 0 {
return nil, err
}
var b LicenceBinding
return &b, json.Unmarshal(e.Value, &b)
},
Put: func(consumer string, b LicenceBinding) error { _, err := st.Put(consumer, b); return err },
Delete: func(consumer string) error { return st.Delete(consumer) },
Keys: st.Keys,
Log: say,
WrittenAt: func(consumer string) (time.Time, error) {
e, err := st.Get(consumer)
if err != nil || e == nil {
return time.Time{}, err
}
return e.At, nil
},
Answered: func() bool { return licenceBindingsView != nil && !licenceBindingsView.Status().Answered.IsZero() },
}
}
// bindingChanged is the body of `binding.changed` as the manager says it (§21, B7; B22: decoded from a copy of the
// writer's form, testdata/binding-changed.json).
type bindingChanged struct {
Consumer string `json:"consumer"`
Licence string `json:"licence"`
Key string `json:"key"`
Generation int64 `json:"generation"`
}
// keep writes a consumer's binding unless the state holds a newer generation; an empty licence is a release.
func (lb LicenceBindings) keep(consumer string, b LicenceBinding) error {
if consumer == "" {
return errors.New("a binding names no consumer")
}
held, err := lb.Get(consumer)
if err != nil {
return err
}
if held != nil && held.Generation > b.Generation {
return nil // the state holds a newer move already
}
if b.Licence == "" {
if held == nil {
return nil
}
return lb.Delete(consumer)
}
if held != nil && *held == b {
return nil
}
return lb.Put(consumer, b)
}
// Heard takes one `binding.changed`.
func (lb LicenceBindings) Heard(body []byte) error {
var e bindingChanged
if err := json.Unmarshal(body, &e); err != nil {
return fmt.Errorf("%s is not a binding's change: %w", BindingChangedEvent, err)
}
if e.Licence != "" && e.Key == "" {
return fmt.Errorf("%s for %s names no licence key", BindingChangedEvent, e.Consumer)
}
return lb.keep(e.Consumer, LicenceBinding{Licence: e.Licence, Key: e.Key, Generation: e.Generation})
}
// FirstView takes the manager's answer to `bindings`, asked at asked, by consumer: every binding it names is kept, and
// every key the state holds for a consumer it does not name is deleted, since that consumer was released, unless an
// event wrote that key after the view was asked (B43): the view does not know that move yet.
func (lb LicenceBindings) FirstView(values map[string]json.RawMessage, asked time.Time) error {
var errs []error
for consumer, raw := range values {
var b LicenceBinding
if err := json.Unmarshal(raw, &b); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", consumer, err))
continue
}
errs = append(errs, lb.keep(consumer, b))
}
held, err := lb.Keys()
if err != nil {
return errors.Join(append(errs, err)...)
}
for _, consumer := range held {
if _, named := values[consumer]; named {
continue
}
if lb.WrittenAt != nil && !asked.IsZero() {
at, err := lb.WrittenAt(consumer)
if err != nil {
errs = append(errs, err)
continue
}
if at.After(asked) {
continue // written by an event after the view was asked (B43)
}
}
errs = append(errs, lb.Delete(consumer))
}
return errors.Join(errs...)
}
// licenceBindingsAnswer is the seat's answer to `bindings` (B10, B25) as a first view, by consumer.
func licenceBindingsAnswer(raw []byte) (views.Answer, error) {
var listed []struct {
Consumer string `json:"consumer"`
LicenceBinding
}
if err := json.Unmarshal(unwrapToolAnswer(raw), &listed); err != nil {
return views.Answer{}, fmt.Errorf("%s answered what is not a list of bindings: %w", LicenceBindingsVerb, err)
}
values := map[string]json.RawMessage{}
for _, b := range listed {
if b.Consumer == "" || b.Licence == "" || b.Key == "" {
return views.Answer{}, fmt.Errorf("%s answered a binding without its consumer, licence or key", LicenceBindingsVerb)
}
raw, _ := json.Marshal(b.LicenceBinding)
values[b.Consumer] = raw
}
return views.Answer{Owner: "claude-licence-manager", State: "bindings", Values: values, At: time.Now()}, nil
}
// licenceBindingsView is the first view's follower; nil until main begins it.
var licenceBindingsView *views.Follower
// newLicenceBindingsView makes the follower of the first view: asked until it answers, and each answer, at the start or
// asked again by hand, written into the state.
func newLicenceBindingsView(ask func(subject string, body any) (json.RawMessage, error), lb LicenceBindings,
findings views.FindingWriter) *views.Follower {
var mu sync.Mutex
var taken time.Time
var f *views.Follower
f = &views.Follower{Owner: "claude-licence-manager", Tool: LicenceBindingsVerb, State: "bindings", Logf: say,
Ask: func(context.Context, string) (views.Answer, error) {
raw, err := ask(LicenceBindingsVerb, map[string]any{})
if err != nil {
return views.Answer{}, err
}
return licenceBindingsAnswer(raw)
},
Raise: func(s views.Status) {
fd := views.UnansweredFinding(Seat, s, time.Now())
if err := findings.Put(fd); err != nil {
say("the finding %s is not written: %v", fd.ID, err)
}
},
Clear: func(s views.Status) { _ = findings.Delete(views.UnansweredFinding(Seat, s, time.Now())) },
// Each answer, once: its picture is the manager's bindings when it answered.
Said: func(s views.Status) {
mu.Lock()
fresh := !s.Answered.IsZero() && s.Answered.After(taken)
if fresh {
taken = s.Answered
}
mu.Unlock()
if !fresh {
return
}
values := f.Values()
if err := lb.FirstView(values, s.Asked); err != nil {
say("the licence bindings of the first view are not all kept: %v", err)
return
}
consumers := make([]string, 0, len(values))
for c := range values {
consumers = append(consumers, c)
}
sort.Strings(consumers)
say("the licence bindings of %d consumer(s) are kept from the first view: %v", len(consumers), consumers)
}}
return f
}
// watchLicenceBindings begins the first view and hears `binding.changed`. It answers whether it began; one that did not
// is begun again at the next minute pass.
func watchLicenceBindings(lb LicenceBindings) bool {
err := stdio.Subscribe(BindingChangedEvent, func(e stdio.Envelope) error {
if err := lb.Heard(e.Body); err != nil {
say("%v", err)
}
return nil
})
if err != nil {
say("does not hear %s yet (%v); asked again at the next pass", BindingChangedEvent, err)
return false
}
if licenceBindingsView == nil {
licenceBindingsView = newLicenceBindingsView(stdio.Ask, lb,
meshconditionsclient.FindingWriter{State: stdio.State(FindingsState)})
go func() {
if err := licenceBindingsView.Start(context.Background()); err != nil {
say("the first view of the licence bindings ended unanswered: %v", err)
}
}()
}
return true
}
// licenceRefusal answers whether name is a licence's secret and, if it is, why the vault does not hand it to caller,
// empty when it does (§16, §17, A1, B3, B8, B25): a grant to any caller (B3), an access token to a machine on which a
// consumer's binding names that licence's key. The rule that a value goes only to a module under a bus account of
// its own does not apply to a licence's secrets (§17).
func (v *Vault) licenceRefusal(caller, name string) (bool, string) {
rest, ok := strings.CutPrefix(name, "licence.")
if !ok {
return false, ""
}
key, part := rest, ""
for _, p := range []string{LicenceGrant, LicenceAccess} {
if k, cut := strings.CutSuffix(rest, "."+p); cut {
key, part = k, p
}
}
if part == "" || !licenceKey.MatchString(key) {
return false, ""
}
if part == LicenceGrant {
return true, ""
}
machine, _, _ := strings.Cut(caller, ".")
if v.LicenceBindings == nil {
return true, "the vault keeps no licence bindings, so no binding names the licence " + key
}
if v.LicenceBindings.Answered != nil && !v.LicenceBindings.Answered() {
return true, "the vault's first view of the licence bindings has not been answered since it started, so it does not yet know which machine a binding names; it asks the licence manager until it answers (B31)"
}
consumers, err := v.LicenceBindings.Keys()
if err != nil {
return true, "the licence bindings cannot be read: " + err.Error()
}
for _, consumer := range consumers {
if c, _, _ := strings.Cut(consumer, "."); c != machine {
continue
}
if b, err := v.LicenceBindings.Get(consumer); err == nil && b != nil && b.Key == key {
return true, ""
}
}
return true, fmt.Sprintf("no consumer on %s is bound to the licence %s, and its token goes only to a machine a binding names", machine, key)
}
@@ -0,0 +1,186 @@
package main
import (
"context"
"encoding/json"
"errors"
"os"
"slices"
"sort"
"testing"
"time"
"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+`"`
}
if !slices.Contains(m.Invokes, LicenceBindingsVerb) || !slices.Contains(m.Consumes, BindingChangedEvent) || !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)
}
}
}
@@ -0,0 +1,80 @@
package main
// A licence's two secrets (design 39 bus-and-switch §15, B3 to B6): `licence.<licence key>.grant` and
// `licence.<licence key>.access`, handed to the vault by the licence manager through `licence-put` in two steps — name
// the licence, the part and the generation and get a call and a key made for it, then send the call and the value sealed
// to that key. The caller's generation is the record's; the vault keeps the newest and refuses an older one, and says
// `secret-changed` with the secret's name and generation, never the value.
import (
"errors"
"fmt"
"regexp"
)
// LicencePutVerb is the verb that hands a licence's secret to the vault.
const LicencePutVerb = "licence-put"
// The parts of a licence the vault holds (§15).
const (
LicenceGrant = "grant"
LicenceAccess = "access"
)
// licenceKey is a licence's key form (§10, B6): lower case, letters, digits, `-`, `.` and `_`.
var licenceKey = regexp.MustCompile(`^[a-z0-9_.-]{1,120}$`)
// LicenceSecret is the name of one part of a licence in the vault.
func LicenceSecret(key, part string) (string, error) {
if !licenceKey.MatchString(key) {
return "", fmt.Errorf("%q is not a licence's key: lower-case letters, digits, -, . and _", key)
}
if part != LicenceGrant && part != LicenceAccess {
return "", fmt.Errorf("the part %q is not a part of a licence: grant or access", part)
}
return "licence." + key + "." + part, nil
}
// LicencePutOpen opens a call to take one part of a licence at a generation.
func (v *Vault) LicencePutOpen(caller, licence, part string, generation int) (Opened, error) {
if err := fromAGrantedCaller(caller, LicencePutVerb); err != nil {
return Opened{}, err
}
secret, err := LicenceSecret(licence, part)
if err != nil {
return Opened{}, err
}
if generation < 1 {
return Opened{}, errors.New("licence-put takes the licence's generation, one or more; nothing is taken")
}
id, key, err := v.openCall(LicencePutVerb, secret, caller, nil)
if err != nil {
return Opened{}, err
}
v.callsMu.Lock()
if c := v.pending[id]; c != nil {
c.generation = generation
}
v.callsMu.Unlock()
return Opened{Call: id, SealTo: key, Secret: secret}, nil
}
// LicencePutTake opens the value sealed to the call's key and keeps it at the call's generation.
func (v *Vault) LicencePutTake(caller, call, sealed string) (Changed, error) {
c, err := v.takeCall(LicencePutVerb, call)
if err != nil {
return Changed{}, err
}
if c.by != caller {
return Changed{}, fmt.Errorf("the licence-put call %q was opened by another caller; nothing was taken", call)
}
value, err := c.open(sealed)
if err != nil {
return Changed{}, err
}
defer zero(value)
if len(value) == 0 {
return Changed{}, errors.New("the value handed in is empty; nothing was taken")
}
return v.keepWith(c.secret, string(value), caller, "", OriginAccepted, keepOptions{generation: c.generation})
}
@@ -0,0 +1,116 @@
package main
import (
"strings"
"testing"
)
// putLicence hands one part of a licence to the vault in licence-put's two steps.
func putLicence(t *testing.T, v testVault, caller, key, part string, generation int, value string) (Changed, error) {
t.Helper()
o, err := v.LicencePutOpen(caller, key, part, generation)
if err != nil {
return Changed{}, err
}
return v.LicencePutTake(caller, o.Call, sealToCall(t, o.SealTo, value))
}
// design 39 bus-and-switch §15, B3, B5: the caller's generation is the record's; an older one is refused; the
// event names the secret and its generation, never the value.
func TestLicencePutKeepsTheNewestGenerationAndRefusesAnOlder(t *testing.T) {
v := newVault(t, nil)
const manager = "claude-licence-manager"
if _, err := putLicence(t, v, manager, "jane_at_example.org", LicenceGrant, 3, `{"refreshToken":"rt-3"}`); err != nil {
t.Fatal(err)
}
rec, held, err := v.Store.Read("licence.jane_at_example.org.grant")
if err != nil || !held || rec.Generation != 3 {
t.Fatalf("held %v at generation %d (%v), want generation 3", held, rec.Generation, err)
}
if _, err := putLicence(t, v, manager, "jane_at_example.org", LicenceGrant, 2, `{"refreshToken":"rt-2"}`); err == nil ||
!strings.Contains(err.Error(), "not newer") {
t.Fatalf("an older generation was taken: %v", err)
}
if c, err := putLicence(t, v, manager, "jane_at_example.org", LicenceGrant, 4, `{"refreshToken":"rt-4"}`); err != nil ||
c.Generation != 4 {
t.Fatalf("generation 4: %+v %v", c, err)
}
said := 0
for _, raw := range v.bus.raw {
if strings.Contains(raw, "rt-") {
t.Fatalf("an event carries the value: %s", raw)
}
if strings.Contains(raw, `"secret-changed"`) && strings.Contains(raw, "licence.jane_at_example.org.grant") {
said++
}
}
if said != 2 {
t.Fatalf("secret-changed said %d times, want 2: %v", said, v.bus.raw)
}
for _, bad := range []struct{ key, part string }{{"Jane@x", LicenceGrant}, {"jane", "refresh"}} {
if _, err := v.LicencePutOpen(manager, bad.key, bad.part, 1); err == nil {
t.Errorf("licence-put took %s/%s", bad.key, bad.part)
}
}
if _, err := v.LicencePutOpen("", "jane", LicenceAccess, 1); err == nil {
t.Error("licence-put took an unproven caller")
}
}
// design 39 bus-and-switch §17/AC1, §16, B3, B8, B25: a licence's access token is refused to a machine no binding names
// and for a licence its binding does not name, and given after a binding.changed naming it, to any consumer of that
// machine; the grant goes to the manager's tool runner, with no machine guard.
func TestATokenIsGivenOnlyToAMachineABindingNames(t *testing.T) {
v := newVault(t, nil)
lb, _ := memLicenceBindings()
v.LicenceBindings = &lb
const manager = "novox.node-tools"
for _, key := range []string{"jane_at_example.org", "api"} {
for _, part := range []string{LicenceGrant, LicenceAccess} {
if _, err := putLicence(t, v, manager, key, part, 1, key+"-"+part); err != nil {
t.Fatal(err)
}
}
}
access := "licence.jane_at_example.org.access"
// B31: until the first view of the bindings is answered, an access token is refused, saying why.
answered := false
lb.Answered = func() bool { return answered }
if err := lb.Heard([]byte(`{"consumer":"g14","licence":"jane","key":"jane_at_example.org","generation":1}`)); err != nil {
t.Fatal(err)
}
if _, _, err := asks(v, "g14.node-tools", access); err == nil || !strings.Contains(err.Error(), "first view of the licence bindings has not been answered") {
t.Fatalf("a token was handed before the first view was answered: %v", err)
}
answered = true
if _, _, err := asks(v, "g14.node-tools", access); err != nil {
t.Fatalf("once the first view is answered the bound machine is refused: %v", err)
}
if err := lb.Heard([]byte(`{"consumer":"g14","licence":"","key":"","generation":2}`)); err != nil {
t.Fatal(err)
}
if _, _, err := asks(v, "g14.node-tools", access); err == nil || !strings.Contains(err.Error(), "no consumer on g14") {
t.Fatalf("a machine no binding names was handed the token: %v", err)
}
if err := lb.Heard([]byte(`{"consumer":"g14","licence":"api","key":"api","generation":4}`)); err != nil {
t.Fatal(err)
}
if _, _, err := asks(v, "g14.node-tools", access); err == nil {
t.Fatal("a licence its binding does not name was handed to g14")
}
if got, _, err := asks(v, "g14.node-tools", "licence.api.access"); err != nil || got != "api-access" {
t.Fatalf("g14's own licence: %q %v", got, err)
}
if err := lb.Heard([]byte(`{"consumer":"g14.worker-1","licence":"jane@example.org","key":"jane_at_example.org","generation":2}`)); err != nil {
t.Fatal(err)
}
if got, _, err := asks(v, "g14.node-tools", access); err != nil || got != "jane_at_example.org-access" {
t.Fatalf("after a binding.changed naming it: %q %v", got, err)
}
if _, _, err := asks(v, "ace.node-tools", access); err == nil {
t.Fatal("another machine was handed g14's token")
}
if got, _, err := asks(v, manager, "licence.jane_at_example.org.grant"); err != nil || got != "jane_at_example.org-grant" {
t.Fatalf("the manager's grant: %q %v", got, err)
}
}
+7 -1
View File
@@ -59,7 +59,8 @@ func build() *Env {
// The assignments as the vault's watch keeps them (watchAssignments), read over the bus until it has caught up.
assigned = &WatchedAssignments{Fallback: readPlanRaw}
watchedPlan := func(key string) ([]byte, error) { raw, err := assigned.Read(key); return asAssignment(key, raw, err) }
env.Vault = &Vault{Store: store, Own: own, Askers: Declared{Read: watchedPlan, Confirm: readAssignment, Store: store},
licenceBindings := busLicenceBindings()
env.Vault = &Vault{Store: store, Own: own, LicenceBindings: &licenceBindings, Askers: Declared{Read: watchedPlan, Confirm: readAssignment, Store: store},
Assignments: Mirror{Keys: assignmentKeys, Read: readAssignment}, Emit: emit, Ask: stdio.Ask,
Now: time.Now, Log: say, Accounts: busAccounts{}, Haves: readHave, WantRead: readWant,
HaveKeys: func() ([]string, error) { return stdio.State(HaveRead).Keys() }, Assigner: seatAssignments, Signers: busSigners{},
@@ -337,6 +338,8 @@ func main() {
watched, watching := watchHandings(env), watchAssignments()
wants := watchWants(env)
leavers := watchLeavers(env)
bindings := busLicenceBindings()
licences := watchLicenceBindings(bindings)
kick := make(chan struct{}, 1)
go func() {
for range kick {
@@ -351,6 +354,9 @@ func main() {
if !leavers {
leavers = watchLeavers(env)
}
if !licences {
licences = watchLicenceBindings(bindings)
}
if !watched {
watched = watchHandings(env)
}
@@ -0,0 +1 @@
{"at":"2026-10-04T12:00:00Z","by":"g14.node-tools","consumer":"laptop","from":"acct-1@example.org","generation":3,"key":"api","kind":"api-key","licence":"api","why":"the switch verb"}
@@ -0,0 +1 @@
[{"consumer":"laptop","licence":"acct-1@example.org","key":"acct-1_at_example.org","kind":"subscription","generation":1013,"since":"2026-10-04T12:00:00Z","why":"carried over","by":"claude-licence-manager"},{"consumer":"server","licence":"api","key":"api","kind":"api-key","generation":1016,"since":"2026-10-04T12:00:00Z","why":"carried over","by":"claude-licence-manager"}]
@@ -208,6 +208,28 @@ func definitions(env *Env) []toolDef {
}
return v.OwnDrift()
}},
{Name: Seat + "." + LicencePutVerb,
Description: "Hand the vault one of a licence's two secrets (design 39 bus-and-switch §15), in two steps: name " +
"the licence by its key, the part (grant or access) and its generation, and get a call and a key made for " +
"it; then send the call and the value sealed to that key. Keeps the newest generation and refuses an older " +
"one; says secret-changed with the secret's name and generation, never the value.",
Input: map[string]any{"type": "object", "properties": map[string]any{
"licence": str("the first step: the licence's key"),
"part": str("the first step: grant or access"),
"generation": map[string]any{"type": "number", "description": "the first step: the licence's generation"},
"call": str("the second step: the call the first step answered"),
"sealed": str("the second step: the value sealed to the call's key (NaCl anonymous box, base64) — never the value")}},
run: func(caller string, a map[string]any) (any, error) {
v, err := env.ready()
if err != nil {
return nil, err
}
if call := arg(a, "call"); call != "" {
return v.LicencePutTake(caller, call, arg(a, "sealed"))
}
g, _ := a["generation"].(float64)
return v.LicencePutOpen(caller, arg(a, "licence"), arg(a, "part"), int(g))
}},
{Name: Seat + ".move-in",
Description: "Take one value of the controller's store into the vault, as it is (design 57's V3): from the " +
"node-engine of a machine it was sealed to, and no other caller, in two steps — name the row (node, " +
@@ -28,6 +28,9 @@ const ChangedEvent = "secret-changed"
// Vault holds the secrets.
type Vault struct {
Store *Store
// LicenceBindings is the vault's own state of the licence bindings (licencebindings.go): which machine a licence's
// access token goes to. Nil hands it to no machine.
LicenceBindings *LicenceBindings
// Own is the vault's own key; the private half never leaves its state directory.
Own seal.KeyPair
// Askers decides who may ask `get` for what. Nil allows nobody.
@@ -150,6 +153,9 @@ type keepOptions struct {
replaceOnly bool
keepPrevious bool
refuse func(before Record) string
// generation, when one or more, is the record's generation as the caller numbers it (licence-put, licences.go): a
// value at a generation no newer than the one held is refused.
generation int
}
// keepWith is keep with the move's options. A covered bus account kept anew has its hash written once it is kept
@@ -234,6 +240,10 @@ func (v *Vault) keepLocked(name, value, by, via, origin string, opt keepOptions)
return Changed{}, errors.New(why)
}
}
if opt.generation > 0 && opt.generation <= before.Generation {
return Changed{}, fmt.Errorf("%s is held at generation %d, and generation %d is not newer: nothing was taken",
name, before.Generation, opt.generation)
}
if opt.neverReplace {
return Changed{}, &HeldAnother{Name: name, Generation: before.Generation, ChangedBy: before.ChangedBy,
ChangedAt: before.ChangedAt, Origin: before.Origin}
@@ -266,6 +276,9 @@ func (v *Vault) keepLocked(name, value, by, via, origin string, opt keepOptions)
} else if !opt.madeAt.IsZero() {
rec.MadeAt = opt.madeAt.UTC()
}
if opt.generation > 0 {
rec.Generation = opt.generation
}
if opt.movedFrom != nil {
moved := *opt.movedFrom
moved.At = now
@@ -376,8 +389,16 @@ func (v *Vault) Get(caller, name, publicKey string) (Answer, error) {
_ = v.recordHanding(Handing{To: caller, Name: name, Outcome: "refused", Why: why})
return Answer{}, fmt.Errorf("%s may not ask for %s: %s", caller, name, why)
}
isLicence, licenceWhy := v.licenceRefusal(caller, name)
if isLogin {
// Judged above: the node's own engine, sealed to its own key.
} else if isLicence {
// A licence's secret, by the licence rule (design 39 bus-and-switch §16, §17).
if licenceWhy != "" {
v.log("refused %s to %s: %s", name, caller, licenceWhy)
_ = v.recordHanding(Handing{To: caller, Name: name, Outcome: "refused", Why: licenceWhy})
return Answer{}, fmt.Errorf("%s may not ask for %s: %s", caller, name, licenceWhy)
}
} else if ok, why := askers.May(caller, name); !ok {
if reason, notYet := strings.CutPrefix(why, notYetPrefix); notYet {
// Not a refusal (issue 928): the client waits and asks again, and nothing is recorded against it.
@@ -148,10 +148,11 @@ func TestNoBucketHoldsASecret(t *testing.T) {
if err := json.Unmarshal(raw, &manifest); err != nil {
t.Fatal(err)
}
if s, _ := json.Marshal(manifest["state"]); string(s) != `[{"history":2,"name":"bus-accounts"},"signers","bound","node-logins","findings"]` {
if s, _ := json.Marshal(manifest["state"]); string(s) != `[{"history":2,"name":"bus-accounts"},"signers","bound","node-logins","findings","licence-bindings"]` {
t.Errorf("the manifest declares buckets %s: a secret is in no bucket, sealed or not (ADR 0201 §13), and the "+
"buckets are the accounts' hashes (ADR 0547 clause 9), the signing keys' public halves (ADR 0550 §2) and the "+
"credentials' outcomes, names and generations alone (ADR 0570 clauses 3, 6) and each node's login in use (ADR 0583)", s)
"credentials' outcomes, names and generations alone (ADR 0570 clauses 3, 6), each node's login in use (ADR 0583) "+
"and the licence bindings, a licence's name, key and generation per consumer (design 39 bus-and-switch §17)", s)
}
if r, _ := json.Marshal(manifest["reads"]); string(r) != `["node-engine.have","mesh-grants.accounts","mesh-provisioner.plans","mesh-provisioner.provisions"]` {
t.Errorf("the manifest reads %s: the vault reads the seat mesh-provisioner's plans and provisions, the haves, the "+
@@ -182,6 +183,12 @@ func TestNoBucketHoldsASecret(t *testing.T) {
code = []byte(strings.Replace(string(code), "stdio.State(NodeLoginsState)."+call, "", -1))
}
}
// The licence bindings, in licencebindings.go alone: the state opened once, a licence's name, key and generation per
// consumer, never a secret (design 39 bus-and-switch §17, B25).
if f == "licencebindings.go" {
code = []byte(strings.Replace(string(code), "st := stdio.State(LicenceBindingsState)", "", 1))
code = []byte(strings.Replace(string(code), "meshconditionsclient.FindingWriter{State: stdio.State(FindingsState)}", "", 1))
}
// The signing keys' public halves, in signing.go alone: one read and one write of its own bucket (ADR 0550 §2).
if f == "signing.go" {
code = []byte(strings.Replace(string(code), "stdio.State(meshvault.StateSigners).Get(", "", 1))