Files
mesh-catalog/modules/mesh-vault/cmd/mesh-vault/licencebindings.go
T
jschoubben 22a90d4267 Join 9: mesh-vault adopts the licence bindings' follower through a views reader, on its one writer (A-134)
The follower main added (issue 1409) used the removed views.FindingWriter: it is adopted by a
views.Reader holding the vault's one finding writer, which the assignments view shares, and hears
claude-licence-manager.binding.changed.<consumer> through the adoption.

Builds: design 47 G A-16, A-28, A-134

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-12 02:01:08 +01:00

296 lines
11 KiB
Go

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"
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, adopted by a views.Reader holding the vault's writer (design
// 47 G A-28, A-134), so the reader writes and clears its findings: asked until it answers, and each answer, at the start or
// asked again by hand, written into the state; each binding.changed.<consumer> is lb.Heard.
func newLicenceBindingsView(ask func(subject string, body any) (json.RawMessage, error), lb LicenceBindings,
findings views.WireWriter) (*views.Follower, *views.Reader, error) {
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)
},
// 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)
}}
r := &views.Reader{Module: Seat, Findings: findings, Logf: say}
manager, event, _ := strings.Cut(BindingChangedEvent, ".")
if err := r.Adopt(f, manager, event, func(_ context.Context, body []byte) error { return lb.Heard(body) }); err != nil {
return nil, nil, err
}
return f, r, nil
}
// 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 {
if licenceBindingsView != nil {
return true
}
w, err := vaultFindings()
if err != nil {
say("the vault's finding writer does not start yet (%v); the licence bindings are begun at the next pass", err)
return false
}
f, r, err := newLicenceBindingsView(stdio.Ask, lb, w)
if err != nil {
say("the licence bindings are not followed: %v", err)
return false
}
licenceBindingsView = f
r.Start(context.Background())
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)
}