From 8067e16fbcb260c8aea792043d2cae0d05afb9c0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 15:54:44 -0500 Subject: [PATCH 1/2] mcpx: write policy gate (policy.write ask/allow/deny) for #1979 --- pkgs/mcpx/docs/configuration.md | 45 ++++ pkgs/mcpx/internal/config/config.go | 11 + pkgs/mcpx/internal/daemon/consumer.go | 133 ++++++++++++ pkgs/mcpx/internal/daemon/input_required.go | 2 +- pkgs/mcpx/internal/daemon/registry.go | 20 +- pkgs/mcpx/internal/daemon/routes_proto.go | 2 +- .../mcpx/internal/daemon/write_policy_test.go | 118 +++++++++++ pkgs/mcpx/internal/defaults/defaults.go | 2 + pkgs/mcpx/internal/defaults/defaults.json | 1 + pkgs/mcpx/internal/policy/policy.go | 192 ++++++++++++++++++ pkgs/mcpx/internal/policy/policy_test.go | 93 +++++++++ pkgs/mcpx/internal/settings/consumer.go | 22 ++ pkgs/mcpx/internal/settings/effect.go | 3 +- 13 files changed, 638 insertions(+), 6 deletions(-) create mode 100644 pkgs/mcpx/internal/daemon/write_policy_test.go create mode 100644 pkgs/mcpx/internal/policy/policy.go create mode 100644 pkgs/mcpx/internal/policy/policy_test.go diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index b3b06cadcc..b00b962247 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -214,6 +214,45 @@ parameter, GitHub's `GITHUB_READ_ONLY` -- which keeps the tool from ever reaching mcpx. Those are each server's own convention; this one works for any server. +## Write policy (`policy.write`) + +A tool call is a **write** when its tool is not annotated `readOnlyHint` +true, read with the specification's defaults: an unannotated tool may +write, and may be destructive. The daemon-wide setting `policy.write` +(default `ask`) gates every such call, between resolving an instance +and using it: + +| mode | what happens to a write call | +| --- | --- | +| `ask` | a confirmation is raised showing the exact call -- the tool and its arguments in canonical (key-sorted) JSON -- and the call proceeds only if somebody answers true | +| `allow` | the call proceeds with no confirmation from the policy | +| `deny` | the call is refused, with an error naming the tool, the mode, and the settings that can change it | + +A server's own `writePolicy` in its `mcpx` block overrides the daemon +mode for that server alone: + +```json +{ "mcpServers": { "datadog": { "command": "...", "mcpx": { "writePolicy": "deny" } } } } +``` + +Under `ask`, a caller that cannot answer questions is **refused**, not +waited out and not let through: the error says the policy is ask, that +there is no question broker to answer it, and that setting +`policy.write` to `allow` (or `deny`) is the escape. An unanswered or +refused confirmation refuses the call too. + +`elicit.confirmDestructive` is a **floor** on top of this, not an +alternative to it: with it on, a destructive call asks even under +`allow` -- raised by the destructive confirmation itself, with its +annotation-trust rules unchanged -- and the floor never weakens a +`deny`. Under `ask` the policy has already asked once, so no call is +asked about twice. + +This gate is an operator consent gate, not the autonomy dial +(`docs/decisions/0002-autonomy-dial.md`): the dial bounds what mcpx +does on its own, the write policy bounds what a caller may do to the +outside world through it, and neither clamps the other. + ## Every setting Everything between the markers below is generated from `settings.Registry()` by @@ -494,6 +533,12 @@ and a switch to turn the report off would have kept it quiet. | `plumbing.strictUnknownKeys` | bool | `false` | client | no | `--plumbing-strict-unknown-keys` | `MCPX_PLUMBING_STRICT_UNKNOWN_KEYS` | *(plumbing)* fail on a configuration key no setting claims | | `plumbing.validatePaths` | bool | `true` | client | no | `--plumbing-validate-paths` | `MCPX_PLUMBING_VALIDATE_PATHS` | *(plumbing)* resolve and verify every referenced path before doing any work | +### policy + +| setting | kind | default | scope | hot | flag | variable | governs | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `policy.write` | enum | `ask` | daemon | no | `--policy-write` | `MCPX_POLICY_WRITE` | what to do before a call that may write: ask for confirmation, allow it, or deny it | + ### pool | setting | kind | default | scope | hot | flag | variable | governs | diff --git a/pkgs/mcpx/internal/config/config.go b/pkgs/mcpx/internal/config/config.go index 9c90bcdbce..a62834c45c 100644 --- a/pkgs/mcpx/internal/config/config.go +++ b/pkgs/mcpx/internal/config/config.go @@ -148,6 +148,10 @@ type Extras struct { // ExcludeTools removes tools from the exposed set, and wins over Tools. // A removed tool is neither listed nor callable. ExcludeTools []string `json:"excludeTools,omitempty"` + // WritePolicy overrides the daemon policy.write setting for this + // server alone: ask, allow or deny (#1979). Empty means inherit the + // daemon mode. + WritePolicy string `json:"writePolicy,omitempty"` // RequiresSecrets names environment variables that must be non-empty for this server to be active. RequiresSecrets []string `json:"requiresSecrets,omitempty"` // RequiresServers names other upstream server namespaces that must be enabled. @@ -459,6 +463,11 @@ type Resolved struct { RequiresServers []string Preconditions map[string]Precondition + // WritePolicy is this server's resolved writePolicy override, from + // its own mcpx block or the pool block; empty means inherit the + // daemon policy.write setting (#1979). + WritePolicy string + // Runtime, when set, returns the value the daemon holds in memory for a // secret: see internal/secrets. It is consulted before this server's own // environment and the daemon's, and nothing here keeps what it returns. @@ -741,6 +750,7 @@ func (c *Config) Resolve(name string) (*Resolved, error) { LogLevel: pickLoggingLevel(ex.Logging, d.Logging), Tools: allow, ExcludeTools: deny, + WritePolicy: pick(ex.WritePolicy, d.WritePolicy), Profiles: append(append([]string{}, d.Profiles...), ex.Profiles...), Tags: append(append([]string{}, d.Tags...), ex.Tags...), ToolTags: mergeToolTags(d.ToolTags, ex.ToolTags), @@ -955,6 +965,7 @@ func mergeExtras(near, far Extras) Extras { near.CallTimeout = pick(near.CallTimeout, far.CallTimeout) near.StartTimeout = pick(near.StartTimeout, far.StartTimeout) near.Namespace = pick(near.Namespace, far.Namespace) + near.WritePolicy = pick(near.WritePolicy, far.WritePolicy) near.Description = pick(near.Description, far.Description) near.Prelude = pick(near.Prelude, far.Prelude) if len(near.Tools) == 0 { diff --git a/pkgs/mcpx/internal/daemon/consumer.go b/pkgs/mcpx/internal/daemon/consumer.go index 4ff237fc3e..946f775a9e 100644 --- a/pkgs/mcpx/internal/daemon/consumer.go +++ b/pkgs/mcpx/internal/daemon/consumer.go @@ -18,6 +18,7 @@ import ( "github.com/dezren39/mcpx/internal/events" "github.com/dezren39/mcpx/internal/mcpclient" "github.com/dezren39/mcpx/internal/model" + "github.com/dezren39/mcpx/internal/policy" "github.com/dezren39/mcpx/internal/pool" "github.com/dezren39/mcpx/internal/recipes" "github.com/dezren39/mcpx/internal/runner" @@ -37,6 +38,7 @@ type ConsumerPolicy struct { Disambiguate string DisambiguateDefault string ConfirmDestructive bool + WritePolicy string AskTimeout time.Duration DiagnosePreflight bool HistoryPerTool int @@ -106,6 +108,7 @@ func defaultConsumerPolicy() ConsumerPolicy { Disambiguate: defaults.Disambiguate, DisambiguateDefault: defaults.DisambiguateDefault, ConfirmDestructive: defaults.ConfirmDestructive, + WritePolicy: defaults.WritePolicy, AskTimeout: defaults.AskTimeout, DiagnosePreflight: defaults.DiagnosePreflight, HistoryPerTool: defaults.HistoryPerTool, @@ -125,6 +128,7 @@ func consumerPolicyFrom(set *settings.Set) ConsumerPolicy { p.Disambiguate = set.String("elicit.disambiguate") p.DisambiguateDefault = set.String("elicit.disambiguateDefault") p.ConfirmDestructive = set.Bool("elicit.confirmDestructive") + p.WritePolicy = set.String("policy.write") p.AskTimeout = set.Duration("elicit.askTimeout") p.DiagnosePreflight = set.Bool("diagnose.preflight") p.HistoryPerTool = set.Int("diagnose.history") @@ -449,6 +453,135 @@ func (r *Registry) confirmDestructive(ctx context.Context, p *pool.Pool, tool st return nil } +// ErrWriteDenied is returned when the write policy refuses a call. +type ErrWriteDenied struct { + Tool string + Mode string + Reason string +} + +func (e ErrWriteDenied) Error() string { + return fmt.Sprintf("%s was refused by the write policy (mode %s): %s; "+ + "change policy.write, or this server's writePolicy, to allow it", e.Tool, e.Mode, e.Reason) +} + +// applyWritePolicy is the write policy gate (#1979, Phase 1): before a +// call, decide from its tool's annotations and the effective mode +// whether it proceeds, asks, or is refused. +// +// The effective mode is the server's own writePolicy when it sets one, +// else the daemon's policy.write. An empty effective mode -- a zero +// ConsumerPolicy, as a registry built for a test has -- is treated as +// allow, so an unconfigured daemon behaves exactly as it did before +// the gate existed. A non-empty mode that is none of ask, allow or +// deny is a configuration error and is refused at call time, naming +// the bad value, rather than silently read as some other mode. +// +// The returned asked reports whether this gate already raised the +// confirmation, so the caller does not ask twice: under ask the policy +// has asked, and elicit.confirmDestructive's floor is then satisfied; +// under allow confirmDestructive still runs, which is how the floor +// reaches a destructive call the policy let through. +func (r *Registry) applyWritePolicy(ctx context.Context, p *pool.Pool, tool string, cc config.CallContext, args any) (bool, error) { + mode := r.consumer.WritePolicy + if cfg := p.Config(); cfg != nil && cfg.WritePolicy != "" { + mode = cfg.WritePolicy + } + if mode == "" { + // Unconfigured (zero-value policy in tests): allow, with no + // schema read, so nothing about the call path changes. + return false, nil + } + parsed, ok := policy.ParseMode(mode) + if !ok { + return false, fmt.Errorf("write policy: invalid mode %q for %s.%s; want ask, allow or deny "+ + "(set policy.write, or this server's writePolicy)", mode, p.Namespace(), tool) + } + if parsed == policy.ModeAllow && !r.consumer.ConfirmDestructive { + // The common path made cheaper on purpose: allow with no + // destructive floor cannot ask or deny anything the evaluator + // would reach, and classifying would cost a schema read on + // every call for a decision that is already known. + return false, nil + } + + // Classification needs the tool's annotations, fetched the way + // confirmDestructive fetches them: from the cache, or read now -- + // failing closed if they cannot be read, because deciding from an + // empty list would let a write through unasked. + all, _, at := p.CachedSchemas() + if at.IsZero() { + fresh, _, err := p.RefreshSchemas(ctx) + if err != nil { + return false, ErrNotConfirmed{Tool: p.Namespace() + "." + tool, + Reason: "write policy: its annotations could not be read: " + err.Error()} + } + all = fresh + } + // A tool the schemas do not name is treated as unannotated, which + // the specification's defaults read as a possibly destructive + // write -- the conservative answer, not an exemption. + class := policy.Classify(nil) + for i := range all { + if all[i].Name == tool { + class = policy.Classify(all[i].Annotations) + break + } + } + + decision := policy.Evaluator{}.Evaluate(policy.Input{ + Mode: parsed, + Classification: class, + ConfirmDestructiveFloor: r.consumer.ConfirmDestructive, + }) + path := p.Namespace() + "." + tool + switch decision.Kind { + case policy.DecideDeny: + return false, ErrWriteDenied{Tool: path, Mode: string(parsed), Reason: decision.Reason} + case policy.DecideAsk: + if r.consumer.ConfirmDestructive && parsed == policy.ModeAllow { + // This ask is the floor's, and confirmDestructive is the + // code that has always raised it, with its annotation + // trust rules (#2191) unchanged. Defer to it rather than + // asking here in a second, subtly different way. + return false, nil + } + if r.broker == nil { + return false, ErrNotConfirmed{Tool: path, + Reason: "write policy is ask but there is no question broker to answer it; " + + "set policy.write to allow or deny, or run a caller that can answer questions"} + } + req := elicit.Confirmation(elicit.Ask{ + Server: p.Name(), + Tool: tool, + Session: cc.SessionID, + Message: fmt.Sprintf("%s.%s is a write call and policy.write is ask. Exact call: %s(%s). Let this call proceed?", + p.Namespace(), tool, path, policy.CanonicalArgs(args)), + Default: "false", + TTL: r.consumer.AskTimeout, + }) + opened, err := r.broker.OpenRequest(req) + if err != nil { + return false, err + } + r.publish(events.Event{Kind: events.ElicitOpened, Server: p.Name(), Data: mustJSON(elicitEventSummary(opened))}) + + actx, cancel := context.WithTimeout(ctx, r.consumer.AskTimeout) + defer cancel() + ans, aerr := r.broker.Await(actx, opened.ID) + if aerr != nil { + return false, ErrNotConfirmed{Tool: path, + Reason: "nobody answered within " + r.consumer.AskTimeout.String()} + } + if v, _ := elicit.Resolve(ans, elicit.FieldConfirm, "false"); v != "true" { + return false, ErrNotConfirmed{Tool: path, Reason: "the answer was " + string(ans.Action)} + } + return true, nil + default: + return false, nil + } +} + // annotationClearsCall reports whether a tool's annotations may clear // its call without asking. Tool annotations are hints, not decisions // (#2191): the specification forbids basing a security decision on diff --git a/pkgs/mcpx/internal/daemon/input_required.go b/pkgs/mcpx/internal/daemon/input_required.go index ef41adc836..c804a6119a 100644 --- a/pkgs/mcpx/internal/daemon/input_required.go +++ b/pkgs/mcpx/internal/daemon/input_required.go @@ -72,7 +72,7 @@ func (r *Registry) CallReporting(ctx context.Context, id, server, tool string, c if !ok { return nil, UnknownServer{Name: server} } - key, err := r.resolveAndGuard(ctx, p, server, tool, cc) + key, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) if err != nil { return nil, err } diff --git a/pkgs/mcpx/internal/daemon/registry.go b/pkgs/mcpx/internal/daemon/registry.go index 5074fb713c..02b347fa72 100644 --- a/pkgs/mcpx/internal/daemon/registry.go +++ b/pkgs/mcpx/internal/daemon/registry.go @@ -1009,7 +1009,12 @@ func failureStatus(err error) int { var unknown UnknownServer var hidden HiddenTool var secret SecretRequired + var denied ErrWriteDenied switch { + case errors.As(err, &denied): + // The write policy refused the call: a permission answer, not + // a bad request and not an upstream failure. + return http.StatusForbidden case errors.As(err, &secret): // A conflict with the state of the daemon, not a fault in the request // and not a failure of the server: it can succeed once a value exists. @@ -1066,7 +1071,7 @@ func (r *Registry) Call(ctx context.Context, server, tool string, cc config.Call if !ok { return nil, UnknownServer{Name: server} } - key, err := r.resolveAndGuard(ctx, p, server, tool, cc) + key, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) if err != nil { return nil, err } @@ -1082,7 +1087,7 @@ func (r *Registry) Call(ctx context.Context, server, tool string, cc config.Call // consumer policies. Every path that calls a tool goes through it: the ask // path once skipped both, so a destructive-tool guard was off for exactly the // clients that declared they could answer it. -func (r *Registry) resolveAndGuard(ctx context.Context, p *pool.Pool, server, tool string, cc config.CallContext) (string, error) { +func (r *Registry) resolveAndGuard(ctx context.Context, p *pool.Pool, server, tool string, cc config.CallContext, args any) (string, error) { // The view, not the pool: aliases share one pool and filter differently. if view, ok := r.View(server); ok { // Before the child is touched: a server waiting for a secret is not @@ -1101,9 +1106,18 @@ func (r *Registry) resolveAndGuard(ctx context.Context, p *pool.Pool, server, to // Two policies sit between resolving the instance and using it, and both // are off unless somebody turned them on. See internal/daemon/consumer.go. key = r.disambiguate(ctx, p, cc, key) - if err := r.confirmDestructive(ctx, p, tool, cc); err != nil { + asked, err := r.applyWritePolicy(ctx, p, tool, cc, args) + if err != nil { return "", err } + if !asked { + // Not asked by the write policy: the destructive floor still + // gets its say. Under ask the policy already asked once, and + // asking twice about one call would be noise, not consent. + if err := r.confirmDestructive(ctx, p, tool, cc); err != nil { + return "", err + } + } return key, nil } diff --git a/pkgs/mcpx/internal/daemon/routes_proto.go b/pkgs/mcpx/internal/daemon/routes_proto.go index a132043bd5..0e14bb5c8e 100644 --- a/pkgs/mcpx/internal/daemon/routes_proto.go +++ b/pkgs/mcpx/internal/daemon/routes_proto.go @@ -299,7 +299,7 @@ func (r *Registry) CallAsk(ctx context.Context, id, server, tool string, cc conf // the table before the upstream request goes out, so it is registered // between the two. The guard's own questions are mcpx's, not the // server's, and are never attributed through the table. - key, err := r.resolveAndGuard(ctx, p, server, tool, cc) + key, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) if err != nil { return nil, err } diff --git a/pkgs/mcpx/internal/daemon/write_policy_test.go b/pkgs/mcpx/internal/daemon/write_policy_test.go new file mode 100644 index 0000000000..3202461842 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/write_policy_test.go @@ -0,0 +1,118 @@ +package daemon + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/dezren39/mcpx/internal/config" + "github.com/dezren39/mcpx/internal/mcpclient" + "github.com/dezren39/mcpx/internal/pool" +) + +// The write policy gate (#1979), in the destructive_test.go fixture +// style: a pool over a locally declared server, its schemas seeded +// into the cache with SetSchemas so no process starts, and a registry +// whose consumer policy is the one under test. The registry here has +// no broker unless a test installs one, which is itself one of the +// cases: ask with nobody to answer must refuse. + +func writePolicyPool(t *testing.T, writePolicy string, annotations string) *pool.Pool { + t.Helper() + p := pool.New(&config.Resolved{ + Server: &config.Server{Command: "demo"}, + Namespace: "demo", + WritePolicy: writePolicy, + }) + p.SetSchemas( + []mcpclient.Tool{{Name: "wipe", Annotations: json.RawMessage(annotations)}}, + nil, nil, "", time.Now(), time.Time{}, false) + return p +} + +func writePolicyRegistry(mode string) *Registry { + return &Registry{consumer: ConsumerPolicy{WritePolicy: mode}} +} + +// (a) Deny refuses a write tool -- an unannotated tool, which the +// specification's defaults read as a possibly destructive write. +func TestWritePolicyDenyRefusesAWriteTool(t *testing.T) { + r := writePolicyRegistry("deny") + p := writePolicyPool(t, "", ``) + asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, map[string]any{"id": 1}) + if asked { + t.Error("a denied call must not report it asked") + } + var denied ErrWriteDenied + if !errors.As(err, &denied) { + t.Fatalf("applyWritePolicy = %v, want ErrWriteDenied", err) + } + if got := failureStatus(err); got != 403 { + t.Errorf("failureStatus(ErrWriteDenied) = %d, want 403", got) + } +} + +// (b) Allow passes a write tool without a broker: no error, no ask, +// and no schema-dependent refusal on the way. +func TestWritePolicyAllowPassesAWriteToolWithoutBroker(t *testing.T) { + r := writePolicyRegistry("allow") + p := writePolicyPool(t, "", ``) + asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, map[string]any{"id": 1}) + if err != nil { + t.Fatalf("applyWritePolicy = %v, want nil", err) + } + if asked { + t.Error("allow must not ask") + } +} + +// (c) Ask with no broker refuses with ErrNotConfirmed: a caller that +// cannot answer gets a clear refusal naming the escape, not a call +// that proceeds unasked or waits out a deadline. +func TestWritePolicyAskWithNoBrokerRefuses(t *testing.T) { + r := writePolicyRegistry("ask") + p := writePolicyPool(t, "", ``) + asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, map[string]any{"id": 1}) + if asked { + t.Error("an unanswered ask must not report it asked") + } + var notConfirmed ErrNotConfirmed + if !errors.As(err, ¬Confirmed) { + t.Fatalf("applyWritePolicy = %v, want ErrNotConfirmed", err) + } +} + +// (d) A per-server writePolicy beats the daemon mode, in both +// directions: deny on the server refuses under a daemon-wide allow, +// and allow on the server passes under a daemon-wide deny. +func TestWritePolicyPerServerOverrideBeatsDaemonMode(t *testing.T) { + r := writePolicyRegistry("allow") + p := writePolicyPool(t, "deny", ``) + if _, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, nil); err == nil { + t.Error("server deny under daemon allow: want a refusal, got nil") + } else { + var denied ErrWriteDenied + if !errors.As(err, &denied) { + t.Errorf("server deny under daemon allow: got %v, want ErrWriteDenied", err) + } + } + + r = writePolicyRegistry("deny") + p = writePolicyPool(t, "allow", ``) + asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, nil) + if err != nil || asked { + t.Errorf("server allow under daemon deny: asked=%v err=%v, want a pass", asked, err) + } +} + +// A read-only tool is not a write, so even deny lets it through. +func TestWritePolicyDenyPassesAReadOnlyTool(t *testing.T) { + r := writePolicyRegistry("deny") + p := writePolicyPool(t, "", `{"readOnlyHint":true}`) + asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, nil) + if err != nil || asked { + t.Errorf("read-only under deny: asked=%v err=%v, want a pass", asked, err) + } +} diff --git a/pkgs/mcpx/internal/defaults/defaults.go b/pkgs/mcpx/internal/defaults/defaults.go index cbb4a53570..1aed062cee 100644 --- a/pkgs/mcpx/internal/defaults/defaults.go +++ b/pkgs/mcpx/internal/defaults/defaults.go @@ -157,6 +157,7 @@ type Defaults struct { Disambiguate string `json:"disambiguate"` DisambiguateDefault string `json:"disambiguateDefault"` ConfirmDestructive bool `json:"confirmDestructive"` + WritePolicy string `json:"writePolicy"` AskTimeout string `json:"askTimeout"` DiagnosePreflight bool `json:"diagnosePreflight"` HistoryPerTool int `json:"historyPerTool"` @@ -655,6 +656,7 @@ var ( Disambiguate = builtin.Consumer.Disambiguate DisambiguateDefault = builtin.Consumer.DisambiguateDefault ConfirmDestructive = builtin.Consumer.ConfirmDestructive + WritePolicy = builtin.Consumer.WritePolicy AskTimeout = mustDur(builtin.Consumer.AskTimeout, "consumer.askTimeout") DiagnosePreflight = builtin.Consumer.DiagnosePreflight HistoryPerTool = builtin.Consumer.HistoryPerTool diff --git a/pkgs/mcpx/internal/defaults/defaults.json b/pkgs/mcpx/internal/defaults/defaults.json index 6ce18d0273..0ffa7d79e0 100644 --- a/pkgs/mcpx/internal/defaults/defaults.json +++ b/pkgs/mcpx/internal/defaults/defaults.json @@ -138,6 +138,7 @@ "disambiguate": "never", "disambiguateDefault": "new", "confirmDestructive": false, + "writePolicy": "ask", "askTimeout": "45s", "diagnosePreflight": true, "historyPerTool": 8, diff --git a/pkgs/mcpx/internal/policy/policy.go b/pkgs/mcpx/internal/policy/policy.go new file mode 100644 index 0000000000..78533f93aa --- /dev/null +++ b/pkgs/mcpx/internal/policy/policy.go @@ -0,0 +1,192 @@ +// Package policy is the mcpx write policy gate (#1979, design #2126): +// whether a tool call that may change something outside mcpx is allowed, +// asked about, or refused, decided before the call is made. +// +// The package is deliberately small and pure. It classifies a call from +// the tool's annotations, renders its arguments canonically for display, +// and evaluates a mode against that classification. It knows nothing +// about pools, brokers or settings: the daemon fetches what it needs, +// hands plain values in, and acts on the decision that comes back. That +// is what makes the gate testable at unit speed, and what will let the +// later phases -- an argument-rule hook and a ledger hook, both stubbed +// here -- slot in without moving the decision itself. +package policy + +import ( + "encoding/json" + "fmt" +) + +// Mode is one write policy: what to do with a call that may write. +type Mode string + +const ( + // ModeAsk asks for confirmation before a write call, showing the + // exact tool and its canonical arguments. + ModeAsk Mode = "ask" + // ModeAllow lets write calls proceed with no confirmation from the + // policy. The destructive floor may still ask; see Evaluate. + ModeAllow Mode = "allow" + // ModeDeny refuses write calls outright. + ModeDeny Mode = "deny" +) + +// Valid reports whether m is one of the three modes. +func (m Mode) Valid() bool { + switch m { + case ModeAsk, ModeAllow, ModeDeny: + return true + } + return false +} + +// ParseMode parses s as a Mode, reporting whether it was one. +func ParseMode(s string) (Mode, bool) { + m := Mode(s) + if m.Valid() { + return m, true + } + return "", false +} + +// Classification is what a tool's annotations say about one call to it, +// read with the specification's defaults, exactly as the daemon's +// destructiveHint has always read them: a tool not annotated +// readOnlyHint true may write, and a write whose destructiveHint is +// absent or true may destroy. +type Classification struct { + // ReadOnly is set when readOnlyHint is true. + ReadOnly bool + // Write is set when the call may change something: readOnlyHint is + // not true. + Write bool + // Destructive is set when a write may be destructive: + // destructiveHint absent or true. + Destructive bool + // DestructiveMarked is set when destructiveHint is present and + // true, regardless of readOnlyHint. A tool that claims to be + // read-only while also marking itself destructive is contradictory, + // and the mark is still worth gating on even though Destructive -- + // which follows the specification's reading -- is not set for it. + DestructiveMarked bool +} + +// Classify reads tool annotations (the raw annotations object, or nil) +// into a Classification. Unreadable annotations say nothing, so the +// specification's defaults stand: the call is a possibly destructive +// write, as an unannotated tool is. +func Classify(annotations json.RawMessage) Classification { + var doc struct { + ReadOnly *bool `json:"readOnlyHint"` + Destructive *bool `json:"destructiveHint"` + } + if len(annotations) > 0 { + // An unmarshal error leaves doc zero, which is the defaults + // reading below; there is nothing better to do with annotations + // that cannot be parsed. + _ = json.Unmarshal(annotations, &doc) + } + c := Classification{} + if doc.ReadOnly != nil && *doc.ReadOnly { + c.ReadOnly = true + } + c.Write = !c.ReadOnly + c.Destructive = c.Write && (doc.Destructive == nil || *doc.Destructive) + c.DestructiveMarked = doc.Destructive != nil && *doc.Destructive + return c +} + +// CanonicalArgs renders a call's arguments in one canonical form for +// display and comparison: JSON, whose marshalling sorts map keys, so +// the same arguments always render the same way and a confirmation +// shows exactly the call that will be made. Arguments that will not +// marshal fall back to their Go rendering rather than failing the +// gate over a display problem. Nil renders as "null". +func CanonicalArgs(args any) string { + b, err := json.Marshal(args) + if err != nil { + return fmt.Sprintf("%v", args) + } + return string(b) +} + +// DecisionKind is the kind of a Decision. +type DecisionKind int + +const ( + // DecideAllow lets the call proceed without asking. + DecideAllow DecisionKind = iota + // DecideAsk asks for confirmation first. + DecideAsk + // DecideDeny refuses the call. + DecideDeny +) + +// Decision is the outcome of evaluating a policy: what to do, and why, +// in words fit for an error or a question. +type Decision struct { + Kind DecisionKind + Reason string +} + +// Input is everything Evaluate decides from. +type Input struct { + Mode Mode + Classification Classification + // ConfirmDestructiveFloor carries elicit.confirmDestructive into + // the evaluation: a destructive call asks even under ModeAllow. + // The floor only ever upgrades allow to ask; it never weakens a + // deny. + ConfirmDestructiveFloor bool +} + +// Evaluator evaluates a write policy. The two hooks are the places +// later phases plug into, in a fixed order before the mode itself is +// consulted: LedgerCheck (Phase 3) may decide a call from the ledger +// of what has already happened, and ArgumentRules (Phase 2) may decide +// it from its arguments. Both are nil in Phase 1, which is the point: +// the order is settled now so neither phase rearranges the gate when +// it lands. A hook that returns ok false has no opinion and evaluation +// continues. +type Evaluator struct { + LedgerCheck func() (Decision, bool) + ArgumentRules func() (Decision, bool) +} + +// Evaluate decides a call, in a fixed order: ledger hook, argument +// rules hook, the write mode, then the destructive floor. +func (e Evaluator) Evaluate(in Input) Decision { + if e.LedgerCheck != nil { + if d, ok := e.LedgerCheck(); ok { + return d + } + } + if e.ArgumentRules != nil { + if d, ok := e.ArgumentRules(); ok { + return d + } + } + c := in.Classification + switch in.Mode { + case ModeDeny: + if c.Write || c.DestructiveMarked { + return Decision{Kind: DecideDeny, + Reason: "write policy deny: the call may write and policy.write is deny"} + } + case ModeAsk: + if c.Write || c.DestructiveMarked { + return Decision{Kind: DecideAsk, + Reason: "write policy ask: the call may write and policy.write is ask"} + } + case ModeAllow: + // No confirmation from the mode; the floor below may still ask. + } + if in.ConfirmDestructiveFloor && c.Destructive { + // The floor reaches only an allow that survived the mode: a + // deny above has already refused a destructive write, and an + // ask has already asked once. It upgrades, never weakens. + return Decision{Kind: DecideAsk, + Reason: "destructive floor: the call may be destructive and elicit.confirmDestructive is on"} + } + return Decision{Kind: DecideAllow, Reason: "the call is not a gated write"} +} diff --git a/pkgs/mcpx/internal/policy/policy_test.go b/pkgs/mcpx/internal/policy/policy_test.go new file mode 100644 index 0000000000..0000aaa403 --- /dev/null +++ b/pkgs/mcpx/internal/policy/policy_test.go @@ -0,0 +1,93 @@ +package policy + +import ( + "encoding/json" + "testing" +) + +func TestClassifyUsesTheSpecDefaults(t *testing.T) { + for _, c := range []struct { + name string + raw string + want Classification + }{ + {"unannotated", ``, Classification{Write: true, Destructive: true}}, + {"empty object", `{}`, Classification{Write: true, Destructive: true}}, + {"readOnly true", `{"readOnlyHint":true}`, + Classification{ReadOnly: true}}, + {"readOnly true and destructive true", `{"readOnlyHint":true,"destructiveHint":true}`, + Classification{ReadOnly: true, DestructiveMarked: true}}, + {"destructive false", `{"destructiveHint":false}`, + Classification{Write: true}}, + {"destructive true", `{"destructiveHint":true}`, + Classification{Write: true, Destructive: true, DestructiveMarked: true}}, + {"readOnly false", `{"readOnlyHint":false}`, + Classification{Write: true, Destructive: true}}, + } { + t.Run(c.name, func(t *testing.T) { + if got := Classify(json.RawMessage(c.raw)); got != c.want { + t.Errorf("Classify(%q) = %+v, want %+v", c.raw, got, c.want) + } + }) + } +} + +func TestCanonicalArgsSortsKeys(t *testing.T) { + got := CanonicalArgs(map[string]any{"b": 1, "a": 2}) + if got != `{"a":2,"b":1}` { + t.Errorf("CanonicalArgs = %s, want keys sorted", got) + } + if got := CanonicalArgs(nil); got != "null" { + t.Errorf("CanonicalArgs(nil) = %s, want null", got) + } +} + +func TestParseMode(t *testing.T) { + for _, s := range []string{"ask", "allow", "deny"} { + if m, ok := ParseMode(s); !ok || m != Mode(s) || !m.Valid() { + t.Errorf("ParseMode(%q) = %q, %v", s, m, ok) + } + } + if _, ok := ParseMode("sometimes"); ok { + t.Error("ParseMode accepted an unknown mode") + } +} + +// The gate's whole table: three modes against a write, a read-only +// call and a destructive write, plus the floor's two directions -- it +// upgrades allow to ask, and it never weakens deny. +func TestEvaluate(t *testing.T) { + write := Classification{Write: true} + readOnly := Classification{ReadOnly: true} + destructive := Classification{Write: true, Destructive: true, DestructiveMarked: true} + for _, c := range []struct { + name string + mode Mode + class Classification + floor bool + want DecisionKind + }{ + {"deny refuses a write", ModeDeny, write, false, DecideDeny}, + {"deny passes a read-only call", ModeDeny, readOnly, false, DecideAllow}, + {"deny refuses a destructive write", ModeDeny, destructive, false, DecideDeny}, + {"ask asks about a write", ModeAsk, write, false, DecideAsk}, + {"ask passes a read-only call", ModeAsk, readOnly, false, DecideAllow}, + {"ask asks about a destructive write", ModeAsk, destructive, false, DecideAsk}, + {"allow passes a write", ModeAllow, write, false, DecideAllow}, + {"allow passes a read-only call", ModeAllow, readOnly, false, DecideAllow}, + {"allow passes a destructive write without the floor", ModeAllow, destructive, false, DecideAllow}, + {"floor upgrades allow to ask for a destructive call", ModeAllow, destructive, true, DecideAsk}, + {"floor leaves a non-destructive write under allow alone", ModeAllow, write, true, DecideAllow}, + {"floor does not weaken deny", ModeDeny, destructive, true, DecideDeny}, + } { + t.Run(c.name, func(t *testing.T) { + d := Evaluator{}.Evaluate(Input{Mode: c.mode, Classification: c.class, ConfirmDestructiveFloor: c.floor}) + if d.Kind != c.want { + t.Errorf("Evaluate = %v (%s), want %v", d.Kind, d.Reason, c.want) + } + if d.Reason == "" { + t.Error("Evaluate returned no reason") + } + }) + } +} diff --git a/pkgs/mcpx/internal/settings/consumer.go b/pkgs/mcpx/internal/settings/consumer.go index 5d531cc3f5..ccffee21ae 100644 --- a/pkgs/mcpx/internal/settings/consumer.go +++ b/pkgs/mcpx/internal/settings/consumer.go @@ -78,6 +78,28 @@ func consumerSettings() []Setting { "on the path of every destructive call, and a caller that cannot " + "answer waits out the deadline before the call proceeds.", }, + { + Path: "policy.write", Scope: ScopeDaemon, Kind: KindEnum, Default: defaults.WritePolicy, + Enum: []string{"ask", "allow", "deny"}, + Name: "Write policy", + Short: "what to do before a call that may write: ask for confirmation, " + + "allow it, or deny it", + Long: "The write policy gate (#1979) sits on every tool call, between " + + "resolving an instance and using it. A call is a write when its tool " + + "is not annotated readOnlyHint true, with the specification's " + + "defaults, and a per-server writePolicy in that server's mcpx block " + + "overrides this daemon-wide mode for that server alone. Ask raises " + + "a confirmation showing the exact tool and its canonical arguments, " + + "and a caller that cannot answer is refused rather than waited out " + + "silently; allow lets writes proceed with no confirmation from the " + + "policy; deny refuses them. elicit.confirmDestructive is a floor, " + + "not an alternative: a destructive call asks even under allow, and " + + "the floor never weakens a deny. This is an operator consent gate, " + + "not the autonomy dial (docs/decisions/0002-autonomy-dial.md): the " + + "dial bounds what mcpx does on its own, this bounds what a caller " + + "may do to the outside world through it, and neither clamps the " + + "other.", + }, { Path: "elicit.askTimeout", Scope: ScopeDaemon, Kind: KindDuration, Default: defaults.AskTimeout.String(), Name: "Question deadline", diff --git a/pkgs/mcpx/internal/settings/effect.go b/pkgs/mcpx/internal/settings/effect.go index 2a3a8354d0..dcd691386e 100644 --- a/pkgs/mcpx/internal/settings/effect.go +++ b/pkgs/mcpx/internal/settings/effect.go @@ -148,6 +148,7 @@ var EffectExemptions = map[string]string{ "elicit.disambiguate": "elicitation flow: its effect needs an interactive client answering (or not answering) inside that window; ask fixtures cover the flow, not this bound", "elicit.disambiguateDefault": "elicitation flow: its effect needs an interactive client answering (or not answering) inside that window; ask fixtures cover the flow, not this bound", "elicit.confirmDestructive": "elicitation flow: its effect needs an interactive client answering (or not answering) inside that window; ask fixtures cover the flow, not this bound", + "policy.write": "elicitation flow: its effect needs an interactive client answering (or not answering) inside that window; daemon unit tests cover the gate, not an e2e with/without probe", "elicit.askTimeout": "elicitation flow: its effect needs an interactive client answering (or not answering) inside that window; ask fixtures cover the flow, not this bound", "elicit.ttl": "elicitation flow: its effect needs an interactive client answering (or not answering) inside that window; ask fixtures cover the flow, not this bound", "elicit.maxAge": "elicitation flow: its effect needs an interactive client answering (or not answering) inside that window; ask fixtures cover the flow, not this bound", @@ -248,7 +249,7 @@ var EffectExemptions = map[string]string{ // EffectExemptionPin is the ratchet: the exemption count at the time // the guard landed. It may only ever be lowered, and only in the PR // that removes an exemption by adding the probe that replaces it. -const EffectExemptionPin = 181 +const EffectExemptionPin = 182 // raised by one for policy.write (#1979), in the elicitation-flow exemption style of elicit.confirmDestructive // CheckEffectCoverage returns one violation per way the probe and // exemption maps fail to cover reg exactly: a setting with neither, From 749ccfd7c1d742f057caf7edc27f9b63bd563f15 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 17:01:14 -0500 Subject: [PATCH 2/2] =?UTF-8?q?fix(mcpx):=20write=20policy=20gate=20?= =?UTF-8?q?=E2=80=94=20view-resolved=20overrides,=20flag-resolved=20settin?= =?UTF-8?q?gs,=20fresh=20annotations,=20strict=20classify=20(#1979)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four Codex findings on PR #2829 dispositioned by fixing: (P1) the per-server override is read from the requested server view, not the shared pool creating config (aliases/reload could inherit allow over deny); (P2) Classify discards partially decoded annotations on unmarshal error instead of trusting a partial readOnlyHint; (P2) initConsumer uses the daemon already-resolved settings set (flags like --policy-write) instead of re-resolving from sources; (P2) the gate refreshes expired schema caches before classifying, failing closed on refresh error (new Pool.SchemaExpired). Also fixes the handover test the gate exposed: handoff lifecycle daemons run with policy.write=allow in their test settings, since their raw clients cannot answer questions and the fake unannotated slow tool is a write — default ask parked it on the broker and the takeover drain timed out (verified: test passed on base a047d531 and on current main, failed at PR head). Tests: new alias-override and malformed-annotation cases; daemon/policy/pool suites green on the laptop. --- pkgs/mcpx/internal/daemon/consumer.go | 48 +++++++++++++++---- .../mcpx/internal/daemon/handoff_load_test.go | 16 ++++++- pkgs/mcpx/internal/daemon/registry.go | 2 +- .../mcpx/internal/daemon/write_policy_test.go | 47 ++++++++++++++---- pkgs/mcpx/internal/policy/policy.go | 15 ++++-- pkgs/mcpx/internal/policy/policy_test.go | 12 +++++ pkgs/mcpx/internal/pool/pool.go | 13 +++++ 7 files changed, 127 insertions(+), 26 deletions(-) diff --git a/pkgs/mcpx/internal/daemon/consumer.go b/pkgs/mcpx/internal/daemon/consumer.go index 946f775a9e..2b6451675d 100644 --- a/pkgs/mcpx/internal/daemon/consumer.go +++ b/pkgs/mcpx/internal/daemon/consumer.go @@ -78,13 +78,26 @@ const CatalogHistoryFile = "catalog-history.json" // diagnostic that says what changed. func (s *Server) initConsumer() { st := &consumerState{policy: defaultConsumerPolicy()} - var sources []string - if s.cfg != nil { - sources = s.cfg.Sources + // The daemon's already-resolved settings are the authority: they + // carry the command-line flags (--policy-write and friends), which + // a fresh settings.Resolve over the config sources would silently + // drop, leaving the gate reading file/environment values the + // operator explicitly overrode. Resolve from sources only when + // the server was built without a set. + set := s.set + if set == nil { + var sources []string + if s.cfg != nil { + sources = s.cfg.Sources + } + resolved, err := settings.Resolve(sources) + if err != nil { + s.logger.Printf("consumer policy: %v; using defaults", err) + } else { + set = resolved + } } - if set, err := settings.Resolve(sources); err != nil { - s.logger.Printf("consumer policy: %v; using defaults", err) - } else { + if set != nil { st.policy = consumerPolicyFrom(set) st.dirs = recipeDirs(set.String("paths.scripts")) } @@ -482,10 +495,17 @@ func (e ErrWriteDenied) Error() string { // has asked, and elicit.confirmDestructive's floor is then satisfied; // under allow confirmDestructive still runs, which is how the floor // reaches a destructive call the policy let through. -func (r *Registry) applyWritePolicy(ctx context.Context, p *pool.Pool, tool string, cc config.CallContext, args any) (bool, error) { +func (r *Registry) applyWritePolicy(ctx context.Context, p *pool.Pool, server, tool string, cc config.CallContext, args any) (bool, error) { mode := r.consumer.WritePolicy - if cfg := p.Config(); cfg != nil && cfg.WritePolicy != "" { - mode = cfg.WritePolicy + // The requested server's VIEW carries the override, never the + // pool's creating config: pools are shared between aliases, so + // p.Config() holds only the configuration that happened to create + // the pool — an alias configured deny could inherit another + // alias's allow, and a Reload that changes a view's writePolicy + // (pools are preserved across reloads; views are rebuilt) would + // never reach the gate. + if view, ok := r.View(server); ok && view.WritePolicy != "" { + mode = view.WritePolicy } if mode == "" { // Unconfigured (zero-value policy in tests): allow, with no @@ -509,8 +529,16 @@ func (r *Registry) applyWritePolicy(ctx context.Context, p *pool.Pool, tool stri // confirmDestructive fetches them: from the cache, or read now -- // failing closed if they cannot be read, because deciding from an // empty list would let a write through unasked. + // Freshness matters as much as presence: an expired cache (a + // modern upstream's ttlMs deadline, or a disk seed past its + // deadline) can carry annotations the tool no longer has — a + // cached read-only hint on a now-writable tool would sail past + // ask and deny alike. Refresh first, failing closed on error: + // RefreshSchemas returns the error instead of serving the stale + // catalogue, and deciding from stale annotations is exactly the + // fail-open this gate exists to prevent. all, _, at := p.CachedSchemas() - if at.IsZero() { + if at.IsZero() || p.SchemaExpired() { fresh, _, err := p.RefreshSchemas(ctx) if err != nil { return false, ErrNotConfirmed{Tool: p.Namespace() + "." + tool, diff --git a/pkgs/mcpx/internal/daemon/handoff_load_test.go b/pkgs/mcpx/internal/daemon/handoff_load_test.go index 844dd83b75..ff6f09a03a 100644 --- a/pkgs/mcpx/internal/daemon/handoff_load_test.go +++ b/pkgs/mcpx/internal/daemon/handoff_load_test.go @@ -17,6 +17,7 @@ import ( "github.com/dezren39/mcpx/internal/config" "github.com/dezren39/mcpx/internal/pool" + "github.com/dezren39/mcpx/internal/settings" "github.com/dezren39/mcpx/internal/testsupport" ) @@ -40,12 +41,25 @@ func handoffPaths(t *testing.T) Paths { } func handoffOptions(paths Paths, cfg *config.Config, version string) Options { - return Options{ + opts := Options{ Config: cfg, Paths: paths, Version: version, Logger: log.New(io.Discard, "", 0), } + // These tests are about handover mechanics, not the write policy: + // their raw clients cannot answer questions, and the fake server's + // unannotated tools are writes, so the policy's default ask would + // park every call on the broker until its timeout and the drain + // would never finish (#1979's gate working as designed, in a test + // that is not about it). Run the lifecycle daemons with the policy + // in allow, as a pre-#1979 daemon behaved. + if sch, err := settings.New(settings.Registry()); err == nil { + opts.Settings = settings.NewSet(sch).WithOverrides(map[string]string{ + "policy.write": "allow", + }, "test") + } + return opts } // cliStyleClient talks to the socket the way the CLI does: one transport, diff --git a/pkgs/mcpx/internal/daemon/registry.go b/pkgs/mcpx/internal/daemon/registry.go index 02b347fa72..7d82f6d669 100644 --- a/pkgs/mcpx/internal/daemon/registry.go +++ b/pkgs/mcpx/internal/daemon/registry.go @@ -1106,7 +1106,7 @@ func (r *Registry) resolveAndGuard(ctx context.Context, p *pool.Pool, server, to // Two policies sit between resolving the instance and using it, and both // are off unless somebody turned them on. See internal/daemon/consumer.go. key = r.disambiguate(ctx, p, cc, key) - asked, err := r.applyWritePolicy(ctx, p, tool, cc, args) + asked, err := r.applyWritePolicy(ctx, p, server, tool, cc, args) if err != nil { return "", err } diff --git a/pkgs/mcpx/internal/daemon/write_policy_test.go b/pkgs/mcpx/internal/daemon/write_policy_test.go index 3202461842..469cc119ff 100644 --- a/pkgs/mcpx/internal/daemon/write_policy_test.go +++ b/pkgs/mcpx/internal/daemon/write_policy_test.go @@ -36,12 +36,22 @@ func writePolicyRegistry(mode string) *Registry { return &Registry{consumer: ConsumerPolicy{WritePolicy: mode}} } +// writePolicyRegistryWithView is a registry whose per-name view for +// "demo" carries its own writePolicy override. +func writePolicyRegistryWithView(mode, viewPolicy string) *Registry { + r := writePolicyRegistry(mode) + r.views = map[string]*config.Resolved{ + "demo": {Namespace: "demo", WritePolicy: viewPolicy}, + } + return r +} + // (a) Deny refuses a write tool -- an unannotated tool, which the // specification's defaults read as a possibly destructive write. func TestWritePolicyDenyRefusesAWriteTool(t *testing.T) { r := writePolicyRegistry("deny") p := writePolicyPool(t, "", ``) - asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, map[string]any{"id": 1}) + asked, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", config.CallContext{}, map[string]any{"id": 1}) if asked { t.Error("a denied call must not report it asked") } @@ -59,7 +69,7 @@ func TestWritePolicyDenyRefusesAWriteTool(t *testing.T) { func TestWritePolicyAllowPassesAWriteToolWithoutBroker(t *testing.T) { r := writePolicyRegistry("allow") p := writePolicyPool(t, "", ``) - asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, map[string]any{"id": 1}) + asked, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", config.CallContext{}, map[string]any{"id": 1}) if err != nil { t.Fatalf("applyWritePolicy = %v, want nil", err) } @@ -74,7 +84,7 @@ func TestWritePolicyAllowPassesAWriteToolWithoutBroker(t *testing.T) { func TestWritePolicyAskWithNoBrokerRefuses(t *testing.T) { r := writePolicyRegistry("ask") p := writePolicyPool(t, "", ``) - asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, map[string]any{"id": 1}) + asked, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", config.CallContext{}, map[string]any{"id": 1}) if asked { t.Error("an unanswered ask must not report it asked") } @@ -88,9 +98,9 @@ func TestWritePolicyAskWithNoBrokerRefuses(t *testing.T) { // directions: deny on the server refuses under a daemon-wide allow, // and allow on the server passes under a daemon-wide deny. func TestWritePolicyPerServerOverrideBeatsDaemonMode(t *testing.T) { - r := writePolicyRegistry("allow") - p := writePolicyPool(t, "deny", ``) - if _, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, nil); err == nil { + r := writePolicyRegistryWithView("allow", "deny") + p := writePolicyPool(t, "", ``) + if _, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", config.CallContext{}, nil); err == nil { t.Error("server deny under daemon allow: want a refusal, got nil") } else { var denied ErrWriteDenied @@ -99,19 +109,36 @@ func TestWritePolicyPerServerOverrideBeatsDaemonMode(t *testing.T) { } } - r = writePolicyRegistry("deny") - p = writePolicyPool(t, "allow", ``) - asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, nil) + r = writePolicyRegistryWithView("deny", "allow") + p = writePolicyPool(t, "", ``) + asked, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", config.CallContext{}, nil) if err != nil || asked { t.Errorf("server allow under daemon deny: asked=%v err=%v, want a pass", asked, err) } } +// The override is read from the requested server's view, not the +// pool's creating config (Codex P1 on PR #2829): aliases share one +// pool, so a pool created from an allow config must still honour a +// deny on the alias the call actually requested. +func TestWritePolicyViewOverrideBeatsPoolConfig(t *testing.T) { + r := writePolicyRegistryWithView("ask", "deny") + p := writePolicyPool(t, "allow", ``) + if _, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", config.CallContext{}, nil); err == nil { + t.Error("view deny over pool-config allow: want a refusal, got nil") + } else { + var denied ErrWriteDenied + if !errors.As(err, &denied) { + t.Errorf("view deny over pool-config allow: got %v, want ErrWriteDenied", err) + } + } +} + // A read-only tool is not a write, so even deny lets it through. func TestWritePolicyDenyPassesAReadOnlyTool(t *testing.T) { r := writePolicyRegistry("deny") p := writePolicyPool(t, "", `{"readOnlyHint":true}`) - asked, err := r.applyWritePolicy(context.Background(), p, "wipe", config.CallContext{}, nil) + asked, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", config.CallContext{}, nil) if err != nil || asked { t.Errorf("read-only under deny: asked=%v err=%v, want a pass", asked, err) } diff --git a/pkgs/mcpx/internal/policy/policy.go b/pkgs/mcpx/internal/policy/policy.go index 78533f93aa..6d5528714c 100644 --- a/pkgs/mcpx/internal/policy/policy.go +++ b/pkgs/mcpx/internal/policy/policy.go @@ -81,10 +81,17 @@ func Classify(annotations json.RawMessage) Classification { Destructive *bool `json:"destructiveHint"` } if len(annotations) > 0 { - // An unmarshal error leaves doc zero, which is the defaults - // reading below; there is nothing better to do with annotations - // that cannot be parsed. - _ = json.Unmarshal(annotations, &doc) + // An unmarshal error does NOT leave doc zero: Unmarshal + // populates the fields it could decode before failing, so a + // malformed object like {"readOnlyHint":true, + // "destructiveHint":"invalid"} would otherwise be read as + // read-only from the partial decode. Discard the partial + // result wholesale: unreadable annotations say nothing, and + // the defaults below (a possibly destructive write) stand. + if err := json.Unmarshal(annotations, &doc); err != nil { + doc.ReadOnly = nil + doc.Destructive = nil + } } c := Classification{} if doc.ReadOnly != nil && *doc.ReadOnly { diff --git a/pkgs/mcpx/internal/policy/policy_test.go b/pkgs/mcpx/internal/policy/policy_test.go index 0000aaa403..4c99a5409c 100644 --- a/pkgs/mcpx/internal/policy/policy_test.go +++ b/pkgs/mcpx/internal/policy/policy_test.go @@ -32,6 +32,18 @@ func TestClassifyUsesTheSpecDefaults(t *testing.T) { } } +// Malformed annotations must not leak a partial decode (Codex P2 on +// PR #2829): json.Unmarshal populates the fields it can before +// failing, so {"readOnlyHint":true,"destructiveHint":"invalid"} would +// otherwise classify as read-only and bypass ask/deny. Unreadable +// annotations get the conservative defaults instead. +func TestClassifyDiscardsPartiallyDecodedAnnotations(t *testing.T) { + c := Classify(json.RawMessage(`{"readOnlyHint":true,"destructiveHint":"invalid"}`)) + if c.ReadOnly || !c.Write || !c.Destructive { + t.Errorf("Classify(malformed) = %+v, want the defaults: a possibly destructive write", c) + } +} + func TestCanonicalArgsSortsKeys(t *testing.T) { got := CanonicalArgs(map[string]any{"b": 1, "a": 2}) if got != `{"a":2,"b":1}` { diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index 0cccd9bf93..bf7115de27 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -1010,6 +1010,19 @@ func (p *Pool) Instructions() string { return p.instructions } +// SchemaExpired reports whether the cached catalogue has passed the +// freshness deadline a modern upstream set for it (#1602). A cache +// with no deadline (legacy upstream, or none fetched yet) never +// expires. Callers that must not decide from stale data — the write +// policy gate (#1979) classifying a call by its annotations — check +// this and refresh first; RefreshSchemas returns a refresh error +// rather than serving the stale catalogue, so they can fail closed. +func (p *Pool) SchemaExpired() bool { + p.schemaMu.RLock() + defer p.schemaMu.RUnlock() + return !p.schemaAt.IsZero() && !p.schemaDeadline.IsZero() && !time.Now().Before(p.schemaDeadline) +} + // CachedSchemas returns whatever is cached without triggering a fetch. func (p *Pool) CachedSchemas() ([]mcpclient.Tool, []mcpclient.Resource, time.Time) { p.schemaMu.RLock()