authz

package
v0.12.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 13, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

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

View Source
const (
	MiddlewareType = "authorization"
)

Factory middleware type constant

Variables

LoadConfig is an alias for authorizers.LoadConfig for backward compatibility.

View Source
var MCPMethodToFeatureOperation = map[string]struct {
	Feature   authorizers.MCPFeature
	Operation authorizers.MCPOperation
}{

	"initialize":      {Feature: "", Operation: ""},
	"ping":            {Feature: "", Operation: ""},
	"progress/update": {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},

	"features/list": {Feature: "", Operation: authorizers.MCPOperationList},
	"roots/list":    {Feature: "", Operation: ""},

	"logging/setLevel": {Feature: "", Operation: ""},

	"completion/complete": {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.

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) (types.MiddlewareFunction, error)

CreateMiddlewareFromConfig creates an HTTP middleware from the configuration.

func GetMiddlewareFromFile

func GetMiddlewareFromFile(serverName, path string) (func(http.Handler) http.Handler, error)

GetMiddlewareFromFile loads the authorization configuration from a file and creates an HTTP middleware.

func Middleware added in v0.7.0

func Middleware(a authorizers.Authorizer, next http.Handler) 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 list operations (tools/list, prompts/list, resources/list), the middleware allows the request to proceed but intercepts the response to filter out items that the user is not authorized to access based on the corresponding call/get/read policies.

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 are injected into the request context so that authorizers can use them for policy decisions.

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 Get). 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.

func NewAnnotationCache added in v0.11.3

func NewAnnotationCache() *AnnotationCache

NewAnnotationCache creates a new empty annotation cache.

func (*AnnotationCache) Get added in v0.11.3

Get retrieves annotations for a tool by name. Returns nil if the tool is not cached or if the cache itself is nil.

func (*AnnotationCache) Set added in v0.11.3

func (c *AnnotationCache) Set(toolName string, annotations *authorizers.ToolAnnotations)

Set stores annotations for a single tool. It is a no-op if the cache is nil.

func (*AnnotationCache) SetFromToolsList added in v0.11.3

func (c *AnnotationCache) SetFromToolsList(tools []mcp.Tool)

SetFromToolsList extracts annotations from a tools/list response and replaces the entire cache contents. The full replacement ensures that tools whose annotations were removed in a subsequent tools/list response do not retain stale cached entries.

Only tools that have at least one non-nil annotation hint are cached; tools with all-nil hints (the zero value) are skipped to avoid unnecessary memory consumption.

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

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,
) *ResponseFilteringWriter

NewResponseFilteringWriter creates a new response filtering writer. The annotationCache parameter is optional; pass nil to disable annotation caching.

func (*ResponseFilteringWriter) Flush added in v0.0.38

func (rfw *ResponseFilteringWriter) Flush()

Flush implements http.Flusher if the underlying ResponseWriter supports it. This method is required for streaming support (SSE, streamable-http).

We must delete the Content-Length header before flushing because httputil.ReverseProxy (with FlushInterval: -1) calls Flush() after copying the backend response. The first Flush() on the underlying writer triggers an implicit WriteHeader(200), sending headers to the wire. If the stale Content-Length is still present at that point, it's too late to remove it in FlushAndFilter().

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

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).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL