The seat git's whole test configures no token: the bundle mints the tools' account's token at the fixture forge with the admin's login, writes it through the vault seat's two-step own-put (sealed to the call's key) and reads it through get (sealed to the process's key), both answered by the test, with the mint's lease watched as the runtime delivers it. After the mint the forge holds exactly one token for the account, mesh-tools-1, the one the vault keeps at generation 1; the old fixed-name token is gone. Builds: design 47 H2 §808 (whole: the forge holds one token for the account after), H-A-422, H-A-430 (1), H-A-439, H-A-453 (3)
809 lines
30 KiB
Go
809 lines
30 KiB
Go
//go:build integration
|
|
|
|
package seatgit
|
|
|
|
// The seat git whole, as the forge module serves it (novox/hq design 47 H §734 to §736, §766, §767, §774; acceptance tests
|
|
// 111, 114 and 115; H-A-61, H-A-87): the module's TypeScript bundle, built here and played over its real stdin and stdout
|
|
// as the node's tool runner plays it, its states key-value buckets of a nats-server of this test alone, its seat events
|
|
// published on that bus and read back from its stream, and the forge an httptest server.
|
|
//
|
|
// - At its start a call kept unsaid, stopped after the second of three merges, says one merge-called naming the two
|
|
// that landed, and is kept said (§766, test 111's stop case).
|
|
// - A runner's step-ended of a failed required step at a pull request's head and fingerprint is kept, and a merge call
|
|
// naming that head merges nothing and names the step (§735, test 114).
|
|
// - A call naming two pull requests in two repositories merges both, in order, and says one merge-called (§734, §736).
|
|
// - An hq pull request, of a source-only registration, whose Go checks failed is refused naming the step (H2 §815).
|
|
// - With the forge's store stopped a merge call answers away, and called again once it is back it lands (H2 §776).
|
|
// - A forge that refuses the second merge gives one merge-called with the first member and `refused`, and merge-partial
|
|
// raised; a later call landing the refused member clears it (§767, test 115).
|
|
// - No token is configured: the bundle mints the tools' account's token at the fixture forge with the admin's login,
|
|
// writes it through the vault seat's two-step sealed own-put and reads it through its sealed get, both answered
|
|
// here, and the forge holds one token for the account after, the old fixed-name token deleted (H2 §808, H-A-422,
|
|
// H-A-430 (1), H-A-453 (3)).
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.novox.be/novox/mesh-sdk/go/seal"
|
|
"git.novox.be/novox/mesh-sdk/go/testbus"
|
|
"github.com/nats-io/nats.go"
|
|
"github.com/nats-io/nats.go/jetstream"
|
|
"golang.org/x/crypto/nacl/box"
|
|
)
|
|
|
|
const within = 30 * time.Second
|
|
|
|
// pull is one pull request of the fixture forge.
|
|
type pull struct {
|
|
repo, base, head string
|
|
number int
|
|
merged, refuse bool
|
|
merge string
|
|
}
|
|
|
|
// forge is the fixture forge: the pull requests by `<owner>/<name>#<number>` and every merge asked.
|
|
type forge struct {
|
|
mu sync.Mutex
|
|
pulls map[string]*pull
|
|
merges []string
|
|
paths []string
|
|
// away is the forge's store stopped (§776): the API answers 503 and the version read names the store unavailable.
|
|
away bool
|
|
// admin is the admin's login, which mints (§808); tokens what each account holds; every other call is refused 401
|
|
// unless it carries one of them.
|
|
admin string
|
|
tokens map[string][]forgeToken
|
|
nextID int
|
|
}
|
|
|
|
// forgeToken is one access token the fixture forge minted.
|
|
type forgeToken struct {
|
|
ID int `json:"id"`
|
|
Name string `json:"name"`
|
|
sha1 string
|
|
}
|
|
|
|
// authorized is the admin's basic login or a token the forge holds.
|
|
func (f *forge) authorized(r *http.Request) bool {
|
|
if u, p, ok := r.BasicAuth(); ok {
|
|
return u == f.admin && p == adminPassword
|
|
}
|
|
given := strings.TrimPrefix(r.Header.Get("Authorization"), "token ")
|
|
for _, held := range f.tokens {
|
|
for _, t := range held {
|
|
if given != "" && t.sha1 == given {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// held answers the names of the tokens an account holds and their values.
|
|
func (f *forge) held(account string) (names, values []string) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
for _, t := range f.tokens[account] {
|
|
names, values = append(names, t.Name), append(values, t.sha1)
|
|
}
|
|
return names, values
|
|
}
|
|
|
|
// serveAdmin answers the admin API the mint uses: the admin's own read, the account and its team, and the account's
|
|
// tokens (mint, list, delete). False when the path is not one of them.
|
|
func (f *forge) serveAdmin(w http.ResponseWriter, r *http.Request) bool {
|
|
switch p := r.URL.Path; {
|
|
case p == "/api/v1/user":
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"login": f.admin})
|
|
case p == "/api/v1/admin/users" && r.Method == http.MethodPost:
|
|
w.WriteHeader(http.StatusCreated)
|
|
case p == "/api/v1/orgs/novox/teams" && r.Method == http.MethodGet:
|
|
_, _ = w.Write([]byte("[]"))
|
|
case p == "/api/v1/orgs/novox/teams" && r.Method == http.MethodPost:
|
|
w.WriteHeader(http.StatusCreated)
|
|
_, _ = w.Write([]byte(`{"id":1}`))
|
|
case strings.HasPrefix(p, "/api/v1/teams/1/members/"):
|
|
w.WriteHeader(http.StatusNoContent)
|
|
default:
|
|
m := regexp.MustCompile(`^/api/v1/users/([^/]+)/tokens(?:/(\d+))?$`).FindStringSubmatch(p)
|
|
if m == nil {
|
|
return false
|
|
}
|
|
account := m[1]
|
|
switch {
|
|
case r.Method == http.MethodPost:
|
|
var asked struct {
|
|
Name string `json:"name"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&asked)
|
|
for _, t := range f.tokens[account] {
|
|
if t.Name == asked.Name {
|
|
http.Error(w, `{"message":"access token name has been used already"}`, http.StatusUnprocessableEntity)
|
|
return true
|
|
}
|
|
}
|
|
f.nextID++
|
|
t := forgeToken{ID: f.nextID, Name: asked.Name, sha1: fmt.Sprintf("%040x", 0xa0000+f.nextID)}
|
|
f.tokens[account] = append(f.tokens[account], t)
|
|
w.WriteHeader(http.StatusCreated)
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": t.ID, "name": t.Name, "sha1": t.sha1})
|
|
case r.Method == http.MethodGet:
|
|
if r.URL.Query().Get("page") != "1" {
|
|
_, _ = w.Write([]byte("[]"))
|
|
return true
|
|
}
|
|
_ = json.NewEncoder(w).Encode(f.tokens[account])
|
|
case r.Method == http.MethodDelete:
|
|
kept := f.tokens[account][:0]
|
|
for _, t := range f.tokens[account] {
|
|
if fmt.Sprint(t.ID) != m[2] {
|
|
kept = append(kept, t)
|
|
}
|
|
}
|
|
f.tokens[account] = kept
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// adminPassword is the admin's password the fixture forge takes, in the file the host would unseal it into.
|
|
const adminPassword = "admin-password"
|
|
|
|
func (f *forge) serve(w http.ResponseWriter, r *http.Request) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.paths = append(f.paths, r.Method+" "+r.URL.Path)
|
|
if r.URL.Path == "/api/v1/version" {
|
|
if f.away {
|
|
http.Error(w, `{"message":"the database is unavailable"}`, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
_, _ = w.Write([]byte(`{"version":"1.27.3"}`))
|
|
return
|
|
}
|
|
if f.away {
|
|
http.Error(w, "Service Unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
if !f.authorized(r) {
|
|
http.Error(w, `{"message":"token is required"}`, http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if f.serveAdmin(w, r) {
|
|
return
|
|
}
|
|
m := regexp.MustCompile(`^/api/v1/repos/([^/]+/[^/]+)/pulls/(\d+)(/merge)?$`).FindStringSubmatch(r.URL.Path)
|
|
if m != nil {
|
|
p := f.pulls[m[1]+"#"+m[2]]
|
|
if p == nil {
|
|
http.Error(w, `{"message":"not found"}`, http.StatusNotFound)
|
|
return
|
|
}
|
|
if m[3] != "" && r.Method == http.MethodPost {
|
|
f.merges = append(f.merges, m[1]+"#"+m[2])
|
|
if p.refuse {
|
|
http.Error(w, `{"message":"merge conflict"}`, http.StatusConflict)
|
|
return
|
|
}
|
|
p.merged, p.merge = true, strings.Repeat(fmt.Sprint(p.number%10), 40)
|
|
return
|
|
}
|
|
body := map[string]any{"number": p.number, "title": "t", "state": "open", "merged": p.merged,
|
|
"base": map[string]any{"ref": p.base}, "head": map[string]any{"ref": "feat", "sha": p.head}}
|
|
if p.merged {
|
|
body["state"], body["merge_commit_sha"] = "closed", p.merge
|
|
}
|
|
_ = json.NewEncoder(w).Encode(body)
|
|
return
|
|
}
|
|
if c := regexp.MustCompile(`^/api/v1/repos/[^/]+/[^/]+/git/commits/([0-9a-f]+)$`).FindStringSubmatch(r.URL.Path); c != nil {
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"sha": c[1], "parents": []any{map[string]any{"sha": c[1]}}})
|
|
return
|
|
}
|
|
http.Error(w, `{"message":"the fixture forge serves no `+r.URL.Path+`"}`, http.StatusNotFound)
|
|
}
|
|
|
|
func (f *forge) merged() []string {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return append([]string(nil), f.merges...)
|
|
}
|
|
|
|
func (f *forge) asked(prefix string) bool {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
for _, p := range f.paths {
|
|
if strings.HasPrefix(p, prefix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// runtime is the half of the conversation the tool runner plays for the bundle.
|
|
type runtime struct {
|
|
t *testing.T
|
|
in io.WriteCloser
|
|
js jetstream.JetStream
|
|
kvs map[string]jetstream.KeyValue
|
|
mu sync.Mutex
|
|
next int
|
|
wait map[string]chan json.RawMessage
|
|
// regs are what the seat mesh-catalog's registrations answers; subs the patterns the bundle subscribed.
|
|
regs []map[string]any
|
|
subs []string
|
|
// vault is the seat mesh-vault as this test answers it (§808, §822): the module's own secrets by name, and the
|
|
// own-put calls opened, each with the key its value is sealed to.
|
|
vault map[string]vaulted
|
|
puts map[string]openPut
|
|
}
|
|
|
|
// openPut is an own-put call its first step opened: the name it puts and the key its value is sealed to.
|
|
type openPut struct {
|
|
name string
|
|
pub, priv *[32]byte
|
|
}
|
|
|
|
// vaulted is one secret the test's vault keeps: its newest value and generation.
|
|
type vaulted struct {
|
|
value string
|
|
generation int
|
|
}
|
|
|
|
// vaultAsk answers the seat mesh-vault's get, sealed to the asking process's key, and its two-step own-put, whose value
|
|
// comes sealed to the key the first step made (§822).
|
|
func (r *runtime) vaultAsk(key string, body json.RawMessage) (any, error) {
|
|
var b struct {
|
|
Name string `json:"name"`
|
|
PublicKey string `json:"public_key"`
|
|
Call string `json:"call"`
|
|
Sealed string `json:"sealed"`
|
|
}
|
|
_ = json.Unmarshal(body, &b)
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
switch {
|
|
case key == "seat:mesh-vault.get":
|
|
v, ok := r.vault[b.Name]
|
|
if !ok {
|
|
return nil, fmt.Errorf("the vault holds no secret named %s", b.Name)
|
|
}
|
|
sealed, err := seal.Seal(v.value, b.PublicKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"generation": v.generation, "changed-at": time.Now().UTC().Format(time.RFC3339), "sealed": sealed}, nil
|
|
case b.Call == "":
|
|
pub, priv, err := box.GenerateKey(rand.Reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r.next++
|
|
call := fmt.Sprintf("put-%d", r.next)
|
|
r.puts[call] = openPut{name: b.Name, pub: pub, priv: priv}
|
|
return map[string]any{"call": call, "seal_to": base64.StdEncoding.EncodeToString(pub[:])}, nil
|
|
default:
|
|
put, ok := r.puts[b.Call]
|
|
if !ok {
|
|
return nil, fmt.Errorf("no own-put call %s is open", b.Call)
|
|
}
|
|
raw, err := base64.StdEncoding.DecodeString(b.Sealed)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
value, ok := box.OpenAnonymous(nil, raw, put.pub, put.priv)
|
|
if !ok {
|
|
return nil, fmt.Errorf("the own-put value of %s is not sealed to its call's key", b.Call)
|
|
}
|
|
// The module named by the caller's account, never by an argument: here always the forge module (§822).
|
|
name := "module/gitea/" + put.name
|
|
delete(r.puts, b.Call)
|
|
v := vaulted{value: string(value), generation: r.vault[name].generation + 1}
|
|
r.vault[name] = v
|
|
return map[string]any{"generation": v.generation}, nil
|
|
}
|
|
}
|
|
|
|
func (r *runtime) subscribed(pattern string) bool {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
for _, s := range r.subs {
|
|
if s == pattern {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (r *runtime) say(m map[string]any) {
|
|
m["jsonrpc"] = "2.0"
|
|
raw, _ := json.Marshal(m)
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
_, _ = r.in.Write(append(raw, '\n'))
|
|
}
|
|
|
|
func (r *runtime) read(out io.Reader) {
|
|
sc := bufio.NewScanner(out)
|
|
sc.Buffer(make([]byte, 1<<20), 1<<24)
|
|
for sc.Scan() {
|
|
var m struct {
|
|
ID json.RawMessage `json:"id"`
|
|
Method string `json:"method"`
|
|
Params json.RawMessage `json:"params"`
|
|
Result json.RawMessage `json:"result"`
|
|
}
|
|
if json.Unmarshal(sc.Bytes(), &m) != nil {
|
|
continue
|
|
}
|
|
if m.Method == "" {
|
|
var id string
|
|
_ = json.Unmarshal(m.ID, &id)
|
|
r.mu.Lock()
|
|
ch := r.wait[id]
|
|
delete(r.wait, id)
|
|
r.mu.Unlock()
|
|
if ch != nil {
|
|
ch <- m.Result
|
|
}
|
|
continue
|
|
}
|
|
go r.answer(m.ID, m.Method, m.Params)
|
|
}
|
|
}
|
|
|
|
// answer is the tool runner's answer to one method the bundle asks.
|
|
func (r *runtime) answer(id json.RawMessage, method string, params json.RawMessage) {
|
|
var p struct {
|
|
State string `json:"state"`
|
|
Key string `json:"key"`
|
|
Value json.RawMessage `json:"value"`
|
|
Subject string `json:"subject"`
|
|
Pattern string `json:"pattern"`
|
|
Body json.RawMessage `json:"body"`
|
|
ID string `json:"id"`
|
|
}
|
|
_ = json.Unmarshal(params, &p)
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
result, err := func() (any, error) {
|
|
kv := r.kvs[p.State]
|
|
switch method {
|
|
case "mesh/subscribe":
|
|
r.mu.Lock()
|
|
r.subs = append(r.subs, p.Pattern)
|
|
r.mu.Unlock()
|
|
return map[string]any{}, nil
|
|
case "mesh/state.watch":
|
|
// The mint's lease is watched for its release (§808): its changes are delivered as the runtime delivers them.
|
|
if p.State == "token-lease" {
|
|
var watch string
|
|
_ = json.Unmarshal(id, &watch)
|
|
return map[string]any{}, r.watchState(kv, p.Key, watch)
|
|
}
|
|
return map[string]any{}, nil
|
|
case "mesh/publish", "mesh/seat.record":
|
|
return map[string]any{}, nil
|
|
case "mesh/capabilities":
|
|
return map[string]any{"words": []string{}}, nil
|
|
case "mesh/seat.publish":
|
|
// The seat's event, published on the bus under its id, as the runtime does.
|
|
_, err := r.js.Publish(ctx, p.Subject, p.Body, jetstream.WithMsgID(p.ID))
|
|
return map[string]any{}, err
|
|
case "mesh/ask":
|
|
var a struct {
|
|
Key string `json:"key"`
|
|
}
|
|
_ = json.Unmarshal(params, &a)
|
|
switch a.Key {
|
|
case "seat:mesh-catalog.registrations":
|
|
return map[string]any{"registrations": r.regs}, nil
|
|
case "seat:mesh-hand-acts.hand-act":
|
|
return map[string]any{}, nil
|
|
case "seat:mesh-vault.get", "seat:mesh-vault.own-put":
|
|
return r.vaultAsk(a.Key, p.Body)
|
|
}
|
|
return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key)
|
|
case "mesh/state.get":
|
|
if kv == nil {
|
|
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
|
}
|
|
e, err := kv.Get(ctx, p.Key)
|
|
if errors.Is(err, jetstream.ErrKeyNotFound) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"key": p.Key, "value": json.RawMessage(e.Value()), "revision": e.Revision()}, nil
|
|
case "mesh/state.create":
|
|
if kv == nil {
|
|
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
|
}
|
|
rev, err := kv.Create(ctx, p.Key, p.Value)
|
|
if errors.Is(err, jetstream.ErrKeyExists) {
|
|
return nil, changed{err}
|
|
}
|
|
return map[string]any{"revision": rev}, err
|
|
case "mesh/state.put":
|
|
if kv == nil {
|
|
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
|
}
|
|
rev, err := kv.Put(ctx, p.Key, p.Value)
|
|
return map[string]any{"revision": rev}, err
|
|
case "mesh/state.delete":
|
|
if kv == nil {
|
|
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
|
}
|
|
return map[string]any{}, kv.Delete(ctx, p.Key)
|
|
case "mesh/state.keys":
|
|
if kv == nil {
|
|
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
|
}
|
|
keys, err := kv.Keys(ctx)
|
|
if errors.Is(err, jetstream.ErrNoKeysFound) {
|
|
return []string{}, nil
|
|
}
|
|
return keys, err
|
|
case "mesh/state.info":
|
|
return map[string]any{"bytes": 0, "keys": 0, "max_bytes": 0}, nil
|
|
}
|
|
return nil, fmt.Errorf("the runtime offers no %s to this bundle", method)
|
|
}()
|
|
if id == nil {
|
|
return
|
|
}
|
|
if err != nil {
|
|
code := -32000
|
|
if errors.As(err, new(changed)) {
|
|
code = -32010
|
|
}
|
|
r.say(map[string]any{"id": id, "error": map[string]any{"code": code, "message": err.Error()}})
|
|
return
|
|
}
|
|
r.say(map[string]any{"id": id, "result": result})
|
|
}
|
|
|
|
// watchState delivers each later change of one key of a state to the bundle's watch, as `mesh/state` requests naming
|
|
// the watch, a delete without its current value.
|
|
func (r *runtime) watchState(kv jetstream.KeyValue, key, watch string) error {
|
|
w, err := kv.Watch(context.Background(), key, jetstream.UpdatesOnly())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r.t.Cleanup(func() { _ = w.Stop() })
|
|
go func() {
|
|
for e := range w.Updates() {
|
|
if e == nil {
|
|
continue
|
|
}
|
|
change := map[string]any{"key": e.Key()}
|
|
if e.Operation() == jetstream.KeyValuePut {
|
|
change["current"] = map[string]any{"value": json.RawMessage(e.Value()), "revision": e.Revision()}
|
|
}
|
|
r.mu.Lock()
|
|
r.next++
|
|
n := r.next
|
|
r.mu.Unlock()
|
|
r.say(map[string]any{"id": fmt.Sprintf("rt-watch-%d", n), "method": "mesh/state", "params": map[string]any{"watch": watch, "change": change}})
|
|
}
|
|
}()
|
|
return nil
|
|
}
|
|
|
|
// changed is the runtime's refusal of a create whose key has a value (mesh-sdk's CODE_CHANGED, -32010).
|
|
type changed struct{ error }
|
|
|
|
// ask sends the bundle one request and answers its result.
|
|
func (r *runtime) ask(method string, params map[string]any) json.RawMessage {
|
|
r.t.Helper()
|
|
r.mu.Lock()
|
|
r.next++
|
|
id := fmt.Sprintf("rt-%d", r.next)
|
|
ch := make(chan json.RawMessage, 1)
|
|
r.wait[id] = ch
|
|
r.mu.Unlock()
|
|
r.say(map[string]any{"id": id, "method": method, "params": params})
|
|
select {
|
|
case raw := <-ch:
|
|
return raw
|
|
case <-time.After(within):
|
|
r.t.Fatalf("%s was not answered in %s", method, within)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// mergePull calls the seat's verb as a proved caller and answers its result.
|
|
func (r *runtime) mergePull(pulls ...map[string]any) map[string]any {
|
|
r.t.Helper()
|
|
raw := r.ask("tools/call", map[string]any{"name": "git.merge-pull", "_meta": map[string]any{"mesh/caller": "shanks.claude-code"},
|
|
"arguments": map[string]any{"by": "lead@shanks", "pulls": pulls}})
|
|
var res struct {
|
|
Content []struct {
|
|
Text string `json:"text"`
|
|
} `json:"content"`
|
|
}
|
|
var out map[string]any
|
|
if json.Unmarshal(raw, &res) != nil || len(res.Content) == 0 || json.Unmarshal([]byte(res.Content[0].Text), &out) != nil {
|
|
r.t.Fatalf("merge-pull answered %s", raw)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func until(t *testing.T, what string, ok func() bool) {
|
|
t.Helper()
|
|
deadline := time.Now().Add(within)
|
|
for !ok() {
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("within %s: %s did not happen", within, what)
|
|
}
|
|
select {
|
|
case <-time.After(20 * time.Millisecond):
|
|
}
|
|
}
|
|
}
|
|
|
|
// said is every merge-called on the bus so far, by call.
|
|
func said(t *testing.T, js jetstream.JetStream) map[string]map[string]any {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
out := map[string]map[string]any{}
|
|
s, err := js.Stream(ctx, "SEAT_git_merge-called")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
info, err := s.Info(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for seq := info.State.FirstSeq; seq <= info.State.LastSeq && info.State.Msgs > 0; seq++ {
|
|
m, err := s.GetMsg(ctx, seq)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
var body map[string]any
|
|
_ = json.Unmarshal(m.Data, &body)
|
|
out[strings.TrimPrefix(m.Subject, "mesh.seat.git.event.merge-called.")] = body
|
|
}
|
|
return out
|
|
}
|
|
|
|
func numbers(v any) []float64 {
|
|
var out []float64
|
|
list, _ := v.([]any)
|
|
for _, m := range list {
|
|
n, _ := m.(map[string]any)["number"].(float64)
|
|
out = append(out, n)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// needTheModulesPackages ends the test NOT RUN, never failed, where what it builds and runs with is missing: node and npm
|
|
// on the PATH and the module's installed SDK package under node_modules. The Go integration level is given the tree
|
|
// without its npm packages and no network (issue 1960, H-A-294), as the Node build module's realMachine skips by name.
|
|
func needTheModulesPackages(t *testing.T, dir string) {
|
|
t.Helper()
|
|
for _, p := range []string{"node", "npm"} {
|
|
if _, err := exec.LookPath(p); err != nil {
|
|
t.Skipf("NOT RUN: no %s installed where this check runs; proven in a working copy of the module after npm install", p)
|
|
}
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "node_modules", "@novox", "mesh-sdk")); err != nil {
|
|
t.Skipf("NOT RUN: the forge module's npm packages are not installed in %s (%v); proven in a working copy of the module after npm install", dir, err)
|
|
}
|
|
}
|
|
|
|
func TestTheSeatGitWholeOverARealBus(t *testing.T) {
|
|
dir, err := filepath.Abs(filepath.Join("..", ".."))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
needTheModulesPackages(t, dir)
|
|
build := exec.Command("npm", "run", "build")
|
|
build.Dir = dir
|
|
if out, err := build.CombinedOutput(); err != nil {
|
|
t.Fatalf("the bundle does not build: %v\n%s", err, out)
|
|
}
|
|
|
|
nc, err := nats.Connect(testbus.URL(t))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(nc.Close)
|
|
js, _ := jetstream.New(nc)
|
|
ctx := context.Background()
|
|
// The seat's stream merge-called is kept on (the definition's keep); the template states as buckets.
|
|
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "SEAT_git_merge-called", Subjects: []string{"mesh.seat.git.event.merge-called.*"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
kvs := map[string]jetstream.KeyValue{}
|
|
for _, name := range []string{"bound", "announced", "findings", "first-views", "transfers", "idle", "failed-steps", "calls", "token-lease"} {
|
|
kv, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "gitea_" + name})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
kvs[name] = kv
|
|
}
|
|
A, B, X, H := strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("e", 40), strings.Repeat("f", 40)
|
|
// A call stopped after the second of three merges, kept and not said (§766).
|
|
stopped, _ := json.Marshal(map[string]any{"by": "lead@shanks", "account": "shanks.claude-code", "at": "2026-11-20T03:00:00Z", "said": false,
|
|
"members": []any{
|
|
map[string]any{"repository": "novox/app", "number": 1, "branch": "main", "head": A, "state": "merged", "commit": strings.Repeat("1", 40)},
|
|
map[string]any{"repository": "novox/app", "number": 2, "branch": "main", "head": A, "state": "merged", "commit": strings.Repeat("2", 40)},
|
|
map[string]any{"repository": "novox/app", "number": 3, "branch": "main", "head": A, "state": "judged"}}})
|
|
if _, err := kvs["calls"].Put(ctx, "call.00000000000000cc", stopped); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
f := &forge{pulls: map[string]*pull{
|
|
"novox/app#5": {repo: "novox/app", base: "main", head: A, number: 5},
|
|
"novox/app#6": {repo: "novox/app", base: "main", head: X, number: 6},
|
|
"novox/app#7": {repo: "novox/app", base: "main", head: A, number: 7},
|
|
"novox/lib#9": {repo: "novox/lib", base: "main", head: B, number: 9, refuse: true},
|
|
"novox/lib#10": {repo: "novox/lib", base: "main", head: B, number: 10},
|
|
"novox/hq#11": {repo: "novox/hq", base: "main", head: H, number: 11},
|
|
}}
|
|
// The forge holds the tools' account's token under its old fixed name, which the first mint replaces (H-A-430 (1)).
|
|
f.admin, f.nextID = "mesh-admin", 1
|
|
f.tokens = map[string][]forgeToken{"mesh-tools": {{ID: 1, Name: "mesh-tools", sha1: strings.Repeat("0", 40)}}}
|
|
srv := httptest.NewServer(http.HandlerFunc(f.serve))
|
|
t.Cleanup(srv.Close)
|
|
|
|
state := t.TempDir()
|
|
passwordFile := filepath.Join(state, "admin.secret")
|
|
if err := os.WriteFile(passwordFile, []byte(adminPassword+"\n"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
launch := `const sdk = await import("@novox/mesh-sdk/stdio"); await import("./dist/index.js"); await import("./dist/tools/index.js"); await sdk.serveRegisteredOverStdio("gitea");`
|
|
cmd := exec.Command("node", "--input-type=module", "-e", launch)
|
|
cmd.Dir = dir
|
|
cmd.Env = append(os.Environ(), "MESH_SERVED_MODULE=gitea", "MESH_MODULE=gitea", "MESH_NODE=test", "MESH_GITEA_URL="+srv.URL,
|
|
"MESH_GITEA_ADMIN_USER=mesh-admin", "MESH_GITEA_ADMIN_PASSWORD_FILE="+passwordFile, "MESH_GITEA_STATE_DIR="+state, "MESH_GITEA_HOOK_PORT=0", "MESH_GITEA_CONFIG_FILE="+filepath.Join(state, "config.json"))
|
|
in, _ := cmd.StdinPipe()
|
|
out, _ := cmd.StdoutPipe()
|
|
cmd.Stderr = testLog{t}
|
|
if err := cmd.Start(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = in.Close(); _ = cmd.Process.Kill(); _ = cmd.Wait() })
|
|
rt := &runtime{t: t, in: in, js: js, kvs: kvs, wait: map[string]chan json.RawMessage{}, regs: []map[string]any{
|
|
{"module": "app", "origin": "novox/app", "branches": []string{"main"}},
|
|
{"module": "lib", "origin": "novox/lib", "branches": []string{"main"}},
|
|
// A source-only registration (H2 §815): no module, one watched branch, its check a build seat's step.
|
|
{"origin": "novox/hq", "branches": []string{"main"}, "policy": map[string]any{"steps": map[string]any{"unit": "required"}},
|
|
"check": map[string]any{"seat": "node-build-go", "step": "unit"}}}}
|
|
rt.vault, rt.puts = map[string]vaulted{}, map[string]openPut{}
|
|
go rt.read(out)
|
|
|
|
// At the start the stopped call says one merge-called naming the two that landed (§766).
|
|
until(t, "the stopped call's merge-called at the start", func() bool { return said(t, js)["00000000000000cc"] != nil })
|
|
if got := numbers(said(t, js)["00000000000000cc"]["members"]); fmt.Sprint(got) != "[1 2]" {
|
|
t.Fatalf("the stopped call names %v, not the two that landed", got)
|
|
}
|
|
until(t, "the stopped call kept said", func() bool {
|
|
e, err := kvs["calls"].Get(ctx, "call.00000000000000cc")
|
|
return err == nil && strings.Contains(string(e.Value()), `"said":true`)
|
|
})
|
|
// The registrations are read, and the heads with them, before a merge is judged against them.
|
|
until(t, "the watched heads read after the registrations", func() bool { return f.asked("GET /api/v1/repos/novox/app/branches") })
|
|
|
|
// A failed required step at a head's fingerprint refuses that head (§735, test 114), heard on the module's consumer.
|
|
until(t, "the runner's step-ended followed", func() bool { return rt.subscribed("mesh-pipeline-runner.step-ended.*.*.*") })
|
|
rt.ask("mesh/event", map[string]any{"envelope": map[string]any{"key": "mesh-pipeline-runner.step-ended.app.main." + X, "node": "test",
|
|
"body": map[string]any{"v": 1, "pipeline": "main.4", "module": "app", "branch": "main", "commit": X, "fingerprint": "fp-x",
|
|
"at": "2026-11-20T03:00:00Z", "result": map[string]any{"step": "unit", "status": "required", "outcome": "failed"}}}})
|
|
refused := rt.mergePull(map[string]any{"repository": "novox/app", "number": 6, "head": X})
|
|
members, _ := refused["members"].([]any)
|
|
if len(members) != 1 || members[0].(map[string]any)["state"] != "refused" ||
|
|
!strings.Contains(fmt.Sprint(members[0].(map[string]any)["why"]), "the unit step of app failed in run main.4") {
|
|
t.Fatalf("a head at a failed required step's fingerprint answered %v", refused)
|
|
}
|
|
if got := f.merged(); len(got) != 0 {
|
|
t.Fatalf("merged %v", got)
|
|
}
|
|
|
|
// An hq pull request whose Go checks fail is refused by merge-pull naming the failed step (H2 §815): the runner's
|
|
// step-ended of a source-only check names the registration's key as its module and the commit's root tree hash as its
|
|
// fingerprint (H-A-408), escaped as one part of its subject, judged as a module's.
|
|
rt.ask("mesh/event", map[string]any{"envelope": map[string]any{"key": "mesh-pipeline-runner.step-ended.source=2enovox=2ehq.main." + H, "node": "test",
|
|
"body": map[string]any{"v": 1, "pipeline": "main.5", "module": "source.novox.hq", "branch": "main", "commit": H, "fingerprint": strings.Repeat("7", 40),
|
|
"at": "2026-11-22T01:00:00Z", "result": map[string]any{"step": "unit", "status": "required", "outcome": "failed"}}}})
|
|
hq := rt.mergePull(map[string]any{"repository": "novox/hq", "number": 11, "head": H})
|
|
hqm, _ := hq["members"].([]any)
|
|
if len(hqm) != 1 || hqm[0].(map[string]any)["state"] != "refused" ||
|
|
!strings.Contains(fmt.Sprint(hqm[0].(map[string]any)["why"]), "the unit step of source.novox.hq failed in run main.5") {
|
|
t.Fatalf("an hq head at a failed check answered %v", hq)
|
|
}
|
|
|
|
// With the forge's store stopped, a merge call answers away, merging nothing (H2 §776); called again once the store is
|
|
// back, it lands (below).
|
|
f.mu.Lock()
|
|
f.away = true
|
|
f.mu.Unlock()
|
|
away := rt.mergePull(map[string]any{"repository": "novox/app", "number": 7, "head": A}, map[string]any{"repository": "novox/lib", "number": 10, "head": B})
|
|
if away["error-kind"] != "away" || away["part"] != "the forge's store" || len(f.merged()) != 0 {
|
|
t.Fatalf("a merge call with the forge's store stopped answered %v, merged %v", away, f.merged())
|
|
}
|
|
f.mu.Lock()
|
|
f.away = false
|
|
f.mu.Unlock()
|
|
|
|
// Two pull requests in two repositories merge, in order, and say one merge-called (§734, §736).
|
|
both := rt.mergePull(map[string]any{"repository": "novox/app", "number": 7, "head": A}, map[string]any{"repository": "novox/lib", "number": 10, "head": B})
|
|
call, _ := both["call"].(string)
|
|
until(t, "the merge-called of the two", func() bool { return said(t, js)[call] != nil })
|
|
if got := numbers(said(t, js)[call]["members"]); fmt.Sprint(got) != "[7 10]" || fmt.Sprint(f.merged()) != "[novox/app#7 novox/lib#10]" {
|
|
t.Fatalf("the call of two said %v, merged %v", got, f.merged())
|
|
}
|
|
|
|
// The forge refuses the second merge: merge-called with the first and refused, merge-partial raised (§767, test 115).
|
|
partial := rt.mergePull(map[string]any{"repository": "novox/app", "number": 5, "head": A}, map[string]any{"repository": "novox/lib", "number": 9, "head": B})
|
|
pc, _ := partial["call"].(string)
|
|
until(t, "the partial call's merge-called", func() bool { return said(t, js)[pc] != nil })
|
|
body := said(t, js)[pc]
|
|
if fmt.Sprint(numbers(body["members"])) != "[5]" || fmt.Sprint(numbers(body["refused"])) != "[9]" {
|
|
t.Fatalf("the partial call said %v", body)
|
|
}
|
|
key := "delivery." + pc + ".merge-partial"
|
|
if e, err := kvs["findings"].Get(ctx, key); err != nil || !strings.Contains(string(e.Value()), `"severity":"urgent"`) {
|
|
t.Fatalf("merge-partial %s is not raised: %v", key, err)
|
|
}
|
|
// A later call landing the refused member clears it.
|
|
f.mu.Lock()
|
|
f.pulls["novox/lib#9"].refuse = false
|
|
f.mu.Unlock()
|
|
rt.mergePull(map[string]any{"repository": "novox/lib", "number": 9, "head": B})
|
|
until(t, "merge-partial cleared by the later call", func() bool {
|
|
_, err := kvs["findings"].Get(ctx, key)
|
|
return errors.Is(err, jetstream.ErrKeyNotFound)
|
|
})
|
|
|
|
// No token was configured: the calls above ran on the token the bundle minted with the admin's login, wrote through
|
|
// the two-step sealed own-put and read through the sealed get; the forge holds one token for the account after, the
|
|
// one the vault keeps, and the old fixed-name token is gone (§808, H-A-430 (1)).
|
|
until(t, "the forge holds one token for the tools' account", func() bool {
|
|
names, _ := f.held("mesh-tools")
|
|
return len(names) == 1
|
|
})
|
|
names, values := f.held("mesh-tools")
|
|
rt.mu.Lock()
|
|
kept := rt.vault["module/gitea/mesh-tools"]
|
|
rt.mu.Unlock()
|
|
var opened struct {
|
|
Token string `json:"token"`
|
|
Scopes []string `json:"scopes"`
|
|
}
|
|
_ = json.Unmarshal([]byte(kept.value), &opened)
|
|
if fmt.Sprint(names) != "[mesh-tools-1]" || opened.Token != values[0] || kept.generation != 1 || len(opened.Scopes) == 0 {
|
|
t.Fatalf("the forge holds %v for the tools' account; the vault keeps generation %d of a token %t to it, scopes %v",
|
|
names, kept.generation, opened.Token == values[0], opened.Scopes)
|
|
}
|
|
}
|
|
|
|
type testLog struct{ t *testing.T }
|
|
|
|
func (w testLog) Write(p []byte) (int, error) {
|
|
defer func() { _ = recover() }()
|
|
w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n"))
|
|
return len(p), nil
|
|
}
|