|
| 1 | +package relay |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
| 9 | + "strings" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/majorcontext/keep" |
| 13 | + "github.com/majorcontext/keep/internal/audit" |
| 14 | + relayconfig "github.com/majorcontext/keep/internal/relay/config" |
| 15 | + "github.com/majorcontext/keep/internal/relay/mcp" |
| 16 | +) |
| 17 | + |
| 18 | +// mockUpstreamWithEcho starts a mock MCP server that echoes tool call args back |
| 19 | +// as JSON in the result content, enabling redaction verification. |
| 20 | +func mockUpstreamWithEcho(t *testing.T, tools []mcp.Tool) *httptest.Server { |
| 21 | + t.Helper() |
| 22 | + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 23 | + var req mcp.JSONRPCRequest |
| 24 | + json.NewDecoder(r.Body).Decode(&req) |
| 25 | + |
| 26 | + var resp mcp.JSONRPCResponse |
| 27 | + resp.JSONRPC = "2.0" |
| 28 | + resp.ID = req.ID |
| 29 | + |
| 30 | + switch req.Method { |
| 31 | + case "initialize": |
| 32 | + resp.Result = mcp.InitializeResult{ |
| 33 | + ProtocolVersion: "2025-03-26", |
| 34 | + Capabilities: mcp.ServerCapabilities{Tools: &mcp.ToolsCapability{}}, |
| 35 | + } |
| 36 | + case "tools/list": |
| 37 | + resp.Result = mcp.ListToolsResult{Tools: tools} |
| 38 | + case "tools/call": |
| 39 | + // Echo back the arguments so tests can verify mutations. |
| 40 | + paramsBytes, _ := json.Marshal(req.Params) |
| 41 | + var params mcp.ToolCallParams |
| 42 | + json.Unmarshal(paramsBytes, ¶ms) |
| 43 | + argsJSON, _ := json.Marshal(params.Arguments) |
| 44 | + resp.Result = mcp.ToolCallResult{ |
| 45 | + Content: []mcp.ContentBlock{{Type: "text", Text: string(argsJSON)}}, |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + json.NewEncoder(w).Encode(resp) |
| 50 | + })) |
| 51 | +} |
| 52 | + |
| 53 | +// mockUpstreamError starts a mock MCP server that always returns a JSON-RPC |
| 54 | +// error for tools/call requests. |
| 55 | +func mockUpstreamError(t *testing.T, tools []mcp.Tool) *httptest.Server { |
| 56 | + t.Helper() |
| 57 | + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 58 | + var req mcp.JSONRPCRequest |
| 59 | + json.NewDecoder(r.Body).Decode(&req) |
| 60 | + |
| 61 | + var resp mcp.JSONRPCResponse |
| 62 | + resp.JSONRPC = "2.0" |
| 63 | + resp.ID = req.ID |
| 64 | + |
| 65 | + switch req.Method { |
| 66 | + case "initialize": |
| 67 | + resp.Result = mcp.InitializeResult{ |
| 68 | + ProtocolVersion: "2025-03-26", |
| 69 | + Capabilities: mcp.ServerCapabilities{Tools: &mcp.ToolsCapability{}}, |
| 70 | + } |
| 71 | + case "tools/list": |
| 72 | + resp.Result = mcp.ListToolsResult{Tools: tools} |
| 73 | + case "tools/call": |
| 74 | + resp.Error = &mcp.JSONRPCError{Code: -32000, Message: "upstream internal error"} |
| 75 | + } |
| 76 | + |
| 77 | + json.NewEncoder(w).Encode(resp) |
| 78 | + })) |
| 79 | +} |
| 80 | + |
| 81 | +// setupTest builds a RelayHandler backed by a mock upstream and the test rules |
| 82 | +// in testdata/rules/. Returns the handler and a buffer that captures audit log |
| 83 | +// output. |
| 84 | +func setupTest(t *testing.T) (*RelayHandler, *bytes.Buffer) { |
| 85 | + t.Helper() |
| 86 | + |
| 87 | + tools := []mcp.Tool{ |
| 88 | + {Name: "allowed_tool", Description: "An allowed tool"}, |
| 89 | + {Name: "dangerous_tool", Description: "A dangerous tool"}, |
| 90 | + {Name: "read_file", Description: "Reads a file"}, |
| 91 | + } |
| 92 | + |
| 93 | + // 1. Start mock upstream with echo behaviour. |
| 94 | + srv := mockUpstreamWithEcho(t, tools) |
| 95 | + t.Cleanup(srv.Close) |
| 96 | + |
| 97 | + // 2. Load Keep engine from testdata/rules/. |
| 98 | + engine, err := keep.Load("testdata/rules") |
| 99 | + if err != nil { |
| 100 | + t.Fatalf("keep.Load: %v", err) |
| 101 | + } |
| 102 | + t.Cleanup(engine.Close) |
| 103 | + |
| 104 | + // 3. Build Router from the mock upstream. |
| 105 | + routes := []relayconfig.Route{ |
| 106 | + {Scope: "test-scope", Upstream: srv.URL}, |
| 107 | + } |
| 108 | + router, err := NewRouter(context.Background(), routes) |
| 109 | + if err != nil { |
| 110 | + t.Fatalf("NewRouter: %v", err) |
| 111 | + } |
| 112 | + |
| 113 | + // 4. Create audit logger writing to a buffer. |
| 114 | + var buf bytes.Buffer |
| 115 | + logger := audit.NewLogger(&buf) |
| 116 | + |
| 117 | + // 5. Create RelayHandler. |
| 118 | + handler := NewRelayHandler(engine, router, logger) |
| 119 | + |
| 120 | + return handler, &buf |
| 121 | +} |
| 122 | + |
| 123 | +// TestHandler_Allow verifies that a tool with no matching deny rules is |
| 124 | +// forwarded to the upstream and the result is returned to the caller. |
| 125 | +func TestHandler_Allow(t *testing.T) { |
| 126 | + handler, _ := setupTest(t) |
| 127 | + |
| 128 | + result, err := handler.HandleToolCall(context.Background(), "allowed_tool", map[string]any{"x": "1"}) |
| 129 | + if err != nil { |
| 130 | + t.Fatalf("HandleToolCall: unexpected error: %v", err) |
| 131 | + } |
| 132 | + if result == nil || len(result.Content) == 0 { |
| 133 | + t.Fatal("HandleToolCall: expected non-empty result") |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +// TestHandler_Deny verifies that a tool matched by a deny rule returns an |
| 138 | +// error containing the rule name and policy message. The upstream must never |
| 139 | +// be called. |
| 140 | +func TestHandler_Deny(t *testing.T) { |
| 141 | + handler, _ := setupTest(t) |
| 142 | + |
| 143 | + result, err := handler.HandleToolCall(context.Background(), "dangerous_tool", map[string]any{}) |
| 144 | + if err == nil { |
| 145 | + t.Fatal("HandleToolCall: expected error for denied tool, got nil") |
| 146 | + } |
| 147 | + if result != nil { |
| 148 | + t.Errorf("HandleToolCall: expected nil result on deny, got %+v", result) |
| 149 | + } |
| 150 | + |
| 151 | + errStr := err.Error() |
| 152 | + if !strings.Contains(errStr, "block-dangerous") { |
| 153 | + t.Errorf("error should contain rule name %q, got: %s", "block-dangerous", errStr) |
| 154 | + } |
| 155 | + if !strings.Contains(errStr, "This tool is blocked by policy.") { |
| 156 | + t.Errorf("error should contain policy message, got: %s", errStr) |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +// TestHandler_Redact verifies that args containing secrets are redacted before |
| 161 | +// being forwarded to the upstream. The mock upstream echoes the args it |
| 162 | +// received so we can inspect them. |
| 163 | +func TestHandler_Redact(t *testing.T) { |
| 164 | + handler, _ := setupTest(t) |
| 165 | + |
| 166 | + args := map[string]any{ |
| 167 | + "path": "/etc/config", |
| 168 | + "content": "value=SECRET_KEY other=SECRET_TOKEN", |
| 169 | + } |
| 170 | + |
| 171 | + result, err := handler.HandleToolCall(context.Background(), "read_file", args) |
| 172 | + if err != nil { |
| 173 | + t.Fatalf("HandleToolCall: unexpected error: %v", err) |
| 174 | + } |
| 175 | + if result == nil || len(result.Content) == 0 { |
| 176 | + t.Fatal("HandleToolCall: expected non-empty result") |
| 177 | + } |
| 178 | + |
| 179 | + // The upstream echoed the args it received. Parse them back. |
| 180 | + echoedText := result.Content[0].Text |
| 181 | + var echoedArgs map[string]any |
| 182 | + if err := json.Unmarshal([]byte(echoedText), &echoedArgs); err != nil { |
| 183 | + t.Fatalf("parse echoed args: %v", err) |
| 184 | + } |
| 185 | + |
| 186 | + content, ok := echoedArgs["content"].(string) |
| 187 | + if !ok { |
| 188 | + t.Fatalf("echoed args missing 'content' string field") |
| 189 | + } |
| 190 | + if strings.Contains(content, "SECRET_KEY") || strings.Contains(content, "SECRET_TOKEN") { |
| 191 | + t.Errorf("upstream received unredacted content: %s", content) |
| 192 | + } |
| 193 | + if !strings.Contains(content, "[REDACTED]") { |
| 194 | + t.Errorf("upstream content does not contain redaction marker: %s", content) |
| 195 | + } |
| 196 | +} |
| 197 | + |
| 198 | +// TestHandler_UnknownTool verifies that a call to a tool not in the router |
| 199 | +// returns an error. |
| 200 | +func TestHandler_UnknownTool(t *testing.T) { |
| 201 | + handler, _ := setupTest(t) |
| 202 | + |
| 203 | + result, err := handler.HandleToolCall(context.Background(), "nonexistent_tool", map[string]any{}) |
| 204 | + if err == nil { |
| 205 | + t.Fatal("HandleToolCall: expected error for unknown tool, got nil") |
| 206 | + } |
| 207 | + if result != nil { |
| 208 | + t.Errorf("HandleToolCall: expected nil result for unknown tool, got %+v", result) |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +// TestHandler_UpstreamError verifies that when the upstream returns an error |
| 213 | +// it is surfaced to the caller. |
| 214 | +func TestHandler_UpstreamError(t *testing.T) { |
| 215 | + tools := []mcp.Tool{ |
| 216 | + {Name: "allowed_tool", Description: "An allowed tool"}, |
| 217 | + } |
| 218 | + srv := mockUpstreamError(t, tools) |
| 219 | + t.Cleanup(srv.Close) |
| 220 | + |
| 221 | + engine, err := keep.Load("testdata/rules") |
| 222 | + if err != nil { |
| 223 | + t.Fatalf("keep.Load: %v", err) |
| 224 | + } |
| 225 | + t.Cleanup(engine.Close) |
| 226 | + |
| 227 | + routes := []relayconfig.Route{ |
| 228 | + {Scope: "test-scope", Upstream: srv.URL}, |
| 229 | + } |
| 230 | + router, err := NewRouter(context.Background(), routes) |
| 231 | + if err != nil { |
| 232 | + t.Fatalf("NewRouter: %v", err) |
| 233 | + } |
| 234 | + |
| 235 | + handler := NewRelayHandler(engine, router, nil) |
| 236 | + |
| 237 | + result, err := handler.HandleToolCall(context.Background(), "allowed_tool", map[string]any{}) |
| 238 | + if err == nil { |
| 239 | + t.Fatal("HandleToolCall: expected upstream error, got nil") |
| 240 | + } |
| 241 | + if result != nil { |
| 242 | + t.Errorf("HandleToolCall: expected nil result on upstream error, got %+v", result) |
| 243 | + } |
| 244 | + if !strings.Contains(err.Error(), "upstream internal error") { |
| 245 | + t.Errorf("error should mention upstream error message, got: %v", err) |
| 246 | + } |
| 247 | +} |
| 248 | + |
| 249 | +// TestHandler_AuditLogged verifies that after a tool call the audit logger |
| 250 | +// buffer contains at least one JSON line with the evaluation decision. |
| 251 | +func TestHandler_AuditLogged(t *testing.T) { |
| 252 | + handler, buf := setupTest(t) |
| 253 | + |
| 254 | + _, _ = handler.HandleToolCall(context.Background(), "allowed_tool", map[string]any{}) |
| 255 | + |
| 256 | + line := buf.String() |
| 257 | + if line == "" { |
| 258 | + t.Fatal("audit buffer is empty; expected a JSON audit entry") |
| 259 | + } |
| 260 | + |
| 261 | + // The line should be valid JSON and contain a "Decision" field. |
| 262 | + var entry map[string]any |
| 263 | + if err := json.Unmarshal([]byte(strings.TrimSpace(line)), &entry); err != nil { |
| 264 | + t.Fatalf("audit entry is not valid JSON: %v\nraw: %s", err, line) |
| 265 | + } |
| 266 | + if _, ok := entry["Decision"]; !ok { |
| 267 | + t.Errorf("audit entry missing 'Decision' field; got keys: %v", entry) |
| 268 | + } |
| 269 | +} |