Documentation
¶
Overview ¶
Package authz provides authorization utilities for MCP servers. It supports a pluggable authorizer architecture where different authorization backends (e.g., Cedar, OPA) can be registered and used based on configuration.
Package authz provides authorization utilities for MCP servers. It supports a pluggable authorizer architecture where different authorization backends (e.g., Cedar, OPA) can be registered and used based on configuration.
Package authz provides authorization utilities for MCP servers.
Index ¶
- Constants
- Variables
- func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
- func CreateMiddlewareFromConfig(c *Config, serverName string, passThroughTools map[string]struct{}) (types.MiddlewareFunction, error)
- func Middleware(a authorizers.Authorizer, next http.Handler, ...) http.Handler
- type AnnotationCache
- func (c *AnnotationCache) Get(toolName string) *authorizers.ToolAnnotationsdeprecated
- func (c *AnnotationCache) Lookup(toolName string) (ann *authorizers.ToolAnnotations, listed bool)
- func (c *AnnotationCache) Set(toolName string, annotations *authorizers.ToolAnnotations)deprecated
- func (c *AnnotationCache) SetFromToolsList(tools []mcp.Tool)
- type Config
- type ConfigType
- type FactoryMiddleware
- type FactoryMiddlewareParams
- type ResponseFilteringWriter
Constants ¶
const MaxDerivedAuthzBudget = 30 * time.Second
MaxDerivedAuthzBudget bounds the total wall-clock time one request may spend making authorization decisions, across all of its derived checks.
The count limit alone does not bound this. authorizers/http issues one outbound POST per decision with its own per-call timeout (30s by default), so a PDP that hangs turns N decisions into N times that timeout -- at the subscription limit, over twenty minutes of a request held open. The budget makes the worst case independent of N.
It is set to the HTTP authorizer's own default per-call timeout on purpose: one request may spend no longer authorizing than a single decision was already allowed to take. That makes this a ceiling on fan-out rather than a new constraint on how slow an individual decision may be.
const (
MiddlewareType = "authorization"
)
Factory middleware type constant
Variables ¶
var LoadConfig = authorizers.LoadConfig
LoadConfig is an alias for authorizers.LoadConfig for backward compatibility.
var MCPMethodToFeatureOperation = map[string]featureOperation{ "initialize": {Feature: "", Operation: ""}, "ping": {Feature: "", Operation: ""}, "tools/call": {Feature: authorizers.MCPFeatureTool, Operation: authorizers.MCPOperationCall}, "tools/list": {Feature: authorizers.MCPFeatureTool, Operation: authorizers.MCPOperationList}, "prompts/get": {Feature: authorizers.MCPFeaturePrompt, Operation: authorizers.MCPOperationGet}, "prompts/list": {Feature: authorizers.MCPFeaturePrompt, Operation: authorizers.MCPOperationList}, "resources/read": {Feature: authorizers.MCPFeatureResource, Operation: authorizers.MCPOperationRead}, "resources/list": {Feature: authorizers.MCPFeatureResource, Operation: authorizers.MCPOperationList}, "resources/templates/list": {Feature: authorizers.MCPFeatureResource, Operation: authorizers.MCPOperationList}, "resources/subscribe": {Feature: authorizers.MCPFeatureResource, Operation: authorizers.MCPOperationRead}, "resources/unsubscribe": {Feature: authorizers.MCPFeatureResource, Operation: authorizers.MCPOperationRead}, "skills/get": {Feature: authorizers.MCPFeatureSkill, Operation: authorizers.MCPOperationGet}, "skills/list": {Feature: authorizers.MCPFeatureSkill, Operation: authorizers.MCPOperationList}, "features/list": {Feature: "", Operation: authorizers.MCPOperationList}, "roots/list": {Feature: "", Operation: ""}, "server/discover": {Feature: "", Operation: ""}, "logging/setLevel": {Feature: "", Operation: ""}, "notifications/message": {Feature: "", Operation: ""}, "notifications/initialized": {Feature: "", Operation: ""}, "notifications/progress": {Feature: "", Operation: ""}, "notifications/cancelled": {Feature: "", Operation: ""}, "notifications/roots/list_changed": {Feature: "", Operation: ""}, "notifications/tools/list_changed": {Feature: "", Operation: ""}, "notifications/prompts/list_changed": {Feature: "", Operation: ""}, "notifications/resources/list_changed": {Feature: "", Operation: ""}, "notifications/resources/updated": {Feature: "", Operation: ""}, "notifications/tasks/status": {Feature: "", Operation: ""}, }
MCPMethodToFeatureOperation maps MCP method names to feature and operation pairs. Methods with empty Feature and Operation are always allowed (protocol-level). Methods not in this map are denied by default for security.
var NewConfig = authorizers.NewConfig
NewConfig is an alias for authorizers.NewConfig for backward compatibility.
Functions ¶
func CreateMiddleware ¶ added in v0.2.8
func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
CreateMiddleware factory function for authorization middleware
func CreateMiddlewareFromConfig ¶ added in v0.7.0
func CreateMiddlewareFromConfig( c *Config, serverName string, passThroughTools map[string]struct{}, ) (types.MiddlewareFunction, error)
CreateMiddlewareFromConfig creates an HTTP middleware from the configuration. The passThroughTools parameter is optional (pass nil for none). Tool names in this set bypass the response filter's policy check in tools/list responses.
func Middleware ¶ added in v0.7.0
func Middleware(a authorizers.Authorizer, next http.Handler, passThroughTools map[string]struct{}) http.Handler
Middleware creates an HTTP middleware that authorizes MCP requests. This middleware extracts the MCP message from the request, determines the feature, operation, and resource ID, and authorizes the request using the configured authorizer.
For protected list operations (tools/list, prompts/list, resources/list, resources/templates/list, and skills/list), the middleware allows the request to proceed only when a response filter is registered, then filters out items that the user is not authorized to access based on the corresponding call/get/read policies. In particular, skills/list entries are filtered individually by get_skill authorization.
An in-memory annotation cache is maintained per middleware instance. When a tools/list response passes through, tool annotations are captured. When a subsequent tools/call request arrives, the cached annotations, with the MCP default for every hint the tool does not declare, are injected into the request context so that authorizers can use them for policy decisions. A tool this instance has never listed gets all four defaults.
The authorizer parameter should implement the authorizers.Authorizer interface, which can be created using authz.CreateMiddlewareFromConfig() or directly from an authorizer package (e.g., cedar.NewCedarAuthorizer()).
Types ¶
type AnnotationCache ¶ added in v0.11.3
type AnnotationCache struct {
// contains filtered or unexported fields
}
AnnotationCache stores tool annotations indexed by tool name. It is safe for concurrent use and nil-safe: calling methods on a nil *AnnotationCache is a no-op that returns zero values.
The cache is populated from tools/list responses (via SetFromToolsList) and read during tools/call authorization (via Lookup). This bridges the gap between the two separate HTTP requests: annotations are visible in the tools/list response but absent from the tools/call request body.
Each tools/list response is merged into the cache; nothing is evicted. A tool is recorded even if it declares no hints, so a Lookup miss means only that this cache has never seen the tool in a tools/list response. The cache is bounded by the tool set of the backend.
The cache stores hints as declared. It does not apply the MCP defaults; the middleware does that for every tools/call, listed or not.
func NewAnnotationCache ¶ added in v0.11.3
func NewAnnotationCache() *AnnotationCache
NewAnnotationCache creates a new empty annotation cache.
func (*AnnotationCache) Get
deprecated
added in
v0.11.3
func (c *AnnotationCache) Get(toolName string) *authorizers.ToolAnnotations
Get returns the cached hints for a tool, as Lookup does, without reporting whether the tool was listed. It returns nil for a tool that declares no hints and for a tool that was never listed.
Deprecated: Use Lookup, which tells the two nil cases apart. Get will be removed in a future release.
func (*AnnotationCache) Lookup ¶ added in v0.74.0
func (c *AnnotationCache) Lookup(toolName string) (ann *authorizers.ToolAnnotations, listed bool)
Lookup returns the cached hints for a tool and whether the tool has been listed. A listed tool that declares no hints returns (nil, true). A tool that was never listed returns (nil, false). A nil cache has listed nothing, so it returns (nil, false) for every name.
The returned hints are exactly what the tools/list response declared. The authorization middleware fills in the MCP default for every missing hint (see authorizers.WithMCPDefaults) before it authorizes a tools/call. Callers must not modify the returned value, because it is shared.
func (*AnnotationCache) Set
deprecated
added in
v0.11.3
func (c *AnnotationCache) Set(toolName string, annotations *authorizers.ToolAnnotations)
Set records one tool as listed with the given hints. A nil annotations records a listed tool that declares no hints. The cache keeps the pointer and does not modify it. It is a no-op if the cache is nil.
Deprecated: Use SetFromToolsList, which records tools as a tools/list response declares them. Set will be removed in a future release.
func (*AnnotationCache) SetFromToolsList ¶ added in v0.11.3
func (c *AnnotationCache) SetFromToolsList(tools []mcp.Tool)
SetFromToolsList merges the tools of a tools/list response into the cache. Tools in the response are added or overwritten with their current hints; tools absent from the response keep their entries. Tools that declare no hints are recorded with a nil entry so Lookup can tell them from tools that were never listed.
This method is a no-op if the cache is nil.
type Config ¶
type Config = authorizers.Config
Config is an alias for authorizers.Config for backward compatibility.
type ConfigType ¶
type ConfigType = authorizers.ConfigType
ConfigType is an alias for authorizers.ConfigType for backward compatibility.
type FactoryMiddleware ¶ added in v0.2.8
type FactoryMiddleware struct {
// contains filtered or unexported fields
}
FactoryMiddleware wraps authorization middleware functionality for factory pattern
func (*FactoryMiddleware) Close ¶ added in v0.2.8
func (*FactoryMiddleware) Close() error
Close cleans up any resources used by the middleware.
func (*FactoryMiddleware) Handler ¶ added in v0.2.8
func (m *FactoryMiddleware) Handler() types.MiddlewareFunction
Handler returns the middleware function used by the proxy.
type FactoryMiddlewareParams ¶ added in v0.2.8
type FactoryMiddlewareParams struct {
ConfigPath string `json:"config_path,omitempty"` // Kept for backwards compatibility
ConfigData *Config `json:"config_data,omitempty"` // New field for config contents
}
FactoryMiddlewareParams represents the parameters for authorization middleware
type ResponseFilteringWriter ¶ added in v0.0.38
type ResponseFilteringWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
ResponseFilteringWriter wraps an http.ResponseWriter to intercept and filter responses
func NewResponseFilteringWriter ¶ added in v0.0.38
func NewResponseFilteringWriter( w http.ResponseWriter, authorizer authorizers.Authorizer, r *http.Request, method string, annotationCache *AnnotationCache, passThroughTools map[string]struct{}, ) *ResponseFilteringWriter
NewResponseFilteringWriter creates a new response filtering writer. The annotationCache parameter is optional; pass nil to disable annotation caching. The passThroughTools parameter is optional; tools whose names appear in this set bypass policy filtering because authorization is enforced elsewhere (e.g., inside the optimizer decorator for find_tool/call_tool).
func (*ResponseFilteringWriter) Flush ¶ added in v0.0.38
func (rfw *ResponseFilteringWriter) Flush()
Flush implements http.Flusher. httputil.ReverseProxy with FlushInterval: -1 calls it through http.NewResponseController after each body write, once on a timer that can fire before the first write, and once after the body is copied when the backend sent trailers, to force chunked encoding before it stores the trailer values in the head map.
For a method whose response is filtered, Flush does nothing. Write buffers the whole body, so a flush would stream no bytes; it would only commit the status and headers before FlushAndFilter can change them. FlushAndFilter commits the head once, with the final status (a 500 when it fails closed on a 2xx), Content-Type, and Cache-Control, and without the backend's entity headers or trailers. ResponseController stops at this method and does not unwrap to the underlying writer, because the writer has no Unwrap.
For any other method, Flush commits the recorded backend status and flushes the underlying writer, which sends the head early. Without the explicit WriteHeader, the first flush would send an implicit 200 in place of a non-2xx backend status. Content-Length is deleted first because the head goes out here, before FlushAndFilter has written any of the body, and could not be corrected afterwards. The body on this path is forwarded unchanged, so the backend's length would still match it. The deletion dates from when Flush also committed filtered responses, and its only effect here is that net/http chunks the body.
func (*ResponseFilteringWriter) FlushAndFilter ¶ added in v0.6.0
func (rfw *ResponseFilteringWriter) FlushAndFilter() error
FlushAndFilter processes the captured response and applies filtering if needed. Returns an error if filtering or writing fails.
func (*ResponseFilteringWriter) Write ¶ added in v0.0.38
func (rfw *ResponseFilteringWriter) Write(data []byte) (int, error)
Write captures the response body for filtering
func (*ResponseFilteringWriter) WriteHeader ¶ added in v0.0.38
func (rfw *ResponseFilteringWriter) WriteHeader(statusCode int)
WriteHeader captures the status code
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package authorizers provides the authorization framework and abstractions for ToolHive.
|
Package authorizers provides the authorization framework and abstractions for ToolHive. |
|
cedar
Package cedar provides authorization utilities using Cedar policies.
|
Package cedar provides authorization utilities using Cedar policies. |
|
http
Package http provides authorization using HTTP-based Policy Decision Points (PDPs).
|
Package http provides authorization using HTTP-based Policy Decision Points (PDPs). |
|
mocks
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |