Merge feat/47-G-fix11-b4c (GR12: the grants part claims mesh-grants and serves grants-for) into feat/47-G-fix11-b4b

This commit is contained in:
2026-11-12 06:11:34 +01:00
22 changed files with 847 additions and 11 deletions
@@ -1281,6 +1281,8 @@ type RevisionInput struct {
Heads string `json:"heads,omitempty"`
// a kept revision; absent: the newest of trunk, or of the candidate named
Revision int64 `json:"revision,omitempty"`
// a candidate's source revision: the revision of the branch's series taken in from it, with its entries (design 47 G section 441)
Source int64 `json:"source,omitempty"`
}
// RevisionAnswer is what revision answers.
@@ -266,6 +266,10 @@
"type": "string",
"description": "a candidate's heads"
},
"source": {
"type": "integer",
"description": "a candidate's source revision: the revision of the branch's series taken in from it, with its entries (design 47 G section 441)"
},
"after": {
"type": "string",
"description": "the last module of the page before; absent: the first page"
@@ -731,6 +731,8 @@ export interface RevisionInput {
"heads"?: string;
/** a kept revision; absent: the newest of trunk, or of the candidate named */
"revision"?: number;
/** a candidate's source revision: the revision of the branch's series taken in from it, with its entries (design 47 G section 441) */
"source"?: number;
}
/** is what revision answers. */
@@ -11,6 +11,7 @@ import (
"sync"
"time"
"git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshgrants"
"git.novox.be/novox/mesh-sdk/go/seatlist"
"git.novox.be/novox/mesh-sdk/go/views"
@@ -257,6 +258,23 @@ func toolsOf(p *grants.Part) []stdio.Tool {
"composed yet by this version of the part, with its step, the acting part, its version, since when, its bound (10 minutes) and " +
"clock-from (the start of this version's first pass), and which have passed their bound. Read-only.",
Run: func(map[string]any) (any, error) { return p.WaitsOf() }},
{Name: grants.ToolCallers, Description: "The callers each verb and each accepted kind of the seat definitions admits (design 47 G §83): " +
"the list the definition names, or the default of the verb's class. Name a seat, or a seat and a verb, or neither for every one. Read-only.",
Input: schema(map[string]string{"seat": "a seat's name (default: every seat)", "verb": "a verb or accepted kind (default: every one)"}),
Run: func(a map[string]any) (any, error) {
return p.Callers(grants.Answer(a, "seat"), grants.Answer(a, "verb"))
}},
{Name: grants.ToolWhyRefused, Description: "Why an account's call of a seat's verb is refused (design 47 G §83): the call subject the account " +
"lacks a grant for (the bus's own answer, nats_user_can) and the definition's callers that leave it out. Read-only.",
Input: schema(map[string]string{"account": "the bus user, e.g. g14.node-tools", "verb": "the verb as <seat>.<verb>", "node": "the node, for a node seat"}, "account", "verb"),
Run: func(a map[string]any) (any, error) {
return p.WhyRefused(grants.Answer(a, "account"), grants.Answer(a, "verb"), grants.Answer(a, "node"))
}},
{Name: meshgrants.Seat + "." + meshgrants.VerbGrantsFor,
Description: "The grants a candidate would compose, per module (design 47 G §441): the grants it would add and remove against the branch's newest.",
Run: func(a map[string]any) (any, error) {
return p.GrantsFor(meshgrants.GrantsForInput{Branch: grants.Answer(a, "branch"), Run: grants.Answer(a, "run"), Source: grants.Answer(a, "source")})
}},
{Name: grants.ToolRelease, Description: "Release one held granting wait by a person's act with why, recorded as a hand act " +
"(the seat mesh-hand-acts) before it is released (design 47 G §276). grants_waits lists them.",
Input: schema(map[string]string{"module": "the held entry's module", "why": "why, kept in the hand act"}, "module", "why"),
+58 -6
View File
@@ -29,6 +29,7 @@ import (
"git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient"
"git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshgrants"
"git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshnodeenroller"
"git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshvault"
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
@@ -91,8 +92,11 @@ type fakeBus struct {
maxValue int
// entries are the catalog half's entries by fingerprint, the manifest each holds as the indexer's manifests state has it
// (entry); entriesAsked says every one is asked, not answered: the half cannot be read yet.
entries map[string]string
entriesAsked bool
entries map[string]string
entriesAsked bool
// revision is the catalog half of mesh-catalog's `revision`: the branch's `newest` and a `candidate` (a source or a group), each
// module's manifest.
revision map[string]map[string]string
catalogWaited []string
}
@@ -363,6 +367,21 @@ func (b *fakeBus) Call(key string, body any) (json.RawMessage, error) {
}
}
return json.Marshal(map[string]any{"users": out})
case grants.CallRevision:
var in meshcatalog.RevisionInput
raw, _ := json.Marshal(body)
_ = json.Unmarshal(raw, &in)
which := "newest"
if in.Group != "" || in.Source != 0 {
which = "candidate"
}
var out meshcatalog.RevisionAnswer
for module, manifest := range b.revision[which] {
var m map[string]any
_ = json.Unmarshal([]byte(manifest), &m)
out.Entries = append(out.Entries, meshcatalog.CatalogEntry{Module: module, Manifest: m})
}
return json.Marshal(out)
case grants.CallStreams:
if stream, _ := args["stream"].(string); stream != "" {
return json.Marshal(map[string]any{"detail": []map[string]any{{"name": stream, "consumer_detail": b.consumers[stream]}}})
@@ -602,10 +621,9 @@ func TestGrants(t *testing.T) {
if err != nil {
t.Fatalf("mesh-sdk cannot decode the manifest: %v", err)
}
// The part claims no seat: the seat mesh-grants served the lease write alone, which went with the controller
// (novox/hq ADR 0590 §3, issue 1126).
if m.Module != "mesh-grants" || len(m.Claims) != 0 {
t.Errorf("module %q claims %v: the part claims no seat", m.Module, m.Claims)
// The part claims the seat mesh-grants, which serves `grants-for` (design 47 G §401, §441).
if m.Module != "mesh-grants" || len(m.Claims) != 1 || m.Claims[0].Name != "mesh-grants" || !slices.Equal(m.Claims[0].Serves, []string{"grants-for"}) {
t.Errorf("module %q claims %v: the part claims the seat mesh-grants alone, serving grants-for", m.Module, m.Claims)
}
for _, row := range []struct {
what string
@@ -5104,3 +5122,37 @@ func TestAnOldStateSectionDeclaresItsCap(t *testing.T) {
}
}
}
// grants-for answers what the composed accounts gain and lose with a candidate's entries in place of the branch's newest (design
// 47 G §441, A-205): a tool the candidate adds is an added grant naming its verb, and an input that names no source nor run is
// refused.
func TestGrantsFor(t *testing.T) {
b := fixture()
candidateX := strings.Replace(strings.Replace(xManifest, `,"logs":[{"name":"history","max-age-days":30}]`, "", 1), `"state"`, `"emits":["hello"],"state"`, 1)
b.revision = map[string]map[string]string{"newest": {"mod-x": xManifest}, "candidate": {"mod-x": candidateX}}
p := partOn(b)
got, err := p.GrantsFor(meshgrants.GrantsForInput{Branch: "main", Run: "r1"})
if err != nil || got.Error != "" || len(got.Modules) != 1 || got.Modules[0].Module != "mod-x" {
t.Fatalf("grants-for: %+v, %v", got, err)
}
var verbs []string
for _, g := range got.Modules[0].Added {
verbs = append(verbs, g.Verb+" "+g.Subject)
}
if !slices.ContainsFunc(got.Modules[0].Added, func(g meshgrants.Grant) bool {
return g.Verb == "hello" && strings.HasPrefix(g.Subject, "mesh.mod.mod-x.")
}) {
t.Errorf("the event the candidate adds is not an added grant: %v / %+v", verbs, got.Modules[0])
}
if len(got.Modules[0].Removed) == 0 {
t.Error("the log the candidate drops is no removed grant")
}
b.revision["candidate"] = b.revision["newest"]
same, _ := p.GrantsFor(meshgrants.GrantsForInput{Branch: "main", Source: "7"})
if len(same.Modules) != 0 {
t.Errorf("a candidate equal to the newest changes grants: %+v", same.Modules)
}
if _, err := p.GrantsFor(meshgrants.GrantsForInput{Branch: "main"}); err == nil {
t.Error("grants-for with neither a source nor a run answered")
}
}
@@ -249,6 +249,11 @@ func boundOf(module string, bindings []membership.BusBinding) boundGrants {
case catalogue.StorageKeyValue:
if b.Bucket == base {
g.States = append(g.States, b.Local)
// Its object store beside it, `<state>-objects`, is its owner's alone (design 47 G §58, §91): the one bucket the
// binding names for this module's own state.
if b.Objects != "" && b.Objects == module+"_"+catalogue.StateObjectsName(b.Local) {
g.Objects = append(g.Objects, b.Objects)
}
}
case catalogue.StorageObjectStore:
if b.ObjectStore == base {
@@ -115,3 +115,6 @@ func callerNamed(user string, pub, sub []string) ([]string, []string) {
}
return unique(pub), unique(sub)
}
// SeatToolSubject is where a seat's verb is served: `mesh.seat.<seat>.tool.<verb>`, with the node last on a node seat.
func SeatToolSubject(s Seat, verb, node string) string { return seatToolSubject(s, verb, node) }
@@ -0,0 +1,69 @@
package buscompose
import "testing"
// Design 47 G §543, §544, §600: a build seat's ask names its asker, each queue has a named worker beside main's, an asker
// is granted the queues of its kinds under its own seat's name alone, and main's subject is the checker's and the builder's.
func TestNamedAsks(t *testing.T) {
build := Seat{Name: "node-build-go", Scope: "node", Accepts: []string{"delivery", "check", "recheck"}, PulledByKind: true,
AcceptCallers: map[string][]string{
"delivery": {"mesh-builds"},
"check": {"mesh-pipeline-runner", "mesh-catalog", "mesh-delivery-checker"},
"recheck": {"mesh-delivery-checker"},
}}
asker := func(module string, held ...string) Principal {
p := Principal{Kind: KindModule, Node: "one", Module: module, Uses: []Seat{build}}
for _, h := range held {
p.Holds = append(p.Holds, Seat{Name: h})
}
return p
}
const base = "mesh.seat.node-build-go.accept."
for _, c := range []struct {
who Principal
want map[string]bool
}{
{asker("runner-module", "mesh-pipeline-runner"), map[string]bool{
base + "check.mesh-pipeline-runner": true, base + "delivery.mesh-pipeline-runner": false,
base + "check.mesh-catalog": false, base + "check": false, base + "delivery": false}},
{asker("an-indexer", "mesh-catalog"), map[string]bool{
base + "check.mesh-catalog": true, base + "check.mesh-pipeline-runner": false, base + "recheck.mesh-catalog": false}},
{asker("the-builder", "mesh-builds"), map[string]bool{
base + "delivery.mesh-builds": true, base + "delivery": true, base + "check": true, base + "check.mesh-builds": false}},
{asker("the-checker", "mesh-delivery-checker"), map[string]bool{
base + "check.mesh-delivery-checker": true, base + "recheck.mesh-delivery-checker": true, base + "recheck": true,
base + "delivery.mesh-delivery-checker": false}},
{asker("a-stranger"), map[string]bool{base + "check": false, base + "delivery": false, base + "check.a-stranger": false}},
} {
perms, err := PermissionsFor(c.who)
if err != nil {
t.Fatal(err)
}
for subject, want := range c.want {
if got := MayPublish(perms, subject); got != want {
t.Errorf("%s may publish %s: %v, want %v", c.who.Module, subject, got, want)
}
}
}
// Each queue's workers: main's and the named one, filtered to subjects that overlap nothing.
held := Seat{Name: "node-build-go", Scope: "node", Accepts: []string{"delivery", "check"}, PulledByKind: true}
tr := SeatTrafficOf("go-module", []Seat{held}, nil, nil)
filters := map[string]string{}
for _, w := range tr.Workers {
filters[w.Consumer] = w.Filter
}
for consumer, filter := range map[string]string{
"SEAT_NODE_BUILD_GO_CHECK_worker": base + "check",
"SEAT_NODE_BUILD_GO_CHECK_named_worker": base + "check.*",
"SEAT_NODE_BUILD_GO_DELIVERY_worker": base + "delivery",
"SEAT_NODE_BUILD_GO_DELIVERY_named_worker": base + "delivery.*",
} {
if filters[consumer] != filter {
t.Errorf("worker %s filters %q, want %q", consumer, filters[consumer], filter)
}
}
_, consumers := SeatTrafficObjects([]Principal{{Kind: KindModule, Node: "one", Module: "go-module", Holds: []Seat{held}}})
if len(consumers) != 4 {
t.Errorf("the work queue's consumers: %d, want 4 (a main and a named worker for each of two queues)", len(consumers))
}
}
@@ -103,6 +103,10 @@ type Seat struct {
// PulledByKind says each accepted kind is a worker of its own on the seat's queue, filtered to that kind, which
// every holder pulls in the order Accepts lists them: the build seats' (novox/hq ADR 0525 §2, ADR 0536 §4).
PulledByKind bool
// AcceptCallers are, for a seat pulled by kind, the seats that may ask each of its queues, by queue: the `seat:<seat>`
// entries of the callers of the accepted kinds the definition puts on that queue (design 47 G §543, §600). The asker
// in a named ask's subject is the asking seat's name (A-163). Empty where the seat list is unread.
AcceptCallers map[string][]string
// HeldByTheEngine says every node's engine holds the seat on its own account (catalogue.Seat.HeldByTheEngine, novox/hq
// ADR 0563 §1): each of its events names the engine's machine as its last token (machineEvent).
HeldByTheEngine bool
@@ -35,6 +35,16 @@ const BuildAskMaxDeliver = 5
// KindedBenches are the seats that may be kinded (ADR 0234 §2): making another is a decision, recorded.
var KindedBenches = map[string]bool{"channel": true, "intake": true}
// NamedWorkerName is the worker of a pulled-by-kind seat's named asks, `accept.<queue>.<asker>`, beside the queue's own (WorkerName):
// two filters that overlap nothing, so the work queue takes both (design 47 G §544).
func NamedWorkerName(seat, queue string) string {
return "SEAT_" + upperSnake(seat) + "_" + upperSnake(queue) + "_named_worker"
}
// MainAskers are the seats that may publish a build seat's ask on main's subject `accept.<queue>`, which names no asker: the
// checker and the builder, until main's subject goes (design 47 G §543, §600, A-184).
var MainAskers = []string{"mesh-delivery-checker", "mesh-builds"}
// WorkerName is the worker a seat's holders pull from: one for the seat, or one per kind on a kinded bench.
func WorkerName(seat, kind string) string {
if kind == "" {
@@ -86,6 +96,9 @@ func SeatTrafficOf(module string, holds, uses, watches []Seat) SeatTraffic {
for _, a := range s.Accepts {
t.Workers = append(t.Workers, Worker{Stream: seatStreamName(s.Name), Consumer: WorkerName(s.Name, a),
Filter: "mesh.seat." + s.Name + ".accept." + a})
// Its named asks have a worker of their own (§544); a holder of G pulls it, one before G knows only main's.
t.Workers = append(t.Workers, Worker{Stream: seatStreamName(s.Name), Consumer: NamedWorkerName(s.Name, a),
Filter: "mesh.seat." + s.Name + ".accept." + a + ".*"})
}
} else if len(s.Accepts) > 0 {
stream := seatStreamName(s.Name)
@@ -121,7 +134,25 @@ func SeatTrafficOf(module string, holds, uses, watches []Seat) SeatTraffic {
if !s.isNewTraffic() {
continue
}
if s.PulledByKind {
// **An ask names its asker** (§543, §600): each asker is granted `accept.<queue>.<asker>` for the queues whose
// kinds it is a caller of, its name the seat it holds, and main's `accept.<queue>` is the checker's and the
// builder's alone.
for _, q := range s.Accepts {
for _, h := range holds {
if namesVerb(s.AcceptCallers[q], h.Name) {
t.Publish = append(t.Publish, seatSubject(s, "accept", q+"."+h.Name))
}
if namesVerb(MainAskers, h.Name) {
t.Publish = append(t.Publish, seatSubject(s, "accept", q))
}
}
}
}
for _, a := range s.Accepts {
if s.PulledByKind {
break
}
switch {
case namesVerb(s.ByCaller, a):
t.Publish = append(t.Publish, seatSubject(s, "accept", a+"."+module))
@@ -205,7 +236,7 @@ func (s Seat) isNewTraffic() bool {
// plainVerbs is a seat's accepts or emits with those the rules above compose taken out: a verb named by
// its caller and every verb of a kinded bench are composed by SeatTrafficOf and nowhere else.
func plainVerbs(s Seat, verbs []string) []string {
if s.Kinded {
if s.Kinded || s.PulledByKind {
return nil
}
var out []string
@@ -0,0 +1,38 @@
package buscompose
import (
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/membership"
)
// Design 47 G §58, §59, §91, §124: a state's `<state>-objects` store is its owner's alone, and a sent store is read, never
// written, by the modules it is for.
func TestStateObjectsAndSentStores(t *testing.T) {
owner, err := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "shop", Bound: []membership.BusBinding{
{Local: "orders", Storage: catalogue.StorageKeyValue, Template: catalogue.TemplateState, Bucket: "shop_orders", Objects: "shop_orders-objects"}}})
if err != nil {
t.Fatal(err)
}
other, err := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "bank"})
if err != nil {
t.Fatal(err)
}
for _, subject := range []string{"$O.shop_orders-objects.C.x", "$O.shop_orders-objects.M.x", "$JS.API.DIRECT.GET.OBJ_shop_orders-objects.x"} {
if !MayPublish(owner, subject) {
t.Errorf("the owner may not publish %s", subject)
}
if MayPublish(other, subject) {
t.Errorf("another module may publish %s", subject)
}
}
reader, err := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "bank", ReadsObjects: []string{"shop_sent-objects"}})
if err != nil {
t.Fatal(err)
}
if !MayPublish(reader, "$JS.API.DIRECT.GET.OBJ_shop_sent-objects.x") || MayPublish(reader, "$O.shop_sent-objects.C.x") ||
MayPublish(reader, "$JS.API.DIRECT.GET.OBJ_other_sent-objects.x") {
t.Error("a reader of a sent store reads that one and writes none")
}
}
@@ -0,0 +1,139 @@
package grants
import (
"encoding/json"
"errors"
"fmt"
"slices"
"sort"
"strings"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"mesh-grants/internal/buscompose"
)
// The tools that say who may call and why a call is refused (design 47 G §83, GR2).
const (
ToolCallers = "grants_callers"
ToolWhyRefused = "grants_why_refused"
)
// CallerLine is one verb's, or one accepted kind's, callers as a seat definition gives them.
type CallerLine struct {
Seat string `json:"seat"`
// Verb is the verb's name, or the accepted kind's.
Verb string `json:"verb"`
// Kind is `verb` or `accepts`.
Kind string `json:"kind"`
Class string `json:"class,omitempty"`
// Callers are the entries the verb admits: the list the definition names, or its class's default.
Callers []string `json:"callers"`
// Named says the definition names the list; false is the class's default (§391).
Named bool `json:"named"`
}
// definitions are the seat definitions the part composes from, or why it has none.
func (p *Part) definitions() (map[string]seatdef.Definition, error) {
d, ok := p.SeatList.(SeatDefinitions)
if !ok {
return nil, errors.New("the seat list is not read here: the definitions' callers are unknown")
}
defs := d.Definitions()
if len(defs) == 0 {
return nil, errors.New("the seat list holds no definitions yet")
}
return defs, nil
}
// CallerLines are the callers each verb and each accepted kind admits, from the definitions, of the seat named (every seat
// when empty) and the verb named (every verb when empty).
func CallerLines(defs map[string]seatdef.Definition, seat, verb string) []CallerLine {
var out []CallerLine
for _, d := range defs {
if seat != "" && d.Seat != seat {
continue
}
for _, v := range d.Verbs {
if verb == "" || v.Name == verb {
out = append(out, CallerLine{Seat: d.Seat, Verb: v.Name, Kind: "verb", Class: v.Class,
Callers: v.EffectiveCallers(), Named: v.Callers != nil && !v.Callers.IsText()})
}
}
for _, a := range d.Accepts {
if verb == "" || a.Name == verb {
l := CallerLine{Seat: d.Seat, Verb: a.Name, Kind: "accepts"}
if a.Callers != nil && !a.Callers.IsText() {
l.Callers, l.Named = a.Callers.List, true
}
out = append(out, l)
}
}
}
sort.Slice(out, func(i, j int) bool {
a, b := out[i], out[j]
return a.Seat+"\x00"+a.Kind+"\x00"+a.Verb < b.Seat+"\x00"+b.Kind+"\x00"+b.Verb
})
return out
}
// Callers answers the tool grants_callers.
func (p *Part) Callers(seat, verb string) (any, error) {
defs, err := p.definitions()
if err != nil {
return nil, err
}
lines := CallerLines(defs, seat, verb)
if len(lines) == 0 {
return nil, fmt.Errorf("no seat definition names a verb or an accepted kind matching seat %q verb %q", seat, verb)
}
return map[string]any{"callers": lines, "count": len(lines)}, nil
}
// WhyRefused answers the tool grants_why_refused: the grant an account lacks to call address (`<seat>.<verb>`), and the
// definition's line that leaves it out. The bus answers whether the account may publish the verb's call subject
// (nats.nats_user_can, the account's grants as the server holds them); the definition's callers say who was meant to.
func (p *Part) WhyRefused(account, address, node string) (any, error) {
seat, verb, ok := strings.Cut(address, ".")
if account == "" || !ok || seat == "" || verb == "" {
return nil, errors.New("why_refused names an account and a verb as <seat>.<verb>")
}
defs, err := p.definitions()
if err != nil {
return nil, err
}
lines := CallerLines(defs, seat, verb)
if len(lines) == 0 {
return nil, fmt.Errorf("no seat definition names the verb %s", address)
}
def := defs[seat]
s := buscompose.Seat{Name: seat, Scope: def.Scope}
subject := buscompose.CalledSubject(buscompose.SeatToolSubject(s, verb, node), account)
if subject == "" {
return nil, fmt.Errorf("%s is not the name of a bus user", account)
}
out := map[string]any{"account": account, "verb": address, "subject": subject, "definition": lines}
raw, err := p.Call.Call(CallUserCan, map[string]any{"user": account, "action": "publish", "subject": subject})
if err != nil {
out["bus"] = "not read: " + err.Error()
return out, nil
}
var can struct {
Allowed *bool `json:"allowed"`
}
_ = json.Unmarshal(raw, &can)
out["bus"] = json.RawMessage(raw)
switch {
case can.Allowed == nil:
out["says"] = "the bus's answer names no verdict; read it beside the definition's line"
case *can.Allowed:
out["says"] = "not refused at the bus: the account holds the grant to publish " + subject
default:
callers := lines[0].Callers
out["says"] = fmt.Sprintf("the account lacks the grant to publish %s; the definition admits %s (%s), and the grants part grants a call only to a caller one of those entries names",
subject, strings.Join(callers, ", "), map[bool]string{true: "named by the definition", false: "the class's default"}[lines[0].Named])
out["lacks"] = subject
out["admitted_by"] = slices.Clone(callers)
}
return out, nil
}
@@ -0,0 +1,57 @@
package grants
import (
"encoding/json"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
type defsGate struct{ defs map[string]seatdef.Definition }
func (defsGate) MayAct(...string) bool { return true }
func (g defsGate) Definitions() map[string]seatdef.Definition { return g.defs }
type canCall struct {
allowed bool
asked map[string]any
}
func (c *canCall) Call(key string, body any) (json.RawMessage, error) {
c.asked = body.(map[string]any)
return json.Marshal(map[string]any{"allowed": c.allowed})
}
// grants_callers and grants_why_refused read the definitions' callers (design 47 G §83): a verb that names none takes its
// class's default, and a refused account is told the call subject it lacks and the callers the definition admits.
func TestCallersAndWhyRefused(t *testing.T) {
defs := map[string]seatdef.Definition{"mesh-wants": {Seat: "mesh-wants", Scope: "mesh", Verbs: []seatdef.Verb{
{Name: "upgrade", Class: seatdef.ClassAct},
{Name: "entry", Callers: &seatdef.Callers{List: []string{"seat:mesh-pipeline-runner", "operator"}}},
}}}
lines := CallerLines(defs, "mesh-wants", "")
if len(lines) != 2 || lines[0].Verb != "entry" || !lines[0].Named || lines[1].Named ||
strings.Join(lines[1].Callers, ",") != "operator,sessions" {
t.Fatalf("lines: %+v", lines)
}
can := &canCall{}
p := &Part{SeatList: defsGate{defs}, Call: can}
got, err := p.WhyRefused("one.shop", "mesh-wants.upgrade", "")
if err != nil {
t.Fatal(err)
}
out := got.(map[string]any)
if out["lacks"] != "mesh.seat.mesh-wants.call.upgrade.one~shop" || can.asked["subject"] != out["lacks"] ||
!strings.Contains(out["says"].(string), "operator, sessions") {
t.Errorf("a refused caller: %+v", out)
}
can.allowed = true
got, _ = p.WhyRefused("one.shop", "mesh-wants.upgrade", "")
if _, lacks := got.(map[string]any)["lacks"]; lacks {
t.Errorf("an allowed caller lacks a grant: %+v", got)
}
if _, err := p.WhyRefused("one.shop", "mesh-wants.nothing", ""); err == nil {
t.Error("a verb no definition names was explained")
}
}
@@ -0,0 +1,188 @@
package grants
import (
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"sort"
"strconv"
"strings"
"git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshgrants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// **The seat mesh-grants' read `grants-for`** (design 47 G §441, §401, A-205): the grants a candidate would compose, per
// module, added and removed against the branch's newest. The candidate's catalog half is taken by mesh-catalog's `revision` (a
// run by its group `run-<id>`, a source revision by the branch and `source`), the branch's newest by `revision` with the branch
// alone; the answer is what the composed memberships' permissions gain and lose with the candidate's entries swapped in for the
// branch's newest.
// RunGroup is the group of a run's candidate in mesh-catalog's `revision` (A-205).
const RunGroup = "run-"
// CallRevision is the seat mesh-catalog's `revision`, as the part calls it.
const CallRevision = "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbRevision
// revisionEntries reads a catalog graph revision's entries, page after page, as manifests by module. none says the branch has
// no revision yet.
func (p *Part) revisionEntries(in meshcatalog.RevisionInput) (manifests map[string]catalogue.Manifest, none bool, err error) {
manifests = map[string]catalogue.Manifest{}
for {
raw, err := p.Call.Call(CallRevision, in)
if err != nil {
return nil, false, fmt.Errorf("%s does not answer: %w", CallRevision, err)
}
var a meshcatalog.RevisionAnswer
if err := json.Unmarshal(raw, &a); err != nil {
return nil, false, fmt.Errorf("%s answered what is not a revision: %w", CallRevision, err)
}
if a.NoneYet {
return nil, true, nil
}
for _, e := range a.Entries {
body, err := json.Marshal(e.Manifest)
if err != nil || len(e.Manifest) == 0 {
continue
}
m, err := catalogue.Decode(body)
if err != nil {
return nil, false, fmt.Errorf("the manifest of %s in the revision does not decode: %w", e.Module, err)
}
manifests[e.Module] = m
}
if a.Next == "" || a.Next == in.After {
return manifests, false, nil
}
in.After = a.Next
}
}
// grantsOfEntries is, by module, the subjects the composed accounts of that module may publish or subscribe, composed from in with
// the entries' manifests in place of the trunk's and of what runs.
func grantsOfEntries(in Inputs, entries map[string]catalogue.Manifest) (map[string]map[string]bool, error) {
in.Manifests = maps.Clone(in.Manifests)
in.Running = maps.Clone(in.Running)
for module, m := range entries {
in.Manifests[module] = m
for key := range in.Running {
if strings.HasSuffix(key, "."+module) {
delete(in.Running, key)
}
}
}
recs, _ := ListRecords(in)
users, refused, err := ComposeEach(recs)
if err != nil {
return nil, err
}
if len(refused) > 0 {
user := sortedKeys(refused)[0]
return nil, fmt.Errorf("the grants of %s do not compose: %s", user, refused[user])
}
out := map[string]map[string]bool{}
for _, u := range users {
_, module, ok := strings.Cut(u.User, ".")
if _, named := entries[module]; !ok || !named {
continue
}
if out[module] == nil {
out[module] = map[string]bool{}
}
for _, s := range append(slices.Clone(u.Publish), u.Subscribe...) {
out[module][s] = true
}
}
return out, nil
}
// verbOf names the verb, event or tool a subject is for: `mesh.seat.<seat>.<kind>.<name>…` and `mesh.mod.<module>.<kind>.<name>…`.
func verbOf(subject string) string {
parts := strings.Split(subject, ".")
if len(parts) >= 5 && parts[0] == "mesh" && (parts[1] == "seat" || parts[1] == "mod") {
return parts[4]
}
return ""
}
func grantList(subjects []string) []meshgrants.Grant {
out := []meshgrants.Grant{}
for _, s := range subjects {
out = append(out, meshgrants.Grant{Subject: s, Verb: verbOf(s)})
}
return out
}
// GrantsFor answers the verb grants-for.
func (p *Part) GrantsFor(in meshgrants.GrantsForInput) (meshgrants.GrantsFor, error) {
if in.Branch == "" {
return meshgrants.GrantsFor{}, errors.New("grants-for names the candidate's watched branch")
}
candidate := meshcatalog.RevisionInput{Branch: in.Branch}
switch {
case in.Run != "":
candidate.Group = RunGroup + in.Run
case in.Source != "":
n, err := strconv.ParseInt(in.Source, 10, 64)
if err != nil {
return meshgrants.GrantsFor{}, fmt.Errorf("the source revision %q is not a number", in.Source)
}
candidate.Source = n
default:
return meshgrants.GrantsFor{}, errors.New("grants-for names a source revision or a run")
}
cand, none, err := p.revisionEntries(candidate)
if err != nil || none {
return meshgrants.GrantsFor{Error: orWhy(err, "the candidate's catalog half is not held: the branch has no revision of it")}, nil
}
newest, none, err := p.revisionEntries(meshcatalog.RevisionInput{Branch: in.Branch})
if err != nil || none {
return meshgrants.GrantsFor{Error: orWhy(err, "the branch's newest catalog half is not held")}, nil
}
base := map[string]catalogue.Manifest{}
for module := range cand {
if m, ok := newest[module]; ok {
base[module] = m
}
}
input := p.inputs()
was, err := grantsOfEntries(input, base)
if err != nil {
return meshgrants.GrantsFor{Error: "the branch's newest does not compose: " + err.Error()}, nil
}
will, err := grantsOfEntries(input, cand)
if err != nil {
return meshgrants.GrantsFor{Error: "the candidate does not compose: " + err.Error()}, nil
}
var out meshgrants.GrantsFor
for _, module := range sortedKeys(will) {
var added, removed []string
for s := range will[module] {
if !was[module][s] {
added = append(added, s)
}
}
for s := range was[module] {
if !will[module][s] {
removed = append(removed, s)
}
}
if len(added)+len(removed) == 0 {
continue
}
sort.Strings(added)
sort.Strings(removed)
out.Modules = append(out.Modules, meshgrants.GrantsForModulesItem{Module: module, Added: grantList(added), Removed: grantList(removed)})
}
return out, nil
}
func orWhy(err error, why string) string {
if err != nil {
return err.Error()
}
return why
}
@@ -190,6 +190,10 @@ type Inputs struct {
// EventSubjects are, by seat, the subjects of its events that carry parts, by the event's local name, as the definitions
// give them: where a node-scoped seat's event names its machine (buscompose.Seat.EventSubjects).
EventSubjects map[string]map[string]string
// AcceptCallers are, by pulled-by-kind seat and queue, the seats that may ask it (acceptCallersOf).
AcceptCallers map[string]map[string][]string
// VerbCallers are, by seat and verb, the callers each verb of the definitions admits (verbCallersOf).
VerbCallers map[string]map[string][]string
// Defined are the events a seat definition of the seat list defines, by local name, and mesh-sdk's finding events: the
// events a `*` emitter before them reaches each declaring module's own stream for (design 47 G §386, §474, §644).
Defined map[string]bool
@@ -370,6 +374,8 @@ func ReadInputs(r Reader, cache *Manifests) Inputs {
in.Kept = buscompose.KeptEventsOf(d.Definitions())
in.Chunked = buscompose.ChunkVerbsOf(d.Definitions())
in.EventSubjects = eventSubjectsOf(d.Definitions())
in.AcceptCallers = acceptCallersOf(d.Definitions())
in.VerbCallers = verbCallersOf(d.Definitions())
in.Defined = definedEventsOf(d.Definitions())
}
nodes := map[string]bool{}
@@ -135,3 +135,45 @@ func withEventSubjects(subjects map[string]map[string]string, d *buscompose.Decl
}
}
}
// acceptCallersOf is, by pulled-by-kind seat and then by queue, the seats that may ask the queue: the `seat:<seat>` entries
// of the callers of every accepted kind the definition puts on it (a kind's `stream` is its queue, else its name is). Never a
// name of the grants part's own: it reads the definitions' lists (design 47 G §543, §600, A-163).
func acceptCallersOf(defs map[string]seatdef.Definition) map[string]map[string][]string {
out := map[string]map[string][]string{}
for _, d := range defs {
if !d.PulledByKind {
continue
}
for _, a := range d.Accepts {
if a.Callers == nil || a.Callers.IsText() {
continue
}
queue := a.Name
if a.Stream != "" {
queue = a.Stream
}
for _, e := range a.Callers.List {
if seat, ok := strings.CutPrefix(e, seatdef.CallerSeatPrefix); ok && !slices.Contains(out[d.Seat][queue], seat) {
if out[d.Seat] == nil {
out[d.Seat] = map[string][]string{}
}
out[d.Seat][queue] = append(out[d.Seat][queue], seat)
}
}
}
}
return out
}
// withAcceptCallers gives each pulled-by-kind seat a declaration holds or uses the askers of its queues (Seat.AcceptCallers).
func withAcceptCallers(askers map[string]map[string][]string, d *buscompose.Declared) {
if len(askers) == 0 {
return
}
for _, list := range []*[]buscompose.Seat{&d.Holds, &d.Uses, &d.Watches} {
for i := range *list {
(*list)[i].AcceptCallers = askers[(*list)[i].Name]
}
}
}
@@ -0,0 +1,36 @@
package grants
import (
"slices"
"testing"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// The askers of a build seat's queue are read from the definition's callers lists (design 47 G §543, §600, A-163): a kind's
// `stream` is its queue, a text callers names none, and only `seat:` entries are askers.
func TestAcceptCallersOf(t *testing.T) {
msg := func(name, stream string, callers ...string) seatdef.Message {
m := seatdef.Message{Name: name, Stream: stream}
if callers != nil {
m.Callers = &seatdef.Callers{List: callers}
}
return m
}
got := acceptCallersOf(map[string]seatdef.Definition{
"node-build-go": {Seat: "node-build-go", PulledByKind: true, Accepts: []seatdef.Message{
msg("check", "", "seat:mesh-catalog", "operator"),
msg("step", "check", "seat:mesh-pipeline-runner"),
msg("delivery", "", "seat:mesh-builds"),
{Name: "recheck", Callers: &seatdef.Callers{Text: "the checker"}},
}},
"other": {Seat: "other", Accepts: []seatdef.Message{msg("go", "", "seat:x")}},
})
if len(got) != 1 {
t.Fatalf("seats: %v, want node-build-go alone", got)
}
q := got["node-build-go"]
if !slices.Equal(q["check"], []string{"mesh-catalog", "mesh-pipeline-runner"}) || !slices.Equal(q["delivery"], []string{"mesh-builds"}) || len(q) != 2 {
t.Errorf("queues: %v", q)
}
}
@@ -102,10 +102,14 @@ func records(in Inputs, union bool) (buscompose.Records, []Gap) {
d.Watches, d.Consumes, d.Hears, keptHeard = keptOutOfHearing(in.Kept, d.Watches, d.Consumes, d.Hears)
d.HearsAStream = d.HearsAStream || keptHeard
d.Reads, d.ReadsObjects, d.ReadsRefused = readsOfObjects(m.Module, node, d.Reads, d.ReadsRefused, declared, values)
// The sent stores of the modules it is for (design 47 G §59, §124), read from the catalog graph's manifests and the
// definitions' callers.
d.ReadsObjects = append(d.ReadsObjects, sentStoresRead(m, in.Manifests, in.VerbCallers)...)
// Its bindings as kept (bindings.go): the same source its membership's `bindings` is written from in this pass,
// so a grant and its binding are written together, never one before the other (issue 1966, the kind of issue 249).
d.Bindings = in.Bindings[m.Module]
withEventSubjects(in.EventSubjects, &d)
withAcceptCallers(in.AcceptCallers, &d)
return d
}
d := declare(m)
@@ -137,6 +141,7 @@ func records(in Inputs, union bool) (buscompose.Records, []Gap) {
out.Engine = &buscompose.Declared{Module: m.Module, Consumes: m.Consumes, Watches: watches, Invokes: m.Invokes,
State: bucketsFor(m, in.Nodes), Logs: logsOf(m), Streams: streamsOf(m)}
withEventSubjects(in.EventSubjects, out.Engine)
withAcceptCallers(in.AcceptCallers, out.Engine)
}
return out, gaps
}
@@ -0,0 +1,86 @@
package grants
import (
"slices"
"strings"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// **A module's sent store is read by the modules it is for** (design 47 G §59, §124): the grants part derives, from the
// catalog graph and the seat definitions, never from a manifest field, a standing read of `<module>_sent-objects` for the
// callers the module's seat definition names for the verbs it serves, and for the consumers whose `consumes` declare its
// events. The grant follows the catalog graph, so it is composed with each module's declaration at every pass.
// verbCallersOf is, by seat and verb, the callers each verb of the definitions admits (a verb naming none takes its class's
// default).
func verbCallersOf(defs map[string]seatdef.Definition) map[string]map[string][]string {
out := map[string]map[string][]string{}
for _, d := range defs {
for _, v := range d.Verbs {
if out[d.Seat] == nil {
out[d.Seat] = map[string][]string{}
}
out[d.Seat][v.Name] = v.EffectiveCallers()
}
}
return out
}
// admits says whether a verb's callers name the module: `invokers` (every module whose manifest invokes the verb), the module
// itself, or a seat it claims.
func admits(callers []string, m catalogue.Manifest) bool {
for _, c := range callers {
switch {
case c == seatdef.CallerInvokers, c == seatdef.CallerModulePrefix+m.Module:
return true
}
if seat, ok := strings.CutPrefix(c, seatdef.CallerSeatPrefix); ok && slices.ContainsFunc(m.Claims, func(x catalogue.Claim) bool { return x.Name == seat }) {
return true
}
}
return false
}
// sentStoresRead are the bus names of the sent stores the module m reads: of each module whose event it consumes (the module's
// own, or the seat a module claims), and of each module claiming a seat whose verb m invokes where the verb's callers admit m.
// Never m's own store, which its binding grants it.
func sentStoresRead(m catalogue.Manifest, all map[string]catalogue.Manifest, callers map[string]map[string][]string) []string {
claimants := func(name string) []string {
var out []string
if _, ok := all[name]; ok {
out = append(out, name)
}
for module, x := range all {
if slices.ContainsFunc(x.Claims, func(c catalogue.Claim) bool { return c.Name == name }) {
out = append(out, module)
}
}
return out
}
var stores []string
for _, c := range m.Consumes {
name, _, ok := strings.Cut(strings.TrimPrefix(c, "seat:"), ".")
if !ok || name == "*" {
continue
}
for _, module := range claimants(name) {
stores = append(stores, catalogue.SentObjectsName(module))
}
}
for _, in := range m.Invokes {
seat, verb, ok := catalogue.SeatInvoke(in)
if !ok || !admits(callers[seat][verb], m) {
continue
}
for module, x := range all {
if slices.ContainsFunc(x.Claims, func(c catalogue.Claim) bool { return c.Name == seat }) {
stores = append(stores, catalogue.SentObjectsName(module))
}
}
}
stores = slices.DeleteFunc(stores, func(s string) bool { return s == catalogue.SentObjectsName(m.Module) })
slices.Sort(stores)
return slices.Compact(stores)
}
@@ -0,0 +1,38 @@
package grants
import (
"slices"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// The sent stores a module reads follow the catalog graph (design 47 G §59, §124): the consumers of a module's events and the
// callers a seat's verb admits, and no other module.
func TestSentStoresRead(t *testing.T) {
holder := catalogue.Manifest{Module: "shop", Claims: []catalogue.Claim{{Name: "orders-seat"}}}
all := map[string]catalogue.Manifest{"shop": holder, "bank": {Module: "bank"}, "plain": {Module: "plain"}}
callers := map[string]map[string][]string{"orders-seat": {
"place": {"seat:billing", "module:plain"}, "list": seatdef.DefaultCallers(seatdef.ClassRead), "wipe": seatdef.DefaultCallers(seatdef.ClassAct)}}
for _, c := range []struct {
name string
m catalogue.Manifest
want []string
}{
{"consumes a module's event", catalogue.Manifest{Module: "bank", Consumes: []string{"shop.sold"}}, []string{"shop_sent-objects"}},
{"consumes a seat's event", catalogue.Manifest{Module: "bank", Consumes: []string{"orders-seat.sold"}}, []string{"shop_sent-objects"}},
{"invokes a verb that names its seat", catalogue.Manifest{Module: "bank", Claims: []catalogue.Claim{{Name: "billing"}},
Invokes: []string{"seat:orders-seat.place"}}, []string{"shop_sent-objects"}},
{"invokes a verb that names it", catalogue.Manifest{Module: "plain", Invokes: []string{"seat:orders-seat.place"}}, []string{"shop_sent-objects"}},
{"invokes a read, its callers include invokers", catalogue.Manifest{Module: "bank", Invokes: []string{"seat:orders-seat.list"}}, []string{"shop_sent-objects"}},
{"invokes an act no one names it for", catalogue.Manifest{Module: "bank", Invokes: []string{"seat:orders-seat.wipe"}}, nil},
{"invokes a verb that names others", catalogue.Manifest{Module: "bank", Invokes: []string{"seat:orders-seat.place"}}, nil},
{"declares neither", catalogue.Manifest{Module: "bank"}, nil},
{"its own store is its binding's", holder, nil},
} {
if got := sentStoresRead(c.m, all, callers); !slices.Equal(got, c.want) {
t.Errorf("%s: %v, want %v", c.name, got, c.want)
}
}
}
+3 -3
View File
@@ -14,8 +14,8 @@ import (
"mesh-grants/internal/buscompose"
)
// The part's tools, as its manifest lists them. The part claims no seat: the seat mesh-grants served the lease write
// alone, which went with the controller (novox/hq ADR 0590 §3, issue 1126).
// The part's tools, as its manifest lists them. The part claims the seat mesh-grants, which serves `grants-for` (design 47 G
// §401, §441); its own tools are named below.
const (
ToolGrants = "grants_grants"
ToolMembership = "grants_membership"
@@ -40,7 +40,7 @@ const (
// Tools is every tool, in the manifest's order.
var Tools = []string{ToolGrants, ToolMembership, ToolUserList, ToolComposeNow, ToolAssert, ToolAccounts, ToolConsumerMatch,
ToolAcceptHashes, ToolFirstViews, ToolFirstViewAgain, ToolRunning, ToolWaits, ToolRelease, ToolSeatList, ToolSeatListAgain}
ToolAcceptHashes, ToolFirstViews, ToolFirstViewAgain, ToolRunning, ToolWaits, ToolRelease, ToolSeatList, ToolSeatListAgain, ToolCallers, ToolWhyRefused}
// WritesGrants is what grants says of the part's own grants: written once the list the bus loaded carries a build's
// accounts, and the one key the assigner reads (ADR 0571 clause 9, which changes ADR 0547 clause 5).
+12 -1
View File
@@ -2,6 +2,15 @@
"module": "mesh-grants",
"version": "0.1",
"slug": "grants",
"claims": [
{
"name": "mesh-grants",
"scope": "mesh",
"serves": [
"grants-for"
]
}
],
"reads": [
"mesh-config.resolved",
"node-engine.have",
@@ -73,7 +82,9 @@
"grants_waits",
"grants_release",
"grants_seat_list",
"grants_seat_list_again"
"grants_seat_list_again",
"grants_callers",
"grants_why_refused"
],
"state": [
{