authz

package
v0.2.11 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2025 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package authz provides authorization utilities using Cedar policies.

Package authz provides authorization utilities using Cedar policies.

Package authz provides authorization utilities using Cedar policies.

Package authz provides authorization utilities using Cedar policies.

Package authz provides authorization utilities using Cedar policies.

Index

Constants

View Source
const (
	MiddlewareType = "authorization"
)

Factory middleware type constant

Variables

View Source
var (
	ErrNoPolicies           = errors.New("no policies loaded")
	ErrInvalidPolicy        = errors.New("invalid policy")
	ErrUnauthorized         = errors.New("unauthorized")
	ErrMissingPrincipal     = errors.New("missing principal")
	ErrMissingAction        = errors.New("missing action")
	ErrMissingResource      = errors.New("missing resource")
	ErrFailedToLoadEntities = errors.New("failed to load entities")
)

Common errors for Cedar authorization

View Source
var MCPMethodToFeatureOperation = map[string]struct {
	Feature   MCPFeature
	Operation MCPOperation
}{
	"tools/call":      {Feature: MCPFeatureTool, Operation: MCPOperationCall},
	"tools/list":      {Feature: MCPFeatureTool, Operation: MCPOperationList},
	"prompts/get":     {Feature: MCPFeaturePrompt, Operation: MCPOperationGet},
	"prompts/list":    {Feature: MCPFeaturePrompt, Operation: MCPOperationList},
	"resources/read":  {Feature: MCPFeatureResource, Operation: MCPOperationRead},
	"resources/list":  {Feature: MCPFeatureResource, Operation: MCPOperationList},
	"features/list":   {Feature: "", Operation: MCPOperationList},
	"ping":            {Feature: "", Operation: ""},
	"progress/update": {Feature: "", Operation: ""},
	"initialize":      {Feature: "", Operation: ""},
}

MCPMethodToFeatureOperation maps MCP method names to feature and operation pairs.

Functions

func CreateMiddleware added in v0.2.8

func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error

CreateMiddleware factory function for authorization middleware

func GetMiddlewareFromFile

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

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

Types

type CedarAuthorizer

type CedarAuthorizer struct {
	// contains filtered or unexported fields
}

CedarAuthorizer authorizes MCP operations using Cedar policies.

func NewCedarAuthorizer

func NewCedarAuthorizer(config CedarAuthorizerConfig) (*CedarAuthorizer, error)

NewCedarAuthorizer creates a new Cedar authorizer.

func (*CedarAuthorizer) AddEntity

func (a *CedarAuthorizer) AddEntity(entity cedar.Entity)

AddEntity adds or updates an entity in the authorizer's entity store.

func (*CedarAuthorizer) AuthorizeWithJWTClaims

func (a *CedarAuthorizer) AuthorizeWithJWTClaims(
	ctx context.Context,
	feature MCPFeature,
	operation MCPOperation,
	resourceID string,
	arguments map[string]interface{},
) (bool, error)

AuthorizeWithJWTClaims demonstrates how to use JWT claims with the Cedar authorization middleware. This method: 1. Extracts JWT claims from the context 2. Extracts the client ID from the claims 3. Includes the JWT claims in the Cedar context 4. Creates entities with appropriate attributes 5. Authorizes the operation using the client ID and claims

func (*CedarAuthorizer) GetEntity

func (a *CedarAuthorizer) GetEntity(uid cedar.EntityUID) (cedar.Entity, bool)

GetEntity retrieves an entity from the authorizer's entity store.

func (*CedarAuthorizer) GetEntityFactory

func (a *CedarAuthorizer) GetEntityFactory() *EntityFactory

GetEntityFactory returns the entity factory associated with this authorizer.

func (*CedarAuthorizer) IsAuthorized

func (a *CedarAuthorizer) IsAuthorized(
	principal, action, resource string,
	contextMap map[string]interface{},
	entities ...cedar.EntityMap,
) (bool, error)

IsAuthorized checks if a request is authorized. This is the core authorization method that all other authorization methods use. It takes: - principal: The entity making the request (e.g., "Client::vscode_extension_123") - action: The operation being performed (e.g., "Action::call_tool") - resource: The object being accessed (e.g., "Tool::weather") - context: Additional information about the request - entities: Optional Cedar entity map with attributes

func (*CedarAuthorizer) Middleware

func (a *CedarAuthorizer) Middleware(next http.Handler) http.Handler

Middleware creates an HTTP middleware that authorizes MCP requests using Cedar policies. This middleware extracts the MCP message from the request, determines the feature, operation, and resource ID, and authorizes the request using Cedar policies.

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.

Example usage:

// Create a Cedar authorizer with a policy that covers all tools and resources
cedarAuthorizer, _ := authz.NewCedarAuthorizer(authz.CedarAuthorizerConfig{
    Policies: []string{
        `permit(principal, action == Action::"call_tool", resource == Tool::"weather");`,
        `permit(principal, action == Action::"get_prompt", resource == Prompt::"greeting");`,
        `permit(principal, action == Action::"read_resource", resource == Resource::"data");`,
    },
})

// Create a transport with the middleware
middlewares := []types.Middleware{
    jwtValidator.Middleware, // JWT middleware should be applied first
    cedarAuthorizer.Middleware, // Cedar middleware is applied second
}

proxy := httpsse.NewHTTPSSEProxy(8080, "my-container", middlewares...)
proxy.Start(context.Background())

