mirror of
https://github.com/pomerium/pomerium.git
synced 2025-07-18 00:58:08 +02:00
mcp: add mcp method and tool logging to authorize (#5668)
## Summary Adds support for extending authorization log with Model Context Protocol details. i.e. ```json { "level": "info", "server-name": "all", "service": "authorize", "mcp-method": "tools/call", "mcp-tool": "describe_table", "mcp-tool-parameters": { "table_name": "Categories" }, "allow": true, "allow-why-true": ["email-ok", "mcp-tool-ok"], "deny": false, "deny-why-false": [], "time": "2025-06-24T17:40:41-04:00", "message": "authorize check" } ``` ## Related issues Fixes https://linear.app/pomerium/issue/ENG-2393/mcp-authorize-each-incoming-request-to-an-mcp-route ## User Explanation <!-- How would you explain this change to the user? If this change doesn't create any user-facing changes, you can leave this blank. If filled out, add the `docs` label --> ## Checklist - [x] reference any related issues - [x] updated unit tests - [x] add appropriate label (`enhancement`, `bug`, `breaking`, `dependencies`, `ci`) - [x] ready for review
This commit is contained in:
parent
eacf19cd64
commit
9363457849
14 changed files with 271 additions and 82 deletions
|
@ -4,7 +4,6 @@ package evaluator
|
|||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
@ -135,12 +134,6 @@ type RequestSession struct {
|
|||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
// RequestMCP is the MCP field in the request.
|
||||
type RequestMCP struct {
|
||||
Tool string `json:"tool,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
}
|
||||
|
||||
// Result is the result of evaluation.
|
||||
type Result struct {
|
||||
Allow RuleResult
|
||||
|
@ -477,36 +470,3 @@ func carryOverJWTAssertion(dst http.Header, src map[string]string) {
|
|||
dst.Add(jwtForKey, jwtFor)
|
||||
}
|
||||
}
|
||||
|
||||
// RequestMCPFromCheckRequest populates a RequestMCP from an Envoy CheckRequest proto for MCP routes.
|
||||
func RequestMCPFromCheckRequest(
|
||||
in *envoy_service_auth_v3.CheckRequest,
|
||||
) (RequestMCP, bool) {
|
||||
var mcpReq RequestMCP
|
||||
|
||||
body := in.GetAttributes().GetRequest().GetHttp().GetBody()
|
||||
if body == "" {
|
||||
return mcpReq, false
|
||||
}
|
||||
|
||||
var jsonRPCReq struct {
|
||||
Method string `json:"method"`
|
||||
Params map[string]any `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(body), &jsonRPCReq); err != nil {
|
||||
return mcpReq, false
|
||||
}
|
||||
|
||||
mcpReq.Method = jsonRPCReq.Method
|
||||
|
||||
if jsonRPCReq.Method == "tools/call" {
|
||||
if name, exists := jsonRPCReq.Params["name"]; exists {
|
||||
if toolName, ok := name.(string); ok {
|
||||
mcpReq.Tool = toolName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return mcpReq, true
|
||||
}
|
||||
|
|
|
@ -689,8 +689,10 @@ func TestEvaluator(t *testing.T) {
|
|||
URL: "https://from.example.com",
|
||||
},
|
||||
MCP: RequestMCP{
|
||||
Tool: "tool_name",
|
||||
Method: "tools/call",
|
||||
ToolCall: &RequestMCPToolCall{
|
||||
Name: "tool_name",
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
|
53
authorize/evaluator/mcp.go
Normal file
53
authorize/evaluator/mcp.go
Normal file
|
@ -0,0 +1,53 @@
|
|||
package evaluator
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
envoy_service_auth_v3 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v3"
|
||||
)
|
||||
|
||||
// RequestMCP is the MCP field in the request.
|
||||
type RequestMCP struct {
|
||||
Method string `json:"method,omitempty"`
|
||||
ToolCall *RequestMCPToolCall `json:"tool_call,omitempty"`
|
||||
}
|
||||
|
||||
// RequestMCPToolCall represents a tool call within an MCP request.
|
||||
type RequestMCPToolCall struct {
|
||||
Name string `json:"name"`
|
||||
Arguments map[string]any `json:"arguments"`
|
||||
}
|
||||
|
||||
// RequestMCPFromCheckRequest populates a RequestMCP from an Envoy CheckRequest proto for MCP routes.
|
||||
func RequestMCPFromCheckRequest(
|
||||
in *envoy_service_auth_v3.CheckRequest,
|
||||
) (RequestMCP, bool) {
|
||||
var mcpReq RequestMCP
|
||||
|
||||
body := in.GetAttributes().GetRequest().GetHttp().GetBody()
|
||||
if body == "" {
|
||||
return mcpReq, false
|
||||
}
|
||||
|
||||
var jsonRPCReq struct {
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(body), &jsonRPCReq); err != nil {
|
||||
return mcpReq, false
|
||||
}
|
||||
|
||||
mcpReq.Method = jsonRPCReq.Method
|
||||
|
||||
if jsonRPCReq.Method == "tools/call" {
|
||||
var toolCall RequestMCPToolCall
|
||||
err := json.Unmarshal(jsonRPCReq.Params, &toolCall)
|
||||
if err != nil {
|
||||
return mcpReq, false
|
||||
}
|
||||
mcpReq.ToolCall = &toolCall
|
||||
}
|
||||
|
||||
return mcpReq, true
|
||||
}
|
|
@ -9,6 +9,8 @@ import (
|
|||
"strings"
|
||||
|
||||
envoy_service_auth_v3 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v3"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
oteltrace "go.opentelemetry.io/otel/trace"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
|
@ -37,18 +39,24 @@ func (a *Authorize) Check(ctx context.Context, in *envoy_service_auth_v3.CheckRe
|
|||
ctx = a.withQuerierForCheckRequest(ctx)
|
||||
|
||||
state := a.state.Load()
|
||||
mcpEnabled := a.currentConfig.Load().Options.IsRuntimeFlagSet(config.RuntimeFlagMCP)
|
||||
|
||||
// convert the incoming envoy-style http request into a go-style http request
|
||||
hreq := getHTTPRequestFromCheckRequest(in)
|
||||
requestID := requestid.FromHTTPHeader(hreq.Header)
|
||||
ctx = requestid.WithValue(ctx, requestID)
|
||||
|
||||
req, err := a.getEvaluatorRequestFromCheckRequest(ctx, in)
|
||||
req, err := a.getEvaluatorRequestFromCheckRequest(ctx, in, mcpEnabled)
|
||||
if err != nil {
|
||||
log.Ctx(ctx).Error().Err(err).Str("request-id", requestID).Msg("error building evaluator request")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Add MCP information to trace if available
|
||||
if mcpEnabled {
|
||||
updateSpanWithMCPInfo(span, req.MCP)
|
||||
}
|
||||
|
||||
// load the session
|
||||
s, err := a.loadSession(ctx, hreq, req)
|
||||
if errors.Is(err, sessions.ErrInvalidSession) {
|
||||
|
@ -68,7 +76,7 @@ func (a *Authorize) Check(ctx context.Context, in *envoy_service_auth_v3.CheckRe
|
|||
// For MCP routes that only require authentication (not full authorization),
|
||||
// if we have a valid session, allow the request without running policy evaluation
|
||||
// as policy for MCP may contain check for i.e. tool calls that are not relevant at this stage.
|
||||
if a.currentConfig.Load().Options.IsRuntimeFlagSet(config.RuntimeFlagMCP) {
|
||||
if mcpEnabled {
|
||||
if req.Policy.IsMCPServer() && strings.HasPrefix(hreq.URL.Path, mcp.DefaultPrefix) {
|
||||
if s != nil {
|
||||
return a.requireLoginResponse(ctx, in, req)
|
||||
|
@ -196,6 +204,7 @@ func (a *Authorize) getMCPSession(
|
|||
func (a *Authorize) getEvaluatorRequestFromCheckRequest(
|
||||
ctx context.Context,
|
||||
in *envoy_service_auth_v3.CheckRequest,
|
||||
mcpEnabled bool,
|
||||
) (*evaluator.Request, error) {
|
||||
attrs := in.GetAttributes()
|
||||
req := &evaluator.Request{
|
||||
|
@ -206,7 +215,7 @@ func (a *Authorize) getEvaluatorRequestFromCheckRequest(
|
|||
}
|
||||
req.Policy = a.getMatchingPolicy(req.EnvoyRouteID)
|
||||
|
||||
if req.Policy.IsMCPServer() {
|
||||
if mcpEnabled && req.Policy.IsMCPServer() {
|
||||
var ok bool
|
||||
req.MCP, ok = evaluator.RequestMCPFromCheckRequest(in)
|
||||
if !ok {
|
||||
|
@ -214,13 +223,6 @@ func (a *Authorize) getEvaluatorRequestFromCheckRequest(
|
|||
Str("request-id", requestid.FromContext(ctx)).
|
||||
Str("route_id", req.EnvoyRouteID).
|
||||
Msg("failed to parse MCP request from check request")
|
||||
} else {
|
||||
log.Ctx(ctx).Debug().
|
||||
Str("request-id", requestid.FromContext(ctx)).
|
||||
Str("route_id", req.EnvoyRouteID).
|
||||
Str("mcp_tool", req.MCP.Tool).
|
||||
Str("mcp_method", req.MCP.Method).
|
||||
Msg("authorize request from check request")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -280,3 +282,13 @@ func getCheckRequestHeaders(req *envoy_service_auth_v3.CheckRequest) map[string]
|
|||
}
|
||||
return hdrs
|
||||
}
|
||||
|
||||
func updateSpanWithMCPInfo(span oteltrace.Span, mcp evaluator.RequestMCP) {
|
||||
if mcp.Method == "" {
|
||||
return
|
||||
}
|
||||
span.SetAttributes(attribute.String("mcp.method", mcp.Method))
|
||||
if tc := mcp.ToolCall; tc != nil {
|
||||
span.SetAttributes(attribute.String("mcp.tool", tc.Name))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -87,6 +87,7 @@ func Test_getEvaluatorRequest(t *testing.T) {
|
|||
},
|
||||
},
|
||||
},
|
||||
false, // mcp disabled
|
||||
)
|
||||
require.NoError(t, err)
|
||||
expect := &evaluator.Request{
|
||||
|
@ -144,7 +145,7 @@ func Test_getEvaluatorRequestWithPortInHostHeader(t *testing.T) {
|
|||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}, false) // mcp disabled
|
||||
require.NoError(t, err)
|
||||
expect := &evaluator.Request{
|
||||
Policy: &a.currentConfig.Load().Options.Policies[0],
|
||||
|
@ -168,6 +169,53 @@ func Test_getEvaluatorRequestWithPortInHostHeader(t *testing.T) {
|
|||
assert.Equal(t, expect, actual)
|
||||
}
|
||||
|
||||
func Test_MCP_TraceAttributes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Test MCP request parsing
|
||||
mcpBody := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"database_query","arguments":{"query":"SELECT * FROM users","limit":10}}}`
|
||||
|
||||
req := &envoy_service_auth_v3.CheckRequest{
|
||||
Attributes: &envoy_service_auth_v3.AttributeContext{
|
||||
Request: &envoy_service_auth_v3.AttributeContext_Request{
|
||||
Http: &envoy_service_auth_v3.AttributeContext_HttpRequest{
|
||||
Body: mcpBody,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
mcpReq, ok := evaluator.RequestMCPFromCheckRequest(req)
|
||||
require.True(t, ok, "should successfully parse MCP request")
|
||||
|
||||
assert.Equal(t, "tools/call", mcpReq.Method)
|
||||
require.NotNil(t, mcpReq.ToolCall)
|
||||
assert.Equal(t, "database_query", mcpReq.ToolCall.Name)
|
||||
assert.NotNil(t, mcpReq.ToolCall.Arguments)
|
||||
assert.Equal(t, "SELECT * FROM users", mcpReq.ToolCall.Arguments["query"])
|
||||
assert.Equal(t, float64(10), mcpReq.ToolCall.Arguments["limit"])
|
||||
|
||||
// Test non-tools/call method
|
||||
mcpBodyList := `{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}`
|
||||
req.Attributes.Request.Http.Body = mcpBodyList
|
||||
|
||||
mcpReq, ok = evaluator.RequestMCPFromCheckRequest(req)
|
||||
require.True(t, ok, "should successfully parse MCP list request")
|
||||
|
||||
assert.Equal(t, "tools/list", mcpReq.Method)
|
||||
assert.Nil(t, mcpReq.ToolCall)
|
||||
|
||||
// Test invalid JSON
|
||||
req.Attributes.Request.Http.Body = `invalid json`
|
||||
mcpReq, ok = evaluator.RequestMCPFromCheckRequest(req)
|
||||
assert.False(t, ok, "should fail to parse invalid JSON")
|
||||
|
||||
// Test empty body
|
||||
req.Attributes.Request.Http.Body = ""
|
||||
mcpReq, ok = evaluator.RequestMCPFromCheckRequest(req)
|
||||
assert.False(t, ok, "should fail to parse empty body")
|
||||
}
|
||||
|
||||
type mockDataBrokerServiceClient struct {
|
||||
databroker.DataBrokerServiceClient
|
||||
|
||||
|
|
|
@ -184,6 +184,21 @@ func populateLogEvent(
|
|||
return evt
|
||||
case log.AuthorizeLogFieldIP:
|
||||
return evt.Str(string(field), req.HTTP.IP)
|
||||
case log.AuthorizeLogFieldMCPMethod:
|
||||
if method := req.MCP.Method; method != "" {
|
||||
return evt.Str(string(field), req.MCP.Method)
|
||||
}
|
||||
return evt
|
||||
case log.AuthorizeLogFieldMCPTool:
|
||||
if req.MCP.ToolCall != nil {
|
||||
return evt.Str(string(field), req.MCP.ToolCall.Name)
|
||||
}
|
||||
return evt
|
||||
case log.AuthorizeLogFieldMCPToolParameters:
|
||||
if req.MCP.ToolCall != nil && req.MCP.ToolCall.Arguments != nil {
|
||||
return evt.Interface(string(field), req.MCP.ToolCall.Arguments)
|
||||
}
|
||||
return evt
|
||||
case log.AuthorizeLogFieldMethod:
|
||||
return evt.Str(string(field), req.HTTP.Method)
|
||||
case log.AuthorizeLogFieldPath:
|
||||
|
|
|
@ -31,6 +31,13 @@ func Test_populateLogEvent(t *testing.T) {
|
|||
Headers: map[string]string{"X-Request-Id": "CHECK-REQUEST-ID"},
|
||||
IP: "127.0.0.1",
|
||||
},
|
||||
MCP: evaluator.RequestMCP{
|
||||
Method: "tools/call",
|
||||
ToolCall: &evaluator.RequestMCPToolCall{
|
||||
Name: "list_tables",
|
||||
Arguments: map[string]interface{}{"database": "test", "schema": "public"},
|
||||
},
|
||||
},
|
||||
EnvoyRouteChecksum: 1234,
|
||||
EnvoyRouteID: "ROUTE-ID",
|
||||
Policy: &config.Policy{
|
||||
|
@ -79,6 +86,9 @@ func Test_populateLogEvent(t *testing.T) {
|
|||
{log.AuthorizeLogFieldImpersonateSessionID, s, `{"impersonate-session-id":"IMPERSONATE-SESSION-ID"}`},
|
||||
{log.AuthorizeLogFieldImpersonateUserID, s, `{"impersonate-user-id":"IMPERSONATE-USER-ID"}`},
|
||||
{log.AuthorizeLogFieldIP, s, `{"ip":"127.0.0.1"}`},
|
||||
{log.AuthorizeLogFieldMCPMethod, s, `{"mcp-method":"tools/call"}`},
|
||||
{log.AuthorizeLogFieldMCPTool, s, `{"mcp-tool":"list_tables"}`},
|
||||
{log.AuthorizeLogFieldMCPToolParameters, s, `{"mcp-tool-parameters":{"database":"test","schema":"public"}}`},
|
||||
{log.AuthorizeLogFieldMethod, s, `{"method":"GET"}`},
|
||||
{log.AuthorizeLogFieldPath, s, `{"path":"/some/path"}`},
|
||||
{log.AuthorizeLogFieldQuery, s, `{"query":"a=b"}`},
|
||||
|
@ -105,3 +115,80 @@ func Test_populateLogEvent(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Test_MCP_LogFields tests that MCP-specific log fields are properly populated
|
||||
func Test_MCP_LogFields(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := t.Context()
|
||||
ctx = requestid.WithValue(ctx, "MCP-REQUEST-ID")
|
||||
|
||||
// Test with a tools/call request
|
||||
req := &evaluator.Request{
|
||||
MCP: evaluator.RequestMCP{
|
||||
Method: "tools/call",
|
||||
ToolCall: &evaluator.RequestMCPToolCall{
|
||||
Name: "database_query",
|
||||
Arguments: map[string]interface{}{
|
||||
"query": "SELECT * FROM users",
|
||||
"limit": 100,
|
||||
"format": "json",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
logger := zerolog.New(&buf)
|
||||
|
||||
// Test MCP method field
|
||||
evt := logger.Log()
|
||||
evt = populateLogEvent(ctx, log.AuthorizeLogFieldMCPMethod, evt, req, nil, nil, nil, nil)
|
||||
evt.Send()
|
||||
assert.Contains(t, buf.String(), `"mcp-method":"tools/call"`)
|
||||
buf.Reset()
|
||||
|
||||
// Test MCP tool field
|
||||
evt = logger.Log()
|
||||
evt = populateLogEvent(ctx, log.AuthorizeLogFieldMCPTool, evt, req, nil, nil, nil, nil)
|
||||
evt.Send()
|
||||
assert.Contains(t, buf.String(), `"mcp-tool":"database_query"`)
|
||||
buf.Reset()
|
||||
|
||||
// Test MCP tool parameters field
|
||||
evt = logger.Log()
|
||||
evt = populateLogEvent(ctx, log.AuthorizeLogFieldMCPToolParameters, evt, req, nil, nil, nil, nil)
|
||||
evt.Send()
|
||||
assert.Contains(t, buf.String(), `"mcp-tool-parameters":`)
|
||||
assert.Contains(t, buf.String(), `"query":"SELECT * FROM users"`)
|
||||
assert.Contains(t, buf.String(), `"limit":100`)
|
||||
assert.Contains(t, buf.String(), `"format":"json"`)
|
||||
buf.Reset()
|
||||
|
||||
// Test with a non-tools/call request (no tool or parameters)
|
||||
req.MCP = evaluator.RequestMCP{
|
||||
Method: "tools/list",
|
||||
}
|
||||
|
||||
evt = logger.Log()
|
||||
evt = populateLogEvent(ctx, log.AuthorizeLogFieldMCPMethod, evt, req, nil, nil, nil, nil)
|
||||
evt.Send()
|
||||
assert.Contains(t, buf.String(), `"mcp-method":"tools/list"`)
|
||||
buf.Reset()
|
||||
|
||||
evt = logger.Log()
|
||||
evt = populateLogEvent(ctx, log.AuthorizeLogFieldMCPTool, evt, req, nil, nil, nil, nil)
|
||||
evt.Send()
|
||||
// Should not contain the field when ToolCall is nil
|
||||
assert.NotContains(t, buf.String(), `"mcp-tool"`)
|
||||
buf.Reset()
|
||||
|
||||
// Test with empty MCP data
|
||||
req.MCP = evaluator.RequestMCP{}
|
||||
|
||||
evt = logger.Log()
|
||||
evt = populateLogEvent(ctx, log.AuthorizeLogFieldMCPToolParameters, evt, req, nil, nil, nil, nil)
|
||||
evt.Send()
|
||||
// Should not contain the field when parameters are nil
|
||||
assert.NotContains(t, buf.String(), `"mcp-tool-parameters"`)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue