From 45d31835baf4a50c65d83a108985ca45504b0995 Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 17:45:29 -0300 Subject: [PATCH 01/15] fix(checks): mask structuredContent and resource text, deny on a redact error (ENG-965) --- audit/audit.go | 2 +- checks/redact.go | 232 +++++++++++++++++----- checks/redact_test.go | 167 +++++++++++++++- docs/architectural/embedding.md | 2 +- docs/architectural/inspection-pipeline.md | 2 +- gateway/redact_test.go | 66 ++++++ 6 files changed, 407 insertions(+), 64 deletions(-) create mode 100644 gateway/redact_test.go diff --git a/audit/audit.go b/audit/audit.go index 547a966..abe7d6f 100644 --- a/audit/audit.go +++ b/audit/audit.go @@ -26,7 +26,7 @@ const ( EventApprovalPending EventType = "mcp.approval_pending" EventApprovalResolved EventType = "mcp.approval_resolved" EventBudgetExceeded EventType = "mcp.budget_exceeded" - EventRedacted EventType = "mcp.redacted" + EventRedacted EventType = "mcp.redacted" // one per masked message; Fields["redactions"] (int) sums the hook counts EventGuardrailBlock EventType = "mcp.guardrail_block" EventSessionKilled EventType = "mcp.session_killed" EventError EventType = "mcp.error" diff --git a/checks/redact.go b/checks/redact.go index 74b68fc..42cb4ea 100644 --- a/checks/redact.go +++ b/checks/redact.go @@ -1,19 +1,26 @@ package checks import ( + "bytes" "context" "encoding/json" + "strings" "github.com/hoophq/mcpproxy/audit" "github.com/hoophq/mcpproxy/inspect" + "github.com/hoophq/mcpproxy/jsonrpc" "github.com/hoophq/mcpproxy/mcp" ) -// Redactor masks sensitive strings in data flowing back to the model. It -// walks only the two payloads that carry backend-controlled bulk text: tool -// results (result.content[]) and resource reads (result.contents[]). Schemas, -// capability blobs, and ids are structural, and rewriting them would break -// the protocol. +// redactReason is what the client reads when a result is withheld. The hook +// error goes to the audit event only, because it can quote the text. +const redactReason = "result withheld: redaction failed" + +// Redactor masks sensitive strings in tools/call and resources/read results: +// content[].text, content[].resource.text, contents[].text and every string +// of structuredContent. Other fields are structural, and rewriting them would +// break the protocol. A Redact hook error denies the result, so unmasked text +// never reaches the client. type Redactor struct { redact func(ctx context.Context, text string) (string, int, error) sink audit.Sink @@ -36,13 +43,7 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms if !m.Env.IsResponse() || m.Env.Error != nil || len(m.Env.Result) == 0 { return inspect.AllowAll } - var field string - switch m.CorrelatedMethod { - case mcp.MethodToolsCall: - field = "content" - case mcp.MethodResourcesRead: - field = "contents" - default: + if m.CorrelatedMethod != mcp.MethodToolsCall && m.CorrelatedMethod != mcp.MethodResourcesRead { return inspect.AllowAll } @@ -50,72 +51,201 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms if err := json.Unmarshal(m.Env.Result, &result); err != nil { return inspect.AllowAll } - var items []json.RawMessage - if err := json.Unmarshal(result[field], &items); err != nil || len(items) == 0 { - return inspect.AllowAll - } + w := &walker{ctx: ctx, redact: r.redact} total := 0 - for i, raw := range items { - out, n := r.redactItem(ctx, raw) - if n == 0 { + var masked []string + for _, field := range []string{"content", "contents", "structuredContent"} { + raw, ok := result[field] + if !ok { continue } - items[i] = out - total += n + var out json.RawMessage + var n int + var err error + if field == "structuredContent" { + out, n, err = w.value(raw) + } else { + out, n, err = w.array(raw, w.item) + } + if err != nil { + return r.deny(ctx, s, m, err) + } + if n > 0 { + result[field] = out + total += n + masked = append(masked, field) + } } if total == 0 { return inspect.AllowAll } - ib, err := json.Marshal(items) - if err != nil { - return inspect.AllowAll - } - result[field] = ib out, err := json.Marshal(result) if err != nil { - return inspect.AllowAll + return r.deny(ctx, s, m, err) } m.Env.Result = out emit(ctx, r.sink, s, audit.Event{ Type: audit.EventRedacted, Backend: m.Backend, Tool: m.CorrelatedTool, - Rule: NameRedact, Fields: map[string]any{"redactions": total, "field": field}, + Rule: NameRedact, Fields: map[string]any{"redactions": total, "field": strings.Join(masked, ",")}, }) return inspect.AllowAll } -// redactItem rewrites the "text" leaf of one content entry, preserving every -// other field. It returns the new bytes and the redaction count; count 0 -// means the entry is unchanged. -func (r *Redactor) redactItem(ctx context.Context, raw json.RawMessage) (json.RawMessage, int) { +func (r *Redactor) deny(ctx context.Context, s inspect.Session, m *inspect.Msg, err error) inspect.Decision { + emit(ctx, r.sink, s, audit.Event{ + Type: audit.EventToolDenied, Backend: m.Backend, Tool: m.CorrelatedTool, + Rule: NameRedact, Reason: redactReason + ": " + err.Error(), + }) + return inspect.Denyf(m.Env, jsonrpc.CodePolicyDenied, NameRedact, redactReason) +} + +// walker runs the Redact hook over the strings of one result. Each method +// returns the new bytes and the redaction count; count 0 means the input is +// unchanged. A value of an unexpected shape carries no text leaf and is left +// as it is. +type walker struct { + ctx context.Context + redact func(ctx context.Context, text string) (string, int, error) +} + +// item masks the text leaf of one content entry and the text of its nested +// resource. +func (w *walker) item(raw json.RawMessage) (json.RawMessage, int, error) { + return w.object(raw, func(fields map[string]json.RawMessage) (int, error) { + n, err := w.leaf(fields, "text") + if err != nil { + return 0, err + } + res, ok := fields["resource"] + if !ok { + return n, nil + } + out, rn, err := w.object(res, func(rf map[string]json.RawMessage) (int, error) { + return w.leaf(rf, "text") + }) + if err != nil { + return 0, err + } + if rn > 0 { + fields["resource"] = out + } + return n + rn, nil + }) +} + +// value masks every string in a JSON value, at any depth. Object keys are +// structure. +func (w *walker) value(raw json.RawMessage) (json.RawMessage, int, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return raw, 0, nil + } + switch trimmed[0] { + case '"': + return w.str(raw) + case '[': + return w.array(raw, w.value) + case '{': + return w.object(raw, func(fields map[string]json.RawMessage) (int, error) { + total := 0 + for k, v := range fields { + n, err := w.set(fields, k, v, w.value) + if err != nil { + return 0, err + } + total += n + } + return total, nil + }) + } + return raw, 0, nil +} + +// array applies fn to each element of a JSON array. +func (w *walker) array(raw json.RawMessage, fn func(json.RawMessage) (json.RawMessage, int, error)) (json.RawMessage, int, error) { + var elems []json.RawMessage + if err := json.Unmarshal(raw, &elems); err != nil { + return raw, 0, nil + } + total := 0 + for i, v := range elems { + out, n, err := fn(v) + if err != nil { + return nil, 0, err + } + if n > 0 { + elems[i] = out + total += n + } + } + if total == 0 { + return raw, 0, nil + } + out, err := json.Marshal(elems) + if err != nil { + return nil, 0, err + } + return out, total, nil +} + +// object decodes a JSON object, lets fn rewrite its fields, and encodes it +// again when fn masked something. +func (w *walker) object(raw json.RawMessage, fn func(map[string]json.RawMessage) (int, error)) (json.RawMessage, int, error) { var fields map[string]json.RawMessage - if err := json.Unmarshal(raw, &fields); err != nil { - return raw, 0 + if err := json.Unmarshal(raw, &fields); err != nil || fields == nil { + return raw, 0, nil } - tv, ok := fields["text"] - if !ok { - return raw, 0 + n, err := fn(fields) + if err != nil { + return nil, 0, err } - var text string - if err := json.Unmarshal(tv, &text); err != nil || text == "" { - return raw, 0 + if n == 0 { + return raw, 0, nil + } + out, err := json.Marshal(fields) + if err != nil { + return nil, 0, err } - masked, n, err := r.redact(ctx, text) + return out, n, nil +} + +// leaf masks fields[key] when it is a string. +func (w *walker) leaf(fields map[string]json.RawMessage, key string) (int, error) { + v, ok := fields[key] + if !ok { + return 0, nil + } + return w.set(fields, key, v, w.str) +} + +// set stores fn(v) under key when fn masked something. +func (w *walker) set(fields map[string]json.RawMessage, key string, v json.RawMessage, fn func(json.RawMessage) (json.RawMessage, int, error)) (int, error) { + out, n, err := fn(v) if err != nil || n == 0 { - // A failing redactor must not pass unmasked text off as clean, and - // it cannot fabricate content either. Leave the entry as-is and - // report zero redactions. - return raw, 0 + return 0, err } - mb, err := json.Marshal(masked) + fields[key] = out + return n, nil +} + +// str runs the hook over one JSON string. +func (w *walker) str(raw json.RawMessage) (json.RawMessage, int, error) { + var text string + if err := json.Unmarshal(raw, &text); err != nil || text == "" { + return raw, 0, nil + } + masked, n, err := w.redact(w.ctx, text) if err != nil { - return raw, 0 + return nil, 0, err } - fields["text"] = mb - out, err := json.Marshal(fields) + if n <= 0 { + return raw, 0, nil + } + out, err := json.Marshal(masked) if err != nil { - return raw, 0 + return nil, 0, err } - return out, n + return out, n, nil } diff --git a/checks/redact_test.go b/checks/redact_test.go index 6fd490f..8860676 100644 --- a/checks/redact_test.go +++ b/checks/redact_test.go @@ -121,21 +121,168 @@ func TestRedactIgnoresUncorrelatedMethods(t *testing.T) { } } -// A failing redactor must not corrupt the payload or invent an audit count. -func TestRedactHookErrorLeavesTextIntact(t *testing.T) { +// responseMsg builds an S2C response to method carrying result. +func responseMsg(t *testing.T, method, tool string, result any) *inspect.Msg { + t.Helper() + return &inspect.Msg{ + Dir: inspect.S2C, CorrelatedMethod: method, CorrelatedTool: tool, + Env: &jsonrpc.Message{JSONRPC: "2.0", ID: rawID("9"), Result: mustJSON(t, result)}, + } +} + +// maskOrFail masks like maskSecret and fails on any text holding "BOOM". +func maskOrFail(ctx context.Context, text string) (string, int, error) { + if strings.Contains(text, "BOOM") { + return "", 1, errors.New("redactor down") + } + return maskSecret(ctx, text) +} + +func TestRedactStructuredContentEveryString(t *testing.T) { s, rec, ctx := newSession(t), &recorder{}, context.Background() - r := NewRedactor(inspect.Hooks{Redact: func(context.Context, string) (string, int, error) { - return "", 3, errors.New("redactor down") - }}, rec) - msg := resultMsg(t, "read_file", []any{textItem("token=SECRET")}) + r := NewRedactor(inspect.Hooks{Redact: maskSecret}, rec) + msg := responseMsg(t, mcp.MethodToolsCall, "lookup", map[string]any{ + "content": []any{textItem("see structuredContent")}, + "structuredContent": json.RawMessage(`{"id":12345678901234567890,` + + `"user":{"name":"SECRET","age":42,"tags":["a SECRET","plain",true,null]},` + + `"SECRET":"keys are structure"}`), + }) if got := r.Inspect(ctx, s, msg); got.Verdict != inspect.Allow { t.Fatalf("verdict = %s, want Allow", verdictString(got.Verdict)) } - if texts := contentTexts(t, msg.Env.Result, "content"); texts[0] != "token=SECRET" { - t.Errorf("text = %q, want it unchanged after a hook error", texts[0]) + var res map[string]json.RawMessage + _ = json.Unmarshal(msg.Env.Result, &res) + sc := string(res["structuredContent"]) + var got struct { + ID json.Number `json:"id"` + User struct { + Name string `json:"name"` + Age int `json:"age"` + Tags []any `json:"tags"` + } `json:"user"` + Key string `json:"SECRET"` + } + dec := json.NewDecoder(strings.NewReader(sc)) + dec.UseNumber() + if err := dec.Decode(&got); err != nil { + t.Fatalf("structuredContent is no longer valid JSON: %v", err) } - if n := rec.count(audit.EventRedacted); n != 0 { - t.Errorf("emitted %d redaction events after a hook error, want 0", n) + if got.User.Name != "[REDACTED]" || got.User.Tags[0] != "a [REDACTED]" { + t.Errorf("nested strings not masked: %+v", got.User) + } + if got.User.Tags[1] != "plain" || got.User.Tags[2] != true || got.User.Tags[3] != nil || got.User.Age != 42 { + t.Errorf("non-matching values changed: %+v", got.User) + } + if got.ID != "12345678901234567890" { + t.Errorf("id = %s, want the number byte for byte", got.ID) + } + if got.Key != "keys are structure" { + t.Errorf("object key or its clean value changed: %q", got.Key) + } + if ev, _ := rec.last(audit.EventRedacted); ev.Fields["redactions"] != 2 { + t.Errorf("redactions = %v, want 2", ev.Fields["redactions"]) + } +} + +func TestRedactNestedResourceText(t *testing.T) { + s, rec, ctx := newSession(t), &recorder{}, context.Background() + r := NewRedactor(inspect.Hooks{Redact: maskSecret}, rec) + msg := responseMsg(t, mcp.MethodToolsCall, "fetch", map[string]any{ + "content": []any{map[string]any{ + "type": "resource", + "resource": map[string]any{"uri": "file:///SECRET.txt", "mimeType": "text/plain", "text": "pw=SECRET"}, + }}, + }) + if got := r.Inspect(ctx, s, msg); got.Verdict != inspect.Allow { + t.Fatalf("verdict = %s, want Allow", verdictString(got.Verdict)) + } + var res struct { + Content []struct { + Type string `json:"type"` + Resource map[string]string `json:"resource"` + } `json:"content"` + } + if err := json.Unmarshal(msg.Env.Result, &res); err != nil { + t.Fatalf("result is no longer valid JSON: %v", err) + } + item := res.Content[0] + if item.Resource["text"] != "pw=[REDACTED]" { + t.Errorf("resource.text = %q, want it masked", item.Resource["text"]) + } + if item.Type != "resource" || item.Resource["uri"] != "file:///SECRET.txt" || item.Resource["mimeType"] != "text/plain" { + t.Errorf("structural fields changed: %+v", item) + } + if ev, _ := rec.last(audit.EventRedacted); ev.Fields["redactions"] != 1 { + t.Errorf("redactions = %v, want 1", ev.Fields["redactions"]) + } +} + +// A host records masked counts from one event per message. +func TestRedactCountsPerMessage(t *testing.T) { + s, rec, ctx := newSession(t), &recorder{}, context.Background() + r := NewRedactor(inspect.Hooks{Redact: maskSecret}, rec) + msg := responseMsg(t, mcp.MethodToolsCall, "lookup", map[string]any{ + "content": []any{ + textItem("SECRET and SECRET"), + map[string]any{"type": "resource", "resource": map[string]any{"uri": "file:///x", "text": "SECRET"}}, + }, + "structuredContent": map[string]any{"a": "SECRET", "b": []any{"SECRET"}}, + }) + r.Inspect(ctx, s, msg) + if n := rec.count(audit.EventRedacted); n != 1 { + t.Fatalf("emitted %d redaction events, want 1 per message", n) + } + ev, _ := rec.last(audit.EventRedacted) + if ev.Fields["redactions"] != 5 { + t.Errorf("redactions = %v, want 5", ev.Fields["redactions"]) + } + if ev.Fields["field"] != "content,structuredContent" { + t.Errorf("field = %v, want content,structuredContent", ev.Fields["field"]) + } +} + +// A Redact hook error on any field denies the whole result: the client gets +// an error, and the text, masked or not, never leaves. +func TestRedactHookErrorDeniesResult(t *testing.T) { + cases := []struct { + name, method string + result map[string]any + }{ + {"content text", mcp.MethodToolsCall, map[string]any{"content": []any{textItem("BOOM")}}}, + {"nested resource text", mcp.MethodToolsCall, map[string]any{"content": []any{ + map[string]any{"type": "resource", "resource": map[string]any{"uri": "file:///x", "text": "BOOM"}}, + }}}, + {"resources/read contents text", mcp.MethodResourcesRead, map[string]any{"contents": []any{ + map[string]any{"uri": "file:///x", "text": "BOOM"}, + }}}, + {"structuredContent after a masked field", mcp.MethodToolsCall, map[string]any{ + "content": []any{textItem("SECRET")}, + "structuredContent": map[string]any{"deep": []any{map[string]any{"v": "BOOM"}}}, + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s, rec, ctx := newSession(t), &recorder{}, context.Background() + r := NewRedactor(inspect.Hooks{Redact: maskOrFail}, rec) + msg := responseMsg(t, tc.method, "read_file", tc.result) + got := r.Inspect(ctx, s, msg) + if got.Verdict != inspect.Deny { + t.Fatalf("verdict = %s, want Deny", verdictString(got.Verdict)) + } + if got.Reply == nil || got.Reply.Error == nil || got.Reply.Error.Code != jsonrpc.CodePolicyDenied { + t.Fatalf("reply = %+v, want a policy-denied error", got.Reply) + } + if strings.Contains(got.Reason, "BOOM") || strings.Contains(got.Reply.Error.Message, "BOOM") { + t.Errorf("the client message quotes the text: %q", got.Reply.Error.Message) + } + if n := rec.count(audit.EventRedacted); n != 0 { + t.Errorf("emitted %d redaction events for a withheld result, want 0", n) + } + ev, ok := rec.last(audit.EventToolDenied) + if !ok || ev.Rule != NameRedact || !strings.Contains(ev.Reason, "redactor down") { + t.Errorf("denial audit = %+v, want rule %q with the hook error", ev, NameRedact) + } + }) } } diff --git a/docs/architectural/embedding.md b/docs/architectural/embedding.md index 90af521..d7a615e 100644 --- a/docs/architectural/embedding.md +++ b/docs/architectural/embedding.md @@ -38,7 +38,7 @@ hooks := inspect.Hooks{ GuardInput: func(ctx context.Context, dir inspect.Direction, text string) error { … }, // Mask sensitive content in result text leaves. Returns redacted - // text + count (count>0 emits mcp.redacted). + // text + count (count>0 emits mcp.redacted). Error => result denied. Redact: func(ctx context.Context, text string) (string, int, error) { … }, // Classify a tool call pre-flight; block=true denies THIS request diff --git a/docs/architectural/inspection-pipeline.md b/docs/architectural/inspection-pipeline.md index 9c12548..738cd34 100644 --- a/docs/architectural/inspection-pipeline.md +++ b/docs/architectural/inspection-pipeline.md @@ -46,7 +46,7 @@ The order is load-bearing: | `rug-pull` | invalidates on `notifications/tools/list_changed` | fingerprints every tool (name + description + input schema, SHA-256); a change on a known tool → Kill (default) or audit alert | | `overrides` | rewrites aliased `tools/call` names back to real names | renames tools / replaces descriptions in the catalog | | `guardrails` | `Hooks.GuardInput` over `tools/call` arguments → Deny | over tool descriptions → Kill (poisoned catalog) | -| `redact` | (no C2S role) | `Hooks.Redact` over `result.content[].text` and `resources/read` contents | +| `redact` | (no C2S role) | `Hooks.Redact` over `content[].text`, `content[].resource.text`, `contents[].text` and every string of `structuredContent` in `tools/call` and `resources/read` results; a hook error denies the result | | `audit-tap` | `mcp.tool_call` (args as SHA-256 digest, never verbatim) | `mcp.tools_listed` | ## Session state (`session.State`) diff --git a/gateway/redact_test.go b/gateway/redact_test.go new file mode 100644 index 0000000..1bc0a5f --- /dev/null +++ b/gateway/redact_test.go @@ -0,0 +1,66 @@ +package gateway_test + +import ( + "context" + "encoding/json" + "errors" + "net/http/httptest" + "strings" + "testing" + + "github.com/hoophq/mcpproxy/audit" + "github.com/hoophq/mcpproxy/backend" + "github.com/hoophq/mcpproxy/checks" + "github.com/hoophq/mcpproxy/config" + "github.com/hoophq/mcpproxy/gateway" + "github.com/hoophq/mcpproxy/inspect" + "github.com/hoophq/mcpproxy/internal/testmcp" + "github.com/hoophq/mcpproxy/jsonrpc" +) + +// A Redact hook error withholds the result: the client gets a policy error +// that does not quote the text, and the session keeps serving. +func TestRedactHookErrorWithholdsResult(t *testing.T) { + t.Parallel() + hs := httptest.NewServer(testmcp.New().HTTPHandler()) + defer hs.Close() + redact := func(_ context.Context, text string) (string, int, error) { + if strings.Contains(text, "BOOM") { + return "", 0, errors.New("masker down") + } + n := strings.Count(text, "SECRET") + return strings.ReplaceAll(text, "SECRET", "[REDACTED]"), n, nil + } + gw, err := gateway.New(gateway.Options{ + Backends: map[string]backend.Factory{ + "main": backend.NewFactory("main", config.Backend{Transport: "streamable-http", URL: hs.URL}, nil), + }, + Pipeline: checks.Assemble(config.Policy{}, inspect.Hooks{Redact: redact}, audit.Discard, false), + }) + if err != nil { + t.Fatalf("gateway.New: %v", err) + } + defer gw.Close() + front := httptest.NewServer(gw.Handler()) + defer front.Close() + + c := &tclient{t: t, url: front.URL} + c.initialize() + + _, body := c.postRaw(`{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"pw":"BOOM"}}}`) + if strings.Contains(body, "BOOM") { + t.Fatalf("withheld text reached the client: %s", body) + } + var resp jsonrpc.Message + if err := json.Unmarshal([]byte(body), &resp); err != nil { + t.Fatalf("bad response %q: %v", body, err) + } + if resp.Error == nil || resp.Error.Code != jsonrpc.CodePolicyDenied || resp.Result != nil { + t.Fatalf("response = %s, want a %d error and no result", body, jsonrpc.CodePolicyDenied) + } + + m, _ := c.post(`{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"echo","arguments":{"pw":"SECRET"}}}`) + if out := mustJSON(m["result"]); !strings.Contains(out, "[REDACTED]") || strings.Contains(out, "SECRET") { + t.Fatalf("next call on the session: %v, want a masked result", m) + } +} From 7b61697ce1c9939ba1aee12a8f3eed40590cd78a Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 17:51:42 -0300 Subject: [PATCH 02/15] fix(gateway): reply to server requests with the session caller's context (ENG-961) --- gateway/caller_test.go | 154 ++++++++++++++++++++++++++++++++++++++++ gateway/conn.go | 29 ++++++-- gateway/gateway.go | 1 + gateway/gateway_test.go | 4 ++ gateway/http.go | 1 + 5 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 gateway/caller_test.go diff --git a/gateway/caller_test.go b/gateway/caller_test.go new file mode 100644 index 0000000..4517bfb --- /dev/null +++ b/gateway/caller_test.go @@ -0,0 +1,154 @@ +package gateway_test + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/hoophq/mcpproxy/audit" + "github.com/hoophq/mcpproxy/auth/outbound" + "github.com/hoophq/mcpproxy/backend" + "github.com/hoophq/mcpproxy/checks" + "github.com/hoophq/mcpproxy/config" + "github.com/hoophq/mcpproxy/gateway" + "github.com/hoophq/mcpproxy/inspect" + "github.com/hoophq/mcpproxy/jsonrpc" +) + +// passthroughResolver moves the caller's upstream credential onto the +// request context, as mcpproxyd and hoop do. +func passthroughResolver(r *http.Request) (inspect.Identity, error) { + if v := r.Header.Get(outbound.UpstreamAuthHeader); v != "" { + *r = *r.WithContext(outbound.WithClientToken(r.Context(), outbound.TrimBearer(v))) + } + return inspect.Identity{Subject: "alice"}, nil +} + +// samplingUpstream is a streamable-HTTP server that answers tools/call with +// a sampling request before the result. It reports the Authorization of +// every reply it receives. +func samplingUpstream(replies chan<- string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + env, err := jsonrpc.Parse(body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + w.Header().Set("Mcp-Session-Id", "up-1") + var res string + switch { + case env.IsResponse(): + replies <- r.Header.Get("Authorization") + w.WriteHeader(http.StatusAccepted) + return + case env.IsNotification(): + w.WriteHeader(http.StatusAccepted) + return + case env.Method == "initialize": + res = `{"protocolVersion":"2025-06-18","capabilities":{},"serverInfo":{"name":"up","version":"0"}}` + case env.Method == "tools/list": + res = `{"tools":[{"name":"ask","inputSchema":{"type":"object"}}]}` + case env.Method == "tools/call": + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, `data: {"jsonrpc":"2.0","id":"s1","method":"sampling/createMessage","params":{"messages":[],"maxTokens":1}}`+"\n\n") + fmt.Fprintf(w, `data: {"jsonrpc":"2.0","id":%s,"result":{"content":[{"type":"text","text":"done"}]}}`+"\n\n", env.ID) + return + default: + res = `{}` + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%s,"result":%s}`, env.ID, res) + } +} + +// The gateway's own reply to a server request reaches the upstream with the +// credential of the session's latest request, through a passthrough +// TokenSource that reads only the context. +func TestServerRequestReplyCarriesSessionCaller(t *testing.T) { + t.Parallel() + replies := make(chan string, 4) + up := httptest.NewServer(samplingUpstream(replies)) + defer up.Close() + gw, err := gateway.New(gateway.Options{ + Backends: map[string]backend.Factory{ + "main": backend.NewFactory("main", config.Backend{Transport: "streamable-http", URL: up.URL}, outbound.NewPassthrough()), + }, + Pipeline: checks.Assemble(config.Policy{}, inspect.Hooks{}, audit.Discard, false), + Resolver: passthroughResolver, + RequestTimeout: 5 * time.Second, + }) + if err != nil { + t.Fatalf("gateway.New: %v", err) + } + defer gw.Close() + front := httptest.NewServer(gw.Handler()) + defer front.Close() + + c := &tclient{t: t, url: front.URL, header: http.Header{outbound.UpstreamAuthHeader: {"Bearer tok-1"}}} + c.initialize() + c.header.Set(outbound.UpstreamAuthHeader, "Bearer tok-2") + if m, _ := c.post(`{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ask","arguments":{}}}`); m["result"] == nil { + t.Fatalf("tools/call: %v", m) + } + + select { + case got := <-replies: + if got != "Bearer tok-2" { + t.Fatalf("reply to the sampling request carried %q, want the session's latest credential", got) + } + case <-time.After(3 * time.Second): + t.Fatal("the denied sampling request got no reply upstream") + } +} + +// ctxBE records the passthrough credential on the context of every reply the +// gateway sends toward the server. +type ctxBE struct { + *fakeBE + tokens chan string +} + +func (b *ctxBE) Send(ctx context.Context, msg []byte) error { + if env, err := jsonrpc.Parse(msg); err == nil && env.IsResponse() { + tok, _ := outbound.ClientTokenFrom(ctx) + b.tokens <- tok + } + return b.fakeBE.Send(ctx, msg) +} + +// A server request the full S2C queue drops is answered with the session's +// caller on the context too. +func TestDroppedServerRequestReplyCarriesSessionCaller(t *testing.T) { + t.Parallel() + be := &ctxBE{fakeBE: newFakeBE("main"), tokens: make(chan string, 16)} + gw, err := gateway.New(gateway.Options{ + Backends: map[string]backend.Factory{"main": func(context.Context) (backend.Backend, error) { return be, nil }}, + Pipeline: checks.Assemble(config.Policy{}, inspect.Hooks{}, audit.Discard, false), + Resolver: passthroughResolver, + }) + if err != nil { + t.Fatalf("gateway.New: %v", err) + } + defer gw.Close() + front := httptest.NewServer(gw.Handler()) + defer front.Close() + + c := &tclient{t: t, url: front.URL, header: http.Header{outbound.UpstreamAuthHeader: {"Bearer tok-1"}}} + c.initialize() + for i := 1; i <= 66; i++ { + be.recv <- []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":"s%d","method":"ping"}`, i)) + } + select { + case got := <-be.tokens: + if got != "tok-1" { + t.Fatalf("drop reply context carried %q, want tok-1", got) + } + case <-time.After(3 * time.Second): + t.Fatal("no drop reply") + } +} diff --git a/gateway/conn.go b/gateway/conn.go index 18da23c..4c1d567 100644 --- a/gateway/conn.go +++ b/gateway/conn.go @@ -66,7 +66,8 @@ type conn struct { mu sync.Mutex last time.Time - initRes []byte // cached initialize result (aggregated) + caller context.Context // values of the latest request, see setCaller + initRes []byte // cached initialize result (aggregated) done chan struct{} shutOnce sync.Once @@ -81,6 +82,26 @@ func (c *conn) touch() { c.mu.Unlock() } +// setCaller keeps the values of a request of the session owner, without its +// cancellation, for messages the gateway sends on its own. +func (c *conn) setCaller(ctx context.Context) { + ctx = context.WithoutCancel(ctx) + c.mu.Lock() + c.caller = ctx + c.mu.Unlock() +} + +// callerContext carries the values of the session's latest request, so a +// backend TokenSource resolves the same caller as for that request. +func (c *conn) callerContext() context.Context { + c.mu.Lock() + defer c.mu.Unlock() + if c.caller == nil { + return context.Background() + } + return c.caller +} + func (c *conn) lastSeen() time.Time { c.mu.Lock() defer c.mu.Unlock() @@ -225,7 +246,7 @@ func (c *conn) offerS2C(msg s2cMsg) []s2cMsg { // waiting, and audits the first drop of the session. The reply goes out off // the pump, with a deadline: the pump must never wait on a backend. func (c *conn) dropS2C(m s2cMsg) { - ctx := context.Background() + ctx := c.callerContext() if env, err := jsonrpc.Parse(m.raw); err == nil && env.IsRequest() { reply := jsonrpc.NewError(env.ID, jsonrpc.CodeInternalError, "client has no stream open for server requests") if rb, err := reply.Marshal(); err == nil { @@ -233,7 +254,7 @@ func (c *conn) dropS2C(m s2cMsg) { case m.bc.replies <- struct{}{}: go func() { defer func() { <-m.bc.replies }() - ctx, cancel := context.WithTimeout(context.Background(), dropReplyTimeout) + ctx, cancel := context.WithTimeout(ctx, dropReplyTimeout) defer cancel() _ = m.bc.b.Send(ctx, rb) }() @@ -254,7 +275,7 @@ func (c *conn) dropS2C(m s2cMsg) { // inspectS2C runs the pipeline on a server-initiated message. Returns the // (possibly mutated) serialized message and whether to forward it. func (c *conn) inspectS2C(bc *backendConn, env *jsonrpc.Message) ([]byte, bool) { - ctx := context.Background() + ctx := c.callerContext() m := &inspect.Msg{Dir: inspect.S2C, Backend: bc.name, Env: env} dec := c.runPipeline(ctx, m) switch dec.Verdict { diff --git a/gateway/gateway.go b/gateway/gateway.go index 1faa010..dd4228f 100644 --- a/gateway/gateway.go +++ b/gateway/gateway.go @@ -191,6 +191,7 @@ func (g *Gateway) startSession(ctx context.Context, identity inspect.Identity) ( done: make(chan struct{}), } c.touch() + c.setCaller(ctx) // Backends live as long as the session, not the initialize request. // ctx here is the POST's request context and cancels the moment the // handler writes the response, which would kill stdio children diff --git a/gateway/gateway_test.go b/gateway/gateway_test.go index 6e58437..9336ae8 100644 --- a/gateway/gateway_test.go +++ b/gateway/gateway_test.go @@ -62,6 +62,7 @@ type tclient struct { url string sid string version string // sent as MCP-Protocol-Version when set + header http.Header } func (c *tclient) request(body string) *http.Request { @@ -74,6 +75,9 @@ func (c *tclient) request(body string) *http.Request { if c.version != "" { req.Header.Set("MCP-Protocol-Version", c.version) } + for k, v := range c.header { + req.Header[k] = v + } return req } diff --git a/gateway/http.go b/gateway/http.go index b11f03c..4a901ea 100644 --- a/gateway/http.go +++ b/gateway/http.go @@ -140,6 +140,7 @@ func (g *Gateway) handlePost(w http.ResponseWriter, r *http.Request, identity in writeJSON(w, http.StatusBadRequest, msg) return } + c.setCaller(r.Context()) } c.touch() From a731dd909d269fedd6b56529c551329beb42c70f Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 17:51:42 -0300 Subject: [PATCH 03/15] fix(backend): refuse a per-caller token source on an sse backend (ENG-961) --- README.md | 9 +++++ backend/factory.go | 3 +- backend/sse.go | 17 +++++++-- backend/sse_test.go | 61 +++++++++++++++++++++++++++++++++ docs/architectural/auth.md | 3 ++ docs/architectural/embedding.md | 9 +++++ 6 files changed, 98 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0241ec1..6bd21a9 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,15 @@ embed the gateway and supply their own implementations of: the host already authenticated the caller) - `gateway.Observer`: telemetry +A reply the gateway sends on its own to a server request carries the +context values of the session's latest request, so a `TokenSource` +resolves the same caller as for that request. + +An `sse` backend takes one lane-wide credential: its event stream opens +once and outlives every request. Its `TokenSource` gets no caller values, +so a per-caller source (passthrough, per-user OAuth, token exchange) is +refused at start. + Import it the way any Go dependency is imported: ```sh diff --git a/backend/factory.go b/backend/factory.go index f6fc15b..edba8ad 100644 --- a/backend/factory.go +++ b/backend/factory.go @@ -24,7 +24,8 @@ const ( // ts, when non-nil, mints the outbound bearer token for each request to a // remote backend. Static, passthrough and OAuth outbound auth all plug in // here. Stdio backends ignore it and inherit credentials through their -// environment instead. +// environment instead. An sse backend calls it with no caller values: it +// takes one lane-wide credential. // // Configuration errors (unknown transport, missing command/url) surface from // the returned Factory rather than from NewFactory, so a misconfigured diff --git a/backend/sse.go b/backend/sse.go index 0b08570..13d185b 100644 --- a/backend/sse.go +++ b/backend/sse.go @@ -33,6 +33,11 @@ type SSEBackend struct { // TokenSource, when non-nil, mints the outbound bearer token for each // request (stream GET and message POSTs alike). Overrides any // Authorization in the static headers. + // + // The stream opens once and outlives every request, so an SSE backend + // takes one lane-wide credential: TokenSource gets no request values, + // and a source that needs the caller (passthrough, per-user OAuth, token + // exchange) fails Start. TokenSource func(ctx context.Context) (string, error) // Client overrides the per-instance HTTP client. Set before Start. @@ -341,14 +346,15 @@ func (b *SSEBackend) Send(ctx context.Context, msg []byte) error { return nil } -// authorize applies the TokenSource bearer, if any. +// authorize applies the TokenSource bearer, if any. The source sees ctx's +// deadline but none of its values, so it cannot pick a credential per caller. func (b *SSEBackend) authorize(ctx context.Context, req *http.Request) error { if b.TokenSource == nil { return nil } - tok, err := b.TokenSource(ctx) + tok, err := b.TokenSource(noValues{ctx}) if err != nil { - return fmt.Errorf("sse backend %s: token source: %w", b.name, err) + return fmt.Errorf("sse backend %s: token source called with no caller (an sse backend takes one lane-wide credential): %w", b.name, err) } if tok != "" { req.Header.Set("Authorization", "Bearer "+tok) @@ -356,6 +362,11 @@ func (b *SSEBackend) authorize(ctx context.Context, req *http.Request) error { return nil } +// noValues keeps a context's deadline and cancellation and hides its values. +type noValues struct{ context.Context } + +func (noValues) Value(any) any { return nil } + // deliver hands one message to the consumer; false once closing. func (b *SSEBackend) deliver(msg []byte) bool { out := make([]byte, len(msg)) diff --git a/backend/sse_test.go b/backend/sse_test.go index d1848b0..75f6029 100644 --- a/backend/sse_test.go +++ b/backend/sse_test.go @@ -13,9 +13,11 @@ import ( "net/http/httptest" "strings" "sync" + "sync/atomic" "testing" "time" + "github.com/hoophq/mcpproxy/auth/outbound" "github.com/hoophq/mcpproxy/config" ) @@ -208,6 +210,65 @@ func TestSSETokenSourceAppliedToStreamAndPosts(t *testing.T) { recvOne(t, b) } +// An SSE backend takes one lane-wide credential: a source that needs the +// caller is refused, even when Start's context carries one. +func TestSSERefusesPerCallerTokenSource(t *testing.T) { + t.Parallel() + f := newFakeSSE(t) + b := NewSSE("test", config.Backend{Transport: "sse", URL: f.srv.URL + "/sse"}, nil) + b.TokenSource = outbound.NewPassthrough() + err := b.Start(outbound.WithClientToken(context.Background(), "tok-alice")) + if err == nil { + _ = b.Close() + t.Fatal("Start accepted a per-caller token source") + } + if !strings.Contains(err.Error(), "one lane-wide credential") { + t.Fatalf("Start = %v, want a refusal naming the lane-wide credential", err) + } +} + +type callerKey struct{} + +// The source keeps the request deadline but never sees a caller value, on +// the stream or on a POST. +func TestSSETokenSourceSeesNoCallerValues(t *testing.T) { + t.Parallel() + f := newFakeSSE(t) + var sawValue, sawDeadline atomic.Bool + b := NewSSE("test", config.Backend{Transport: "sse", URL: f.srv.URL + "/sse"}, nil) + b.TokenSource = func(ctx context.Context) (string, error) { + if ctx.Value(callerKey{}) != nil { + sawValue.Store(true) + } + if _, ok := ctx.Deadline(); ok { + sawDeadline.Store(true) + } + return "lane", nil + } + caller := context.WithValue(context.Background(), callerKey{}, "alice") + if err := b.Start(caller); err != nil { + t.Fatalf("Start: %v", err) + } + t.Cleanup(func() { _ = b.Close() }) + ctx, cancel := context.WithTimeout(caller, 5*time.Second) + defer cancel() + if err := b.Send(ctx, []byte(`{"jsonrpc":"2.0","id":4,"method":"ping"}`)); err != nil { + t.Fatalf("Send: %v", err) + } + recvOne(t, b) + if sawValue.Load() { + t.Fatal("token source saw a caller value") + } + if !sawDeadline.Load() { + t.Fatal("token source lost the request deadline") + } + f.mu.Lock() + defer f.mu.Unlock() + if f.authHdr != "Bearer lane" { + t.Fatalf("stream GET bearer = %q, want the lane-wide one", f.authHdr) + } +} + func TestSSEServerStreamCloseTerminatesBackend(t *testing.T) { t.Parallel() f := newFakeSSE(t) diff --git a/docs/architectural/auth.md b/docs/architectural/auth.md index 2421392..5b03c06 100644 --- a/docs/architectural/auth.md +++ b/docs/architectural/auth.md @@ -43,6 +43,9 @@ tokens it issued itself. | `passthrough` | caller supplies the upstream credential per request via `X-Mcpproxy-Upstream-Authorization`; gateway stores nothing | | `oauth` | the full MCP authorization flow (below) | +An `sse` backend takes one lane-wide credential, so it refuses the +per-caller modes: `passthrough`, `oauth.per_user` and `oauth.token_exchange`. + ### The OAuth flow ``` diff --git a/docs/architectural/embedding.md b/docs/architectural/embedding.md index d7a615e..5392ef1 100644 --- a/docs/architectural/embedding.md +++ b/docs/architectural/embedding.md @@ -110,6 +110,15 @@ grant keys), `outbound.WithClientToken` (passthrough), and context before the gateway handles it. Do this in the resolver, which runs first and may rewrite the request context. +A reply the gateway sends on its own to a server request carries the +context values of the session's latest request, so a `TokenSource` +resolves the same caller as for that request. + +An `sse` backend takes one lane-wide credential: its event stream opens +once and outlives every request. Its `TokenSource` gets no caller values, +so a per-caller source (passthrough, per-user OAuth, token exchange) is +refused at start. + ## Custom checks A check is one interface: From d23902439294594ef1d4fe7365061574f61cb143 Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 18:31:52 -0300 Subject: [PATCH 04/15] fix(checks): keep the redact hook error out of the denial (ENG-965) --- checks/redact.go | 21 ++++++++++++--------- checks/redact_test.go | 36 +++++++++++++++++++++++------------- 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/checks/redact.go b/checks/redact.go index 42cb4ea..0474a2a 100644 --- a/checks/redact.go +++ b/checks/redact.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "strings" "github.com/hoophq/mcpproxy/audit" @@ -12,9 +13,9 @@ import ( "github.com/hoophq/mcpproxy/mcp" ) -// redactReason is what the client reads when a result is withheld. The hook -// error goes to the audit event only, because it can quote the text. -const redactReason = "result withheld: redaction failed" +// errRedactHook replaces a Redact hook error, which can quote the text: the +// hook's own error never reaches an event, a log line or the client. +var errRedactHook = errors.New("redaction failed") // Redactor masks sensitive strings in tools/call and resources/read results: // content[].text, content[].resource.text, contents[].text and every string @@ -69,7 +70,7 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms out, n, err = w.array(raw, w.item) } if err != nil { - return r.deny(ctx, s, m, err) + return r.deny(ctx, s, m) } if n > 0 { result[field] = out @@ -83,7 +84,7 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms out, err := json.Marshal(result) if err != nil { - return r.deny(ctx, s, m, err) + return r.deny(ctx, s, m) } m.Env.Result = out emit(ctx, r.sink, s, audit.Event{ @@ -93,12 +94,14 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms return inspect.AllowAll } -func (r *Redactor) deny(ctx context.Context, s inspect.Session, m *inspect.Msg, err error) inspect.Decision { +// deny withholds the result with a fixed reason. +func (r *Redactor) deny(ctx context.Context, s inspect.Session, m *inspect.Msg) inspect.Decision { + reason := "result withheld: " + errRedactHook.Error() emit(ctx, r.sink, s, audit.Event{ Type: audit.EventToolDenied, Backend: m.Backend, Tool: m.CorrelatedTool, - Rule: NameRedact, Reason: redactReason + ": " + err.Error(), + Rule: NameRedact, Reason: reason, }) - return inspect.Denyf(m.Env, jsonrpc.CodePolicyDenied, NameRedact, redactReason) + return inspect.Denyf(m.Env, jsonrpc.CodePolicyDenied, NameRedact, reason) } // walker runs the Redact hook over the strings of one result. Each method @@ -238,7 +241,7 @@ func (w *walker) str(raw json.RawMessage) (json.RawMessage, int, error) { } masked, n, err := w.redact(w.ctx, text) if err != nil { - return nil, 0, err + return nil, 0, errRedactHook } if n <= 0 { return raw, 0, nil diff --git a/checks/redact_test.go b/checks/redact_test.go index 8860676..f6fbd78 100644 --- a/checks/redact_test.go +++ b/checks/redact_test.go @@ -3,7 +3,7 @@ package checks import ( "context" "encoding/json" - "errors" + "fmt" "strings" "testing" @@ -130,10 +130,11 @@ func responseMsg(t *testing.T, method, tool string, result any) *inspect.Msg { } } -// maskOrFail masks like maskSecret and fails on any text holding "BOOM". +// maskOrFail masks like maskSecret and fails on any text holding "BOOM", with +// an error that quotes the text, as some engines do. func maskOrFail(ctx context.Context, text string) (string, int, error) { if strings.Contains(text, "BOOM") { - return "", 1, errors.New("redactor down") + return "", 1, fmt.Errorf("cannot mask %q", text) } return maskSecret(ctx, text) } @@ -242,22 +243,24 @@ func TestRedactCountsPerMessage(t *testing.T) { } // A Redact hook error on any field denies the whole result: the client gets -// an error, and the text, masked or not, never leaves. +// an error, and the text, masked or not, never leaves. The hook's error quotes +// the text, so it enters neither the reply nor the audit event. func TestRedactHookErrorDeniesResult(t *testing.T) { + const pii = "BOOM ana@example.com SSN 123-45-6789" cases := []struct { name, method string result map[string]any }{ - {"content text", mcp.MethodToolsCall, map[string]any{"content": []any{textItem("BOOM")}}}, + {"content text", mcp.MethodToolsCall, map[string]any{"content": []any{textItem(pii)}}}, {"nested resource text", mcp.MethodToolsCall, map[string]any{"content": []any{ - map[string]any{"type": "resource", "resource": map[string]any{"uri": "file:///x", "text": "BOOM"}}, + map[string]any{"type": "resource", "resource": map[string]any{"uri": "file:///x", "text": pii}}, }}}, {"resources/read contents text", mcp.MethodResourcesRead, map[string]any{"contents": []any{ - map[string]any{"uri": "file:///x", "text": "BOOM"}, + map[string]any{"uri": "file:///x", "text": pii}, }}}, {"structuredContent after a masked field", mcp.MethodToolsCall, map[string]any{ "content": []any{textItem("SECRET")}, - "structuredContent": map[string]any{"deep": []any{map[string]any{"v": "BOOM"}}}, + "structuredContent": map[string]any{"deep": []any{map[string]any{"v": pii}}}, }}, } for _, tc := range cases { @@ -272,15 +275,22 @@ func TestRedactHookErrorDeniesResult(t *testing.T) { if got.Reply == nil || got.Reply.Error == nil || got.Reply.Error.Code != jsonrpc.CodePolicyDenied { t.Fatalf("reply = %+v, want a policy-denied error", got.Reply) } - if strings.Contains(got.Reason, "BOOM") || strings.Contains(got.Reply.Error.Message, "BOOM") { - t.Errorf("the client message quotes the text: %q", got.Reply.Error.Message) - } if n := rec.count(audit.EventRedacted); n != 0 { t.Errorf("emitted %d redaction events for a withheld result, want 0", n) } ev, ok := rec.last(audit.EventToolDenied) - if !ok || ev.Rule != NameRedact || !strings.Contains(ev.Reason, "redactor down") { - t.Errorf("denial audit = %+v, want rule %q with the hook error", ev, NameRedact) + if !ok || ev.Rule != NameRedact { + t.Fatalf("denial audit = %+v, want rule %q", ev, NameRedact) + } + for _, leak := range []string{"BOOM", "ana@", "123-45", "cannot mask"} { + for where, s := range map[string]string{ + "reply": got.Reply.Error.Message, "reason": got.Reason, + "event": fmt.Sprintf("%+v", ev), + } { + if strings.Contains(s, leak) { + t.Errorf("%s holds %q: %s", where, leak, s) + } + } } }) } From 967437c2faee5e7d30a1eeb158b3c619dc098eae Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 18:34:25 -0300 Subject: [PATCH 05/15] fix(checks): mask structuredContent in one pass, deny past 128 levels or on cancel (ENG-965) --- checks/redact.go | 137 +++++++++++++++++++++++++++++------------- checks/redact_test.go | 111 +++++++++++++++++++++++----------- 2 files changed, 172 insertions(+), 76 deletions(-) diff --git a/checks/redact.go b/checks/redact.go index 0474a2a..8903d33 100644 --- a/checks/redact.go +++ b/checks/redact.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "strings" "github.com/hoophq/mcpproxy/audit" @@ -13,9 +14,18 @@ import ( "github.com/hoophq/mcpproxy/mcp" ) -// errRedactHook replaces a Redact hook error, which can quote the text: the -// hook's own error never reaches an event, a log line or the client. -var errRedactHook = errors.New("redaction failed") +// maxRedactDepth caps the nesting of structuredContent. A deeper value is +// denied, as on a hook error. +const maxRedactDepth = 128 + +// The reasons a result is withheld. A Redact hook error can quote the text, +// so errRedactHook replaces it: the hook's own error never reaches an event, +// a log line or the client. +var ( + errRedactHook = errors.New("redaction failed") + errRedactDepth = fmt.Errorf("structuredContent nests deeper than %d levels", maxRedactDepth) + errRedactCanceled = errors.New("redaction canceled") +) // Redactor masks sensitive strings in tools/call and resources/read results: // content[].text, content[].resource.text, contents[].text and every string @@ -65,12 +75,12 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms var n int var err error if field == "structuredContent" { - out, n, err = w.value(raw) + out, n, err = w.values(raw) } else { out, n, err = w.array(raw, w.item) } if err != nil { - return r.deny(ctx, s, m) + return r.deny(ctx, s, m, err) } if n > 0 { result[field] = out @@ -82,9 +92,9 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms return inspect.AllowAll } - out, err := json.Marshal(result) + out, err := encode(result) if err != nil { - return r.deny(ctx, s, m) + return r.deny(ctx, s, m, err) } m.Env.Result = out emit(ctx, r.sink, s, audit.Event{ @@ -94,9 +104,15 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms return inspect.AllowAll } -// deny withholds the result with a fixed reason. -func (r *Redactor) deny(ctx context.Context, s inspect.Session, m *inspect.Msg) inspect.Decision { - reason := "result withheld: " + errRedactHook.Error() +// deny withholds the result. The reason is one of the fixed errRedact* texts. +func (r *Redactor) deny(ctx context.Context, s inspect.Session, m *inspect.Msg, err error) inspect.Decision { + cause := errRedactHook + for _, known := range []error{errRedactDepth, errRedactCanceled} { + if errors.Is(err, known) { + cause = known + } + } + reason := "result withheld: " + cause.Error() emit(ctx, r.sink, s, audit.Event{ Type: audit.EventToolDenied, Backend: m.Backend, Tool: m.CorrelatedTool, Rule: NameRedact, Reason: reason, @@ -138,32 +154,61 @@ func (w *walker) item(raw json.RawMessage) (json.RawMessage, int, error) { }) } -// value masks every string in a JSON value, at any depth. Object keys are -// structure. -func (w *walker) value(raw json.RawMessage) (json.RawMessage, int, error) { - trimmed := bytes.TrimSpace(raw) - if len(trimmed) == 0 { - return raw, 0, nil - } - switch trimmed[0] { - case '"': - return w.str(raw) - case '[': - return w.array(raw, w.value) - case '{': - return w.object(raw, func(fields map[string]json.RawMessage) (int, error) { - total := 0 - for k, v := range fields { - n, err := w.set(fields, k, v, w.value) +// values masks every string value of a JSON value in one pass over its bytes. +// Object keys, numbers and unmasked strings are copied byte for byte. +func (w *walker) values(raw json.RawMessage) (json.RawMessage, int, error) { + var out, stack []byte + key := false + last, total := 0, 0 + for i := 0; i < len(raw); i++ { + switch c := raw[i]; c { + case '{', '[': + if len(stack) == maxRedactDepth { + return nil, 0, errRedactDepth + } + stack = append(stack, c) + key = c == '{' + case '}', ']': + if len(stack) > 0 { + stack = stack[:len(stack)-1] + } + case ',': + key = len(stack) > 0 && stack[len(stack)-1] == '{' + case ':': + key = false + case '"': + end := stringEnd(raw, i) + if !key { + masked, n, err := w.str(raw[i:end]) if err != nil { - return 0, err + return nil, 0, err + } + if n > 0 { + out = append(append(out, raw[last:i]...), masked...) + last = end + total += n } - total += n } - return total, nil - }) + i = end - 1 + } + } + if total == 0 { + return raw, 0, nil + } + return append(out, raw[last:]...), total, nil +} + +// stringEnd returns the index just past the JSON string that opens at raw[i]. +func stringEnd(raw []byte, i int) int { + for j := i + 1; j < len(raw); j++ { + switch raw[j] { + case '\\': + j++ + case '"': + return j + 1 + } } - return raw, 0, nil + return len(raw) } // array applies fn to each element of a JSON array. @@ -186,7 +231,7 @@ func (w *walker) array(raw json.RawMessage, fn func(json.RawMessage) (json.RawMe if total == 0 { return raw, 0, nil } - out, err := json.Marshal(elems) + out, err := encode(elems) if err != nil { return nil, 0, err } @@ -207,7 +252,7 @@ func (w *walker) object(raw json.RawMessage, fn func(map[string]json.RawMessage) if n == 0 { return raw, 0, nil } - out, err := json.Marshal(fields) + out, err := encode(fields) if err != nil { return nil, 0, err } @@ -220,12 +265,7 @@ func (w *walker) leaf(fields map[string]json.RawMessage, key string) (int, error if !ok { return 0, nil } - return w.set(fields, key, v, w.str) -} - -// set stores fn(v) under key when fn masked something. -func (w *walker) set(fields map[string]json.RawMessage, key string, v json.RawMessage, fn func(json.RawMessage) (json.RawMessage, int, error)) (int, error) { - out, n, err := fn(v) + out, n, err := w.str(v) if err != nil || n == 0 { return 0, err } @@ -239,6 +279,9 @@ func (w *walker) str(raw json.RawMessage) (json.RawMessage, int, error) { if err := json.Unmarshal(raw, &text); err != nil || text == "" { return raw, 0, nil } + if w.ctx.Err() != nil { + return nil, 0, errRedactCanceled + } masked, n, err := w.redact(w.ctx, text) if err != nil { return nil, 0, errRedactHook @@ -246,9 +289,21 @@ func (w *walker) str(raw json.RawMessage) (json.RawMessage, int, error) { if n <= 0 { return raw, 0, nil } - out, err := json.Marshal(masked) + out, err := encode(masked) if err != nil { return nil, 0, err } return out, n, nil } + +// encode marshals v without HTML escaping, so keys and strings already on the +// wire keep their bytes. +func encode(v any) (json.RawMessage, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return nil, err + } + return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil +} diff --git a/checks/redact_test.go b/checks/redact_test.go index f6fbd78..37321a5 100644 --- a/checks/redact_test.go +++ b/checks/redact_test.go @@ -5,7 +5,9 @@ import ( "encoding/json" "fmt" "strings" + "sync/atomic" "testing" + "time" "github.com/hoophq/mcpproxy/audit" "github.com/hoophq/mcpproxy/inspect" @@ -142,46 +144,85 @@ func maskOrFail(ctx context.Context, text string) (string, int, error) { func TestRedactStructuredContentEveryString(t *testing.T) { s, rec, ctx := newSession(t), &recorder{}, context.Background() r := NewRedactor(inspect.Hooks{Redact: maskSecret}, rec) - msg := responseMsg(t, mcp.MethodToolsCall, "lookup", map[string]any{ - "content": []any{textItem("see structuredContent")}, - "structuredContent": json.RawMessage(`{"id":12345678901234567890,` + - `"user":{"name":"SECRET","age":42,"tags":["a SECRET","plain",true,null]},` + - `"SECRET":"keys are structure"}`), - }) + in := `{"id":12345678901234567890,"a",` + + `"user":{"name":"SECRET","age":42,"tags":["a SECRET","plain",true,null]},` + + `"SECRET":"keys are structure","SECRET":"dup SECRET"}` + want := `{"id":12345678901234567890,"a",` + + `"user":{"name":"[REDACTED]","age":42,"tags":["a [REDACTED]","plain",true,null]},` + + `"SECRET":"keys are structure","SECRET":"dup [REDACTED]"}` + msg := responseMsg(t, mcp.MethodToolsCall, "lookup", nil) + msg.Env.Result = json.RawMessage(`{"content":[{"type":"text","text":"see structuredContent"}],"structuredContent":` + in + `}`) if got := r.Inspect(ctx, s, msg); got.Verdict != inspect.Allow { t.Fatalf("verdict = %s, want Allow", verdictString(got.Verdict)) } var res map[string]json.RawMessage _ = json.Unmarshal(msg.Env.Result, &res) - sc := string(res["structuredContent"]) - var got struct { - ID json.Number `json:"id"` - User struct { - Name string `json:"name"` - Age int `json:"age"` - Tags []any `json:"tags"` - } `json:"user"` - Key string `json:"SECRET"` - } - dec := json.NewDecoder(strings.NewReader(sc)) - dec.UseNumber() - if err := dec.Decode(&got); err != nil { - t.Fatalf("structuredContent is no longer valid JSON: %v", err) - } - if got.User.Name != "[REDACTED]" || got.User.Tags[0] != "a [REDACTED]" { - t.Errorf("nested strings not masked: %+v", got.User) - } - if got.User.Tags[1] != "plain" || got.User.Tags[2] != true || got.User.Tags[3] != nil || got.User.Age != 42 { - t.Errorf("non-matching values changed: %+v", got.User) - } - if got.ID != "12345678901234567890" { - t.Errorf("id = %s, want the number byte for byte", got.ID) - } - if got.Key != "keys are structure" { - t.Errorf("object key or its clean value changed: %q", got.Key) - } - if ev, _ := rec.last(audit.EventRedacted); ev.Fields["redactions"] != 2 { - t.Errorf("redactions = %v, want 2", ev.Fields["redactions"]) + if got := string(res["structuredContent"]); got != want { + t.Errorf("structuredContent =\n%s\nwant only the string values masked, keys and numbers byte for byte:\n%s", got, want) + } + if ev, _ := rec.last(audit.EventRedacted); ev.Fields["redactions"] != 3 { + t.Errorf("redactions = %v, want 3", ev.Fields["redactions"]) + } +} + +// Nesting past the cap is denied before any hook call, and fast. A result at +// the cap is still masked. +func TestRedactStructuredContentDepthCap(t *testing.T) { + nested := func(depth int) string { + return strings.Repeat("[", depth) + `"ana SECRET"` + strings.Repeat("]", depth) + } + var calls atomic.Int64 + count := func(ctx context.Context, text string) (string, int, error) { + calls.Add(1) + return maskSecret(ctx, text) + } + + s, rec, ctx := newSession(t), &recorder{}, context.Background() + r := NewRedactor(inspect.Hooks{Redact: count}, rec) + msg := responseMsg(t, mcp.MethodToolsCall, "deep", map[string]any{"structuredContent": json.RawMessage(nested(maxRedactDepth))}) + if got := r.Inspect(ctx, s, msg); got.Verdict != inspect.Allow { + t.Fatalf("depth %d: verdict = %s, want Allow", maxRedactDepth, verdictString(got.Verdict)) + } + if !strings.Contains(string(msg.Env.Result), `"ana [REDACTED]"`) { + t.Fatalf("depth %d: leaf not masked: %.200s", maxRedactDepth, msg.Env.Result) + } + + for _, depth := range []int{maxRedactDepth + 1, 9000} { + calls.Store(0) + msg := responseMsg(t, mcp.MethodToolsCall, "deep", map[string]any{"structuredContent": json.RawMessage(nested(depth))}) + start := time.Now() + got := r.Inspect(ctx, s, msg) + took := time.Since(start) + if got.Verdict != inspect.Deny || !strings.Contains(got.Reason, "nests deeper") { + t.Fatalf("depth %d: verdict = %s (%q), want Deny for nesting", depth, verdictString(got.Verdict), got.Reason) + } + if calls.Load() != 0 { + t.Errorf("depth %d: hook called %d times before the refusal", depth, calls.Load()) + } + if took > 100*time.Millisecond { + t.Errorf("depth %d: took %s", depth, took) + } + } +} + +// A canceled request stops the walk and withholds the result. +func TestRedactStopsOnCancel(t *testing.T) { + var calls atomic.Int64 + count := func(ctx context.Context, text string) (string, int, error) { + calls.Add(1) + return maskSecret(ctx, text) + } + s, rec := newSession(t), &recorder{} + r := NewRedactor(inspect.Hooks{Redact: count}, rec) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + msg := responseMsg(t, mcp.MethodToolsCall, "t", map[string]any{"structuredContent": map[string]any{"a": "SECRET"}}) + got := r.Inspect(ctx, s, msg) + if got.Verdict != inspect.Deny || !strings.Contains(got.Reason, "canceled") { + t.Fatalf("verdict = %s (%q), want Deny on cancel", verdictString(got.Verdict), got.Reason) + } + if calls.Load() != 0 { + t.Errorf("hook called %d times after cancel", calls.Load()) } } From f10d5698ecc2b2f39836a4d9ad6f848db237243d Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 18:35:21 -0300 Subject: [PATCH 06/15] fix(checks): mask tasks/result results (ENG-965) --- checks/redact.go | 16 ++++++++++------ checks/redact_test.go | 20 ++++++++++++++++++++ gateway/redact_test.go | 27 +++++++++++++++++++++++++++ mcp/mcp.go | 1 + 4 files changed, 58 insertions(+), 6 deletions(-) diff --git a/checks/redact.go b/checks/redact.go index 8903d33..1c081af 100644 --- a/checks/redact.go +++ b/checks/redact.go @@ -27,11 +27,13 @@ var ( errRedactCanceled = errors.New("redaction canceled") ) -// Redactor masks sensitive strings in tools/call and resources/read results: -// content[].text, content[].resource.text, contents[].text and every string -// of structuredContent. Other fields are structural, and rewriting them would -// break the protocol. A Redact hook error denies the result, so unmasked text -// never reaches the client. +// Redactor masks sensitive strings in tools/call, resources/read and +// tasks/result results: content[].text, content[].resource.text, +// contents[].text and every string value of structuredContent. Object keys +// and other fields are structural, and rewriting them would break the +// protocol. Only those exact keys are read: another spelling, or a duplicate +// of one of them, is not masked. A Redact hook error denies the result, so +// unmasked text never reaches the client. type Redactor struct { redact func(ctx context.Context, text string) (string, int, error) sink audit.Sink @@ -54,7 +56,9 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms if !m.Env.IsResponse() || m.Env.Error != nil || len(m.Env.Result) == 0 { return inspect.AllowAll } - if m.CorrelatedMethod != mcp.MethodToolsCall && m.CorrelatedMethod != mcp.MethodResourcesRead { + switch m.CorrelatedMethod { + case mcp.MethodToolsCall, mcp.MethodResourcesRead, mcp.MethodTasksResult: + default: return inspect.AllowAll } diff --git a/checks/redact_test.go b/checks/redact_test.go index 37321a5..4ba3d3e 100644 --- a/checks/redact_test.go +++ b/checks/redact_test.go @@ -70,6 +70,26 @@ func TestRedactToolResultContent(t *testing.T) { } } +// tasks/result carries the result of a task-augmented request, a tool result +// included. +func TestRedactTasksResult(t *testing.T) { + s, rec, ctx := newSession(t), &recorder{}, context.Background() + r := NewRedactor(inspect.Hooks{Redact: maskSecret}, rec) + msg := responseMsg(t, mcp.MethodTasksResult, "", map[string]any{ + "content": []any{textItem("task output SECRET")}, + "structuredContent": map[string]any{"email": "SECRET@x.io"}, + }) + if got := r.Inspect(ctx, s, msg); got.Verdict != inspect.Allow { + t.Fatalf("verdict = %s, want Allow", verdictString(got.Verdict)) + } + if strings.Contains(string(msg.Env.Result), "SECRET") { + t.Errorf("tasks/result not masked: %s", msg.Env.Result) + } + if ev, _ := rec.last(audit.EventRedacted); ev.Fields["redactions"] != 2 { + t.Errorf("redactions = %v, want 2", ev.Fields["redactions"]) + } +} + func TestRedactResourcesRead(t *testing.T) { s, rec, ctx := newSession(t), &recorder{}, context.Background() r := NewRedactor(inspect.Hooks{Redact: maskSecret}, rec) diff --git a/gateway/redact_test.go b/gateway/redact_test.go index 1bc0a5f..8866d96 100644 --- a/gateway/redact_test.go +++ b/gateway/redact_test.go @@ -64,3 +64,30 @@ func TestRedactHookErrorWithholdsResult(t *testing.T) { t.Fatalf("next call on the session: %v, want a masked result", m) } } + +// The gateway correlates a tasks/result response, so the redactor masks it. +func TestRedactMasksTasksResult(t *testing.T) { + t.Parallel() + be := newFakeBE("main") + maskOK := func(_ context.Context, text string) (string, int, error) { + n := strings.Count(text, "ok") + return strings.ReplaceAll(text, "ok", "[MASKED]"), n, nil + } + gw, err := gateway.New(gateway.Options{ + Backends: map[string]backend.Factory{"main": func(context.Context) (backend.Backend, error) { return be, nil }}, + Pipeline: checks.Assemble(config.Policy{}, inspect.Hooks{Redact: maskOK}, audit.Discard, false), + }) + if err != nil { + t.Fatalf("gateway.New: %v", err) + } + defer gw.Close() + front := httptest.NewServer(gw.Handler()) + defer front.Close() + + c := &tclient{t: t, url: front.URL} + c.initialize() + m, _ := c.post(`{"jsonrpc":"2.0","id":5,"method":"tasks/result","params":{"taskId":"t1"}}`) + if out := mustJSON(m["result"]); !strings.Contains(out, "[MASKED]") { + t.Fatalf("tasks/result = %v, want the fake result text masked", m) + } +} diff --git a/mcp/mcp.go b/mcp/mcp.go index 48baa31..c30e5f5 100644 --- a/mcp/mcp.go +++ b/mcp/mcp.go @@ -13,6 +13,7 @@ const ( MethodToolsListChanged = "notifications/tools/list_changed" MethodResourcesList = "resources/list" MethodResourcesRead = "resources/read" + MethodTasksResult = "tasks/result" MethodPromptsList = "prompts/list" MethodPromptsGet = "prompts/get" MethodSamplingCreateMessage = "sampling/createMessage" From 49c77d8259907d1e9a448473f3e66f7fd932a34f Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 18:35:40 -0300 Subject: [PATCH 07/15] docs: state which result strings the redactor masks and what it costs (ENG-965) --- README.md | 12 ++++++++++++ docs/architectural/embedding.md | 3 ++- docs/architectural/inspection-pipeline.md | 2 +- inspect/hooks.go | 6 +++++- 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6bd21a9..4b961ff 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,18 @@ embed the gateway and supply their own implementations of: the host already authenticated the caller) - `gateway.Observer`: telemetry +`inspect.Hooks.Redact` masks string values, never object keys, in +`tools/call`, `resources/read` and `tasks/result` results: `content[].text`, +`content[].resource.text`, `contents[].text` and every string of +`structuredContent`. Only those exact keys are read; another spelling or a +duplicate key is not masked. + +The hook runs once per string: a `structuredContent` table of 1,000 rows by +10 columns costs 10,000 calls. + +A hook error withholds the result: the client gets `-32010`, and the hook's +error is never recorded. + A reply the gateway sends on its own to a server request carries the context values of the session's latest request, so a `TokenSource` resolves the same caller as for that request. diff --git a/docs/architectural/embedding.md b/docs/architectural/embedding.md index 5392ef1..ddbcfbd 100644 --- a/docs/architectural/embedding.md +++ b/docs/architectural/embedding.md @@ -38,7 +38,8 @@ hooks := inspect.Hooks{ GuardInput: func(ctx context.Context, dir inspect.Direction, text string) error { … }, // Mask sensitive content in result text leaves. Returns redacted - // text + count (count>0 emits mcp.redacted). Error => result denied. + // text + count (count>0 emits mcp.redacted). Called once per string + // value; keys are not masked. Error => result denied. Redact: func(ctx context.Context, text string) (string, int, error) { … }, // Classify a tool call pre-flight; block=true denies THIS request diff --git a/docs/architectural/inspection-pipeline.md b/docs/architectural/inspection-pipeline.md index 738cd34..0559dc7 100644 --- a/docs/architectural/inspection-pipeline.md +++ b/docs/architectural/inspection-pipeline.md @@ -46,7 +46,7 @@ The order is load-bearing: | `rug-pull` | invalidates on `notifications/tools/list_changed` | fingerprints every tool (name + description + input schema, SHA-256); a change on a known tool → Kill (default) or audit alert | | `overrides` | rewrites aliased `tools/call` names back to real names | renames tools / replaces descriptions in the catalog | | `guardrails` | `Hooks.GuardInput` over `tools/call` arguments → Deny | over tool descriptions → Kill (poisoned catalog) | -| `redact` | (no C2S role) | `Hooks.Redact` over `content[].text`, `content[].resource.text`, `contents[].text` and every string of `structuredContent` in `tools/call` and `resources/read` results; a hook error denies the result | +| `redact` | (no C2S role) | `Hooks.Redact` over `content[].text`, `content[].resource.text`, `contents[].text` and every string value of `structuredContent` in `tools/call`, `resources/read` and `tasks/result` results, once per string; object keys are not masked; a hook error, or `structuredContent` deeper than 128 levels, denies the result | | `audit-tap` | `mcp.tool_call` (args as SHA-256 digest, never verbatim) | `mcp.tools_listed` | ## Session state (`session.State`) diff --git a/inspect/hooks.go b/inspect/hooks.go index 06920ce..1f0a9db 100644 --- a/inspect/hooks.go +++ b/inspect/hooks.go @@ -13,7 +13,11 @@ type Hooks struct { // toward a backend. A non-nil error blocks the message. GuardInput func(ctx context.Context, dir Direction, text string) error // Redact masks sensitive content in result text leaves, returning the - // redacted text and the number of redactions applied. + // redacted text and the number of redactions applied. It runs once per + // string value of content[].text, content[].resource.text, + // contents[].text and structuredContent in tools/call, resources/read + // and tasks/result results. Object keys are not masked, and only those + // exact keys are read. An error withholds the result. Redact func(ctx context.Context, text string) (string, int, error) // Analyze classifies a tool call before it reaches the backend. // block=true rejects this single request. From 313b63396c9725e8d5f9d08890dcd827caec6e33 Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 18:36:19 -0300 Subject: [PATCH 08/15] Revert "fix(backend): refuse a per-caller token source on an sse backend (ENG-961)" This reverts commit a731dd909d269fedd6b56529c551329beb42c70f. --- README.md | 5 --- backend/factory.go | 3 +- backend/sse.go | 17 ++------- backend/sse_test.go | 61 --------------------------------- docs/architectural/auth.md | 3 -- docs/architectural/embedding.md | 9 ----- 6 files changed, 4 insertions(+), 94 deletions(-) diff --git a/README.md b/README.md index 4b961ff..737de21 100644 --- a/README.md +++ b/README.md @@ -175,11 +175,6 @@ A reply the gateway sends on its own to a server request carries the context values of the session's latest request, so a `TokenSource` resolves the same caller as for that request. -An `sse` backend takes one lane-wide credential: its event stream opens -once and outlives every request. Its `TokenSource` gets no caller values, -so a per-caller source (passthrough, per-user OAuth, token exchange) is -refused at start. - Import it the way any Go dependency is imported: ```sh diff --git a/backend/factory.go b/backend/factory.go index edba8ad..f6fc15b 100644 --- a/backend/factory.go +++ b/backend/factory.go @@ -24,8 +24,7 @@ const ( // ts, when non-nil, mints the outbound bearer token for each request to a // remote backend. Static, passthrough and OAuth outbound auth all plug in // here. Stdio backends ignore it and inherit credentials through their -// environment instead. An sse backend calls it with no caller values: it -// takes one lane-wide credential. +// environment instead. // // Configuration errors (unknown transport, missing command/url) surface from // the returned Factory rather than from NewFactory, so a misconfigured diff --git a/backend/sse.go b/backend/sse.go index 13d185b..0b08570 100644 --- a/backend/sse.go +++ b/backend/sse.go @@ -33,11 +33,6 @@ type SSEBackend struct { // TokenSource, when non-nil, mints the outbound bearer token for each // request (stream GET and message POSTs alike). Overrides any // Authorization in the static headers. - // - // The stream opens once and outlives every request, so an SSE backend - // takes one lane-wide credential: TokenSource gets no request values, - // and a source that needs the caller (passthrough, per-user OAuth, token - // exchange) fails Start. TokenSource func(ctx context.Context) (string, error) // Client overrides the per-instance HTTP client. Set before Start. @@ -346,15 +341,14 @@ func (b *SSEBackend) Send(ctx context.Context, msg []byte) error { return nil } -// authorize applies the TokenSource bearer, if any. The source sees ctx's -// deadline but none of its values, so it cannot pick a credential per caller. +// authorize applies the TokenSource bearer, if any. func (b *SSEBackend) authorize(ctx context.Context, req *http.Request) error { if b.TokenSource == nil { return nil } - tok, err := b.TokenSource(noValues{ctx}) + tok, err := b.TokenSource(ctx) if err != nil { - return fmt.Errorf("sse backend %s: token source called with no caller (an sse backend takes one lane-wide credential): %w", b.name, err) + return fmt.Errorf("sse backend %s: token source: %w", b.name, err) } if tok != "" { req.Header.Set("Authorization", "Bearer "+tok) @@ -362,11 +356,6 @@ func (b *SSEBackend) authorize(ctx context.Context, req *http.Request) error { return nil } -// noValues keeps a context's deadline and cancellation and hides its values. -type noValues struct{ context.Context } - -func (noValues) Value(any) any { return nil } - // deliver hands one message to the consumer; false once closing. func (b *SSEBackend) deliver(msg []byte) bool { out := make([]byte, len(msg)) diff --git a/backend/sse_test.go b/backend/sse_test.go index 75f6029..d1848b0 100644 --- a/backend/sse_test.go +++ b/backend/sse_test.go @@ -13,11 +13,9 @@ import ( "net/http/httptest" "strings" "sync" - "sync/atomic" "testing" "time" - "github.com/hoophq/mcpproxy/auth/outbound" "github.com/hoophq/mcpproxy/config" ) @@ -210,65 +208,6 @@ func TestSSETokenSourceAppliedToStreamAndPosts(t *testing.T) { recvOne(t, b) } -// An SSE backend takes one lane-wide credential: a source that needs the -// caller is refused, even when Start's context carries one. -func TestSSERefusesPerCallerTokenSource(t *testing.T) { - t.Parallel() - f := newFakeSSE(t) - b := NewSSE("test", config.Backend{Transport: "sse", URL: f.srv.URL + "/sse"}, nil) - b.TokenSource = outbound.NewPassthrough() - err := b.Start(outbound.WithClientToken(context.Background(), "tok-alice")) - if err == nil { - _ = b.Close() - t.Fatal("Start accepted a per-caller token source") - } - if !strings.Contains(err.Error(), "one lane-wide credential") { - t.Fatalf("Start = %v, want a refusal naming the lane-wide credential", err) - } -} - -type callerKey struct{} - -// The source keeps the request deadline but never sees a caller value, on -// the stream or on a POST. -func TestSSETokenSourceSeesNoCallerValues(t *testing.T) { - t.Parallel() - f := newFakeSSE(t) - var sawValue, sawDeadline atomic.Bool - b := NewSSE("test", config.Backend{Transport: "sse", URL: f.srv.URL + "/sse"}, nil) - b.TokenSource = func(ctx context.Context) (string, error) { - if ctx.Value(callerKey{}) != nil { - sawValue.Store(true) - } - if _, ok := ctx.Deadline(); ok { - sawDeadline.Store(true) - } - return "lane", nil - } - caller := context.WithValue(context.Background(), callerKey{}, "alice") - if err := b.Start(caller); err != nil { - t.Fatalf("Start: %v", err) - } - t.Cleanup(func() { _ = b.Close() }) - ctx, cancel := context.WithTimeout(caller, 5*time.Second) - defer cancel() - if err := b.Send(ctx, []byte(`{"jsonrpc":"2.0","id":4,"method":"ping"}`)); err != nil { - t.Fatalf("Send: %v", err) - } - recvOne(t, b) - if sawValue.Load() { - t.Fatal("token source saw a caller value") - } - if !sawDeadline.Load() { - t.Fatal("token source lost the request deadline") - } - f.mu.Lock() - defer f.mu.Unlock() - if f.authHdr != "Bearer lane" { - t.Fatalf("stream GET bearer = %q, want the lane-wide one", f.authHdr) - } -} - func TestSSEServerStreamCloseTerminatesBackend(t *testing.T) { t.Parallel() f := newFakeSSE(t) diff --git a/docs/architectural/auth.md b/docs/architectural/auth.md index 5b03c06..2421392 100644 --- a/docs/architectural/auth.md +++ b/docs/architectural/auth.md @@ -43,9 +43,6 @@ tokens it issued itself. | `passthrough` | caller supplies the upstream credential per request via `X-Mcpproxy-Upstream-Authorization`; gateway stores nothing | | `oauth` | the full MCP authorization flow (below) | -An `sse` backend takes one lane-wide credential, so it refuses the -per-caller modes: `passthrough`, `oauth.per_user` and `oauth.token_exchange`. - ### The OAuth flow ``` diff --git a/docs/architectural/embedding.md b/docs/architectural/embedding.md index ddbcfbd..91929a2 100644 --- a/docs/architectural/embedding.md +++ b/docs/architectural/embedding.md @@ -111,15 +111,6 @@ grant keys), `outbound.WithClientToken` (passthrough), and context before the gateway handles it. Do this in the resolver, which runs first and may rewrite the request context. -A reply the gateway sends on its own to a server request carries the -context values of the session's latest request, so a `TokenSource` -resolves the same caller as for that request. - -An `sse` backend takes one lane-wide credential: its event stream opens -once and outlives every request. Its `TokenSource` gets no caller values, -so a per-caller source (passthrough, per-user OAuth, token exchange) is -refused at start. - ## Custom checks A check is one interface: From d5d7e0ddbb627c97e16d9c309cf5bb1ab256beb3 Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 18:37:15 -0300 Subject: [PATCH 09/15] test(gateway): an sse stream keeps the session opener's credential (ENG-961) --- README.md | 5 ++ backend/sse.go | 4 +- docs/architectural/auth.md | 4 ++ docs/architectural/embedding.md | 9 +++ gateway/sse_caller_test.go | 119 ++++++++++++++++++++++++++++++++ 5 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 gateway/sse_caller_test.go diff --git a/README.md b/README.md index 737de21..0e1a9d5 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,11 @@ A reply the gateway sends on its own to a server request carries the context values of the session's latest request, so a `TokenSource` resolves the same caller as for that request. +An `sse` backend opens its event stream once, at session start, with the +credential of the caller that opened the session. A token the caller +rotates later is not used on that stream; each message POST carries the +credential of its own request. + Import it the way any Go dependency is imported: ```sh diff --git a/backend/sse.go b/backend/sse.go index 0b08570..cc52a44 100644 --- a/backend/sse.go +++ b/backend/sse.go @@ -32,7 +32,9 @@ import ( type SSEBackend struct { // TokenSource, when non-nil, mints the outbound bearer token for each // request (stream GET and message POSTs alike). Overrides any - // Authorization in the static headers. + // Authorization in the static headers. The stream GET calls it once, + // with Start's context: in the gateway, the request that opened the + // session. Each POST calls it with the context of its Send. TokenSource func(ctx context.Context) (string, error) // Client overrides the per-instance HTTP client. Set before Start. diff --git a/docs/architectural/auth.md b/docs/architectural/auth.md index 2421392..85ff93e 100644 --- a/docs/architectural/auth.md +++ b/docs/architectural/auth.md @@ -43,6 +43,10 @@ tokens it issued itself. | `passthrough` | caller supplies the upstream credential per request via `X-Mcpproxy-Upstream-Authorization`; gateway stores nothing | | `oauth` | the full MCP authorization flow (below) | +On an `sse` backend the event stream opens once per session, with the +credential of the caller that opened it. A token the caller rotates later +reaches the message POSTs, not that stream. + ### The OAuth flow ``` diff --git a/docs/architectural/embedding.md b/docs/architectural/embedding.md index 91929a2..ce17936 100644 --- a/docs/architectural/embedding.md +++ b/docs/architectural/embedding.md @@ -111,6 +111,15 @@ grant keys), `outbound.WithClientToken` (passthrough), and context before the gateway handles it. Do this in the resolver, which runs first and may rewrite the request context. +A reply the gateway sends on its own to a server request carries the +context values of the session's latest request, so a `TokenSource` +resolves the same caller as for that request. + +An `sse` backend opens its event stream once, at session start, with the +credential of the caller that opened the session. A token the caller +rotates later is not used on that stream; each message POST carries the +credential of its own request. + ## Custom checks A check is one interface: diff --git a/gateway/sse_caller_test.go b/gateway/sse_caller_test.go new file mode 100644 index 0000000..3ac611a --- /dev/null +++ b/gateway/sse_caller_test.go @@ -0,0 +1,119 @@ +package gateway_test + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/hoophq/mcpproxy/audit" + "github.com/hoophq/mcpproxy/auth/outbound" + "github.com/hoophq/mcpproxy/backend" + "github.com/hoophq/mcpproxy/checks" + "github.com/hoophq/mcpproxy/config" + "github.com/hoophq/mcpproxy/gateway" + "github.com/hoophq/mcpproxy/inspect" + "github.com/hoophq/mcpproxy/jsonrpc" +) + +// sseUpstream speaks the legacy HTTP+SSE transport for one session and +// records the Authorization of the stream and of every message POST. +type sseUpstream struct { + mu sync.Mutex + stream []string + posts []string + frames chan string +} + +func (u *sseUpstream) auth() (stream, posts []string) { + u.mu.Lock() + defer u.mu.Unlock() + return append([]string(nil), u.stream...), append([]string(nil), u.posts...) +} + +func (u *sseUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + u.mu.Lock() + if r.Method == http.MethodGet { + u.stream = append(u.stream, r.Header.Get("Authorization")) + } else { + u.posts = append(u.posts, r.Header.Get("Authorization")) + } + u.mu.Unlock() + + if r.Method == http.MethodGet { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "event: endpoint\ndata: /messages\n\n") + w.(http.Flusher).Flush() + for { + select { + case f := <-u.frames: + fmt.Fprint(w, f) + w.(http.Flusher).Flush() + case <-r.Context().Done(): + return + } + } + } + body, _ := io.ReadAll(r.Body) + env, err := jsonrpc.Parse(body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + w.WriteHeader(http.StatusAccepted) + if !env.IsRequest() { + return + } + res := `{}` + switch env.Method { + case "initialize": + res = `{"protocolVersion":"2025-06-18","capabilities":{},"serverInfo":{"name":"up","version":"0"}}` + case "tools/list": + res = `{"tools":[{"name":"ask","inputSchema":{"type":"object"}}]}` + case "tools/call": + res = `{"content":[{"type":"text","text":"done"}]}` + } + u.frames <- fmt.Sprintf("event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":%s}\n\n", env.ID, res) +} + +// An SSE backend opens its stream with the credential of the caller that +// opened the session and keeps it; each message POST carries the credential +// of its own request, a rotated one included. +func TestSSEStreamUsesSessionOpenerCredential(t *testing.T) { + t.Parallel() + u := &sseUpstream{frames: make(chan string, 16)} + up := httptest.NewServer(u) + defer up.Close() + gw, err := gateway.New(gateway.Options{ + Backends: map[string]backend.Factory{ + "main": backend.NewFactory("main", config.Backend{Transport: "sse", URL: up.URL + "/sse"}, outbound.NewPassthrough()), + }, + Pipeline: checks.Assemble(config.Policy{}, inspect.Hooks{}, audit.Discard, false), + Resolver: passthroughResolver, + RequestTimeout: 5 * time.Second, + }) + if err != nil { + t.Fatalf("gateway.New: %v", err) + } + defer gw.Close() + front := httptest.NewServer(gw.Handler()) + defer front.Close() + + c := &tclient{t: t, url: front.URL, header: http.Header{outbound.UpstreamAuthHeader: {"Bearer tok-opener"}}} + c.initialize() + c.header.Set(outbound.UpstreamAuthHeader, "Bearer tok-rotated") + if m, _ := c.post(`{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ask","arguments":{}}}`); m["result"] == nil { + t.Fatalf("tools/call: %v", m) + } + + stream, posts := u.auth() + if len(stream) != 1 || stream[0] != "Bearer tok-opener" { + t.Errorf("stream opened with %q, want once with the session opener's credential", stream) + } + if len(posts) == 0 || posts[0] != "Bearer tok-opener" || posts[len(posts)-1] != "Bearer tok-rotated" { + t.Errorf("message POSTs carried %q, want each request's own credential", posts) + } +} From dbdf63ab3f1dc001d46f45356e389965b53713d4 Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Thu, 5 Nov 2026 18:54:25 -0300 Subject: [PATCH 10/15] docs: name which duplicate keys the redactor does not mask (ENG-965) --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0e1a9d5..ea7507c 100644 --- a/README.md +++ b/README.md @@ -162,8 +162,9 @@ embed the gateway and supply their own implementations of: `inspect.Hooks.Redact` masks string values, never object keys, in `tools/call`, `resources/read` and `tasks/result` results: `content[].text`, `content[].resource.text`, `contents[].text` and every string of -`structuredContent`. Only those exact keys are read; another spelling or a -duplicate key is not masked. +`structuredContent`. Only those exact keys are read: another spelling, or an +earlier duplicate of `content`, `contents`, `structuredContent`, `text` or +`resource`, is not masked. Duplicate keys inside `structuredContent` are. The hook runs once per string: a `structuredContent` table of 1,000 rows by 10 columns costs 10,000 calls. From 94811bb8b663f15949d9a0b05bf9944ff5e16cc8 Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Fri, 6 Nov 2026 11:20:23 -0300 Subject: [PATCH 11/15] fix(checks): withhold a result with an ambiguous key or a hook canceled mid-call (ENG-965) --- README.md | 16 ++++-- checks/redact.go | 30 +++++++--- checks/redact_test.go | 70 +++++++++++++++++++++++ docs/architectural/embedding.md | 3 +- docs/architectural/inspection-pipeline.md | 2 +- inspect/hooks.go | 5 +- mcp/toolcall.go | 43 ++++++++------ 7 files changed, 132 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index ea7507c..7b6ef37 100644 --- a/README.md +++ b/README.md @@ -162,12 +162,16 @@ embed the gateway and supply their own implementations of: `inspect.Hooks.Redact` masks string values, never object keys, in `tools/call`, `resources/read` and `tasks/result` results: `content[].text`, `content[].resource.text`, `contents[].text` and every string of -`structuredContent`. Only those exact keys are read: another spelling, or an -earlier duplicate of `content`, `contents`, `structuredContent`, `text` or -`resource`, is not masked. Duplicate keys inside `structuredContent` are. - -The hook runs once per string: a `structuredContent` table of 1,000 rows by -10 columns costs 10,000 calls. +`structuredContent`. A client that matches keys without case could read a +value the hook never saw, so a result is withheld when the response, the +result, a content entry or its resource repeats a key or spells `result`, +`content`, `contents`, `structuredContent`, `text` or `resource` another way. +Duplicate keys inside `structuredContent` are masked. + +The hook runs once per string, in turn: a `structuredContent` table of 1,000 +rows by 10 columns costs 10,000 calls. They share the request's +`RequestTimeout` with the backend call, and a result still unmasked when it +expires is withheld. A hook error withholds the result: the client gets `-32010`, and the hook's error is never recorded. diff --git a/checks/redact.go b/checks/redact.go index 1c081af..180bb9b 100644 --- a/checks/redact.go +++ b/checks/redact.go @@ -25,15 +25,17 @@ var ( errRedactHook = errors.New("redaction failed") errRedactDepth = fmt.Errorf("structuredContent nests deeper than %d levels", maxRedactDepth) errRedactCanceled = errors.New("redaction canceled") + errRedactKeys = errors.New("a result key repeats or differs in case") ) // Redactor masks sensitive strings in tools/call, resources/read and // tasks/result results: content[].text, content[].resource.text, // contents[].text and every string value of structuredContent. Object keys // and other fields are structural, and rewriting them would break the -// protocol. Only those exact keys are read: another spelling, or a duplicate -// of one of them, is not masked. A Redact hook error denies the result, so -// unmasked text never reaches the client. +// protocol. A client that matches keys without case could read a value the +// redactor did not, so a repeated key, or one that only folds to a key read +// here, denies the result. So does a Redact hook error: unmasked text never +// reaches the client. type Redactor struct { redact func(ctx context.Context, text string) (string, int, error) sink audit.Sink @@ -62,10 +64,16 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms return inspect.AllowAll } + if _, ok := m.Env.FoldedField(); ok { + return r.deny(ctx, s, m, errRedactKeys) + } var result map[string]json.RawMessage if err := json.Unmarshal(m.Env.Result, &result); err != nil { return inspect.AllowAll } + if mcp.ExactKeys(m.Env.Result, result, "content", "contents", "structuredContent") != nil { + return r.deny(ctx, s, m, errRedactKeys) + } w := &walker{ctx: ctx, redact: r.redact} total := 0 @@ -111,7 +119,7 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms // deny withholds the result. The reason is one of the fixed errRedact* texts. func (r *Redactor) deny(ctx context.Context, s inspect.Session, m *inspect.Msg, err error) inspect.Decision { cause := errRedactHook - for _, known := range []error{errRedactDepth, errRedactCanceled} { + for _, known := range []error{errRedactDepth, errRedactCanceled, errRedactKeys} { if errors.Is(err, known) { cause = known } @@ -136,7 +144,7 @@ type walker struct { // item masks the text leaf of one content entry and the text of its nested // resource. func (w *walker) item(raw json.RawMessage) (json.RawMessage, int, error) { - return w.object(raw, func(fields map[string]json.RawMessage) (int, error) { + return w.object(raw, []string{"text", "resource"}, func(fields map[string]json.RawMessage) (int, error) { n, err := w.leaf(fields, "text") if err != nil { return 0, err @@ -145,7 +153,7 @@ func (w *walker) item(raw json.RawMessage) (json.RawMessage, int, error) { if !ok { return n, nil } - out, rn, err := w.object(res, func(rf map[string]json.RawMessage) (int, error) { + out, rn, err := w.object(res, []string{"text"}, func(rf map[string]json.RawMessage) (int, error) { return w.leaf(rf, "text") }) if err != nil { @@ -243,12 +251,15 @@ func (w *walker) array(raw json.RawMessage, fn func(json.RawMessage) (json.RawMe } // object decodes a JSON object, lets fn rewrite its fields, and encodes it -// again when fn masked something. -func (w *walker) object(raw json.RawMessage, fn func(map[string]json.RawMessage) (int, error)) (json.RawMessage, int, error) { +// again when fn masked something. keys are the fields fn reads. +func (w *walker) object(raw json.RawMessage, keys []string, fn func(map[string]json.RawMessage) (int, error)) (json.RawMessage, int, error) { var fields map[string]json.RawMessage if err := json.Unmarshal(raw, &fields); err != nil || fields == nil { return raw, 0, nil } + if mcp.ExactKeys(raw, fields, keys...) != nil { + return nil, 0, errRedactKeys + } n, err := fn(fields) if err != nil { return nil, 0, err @@ -290,6 +301,9 @@ func (w *walker) str(raw json.RawMessage) (json.RawMessage, int, error) { if err != nil { return nil, 0, errRedactHook } + if w.ctx.Err() != nil { + return nil, 0, errRedactCanceled + } if n <= 0 { return raw, 0, nil } diff --git a/checks/redact_test.go b/checks/redact_test.go index 4ba3d3e..1605a24 100644 --- a/checks/redact_test.go +++ b/checks/redact_test.go @@ -368,3 +368,73 @@ func TestRedactSkipsErrorResponses(t *testing.T) { t.Fatalf("verdict = %s, want Allow", verdictString(got.Verdict)) } } + +func TestRedactDeniesAResultKeyThatRepeatsOrDiffersInCase(t *testing.T) { + r := NewRedactor(inspect.Hooks{Redact: maskSecret}, &recorder{}) + deny := func(t *testing.T, env *jsonrpc.Message) { + t.Helper() + msg := &inspect.Msg{Dir: inspect.S2C, CorrelatedMethod: mcp.MethodToolsCall, CorrelatedTool: "t", Env: env} + got := r.Inspect(context.Background(), newSession(t), msg) + if got.Verdict != inspect.Deny || !strings.Contains(got.Reason, errRedactKeys.Error()) { + t.Errorf("verdict = %s (%q), want Deny", verdictString(got.Verdict), got.Reason) + } + if strings.Contains(got.Reason, "SECRET") { + t.Errorf("reason quotes the result: %q", got.Reason) + } + } + for _, result := range []string{ + `{"Content":[{"type":"text","text":"SECRET"}]}`, + `{"content":[{"type":"text","text":"ok"}],"CONTENT":[{"type":"text","text":"SECRET"}]}`, + `{"content":[{"type":"text","text":"SECRET"}],"content":[]}`, + `{"contentſ":[{"type":"text","text":"SECRET"}]}`, + `{"ſtructuredContent":{"a":"SECRET"}}`, + `{"content":[{"type":"text","Text":"SECRET"}]}`, + `{"content":[{"type":"text","text":"SECRET","text":"ok"}]}`, + `{"content":[{"type":"text","text":"ok","text":"SECRET"}]}`, + `{"content":[{"type":"resource","resource":{"uri":"u","Text":"SECRET"}}]}`, + `{"content":[{"type":"resource","Resource":{"uri":"u","text":"SECRET"}}]}`, + `{"contents":[{"uri":"u","TEXT":"SECRET"}]}`, + } { + t.Run(result, func(t *testing.T) { + deny(t, &jsonrpc.Message{JSONRPC: "2.0", ID: rawID("9"), Result: json.RawMessage(result)}) + }) + } + t.Run("envelope", func(t *testing.T) { + env, err := jsonrpc.Parse([]byte(`{"jsonrpc":"2.0","id":9,"result":{"content":[]},"Result":{"content":[{"type":"text","text":"SECRET"}]}}`)) + if err != nil { + t.Fatal(err) + } + deny(t, env) + }) +} + +func TestRedactKeepsAResultWithOtherKeys(t *testing.T) { + r := NewRedactor(inspect.Hooks{Redact: maskSecret}, &recorder{}) + msg := responseMsg(t, mcp.MethodToolsCall, "t", map[string]any{ + "content": []any{map[string]any{"type": "text", "text": "SECRET", "_meta": map[string]any{}}}, + "structuredContent": map[string]any{"Text": "SECRET", "text": "ok"}, + "isError": false, + "_meta": map[string]any{"k": 1}, + }) + if got := r.Inspect(context.Background(), newSession(t), msg); got.Verdict != inspect.Allow { + t.Fatalf("verdict = %s (%q), want Allow", verdictString(got.Verdict), got.Reason) + } + if strings.Contains(string(msg.Env.Result), "SECRET") { + t.Fatalf("result not masked: %s", msg.Env.Result) + } +} + +func TestRedactDeniesWhenCanceledDuringTheLastHookCall(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + hook := func(_ context.Context, text string) (string, int, error) { + cancel() + return text, 0, nil + } + r := NewRedactor(inspect.Hooks{Redact: hook}, &recorder{}) + msg := responseMsg(t, mcp.MethodToolsCall, "t", map[string]any{"content": []any{textItem("SECRET")}}) + got := r.Inspect(ctx, newSession(t), msg) + if got.Verdict != inspect.Deny || !strings.Contains(got.Reason, errRedactCanceled.Error()) { + t.Fatalf("verdict = %s (%q), want Deny on cancel", verdictString(got.Verdict), got.Reason) + } +} diff --git a/docs/architectural/embedding.md b/docs/architectural/embedding.md index ce17936..6dc7aa3 100644 --- a/docs/architectural/embedding.md +++ b/docs/architectural/embedding.md @@ -39,7 +39,8 @@ hooks := inspect.Hooks{ // Mask sensitive content in result text leaves. Returns redacted // text + count (count>0 emits mcp.redacted). Called once per string - // value; keys are not masked. Error => result denied. + // value, within RequestTimeout; keys are not masked. Error, timeout + // or an ambiguous key => result denied. Redact: func(ctx context.Context, text string) (string, int, error) { … }, // Classify a tool call pre-flight; block=true denies THIS request diff --git a/docs/architectural/inspection-pipeline.md b/docs/architectural/inspection-pipeline.md index 0559dc7..a9dd68b 100644 --- a/docs/architectural/inspection-pipeline.md +++ b/docs/architectural/inspection-pipeline.md @@ -46,7 +46,7 @@ The order is load-bearing: | `rug-pull` | invalidates on `notifications/tools/list_changed` | fingerprints every tool (name + description + input schema, SHA-256); a change on a known tool → Kill (default) or audit alert | | `overrides` | rewrites aliased `tools/call` names back to real names | renames tools / replaces descriptions in the catalog | | `guardrails` | `Hooks.GuardInput` over `tools/call` arguments → Deny | over tool descriptions → Kill (poisoned catalog) | -| `redact` | (no C2S role) | `Hooks.Redact` over `content[].text`, `content[].resource.text`, `contents[].text` and every string value of `structuredContent` in `tools/call`, `resources/read` and `tasks/result` results, once per string; object keys are not masked; a hook error, or `structuredContent` deeper than 128 levels, denies the result | +| `redact` | (no C2S role) | `Hooks.Redact` over `content[].text`, `content[].resource.text`, `contents[].text` and every string value of `structuredContent` in `tools/call`, `resources/read` and `tasks/result` results, once per string; object keys are not masked; a hook error, a canceled request, a key read here that repeats or differs in case, or `structuredContent` deeper than 128 levels, denies the result | | `audit-tap` | `mcp.tool_call` (args as SHA-256 digest, never verbatim) | `mcp.tools_listed` | ## Session state (`session.State`) diff --git a/inspect/hooks.go b/inspect/hooks.go index 1f0a9db..3f73887 100644 --- a/inspect/hooks.go +++ b/inspect/hooks.go @@ -16,8 +16,9 @@ type Hooks struct { // redacted text and the number of redactions applied. It runs once per // string value of content[].text, content[].resource.text, // contents[].text and structuredContent in tools/call, resources/read - // and tasks/result results. Object keys are not masked, and only those - // exact keys are read. An error withholds the result. + // and tasks/result results. Object keys are not masked. A key that + // repeats or only folds to one of those withholds the result, and so do + // an error and a canceled ctx, which also ends at RequestTimeout. Redact func(ctx context.Context, text string) (string, int, error) // Analyze classifies a tool call before it reaches the backend. // block=true rejects this single request. diff --git a/mcp/toolcall.go b/mcp/toolcall.go index 6cccad3..8bf0805 100644 --- a/mcp/toolcall.go +++ b/mcp/toolcall.go @@ -8,11 +8,6 @@ import ( "unicode" ) -var ( - foldedName = foldKey("name") - foldedArguments = foldKey("arguments") -) - // ParseToolCall reads a tools/call's name and arguments by their exact keys, // as an MCP server does. Go's JSON decoder matches keys without case, so it // refuses params with two keys equal under strings.EqualFold, or a key that @@ -23,29 +18,39 @@ func ParseToolCall(params json.RawMessage) (ToolsCallParams, error) { if err := json.Unmarshal(params, &fields); err != nil || fields == nil { return ToolsCallParams{}, errors.New("params are not an object") } - if members(params) != len(fields) { - return ToolsCallParams{}, errors.New("params repeat a key") + if err := ExactKeys(params, fields, "name", "arguments"); err != nil { + return ToolsCallParams{}, fmt.Errorf("params: %w", err) + } + var p ToolsCallParams + if err := json.Unmarshal(fields["name"], &p.Name); err != nil || p.Name == "" { + return ToolsCallParams{}, errors.New("a tool name is required") + } + p.Arguments = fields["arguments"] + return p, nil +} + +// ExactKeys refuses obj, a JSON object decoded into fields, when a reader that +// matches keys without case, as Go's JSON decoder does, could read another +// value than fields[k] for one of keys: obj repeats a key, holds two keys +// equal under strings.EqualFold, or a key that only folds to one of keys. +func ExactKeys(obj json.RawMessage, fields map[string]json.RawMessage, keys ...string) error { + if members(obj) != len(fields) { + return errors.New("a key repeats") } seen := make(map[string]string, len(fields)) for key := range fields { f := foldKey(key) if prev, dup := seen[f]; dup { - return ToolsCallParams{}, fmt.Errorf("keys %q and %q are equal without case", prev, key) + return fmt.Errorf("keys %q and %q are equal without case", prev, key) } seen[f] = key - switch { - case f == foldedName && key != "name": - return ToolsCallParams{}, fmt.Errorf("key %q is not %q", key, "name") - case f == foldedArguments && key != "arguments": - return ToolsCallParams{}, fmt.Errorf("key %q is not %q", key, "arguments") - } } - var p ToolsCallParams - if err := json.Unmarshal(fields["name"], &p.Name); err != nil || p.Name == "" { - return ToolsCallParams{}, errors.New("a tool name is required") + for _, want := range keys { + if key, ok := seen[foldKey(want)]; ok && key != want { + return fmt.Errorf("key %q is not %q", key, want) + } } - p.Arguments = fields["arguments"] - return p, nil + return nil } // members counts the members of obj, a valid JSON object. From 861b327c6c8d79dabc04cb7376a8ea96b48e79ad Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Fri, 6 Nov 2026 14:35:06 -0300 Subject: [PATCH 12/15] fix(gateway): observe a message refused before the pipeline as a deny (ENG-984) --- gateway/conn.go | 13 +++++++ gateway/http.go | 3 ++ gateway/observe_test.go | 80 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 gateway/observe_test.go diff --git a/gateway/conn.go b/gateway/conn.go index 4c1d567..0a2f022 100644 --- a/gateway/conn.go +++ b/gateway/conn.go @@ -327,6 +327,19 @@ func (c *conn) runPipeline(ctx context.Context, m *inspect.Msg) inspect.Decision return dec } +// observeRefused reports a client message refused before the pipeline ran. +func (g *Gateway) observeRefused(env *jsonrpc.Message) { + obs := g.opts.Observer + if obs == nil { + return + } + tool := "" + if env.Method == mcp.MethodToolsCall { + tool = inspect.RawTool(env.Params) + } + obs.ObserveMessage(inspect.C2S, "", env.Method, tool, verdictName(inspect.Deny), 0) +} + func verdictName(v inspect.Verdict) string { switch v { case inspect.Allow: diff --git a/gateway/http.go b/gateway/http.go index 4a901ea..cab3417 100644 --- a/gateway/http.go +++ b/gateway/http.go @@ -100,6 +100,7 @@ func (g *Gateway) handlePost(w http.ResponseWriter, r *http.Request, identity in return } if k, ok := env.FoldedField(); ok { + g.observeRefused(env) writeJSON(w, http.StatusOK, jsonrpc.NewError(env.ID, jsonrpc.CodeInvalidRequest, fmt.Sprintf("field %q equals a JSON-RPC field without case", k))) return @@ -186,12 +187,14 @@ func (c *conn) handleC2S(ctx context.Context, env *jsonrpc.Message) (*jsonrpc.Me Time: time.Now(), Type: audit.EventToolDenied, Session: c.state.ID(), User: c.state.Identity().Subject, Rule: "invalid_params", Reason: reason, }) + c.g.observeRefused(env) return jsonrpc.NewError(env.ID, jsonrpc.CodeInvalidParams, reason), nil } full := call.Name var bare string bc, bare, err = c.routeTool(full) if err != nil { + c.g.observeRefused(env) return jsonrpc.NewError(env.ID, jsonrpc.CodeMethodNotFound, err.Error()), nil } toolName = bare diff --git a/gateway/observe_test.go b/gateway/observe_test.go new file mode 100644 index 0000000..3b2ddb1 --- /dev/null +++ b/gateway/observe_test.go @@ -0,0 +1,80 @@ +package gateway_test + +import ( + "fmt" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/hoophq/mcpproxy/audit" + "github.com/hoophq/mcpproxy/backend" + "github.com/hoophq/mcpproxy/checks" + "github.com/hoophq/mcpproxy/config" + "github.com/hoophq/mcpproxy/gateway" + "github.com/hoophq/mcpproxy/inspect" + "github.com/hoophq/mcpproxy/internal/testmcp" +) + +type observed struct { + mu sync.Mutex + msgs []string +} + +func (o *observed) ObserveMessage(dir inspect.Direction, _, method, tool, decision string, _ time.Duration) { + o.mu.Lock() + defer o.mu.Unlock() + o.msgs = append(o.msgs, fmt.Sprintf("%v|%s|%s|%s", dir, method, tool, decision)) +} + +func (o *observed) count(msg string) int { + o.mu.Lock() + defer o.mu.Unlock() + n := 0 + for _, m := range o.msgs { + if m == msg { + n++ + } + } + return n +} + +// A message refused before the pipeline still reaches the observer as a +// deny, so a host that counts denials from it misses none. +func TestAMessageRefusedBeforeThePipelineIsObserved(t *testing.T) { + up := httptest.NewServer(testmcp.New().HTTPHandler()) + t.Cleanup(up.Close) + obs := &observed{} + gw, err := gateway.New(gateway.Options{ + Backends: map[string]backend.Factory{ + "main": backend.NewFactory("main", config.Backend{Transport: "streamable-http", URL: up.URL}, nil), + }, + Pipeline: checks.Assemble(config.Policy{}, inspect.Hooks{}, audit.Discard, false), + Observer: obs, + }) + if err != nil { + t.Fatal(err) + } + front := httptest.NewServer(gw.Handler()) + t.Cleanup(func() { front.Close(); gw.Close() }) + c := &tclient{t: t, url: front.URL} + c.initialize() + + for i, tc := range []struct{ msg, code string }{ + {`"method":"tools/call","params":{"name":"slow","arguments":{},"Arguments":{}}`, "-32602"}, + {`"method":"tools/call","params":{"name":"echo"},"Method":"ping"`, "-32600"}, + } { + m, code := c.post(fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,%s}`, 10+i, tc.msg)) + if code != http.StatusOK || fmt.Sprint(errorCode(m)) != tc.code { + t.Errorf("%s: %d %v, want %s", tc.msg, code, m, tc.code) + } + } + c2s := fmt.Sprint(inspect.C2S) + if n := obs.count(c2s + "|tools/call|slow|deny"); n != 1 { + t.Errorf("invalid params observed %d times, want 1: %v", n, obs.msgs) + } + if n := obs.count(c2s + "|tools/call|echo|deny"); n != 1 { + t.Errorf("folded field observed %d times, want 1: %v", n, obs.msgs) + } +} From 826f2e66df5efe95387edb5156fb48ffc39cbdff Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Fri, 6 Nov 2026 14:43:12 -0300 Subject: [PATCH 13/15] fix(gateway): name no tool for a message refused before the pipeline (ENG-984) --- gateway/conn.go | 11 +++-------- gateway/observe_test.go | 8 ++------ 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/gateway/conn.go b/gateway/conn.go index 0a2f022..3287427 100644 --- a/gateway/conn.go +++ b/gateway/conn.go @@ -328,16 +328,11 @@ func (c *conn) runPipeline(ctx context.Context, m *inspect.Msg) inspect.Decision } // observeRefused reports a client message refused before the pipeline ran. +// Its params are not trusted, so it names no tool. func (g *Gateway) observeRefused(env *jsonrpc.Message) { - obs := g.opts.Observer - if obs == nil { - return - } - tool := "" - if env.Method == mcp.MethodToolsCall { - tool = inspect.RawTool(env.Params) + if obs := g.opts.Observer; obs != nil { + obs.ObserveMessage(inspect.C2S, "", env.Method, "", verdictName(inspect.Deny), 0) } - obs.ObserveMessage(inspect.C2S, "", env.Method, tool, verdictName(inspect.Deny), 0) } func verdictName(v inspect.Verdict) string { diff --git a/gateway/observe_test.go b/gateway/observe_test.go index 3b2ddb1..d3cba7f 100644 --- a/gateway/observe_test.go +++ b/gateway/observe_test.go @@ -70,11 +70,7 @@ func TestAMessageRefusedBeforeThePipelineIsObserved(t *testing.T) { t.Errorf("%s: %d %v, want %s", tc.msg, code, m, tc.code) } } - c2s := fmt.Sprint(inspect.C2S) - if n := obs.count(c2s + "|tools/call|slow|deny"); n != 1 { - t.Errorf("invalid params observed %d times, want 1: %v", n, obs.msgs) - } - if n := obs.count(c2s + "|tools/call|echo|deny"); n != 1 { - t.Errorf("folded field observed %d times, want 1: %v", n, obs.msgs) + if n := obs.count(fmt.Sprint(inspect.C2S) + "|tools/call||deny"); n != 2 { + t.Errorf("observed %d refusals with no tool, want 2: %v", n, obs.msgs) } } From 7d089fd0460c8dc2e7d6f0be1a6af9dc035f4f56 Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Fri, 6 Nov 2026 15:04:26 -0300 Subject: [PATCH 14/15] fix(checks): withhold a result or a read field of an unexpected type (ENG-965) --- README.md | 4 ++- checks/redact.go | 25 ++++++++----- checks/redact_test.go | 44 +++++++++++++++++++++++ docs/architectural/inspection-pipeline.md | 2 +- 4 files changed, 64 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 7b6ef37..aed2827 100644 --- a/README.md +++ b/README.md @@ -166,7 +166,9 @@ embed the gateway and supply their own implementations of: value the hook never saw, so a result is withheld when the response, the result, a content entry or its resource repeats a key or spells `result`, `content`, `contents`, `structuredContent`, `text` or `resource` another way. -Duplicate keys inside `structuredContent` are masked. +A result that is not an object, or one of those fields of an unexpected type +(a `content` that is not an array, a `text` that is not a string), is withheld +too. Duplicate keys inside `structuredContent` are masked. The hook runs once per string, in turn: a `structuredContent` table of 1,000 rows by 10 columns costs 10,000 calls. They share the request's diff --git a/checks/redact.go b/checks/redact.go index 180bb9b..5571214 100644 --- a/checks/redact.go +++ b/checks/redact.go @@ -26,6 +26,7 @@ var ( errRedactDepth = fmt.Errorf("structuredContent nests deeper than %d levels", maxRedactDepth) errRedactCanceled = errors.New("redaction canceled") errRedactKeys = errors.New("a result key repeats or differs in case") + errRedactShape = errors.New("a result field has an unexpected type") ) // Redactor masks sensitive strings in tools/call, resources/read and @@ -34,8 +35,8 @@ var ( // and other fields are structural, and rewriting them would break the // protocol. A client that matches keys without case could read a value the // redactor did not, so a repeated key, or one that only folds to a key read -// here, denies the result. So does a Redact hook error: unmasked text never -// reaches the client. +// here, denies the result. So do a field read here of an unexpected type and +// a Redact hook error: unmasked text never reaches the client. type Redactor struct { redact func(ctx context.Context, text string) (string, int, error) sink audit.Sink @@ -69,7 +70,7 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms } var result map[string]json.RawMessage if err := json.Unmarshal(m.Env.Result, &result); err != nil { - return inspect.AllowAll + return r.deny(ctx, s, m, errRedactShape) } if mcp.ExactKeys(m.Env.Result, result, "content", "contents", "structuredContent") != nil { return r.deny(ctx, s, m, errRedactKeys) @@ -119,7 +120,7 @@ func (r *Redactor) Inspect(ctx context.Context, s inspect.Session, m *inspect.Ms // deny withholds the result. The reason is one of the fixed errRedact* texts. func (r *Redactor) deny(ctx context.Context, s inspect.Session, m *inspect.Msg, err error) inspect.Decision { cause := errRedactHook - for _, known := range []error{errRedactDepth, errRedactCanceled, errRedactKeys} { + for _, known := range []error{errRedactDepth, errRedactCanceled, errRedactKeys, errRedactShape} { if errors.Is(err, known) { cause = known } @@ -134,8 +135,8 @@ func (r *Redactor) deny(ctx context.Context, s inspect.Session, m *inspect.Msg, // walker runs the Redact hook over the strings of one result. Each method // returns the new bytes and the redaction count; count 0 means the input is -// unchanged. A value of an unexpected shape carries no text leaf and is left -// as it is. +// unchanged. A null value is left as it is; a value of another unexpected type +// fails with errRedactShape. type walker struct { ctx context.Context redact func(ctx context.Context, text string) (string, int, error) @@ -227,7 +228,7 @@ func stringEnd(raw []byte, i int) int { func (w *walker) array(raw json.RawMessage, fn func(json.RawMessage) (json.RawMessage, int, error)) (json.RawMessage, int, error) { var elems []json.RawMessage if err := json.Unmarshal(raw, &elems); err != nil { - return raw, 0, nil + return nil, 0, errRedactShape } total := 0 for i, v := range elems { @@ -254,7 +255,10 @@ func (w *walker) array(raw json.RawMessage, fn func(json.RawMessage) (json.RawMe // again when fn masked something. keys are the fields fn reads. func (w *walker) object(raw json.RawMessage, keys []string, fn func(map[string]json.RawMessage) (int, error)) (json.RawMessage, int, error) { var fields map[string]json.RawMessage - if err := json.Unmarshal(raw, &fields); err != nil || fields == nil { + if err := json.Unmarshal(raw, &fields); err != nil { + return nil, 0, errRedactShape + } + if fields == nil { return raw, 0, nil } if mcp.ExactKeys(raw, fields, keys...) != nil { @@ -291,7 +295,10 @@ func (w *walker) leaf(fields map[string]json.RawMessage, key string) (int, error // str runs the hook over one JSON string. func (w *walker) str(raw json.RawMessage) (json.RawMessage, int, error) { var text string - if err := json.Unmarshal(raw, &text); err != nil || text == "" { + if err := json.Unmarshal(raw, &text); err != nil { + return nil, 0, errRedactShape + } + if text == "" { return raw, 0, nil } if w.ctx.Err() != nil { diff --git a/checks/redact_test.go b/checks/redact_test.go index 1605a24..4372781 100644 --- a/checks/redact_test.go +++ b/checks/redact_test.go @@ -424,6 +424,50 @@ func TestRedactKeepsAResultWithOtherKeys(t *testing.T) { } } +func TestRedactDeniesAFieldOfAnUnexpectedType(t *testing.T) { + r := NewRedactor(inspect.Hooks{Redact: maskSecret}, &recorder{}) + inspectResult := func(t *testing.T, method, result string) inspect.Decision { + t.Helper() + msg := &inspect.Msg{Dir: inspect.S2C, CorrelatedMethod: method, CorrelatedTool: "t", + Env: &jsonrpc.Message{JSONRPC: "2.0", ID: rawID("9"), Result: json.RawMessage(result)}} + got := r.Inspect(context.Background(), newSession(t), msg) + if got.Verdict == inspect.Allow && strings.Contains(string(msg.Env.Result), "SECRET") { + t.Errorf("SECRET left in clear: %s", msg.Env.Result) + } + return got + } + for _, result := range []string{ + `[{"type":"text","text":"SECRET"}]`, + `"SECRET"`, + `{"content":{"type":"text","text":"SECRET"}}`, + `{"content":["SECRET"]}`, + `{"content":[{"type":"text","text":["SECRET"]}]}`, + `{"content":[{"type":"text","text":{"a":"SECRET"}}]}`, + `{"content":[{"type":"resource","resource":["SECRET"]}]}`, + `{"content":[{"type":"resource","resource":{"uri":"u","text":{"a":"SECRET"}}}]}`, + `{"contents":{"uri":"u","text":"SECRET"}}`, + } { + t.Run(result, func(t *testing.T) { + got := inspectResult(t, mcp.MethodToolsCall, result) + if got.Verdict != inspect.Deny || !strings.Contains(got.Reason, errRedactShape.Error()) { + t.Errorf("verdict = %s (%q), want Deny", verdictString(got.Verdict), got.Reason) + } + }) + } + for _, result := range []string{ + `null`, + `{"content":null,"contents":null,"structuredContent":null}`, + `{"content":[null,{"type":"text","text":null},{"type":"resource","resource":null}]}`, + `{"content":[{"type":"image","data":"aGk=","mimeType":"image/png"}]}`, + } { + t.Run(result, func(t *testing.T) { + if got := inspectResult(t, mcp.MethodToolsCall, result); got.Verdict != inspect.Allow { + t.Errorf("verdict = %s (%q), want Allow", verdictString(got.Verdict), got.Reason) + } + }) + } +} + func TestRedactDeniesWhenCanceledDuringTheLastHookCall(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/docs/architectural/inspection-pipeline.md b/docs/architectural/inspection-pipeline.md index a9dd68b..fb9be86 100644 --- a/docs/architectural/inspection-pipeline.md +++ b/docs/architectural/inspection-pipeline.md @@ -46,7 +46,7 @@ The order is load-bearing: | `rug-pull` | invalidates on `notifications/tools/list_changed` | fingerprints every tool (name + description + input schema, SHA-256); a change on a known tool → Kill (default) or audit alert | | `overrides` | rewrites aliased `tools/call` names back to real names | renames tools / replaces descriptions in the catalog | | `guardrails` | `Hooks.GuardInput` over `tools/call` arguments → Deny | over tool descriptions → Kill (poisoned catalog) | -| `redact` | (no C2S role) | `Hooks.Redact` over `content[].text`, `content[].resource.text`, `contents[].text` and every string value of `structuredContent` in `tools/call`, `resources/read` and `tasks/result` results, once per string; object keys are not masked; a hook error, a canceled request, a key read here that repeats or differs in case, or `structuredContent` deeper than 128 levels, denies the result | +| `redact` | (no C2S role) | `Hooks.Redact` over `content[].text`, `content[].resource.text`, `contents[].text` and every string value of `structuredContent` in `tools/call`, `resources/read` and `tasks/result` results, once per string; object keys are not masked; a hook error, a canceled request, a key read here that repeats or differs in case, a result or a field read here of an unexpected type, or `structuredContent` deeper than 128 levels, denies the result | | `audit-tap` | `mcp.tool_call` (args as SHA-256 digest, never verbatim) | `mcp.tools_listed` | ## Session state (`session.State`) From 8048505e962f9a663878f253d3dd4a50e103c13d Mon Sep 17 00:00:00 2001 From: Luan Lorenzo Date: Fri, 6 Nov 2026 17:48:02 -0300 Subject: [PATCH 15/15] docs: a null result field passes the redactor (ENG-965) --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index aed2827..e79fade 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,8 @@ result, a content entry or its resource repeats a key or spells `result`, `content`, `contents`, `structuredContent`, `text` or `resource` another way. A result that is not an object, or one of those fields of an unexpected type (a `content` that is not an array, a `text` that is not a string), is withheld -too. Duplicate keys inside `structuredContent` are masked. +too. A `null` in any of those places carries no text and passes. Duplicate +keys inside `structuredContent` are masked. The hook runs once per string, in turn: a `structuredContent` table of 1,000 rows by 10 columns costs 10,000 calls. They share the request's