func (*CedarAuthorizer) RemoveEntity

func (a *CedarAuthorizer) RemoveEntity(uid cedar.EntityUID)

RemoveEntity removes an entity from the authorizer's entity store.

func (*CedarAuthorizer) UpdateEntities

func (a *CedarAuthorizer) UpdateEntities(entitiesJSON string) error

UpdateEntities updates the Cedar entities.

func (*CedarAuthorizer) UpdatePolicies

func (a *CedarAuthorizer) UpdatePolicies(policies []string) error

UpdatePolicies updates the Cedar policies.

type CedarAuthorizerConfig

type CedarAuthorizerConfig struct {
	// Policies is a list of Cedar policy strings
	Policies []string
	// EntitiesJSON is the JSON string representing Cedar entities
	EntitiesJSON string
}

CedarAuthorizerConfig contains configuration for the Cedar authorizer.

type CedarConfig

type CedarConfig struct {
	// Policies is a list of Cedar policy strings
	Policies []string `json:"policies" yaml:"policies"`

	// EntitiesJSON is the JSON string representing Cedar entities
	EntitiesJSON string `json:"entities_json" yaml:"entities_json"`
}

CedarConfig represents the Cedar-specific authorization configuration.

type ClientIDContextKey

type ClientIDContextKey struct{}

ClientIDContextKey is the key used to store client ID in the context.

type Config

type Config struct {
	// Version is the version of the configuration format.
	Version string `json:"version" yaml:"version"`

	// Type is the type of authorization configuration.
	Type ConfigType `json:"type" yaml:"type"`

	// Cedar is the Cedar-specific configuration.
	// This is only used when Type is ConfigTypeCedarV1.
	Cedar *CedarConfig `json:"cedar,omitempty" yaml:"cedar,omitempty"`
}

Config represents the authorization configuration.

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig loads the authorization configuration from a file. It supports both JSON and YAML formats, detected by file extension.

func (*Config) CreateMiddleware

func (c *Config) CreateMiddleware() (types.MiddlewareFunction, error)

CreateMiddleware creates an HTTP middleware from the configuration.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the authorization configuration.

type ConfigType

type ConfigType string

ConfigType represents the type of authorization configuration.

const (
	// ConfigTypeCedarV1 represents the Cedar v1 authorization configuration.
	ConfigTypeCedarV1 ConfigType = "cedarv1"
)

type EntityFactory

type EntityFactory struct{}

EntityFactory creates Cedar entities for authorization.

func NewEntityFactory

func NewEntityFactory() *EntityFactory

NewEntityFactory creates a new entity factory.

func (*EntityFactory) CreateActionEntity

func (*EntityFactory) CreateActionEntity(
	actionType, actionID string,
	attributes map[string]interface{},
) (cedar.EntityUID, cedar.Entity)

CreateActionEntity creates an action entity with the given ID and attributes.

func (*EntityFactory) CreateEntitiesForRequest

func (f *EntityFactory) CreateEntitiesForRequest(
	principal, action, resource string,
	claimsMap map[string]interface{},
	attributes map[string]interface{},
) (cedar.EntityMap, error)

CreateEntitiesForRequest creates entities for a specific authorization request.

func (*EntityFactory) CreatePrincipalEntity

func (*EntityFactory) CreatePrincipalEntity(
	principalType, principalID string,
	attributes map[string]interface{},
) (cedar.EntityUID, cedar.Entity)

CreatePrincipalEntity creates a principal entity with the given ID and attributes.

func (*EntityFactory) CreateResourceEntity

func (*EntityFactory) CreateResourceEntity(
	resourceType, resourceID string,
	attributes map[string]interface{},
) (cedar.EntityUID, cedar.Entity)

CreateResourceEntity creates a resource entity with the given ID and attributes.

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 MCPFeature

type MCPFeature string

MCPFeature represents an MCP feature type. In the MCP protocol, there are three main features: - Tools: Allow models to call functions in external systems - Prompts: Provide structured templates for interacting with language models - Resources: Share data that provides context to language models

const (
	// MCPFeatureTool represents the MCP tool feature.
	MCPFeatureTool MCPFeature = "tool"
	// MCPFeaturePrompt represents the MCP prompt feature.
	MCPFeaturePrompt MCPFeature = "prompt"
	// MCPFeatureResource represents the MCP resource feature.
	MCPFeatureResource MCPFeature = "resource"
)

type MCPOperation

type MCPOperation string

MCPOperation represents an operation on an MCP feature. Each feature supports different operations: - List: Get a list of available items (tools, prompts, resources) - Get: Get a specific prompt - Call: Call a specific tool - Read: Read a specific resource

const (
	// MCPOperationList represents a list operation.
	MCPOperationList MCPOperation = "list"
	// MCPOperationGet represents a get operation.
	MCPOperationGet MCPOperation = "get"
	// MCPOperationCall represents a call operation.
	MCPOperationCall MCPOperation = "call"
	// MCPOperationRead represents a read operation.
	MCPOperationRead MCPOperation = "read"
)

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 *CedarAuthorizer, r *http.Request, method string,
) *ResponseFilteringWriter

NewResponseFilteringWriter creates a new response filtering writer

func (*ResponseFilteringWriter) Flush added in v0.0.38

func (rfw *ResponseFilteringWriter) Flush() error

Flush processes the captured response and applies filtering if needed

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

Jump to

Keyboard shortcuts

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