feat(judgement,connectors): guard extension contract; every running guard judges with the built-ins and records its name and digest (archie #1986)

This commit is contained in:
sam committed 2026-11-16 05:17:58 +11:00
1 parent 400699cfbb
commit 55077620bb
11 files changed
+1750 -17

No files matched your search

+148
View File
@@ -0,0 +1,148 @@
package connectors
import (
"context"
"errors"
"fmt"
"time"
goplugin "github.com/hashicorp/go-plugin"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
gpb "github.com/samcharles93/archie-core/internal/contracts/guard/v1"
"github.com/samcharles93/archie-core/modules/connectors/internal/host"
)
// guardSurface names the guard contract in the plugin handshake.
const guardSurface = "guard"
// GuardRequest is one concrete action put to a guard extension.
type GuardRequest struct {
Connector string
Name string
Input []byte
Digest string
Target Target
Effect Effect
RunID string
DecisionKey string
// Deadline is how long the host waits; the caller's context enforces it.
Deadline time.Duration
At time.Time
}
// GuardFinding is one thing a guard noticed. Strength is "weak", "moderate"
// or "strong", or empty when the guard didn't say.
type GuardFinding struct {
Text string
Evidence string
Strength string
}
// GuardAnswer is a guard extension's verdict. Ceiling is 1 (act quietly) to 5
// (never), or 0 when the guard gave none.
type GuardAnswer struct {
Ceiling int
Findings []GuardFinding
BlindSpots []string
}
// Guard is a running guard extension.
type Guard struct {
name string
version string
digest string
advisory bool
client gpb.GuardServiceClient
}
// NewGuard wraps a client of a guard extension. digest is the package digest
// recorded with every verdict.
func NewGuard(name, version, digest string, advisory bool, client gpb.GuardServiceClient) *Guard {
return &Guard{name: name, version: version, digest: digest, advisory: advisory, client: client}
}
// Name is the guard's name in verdicts.
func (g *Guard) Name() string { return g.name }
// Version is the guard's own release, as it described itself.
func (g *Guard) Version() string { return g.version }
// Digest is the SHA-256 of the package that is running.
func (g *Guard) Digest() string { return g.digest }
// Advisory says the guard's verdicts set no ceiling.
func (g *Guard) Advisory() bool { return g.advisory }
// Judge asks the guard about one action. ctx bounds the wait.
func (g *Guard) Judge(ctx context.Context, r GuardRequest) (GuardAnswer, error) {
resp, err := g.client.Judge(ctx, &gpb.JudgeRequest{
Connector: r.Connector, Name: r.Name, Input: r.Input, Digest: r.Digest,
Target: &gpb.Target{Kind: r.Target.Kind, Id: r.Target.ID, Environment: r.Target.Environment, Disposable: r.Target.Disposable},
Effect: &gpb.Effect{ReadOnly: r.Effect.ReadOnly, Reversibility: gpb.Reversibility(r.Effect.Reversibility), Summary: r.Effect.Summary},
Run: &gpb.RunContext{RunId: r.RunID, DecisionKey: r.DecisionKey},
Deadline: durationpb.New(r.Deadline),
At: timestamppb.New(r.At),
})
if err != nil {
return GuardAnswer{}, fmt.Errorf("guard %q: %w", g.name, err)
}
a := GuardAnswer{Ceiling: int(resp.GetCeiling()), BlindSpots: resp.GetBlindSpots()}
for _, f := range resp.GetFindings() {
a.Findings = append(a.Findings, GuardFinding{Text: f.GetText(), Evidence: f.GetEvidence(), Strength: strengthName(f.GetStrength())})
}
return a, nil
}
func strengthName(s gpb.Strength) string {
switch s {
case gpb.Strength_STRENGTH_WEAK:
return "weak"
case gpb.Strength_STRENGTH_MODERATE:
return "moderate"
case gpb.Strength_STRENGTH_STRONG:
return "strong"
}
return ""
}
// StartGuard launches a guard extension, configures it and asks it to
// describe itself.
func (h *Host) StartGuard(ctx context.Context, spec Spec) (*Guard, error) {
raw, err := h.procs.Start(ctx, host.Spec{
Name: spec.Name, Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
}, guardSurface, &guardPlugin{})
if err != nil {
return nil, err
}
client, ok := raw.(gpb.GuardServiceClient)
if !ok {
h.procs.Stop(spec.Name)
return nil, fmt.Errorf("guard %q: plugin is not a guard", spec.Name)
}
if _, err := client.Configure(ctx, &gpb.ConfigureRequest{Settings: spec.Settings, Secrets: spec.Secrets}); err != nil {
h.procs.Stop(spec.Name)
return nil, fmt.Errorf("guard %q: configure: %w", spec.Name, err)
}
desc, err := client.Describe(ctx, &gpb.DescribeRequest{})
if err != nil {
h.procs.Stop(spec.Name)
return nil, fmt.Errorf("guard %q: describe: %w", spec.Name, err)
}
return NewGuard(spec.Name, desc.GetVersion(), spec.SHA256, desc.GetAdvisory(), client), nil
}
// guardPlugin is the host side of the go-plugin handshake for guards.
type guardPlugin struct {
goplugin.NetRPCUnsupportedPlugin
}
func (*guardPlugin) GRPCServer(*goplugin.GRPCBroker, *grpc.Server) error {
return errors.New("guards are served by extensions, not by the host")
}
func (*guardPlugin) GRPCClient(_ context.Context, _ *goplugin.GRPCBroker, conn *grpc.ClientConn) (any, error) {
return gpb.NewGuardServiceClient(conn), nil
}
+3 -1
View File
@@ -24,7 +24,8 @@ type Accepted struct {
Egress Strings `db:"egress"`
Env Strings `db:"env"`
Settings jsontext.Value `db:"settings"`
// Contract is ContractConnector, ContractSecretEngine or ContractMCP.
// Contract is ContractConnector, ContractSecretEngine, ContractMCP or
// ContractGuard.
Contract string `db:"contract"`
// Credentials maps a slot to a credential name, as a JSON object.
Credentials jsontext.Value `db:"credentials"`
@@ -42,6 +43,7 @@ const (
ContractConnector = "connector"
ContractSecretEngine = "secretengine"
ContractMCP = "mcp"
ContractGuard = "guard"
)
// Credential is a credential's sealed fields.
+37 -3
View File
@@ -26,7 +26,7 @@ import (
// validName is the shape of a connector name: it appears in logs and URLs.
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
// Module runs an organisation's accepted connectors and secret engines,
// Module runs an organisation's accepted connectors, secret engines and guards,
// keeps the credentials they are configured with, and serves their
// administration.
type Module struct {
@@ -39,6 +39,7 @@ type Module struct {
mu sync.RWMutex
running map[string]*Connector
engines map[string]*Engine
guards map[string]*Guard
// servers are the accepted MCP servers, and stops ends each one's
// supervisor.
servers map[string]*Server
@@ -71,7 +72,7 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealing Sealing) (*M
}
return &Module{
orgID: orgID, host: NewHost(log), store: store.New(db), sealer: sealer, log: log,
running: map[string]*Connector{}, engines: map[string]*Engine{}, failed: map[string]string{},
running: map[string]*Connector{}, engines: map[string]*Engine{}, guards: map[string]*Guard{}, failed: map[string]string{},
servers: map[string]*Server{}, stops: map[string]context.CancelFunc{},
}, nil
}
@@ -131,6 +132,17 @@ func (m *Module) Tool(name string) (Tool, bool) {
return s, ok
}
// Guards lists the running guard extensions in name order.
func (m *Module) Guards() []*Guard {
m.mu.RLock()
defer m.mu.RUnlock()
var out []*Guard
for _, name := range slices.Sorted(maps.Keys(m.guards)) {
out = append(out, m.guards[name])
}
return out
}
// Delivering lists the running connectors that send the named delivery, in
// name order: the channels a message goes out on.
func (m *Module) Delivering(delivery string) []*Connector {
@@ -178,6 +190,11 @@ func (m *Module) Ready(context.Context) error {
problems = append(problems, name+": process exited")
}
}
for name := range m.guards {
if !m.host.Alive(name) {
problems = append(problems, name+": process exited")
}
}
servers := maps.Clone(m.servers)
m.mu.RUnlock()
for _, name := range slices.Sorted(maps.Keys(servers)) {
@@ -211,9 +228,11 @@ func (m *Module) Close() {
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
mux.Handle("PUT /api/connectors/{name}", guard(m.accept(store.ContractConnector)))
mux.Handle("PUT /api/secret-engines/{name}", guard(m.accept(store.ContractSecretEngine)))
mux.Handle("PUT /api/guards/{name}", guard(m.accept(store.ContractGuard)))
mux.Handle("PUT /api/mcp-servers/{name}", guard(http.HandlerFunc(m.acceptServer)))
mux.Handle("DELETE /api/connectors/{name}", guard(m.remove(store.ContractConnector)))
mux.Handle("DELETE /api/secret-engines/{name}", guard(m.remove(store.ContractSecretEngine)))
mux.Handle("DELETE /api/guards/{name}", guard(m.remove(store.ContractGuard)))
mux.Handle("DELETE /api/mcp-servers/{name}", guard(m.remove(store.ContractMCP)))
mux.Handle("PUT /api/credentials/{name}", guard(http.HandlerFunc(m.putCredential)))
mux.Handle("GET /api/credentials", guard(http.HandlerFunc(m.listCredentials)))
@@ -307,6 +326,18 @@ func (m *Module) launch(ctx context.Context, a store.Accepted) error {
m.log.InfoContext(ctx, "secret engine started", "engine", a.Name)
return nil
}
if a.Contract == store.ContractGuard {
g, err := m.host.StartGuard(ctx, spec)
if err != nil {
return m.fail(ctx, a.Name, err)
}
m.mu.Lock()
m.guards[a.Name] = g
delete(m.failed, a.Name)
m.mu.Unlock()
m.log.InfoContext(ctx, "guard started", "guard", a.Name)
return nil
}
c, err := m.host.Start(ctx, spec)
if err != nil {
return m.fail(ctx, a.Name, err)
@@ -325,13 +356,15 @@ func (m *Module) release(name string) {
m.mu.Lock()
_, running := m.running[name]
_, engine := m.engines[name]
_, guard := m.guards[name]
s, stop := m.servers[name], m.stops[name]
delete(m.running, name)
delete(m.engines, name)
delete(m.guards, name)
delete(m.servers, name)
delete(m.stops, name)
m.mu.Unlock()
if running || engine {
if running || engine || guard {
m.host.Stop(name)
}
if stop != nil {
@@ -346,6 +379,7 @@ func (m *Module) fail(ctx context.Context, name string, err error) error {
m.mu.Lock()
delete(m.running, name)
delete(m.engines, name)
delete(m.guards, name)
m.failed[name] = err.Error()
m.mu.Unlock()
m.log.ErrorContext(ctx, "extension failed to start", "extension", name, "error", err)
+73
View File
@@ -0,0 +1,73 @@
package judgement
import (
"context"
"time"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/connectors"
)
// GuardExtensions lists the guard extensions running now.
type GuardExtensions interface {
Guards() []*connectors.Guard
}
// identified is a guard that says which package answered.
type identified interface {
Version() string
Digest() string
}
// RunContext is the run an action belongs to, passed to guards that want it.
type RunContext struct {
RunID uuid.UUID
Key string
}
type runKey struct{}
func withRun(ctx context.Context, r RunContext) context.Context {
return context.WithValue(ctx, runKey{}, r)
}
func runFrom(ctx context.Context) RunContext {
r, _ := ctx.Value(runKey{}).(RunContext)
return r
}
// extensionGuard adapts a guard extension to Guard.
type extensionGuard struct {
g *connectors.Guard
}
func (e extensionGuard) Name() string { return e.g.Name() }
func (e extensionGuard) Advisory() bool { return e.g.Advisory() }
func (e extensionGuard) Version() string { return e.g.Version() }
func (e extensionGuard) Digest() string { return e.g.Digest() }
// Judge puts the action to the extension. The caller's context carries the
// deadline the host enforces. A ceiling outside the scale is left for judge to
// hold.
func (e extensionGuard) Judge(ctx context.Context, a Action) (Verdict, error) {
run := runFrom(ctx)
req := connectors.GuardRequest{
Connector: a.Connector, Name: a.Name, Input: a.Input, Digest: a.Digest,
Target: a.Target, Effect: a.Effect,
RunID: run.RunID.String(), DecisionKey: run.Key,
At: time.Now(),
}
if d, ok := ctx.Deadline(); ok {
req.Deadline = time.Until(d)
}
ans, err := e.g.Judge(ctx, req)
if err != nil {
return Verdict{}, err
}
v := Verdict{Ceiling: Level(ans.Ceiling), BlindSpots: ans.BlindSpots}
for _, f := range ans.Findings {
v.Findings = append(v.Findings, Finding{Text: f.Text, Evidence: f.Evidence, Strength: f.Strength})
}
return v, nil
}
+134
View File
@@ -0,0 +1,134 @@
package judgement
import (
"context"
"errors"
"testing"
"time"
"google.golang.org/grpc"
gpb "github.com/samcharles93/archie-core/internal/contracts/guard/v1"
"github.com/samcharles93/archie-core/modules/connectors"
)
// fakeGuardClient answers Judge as a guard extension's client would.
type fakeGuardClient struct {
resp *gpb.JudgeResponse
err error
// hang blocks until the host's deadline ends the call.
hang bool
}
func (*fakeGuardClient) Configure(context.Context, *gpb.ConfigureRequest, ...grpc.CallOption) (*gpb.ConfigureResponse, error) {
return &gpb.ConfigureResponse{}, nil
}
func (*fakeGuardClient) Describe(context.Context, *gpb.DescribeRequest, ...grpc.CallOption) (*gpb.DescribeResponse, error) {
return &gpb.DescribeResponse{}, nil
}
func (c *fakeGuardClient) Judge(ctx context.Context, _ *gpb.JudgeRequest, _ ...grpc.CallOption) (*gpb.JudgeResponse, error) {
if c.hang {
<-ctx.Done()
return nil, ctx.Err()
}
return c.resp, c.err
}
type extensions []*connectors.Guard
func (e extensions) Guards() []*connectors.Guard { return e }
// TestGuardExtensionsDecideAtTheLowestCeiling guards the extension path of the
// weakest-link decision (spec section 5, R22): two guard extensions judging
// one action run it at the lower ceiling, a guard that errors, times out or
// answers without a ceiling holds it, an advisory verdict is recorded without
// setting the level, and every verdict names the package that answered.
func TestGuardExtensionsDecideAtTheLowestCeiling(t *testing.T) {
answer := func(c gpb.Ceiling) *gpb.JudgeResponse {
return &gpb.JudgeResponse{Ceiling: c, Findings: []*gpb.Finding{{Text: "seen", Evidence: "log", Strength: gpb.Strength_STRENGTH_STRONG}}}
}
guard := func(name string, advisory bool, c *fakeGuardClient) *connectors.Guard {
return connectors.NewGuard(name, "1.0.0", "digest-"+name, advisory, c)
}
tests := []struct {
name string
guards []*connectors.Guard
want Level
wantFailed string
}{
{
name: "the lower of two ceilings wins",
guards: []*connectors.Guard{
guard("hours", false, &fakeGuardClient{resp: answer(gpb.Ceiling_CEILING_ACT_AND_TELL)}),
guard("budget", false, &fakeGuardClient{resp: answer(gpb.Ceiling_CEILING_ESCALATE)}),
},
want: Escalate,
},
{
name: "a failing guard holds the action",
guards: []*connectors.Guard{
guard("hours", false, &fakeGuardClient{resp: answer(gpb.Ceiling_CEILING_ACT_QUIETLY)}),
guard("broken", false, &fakeGuardClient{err: errors.New("unavailable")}),
},
want: ProposeAndWait, wantFailed: "broken",
},
{
name: "a guard that outlasts the deadline holds the action",
guards: []*connectors.Guard{
guard("hours", false, &fakeGuardClient{resp: answer(gpb.Ceiling_CEILING_ACT_QUIETLY)}),
guard("slow", false, &fakeGuardClient{hang: true}),
},
want: ProposeAndWait, wantFailed: "slow",
},
{
name: "a guard answering without a ceiling holds the action",
guards: []*connectors.Guard{
guard("hours", false, &fakeGuardClient{resp: answer(gpb.Ceiling_CEILING_ACT_QUIETLY)}),
guard("partial", false, &fakeGuardClient{resp: &gpb.JudgeResponse{}}),
},
want: ProposeAndWait, wantFailed: "partial",
},
{
name: "an advisory verdict sets no level",
guards: []*connectors.Guard{
guard("hours", false, &fakeGuardClient{resp: answer(gpb.Ceiling_CEILING_ACT_QUIETLY)}),
guard("opinion", true, &fakeGuardClient{resp: answer(gpb.Ceiling_CEILING_NEVER)}),
},
want: ActQuietly,
},
{
name: "a failing advisory guard sets no level",
guards: []*connectors.Guard{
guard("hours", false, &fakeGuardClient{resp: answer(gpb.Ceiling_CEILING_ACT_AND_TELL)}),
guard("opinion", true, &fakeGuardClient{err: errors.New("unavailable")}),
},
want: ActAndTell, wantFailed: "opinion",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := &Module{timeout: 50 * time.Millisecond}
m.UseExtensions(extensions(tt.guards))
d := m.decide(t.Context(), Action{Connector: "c", Name: "delete"})
if d.Level != tt.want {
t.Fatalf("level = %s, want %s (verdicts %+v)", d.Level, tt.want, d.Verdicts)
}
if len(d.Verdicts) != len(tt.guards) {
t.Fatalf("verdicts = %d, want one per guard", len(d.Verdicts))
}
for i, v := range d.Verdicts {
if v.Guard != tt.guards[i].Name() || v.Digest != "digest-"+v.Guard || v.Version != "1.0.0" {
t.Fatalf("verdict %d = %+v, want the guard's name, version and package digest", i, v)
}
if (v.Failed != "") != (v.Guard == tt.wantFailed) {
t.Fatalf("verdict %q failed = %q, want failure only for %q", v.Guard, v.Failed, tt.wantFailed)
}
if v.Failed == "" && (len(v.Findings) != 1 || v.Findings[0].Strength != "strong" || v.Findings[0].Evidence != "log") {
t.Fatalf("verdict %q lost its findings: %+v", v.Guard, v.Findings)
}
}
})
}
}
+46 -10
View File
@@ -11,6 +11,7 @@ import (
"errors"
"fmt"
"log/slog"
"slices"
"sync"
"time"
@@ -63,11 +64,18 @@ func (a Action) Class() Class {
type Finding struct {
Text string `json:"text"`
Evidence string `json:"evidence,omitzero"`
// Strength is how much the evidence supports the finding: weak, moderate
// or strong.
Strength string `json:"strength,omitzero"`
}
// Verdict is one guard's judgement of one action.
type Verdict struct {
Guard string `json:"guard"`
Guard string `json:"guard"`
// Version and Digest say which extension answered: its own release and
// the digest of the package that ran. Built-in guards have neither.
Version string `json:"version,omitzero"`
Digest string `json:"digest,omitzero"`
Ceiling Level `json:"ceiling"`
Findings []Finding `json:"findings,omitzero"`
BlindSpots []string `json:"blind_spots,omitzero"`
@@ -144,10 +152,18 @@ type Module struct {
guards []Guard
store recorder
failed FailureRecorder
log *slog.Logger
now func() time.Time
// extensions are the guard extensions asked alongside the built-in guards.
extensions GuardExtensions
// timeout bounds one guard; zero means guardTimeout.
timeout time.Duration
log *slog.Logger
now func() time.Time
}
// UseExtensions makes the module ask every running guard extension alongside
// its built-in guards, on each decision.
func (m *Module) UseExtensions(e GuardExtensions) { m.extensions = e }
// NewModule returns the judgement module for orgID, with its hard rules and
// guards. An action of a class that fails is reported to failed.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tools Tools, rules []HardRule, guards []Guard, failed FailureRecorder) *Module {
@@ -169,7 +185,7 @@ func (m *Module) Assess(ctx context.Context, req Request) (Decision, error) {
Connector: req.Connector, Name: req.Action, Input: req.Input,
Digest: connectors.Digest(req.Action, req.Input), Target: res.Target, Effect: res.Effect,
}
d := m.decide(ctx, a)
d := m.decide(withRun(ctx, RunContext{RunID: req.RunID, Key: req.Key}), a)
d.ID, d.RunID, d.Key, d.At = uuid.New(), req.RunID, req.Key, m.now().UTC()
return m.record(ctx, d)
}
@@ -182,10 +198,16 @@ func (m *Module) decide(ctx context.Context, a Action) Decision {
return Decision{Action: a, Level: Never, RefusedBy: r.Name(), Reason: reason, Verdicts: []Verdict{}}
}
}
verdicts := make([]Verdict, len(m.guards))
guards := slices.Clone(m.guards)
if m.extensions != nil {
for _, e := range m.extensions.Guards() {
guards = append(guards, extensionGuard{e})
}
}
verdicts := make([]Verdict, len(guards))
var wg sync.WaitGroup
for i, g := range m.guards {
wg.Go(func() { verdicts[i] = judge(ctx, g, a) })
for i, g := range guards {
wg.Go(func() { verdicts[i] = judge(ctx, g, a, m.guardTimeout()) })
}
wg.Wait()
ceilings := []Level{}
@@ -203,11 +225,15 @@ func (m *Module) decide(ctx context.Context, a Action) Decision {
// judge asks one guard, turning a failure, a timeout or a missing ceiling
// into propose and wait. A panic is a failure too.
func judge(ctx context.Context, g Guard, a Action) (v Verdict) {
ctx, cancel := context.WithTimeout(ctx, guardTimeout)
func judge(ctx context.Context, g Guard, a Action, timeout time.Duration) (v Verdict) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
failed := func(why string) Verdict {
return Verdict{Guard: g.Name(), Ceiling: ProposeAndWait, Advisory: g.Advisory(), Failed: why}
v := Verdict{Guard: g.Name(), Ceiling: ProposeAndWait, Advisory: g.Advisory(), Failed: why}
if e, ok := g.(identified); ok {
v.Version, v.Digest = e.Version(), e.Digest()
}
return v
}
defer func() {
if r := recover(); r != nil {
@@ -222,9 +248,19 @@ func judge(ctx context.Context, g Guard, a Action) (v Verdict) {
return failed("returned no ceiling")
}
got.Guard, got.Advisory = g.Name(), g.Advisory()
if e, ok := g.(identified); ok {
got.Version, got.Digest = e.Version(), e.Digest()
}
return got
}
func (m *Module) guardTimeout() time.Duration {
if m.timeout > 0 {
return m.timeout
}
return guardTimeout
}
// Execute runs a decided action if its level lets it run and the input is
// exactly the one judged. key is the idempotency key the connector honours.
func (m *Module) Execute(ctx context.Context, d Decision, input jsontext.Value, key string) (string, error) {