Update scope validation implementation

This commit is contained in:
NipuniBhagya 2025-05-21 10:00:01 +05:30
parent 5c22f36ddc
commit 64caaa0f7c
7 changed files with 202 additions and 138 deletions

View file

@ -32,9 +32,7 @@ A lightweight authorization proxy for Model Context Protocol (MCP) servers that
| Version | Behavior | | Version | Behavior |
| :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 2025-03-26 | Only signature check of Bearer JWT on both `/sse` and `/message`<br> No scope or audience enforcement | | 2025-03-26 | Only signature check of Bearer JWT on both `/sse` and `/message`<br> No scope or audience enforcement |
| Latest(draft) | Read `MCP-Protocol-Version` from client header<br> SSE handshake returns `WWW-Authenticate: Bearer resource_metadata="…"`<br> `/message` enforces:<br> 1. `aud` claim == `ResourceIdentifier`<br> 2. `scope` claim contains per-path `requiredScope`<br> 3. PolicyEngine decision<br> Rich `WWW-Authenticate` on 401s<br> Serves `/.well-known/oauth-protected-resource` JSON | | Latest(draft) | Read `MCP-Protocol-Version` from client header<br> SSE handshake returns `WWW-Authenticate: Bearer resource_metadata="…"`<br> `/message` enforces:<br>`aud` claim == `ResourceIdentifier`<br>`scope` claim contains `requiredScope`<br>Scope based access control<br>Rich `WWW-Authenticate` on 401s<br>Serves `/.well-known/oauth-protected-resource` JSON |
> ⚠️ **Note:** MCP v2 support is available **only in SSE mode**. The stdio mode supports only v1.
## 🛠️ Quick Start ## 🛠️ Quick Start
@ -101,23 +99,14 @@ To enable authorization through your Asgardeo organization:
base_url: "http://localhost:8000" # URL of your MCP server base_url: "http://localhost:8000" # URL of your MCP server
listen_port: 8080 # Address where the proxy will listen listen_port: 8080 # Address where the proxy will listen
asgardeo: resource_identifier: "http://localhost:8080" # Proxy server URL
org_name: "<org_name>" # Your Asgardeo org name scopes_supported: # Scopes required to access the MCP server
client_id: "<client_id>" # Client ID of the M2M app - "read:tools"
client_secret: "<client_secret>" # Client secret of the M2M app - "read:resources"
audience: "<audience_value>" # Access token audience
resource_identifier: "http://localhost:8080" authorization_servers: # Authorization server URL
scopes_supported: - "https://api.asgardeo.io/t/acme"
- "read:tools" jwks_uri: "https://api.asgardeo.io/t/acme/oauth2/jwks" # JWKS URL of the Authorization server
- "read:resources"
audience: "<audience_value>"
authorization_servers:
- "https://api.asgardeo.io/t/acme"
jwks_uri: "https://api.asgardeo.io/t/acme/oauth2/jwks"
bearer_methods_supported:
- header
- body
- query
``` ```
4. Start the proxy with Asgardeo integration: 4. Start the proxy with Asgardeo integration:
@ -240,22 +229,14 @@ demo:
client_secret: "qFHfiBp5gNGAO9zV4YPnDofBzzfInatfUbHyPZvM0jka" client_secret: "qFHfiBp5gNGAO9zV4YPnDofBzzfInatfUbHyPZvM0jka"
# Asgardeo configuration (used with --asgardeo flag) # Asgardeo configuration (used with --asgardeo flag)
asgardeo: resource_identifier: "http://localhost:8080"
org_name: "<org_name>" scopes_supported:
client_id: "<client_id>" - "read:tools"
client_secret: "<client_secret>" - "read:resources"
resource_identifier: "http://localhost:8080" audience: "<audience_value>"
scopes_supported: authorization_servers:
- "read:tools" - "https://api.asgardeo.io/t/acme"
- "read:resources" jwks_uri: "https://api.asgardeo.io/t/acme/oauth2/jwks"
audience: "<audience_value>"
authorization_servers:
- "https://api.asgardeo.io/t/acme"
jwks_uri: "https://api.asgardeo.io/t/acme/oauth2/jwks"
bearer_methods_supported:
- header
- body
- query
``` ```
### 🖥️ Build from source ### 🖥️ Build from source

View file

@ -11,7 +11,6 @@ import (
"github.com/wso2/open-mcp-auth-proxy/internal/authz" "github.com/wso2/open-mcp-auth-proxy/internal/authz"
"github.com/wso2/open-mcp-auth-proxy/internal/config" "github.com/wso2/open-mcp-auth-proxy/internal/config"
"github.com/wso2/open-mcp-auth-proxy/internal/constants"
"github.com/wso2/open-mcp-auth-proxy/internal/logging" "github.com/wso2/open-mcp-auth-proxy/internal/logging"
"github.com/wso2/open-mcp-auth-proxy/internal/proxy" "github.com/wso2/open-mcp-auth-proxy/internal/proxy"
"github.com/wso2/open-mcp-auth-proxy/internal/subprocess" "github.com/wso2/open-mcp-auth-proxy/internal/subprocess"
@ -68,23 +67,7 @@ func main() {
} }
// 3. Create the chosen provider // 3. Create the chosen provider
var provider authz.Provider var provider authz.Provider = MakeProvider(cfg, *demoMode, *asgardeoMode)
if *demoMode {
cfg.Mode = "demo"
cfg.AuthServerBaseURL = constants.ASGARDEO_BASE_URL + cfg.Demo.OrgName + "/oauth2"
cfg.JWKSURL = constants.ASGARDEO_BASE_URL + cfg.Demo.OrgName + "/oauth2/jwks"
provider = authz.NewAsgardeoProvider(cfg)
} else if *asgardeoMode {
cfg.Mode = "asgardeo"
cfg.AuthServerBaseURL = constants.ASGARDEO_BASE_URL + cfg.Asgardeo.OrgName + "/oauth2"
cfg.JWKSURL = constants.ASGARDEO_BASE_URL + cfg.Asgardeo.OrgName + "/oauth2/jwks"
provider = authz.NewAsgardeoProvider(cfg)
} else {
cfg.Mode = "default"
cfg.JWKSURL = cfg.Default.JWKSURL
cfg.AuthServerBaseURL = cfg.Default.BaseURL
provider = authz.NewDefaultProvider(cfg)
}
// 4. (Optional) Fetch JWKS if you want local JWT validation // 4. (Optional) Fetch JWKS if you want local JWT validation
if err := util.FetchJWKS(cfg.JWKSURL); err != nil { if err := util.FetchJWKS(cfg.JWKSURL); err != nil {

45
cmd/proxy/provider.go Normal file
View file

@ -0,0 +1,45 @@
package main
import (
"github.com/wso2/open-mcp-auth-proxy/internal/authz"
"github.com/wso2/open-mcp-auth-proxy/internal/config"
"github.com/wso2/open-mcp-auth-proxy/internal/constants"
)
func MakeProvider(cfg *config.Config, demoMode, asgardeoMode bool) authz.Provider {
var mode, orgName string
switch {
case demoMode:
mode = "demo"
orgName = cfg.Demo.OrgName
case asgardeoMode:
mode = "asgardeo"
orgName = cfg.Asgardeo.OrgName
default:
mode = "default"
}
cfg.Mode = mode
switch mode {
case "demo", "asgardeo":
if len(cfg.AuthorizationServers) == 0 && cfg.JwksURI == "" {
base := constants.ASGARDEO_BASE_URL + orgName + "/oauth2"
cfg.AuthServerBaseURL = base
cfg.JWKSURL = base + "/jwks"
} else {
cfg.AuthServerBaseURL = cfg.AuthorizationServers[0]
cfg.JWKSURL = cfg.JwksURI
}
return authz.NewAsgardeoProvider(cfg)
default:
if cfg.Default.BaseURL != "" && cfg.Default.JWKSURL != "" {
cfg.AuthServerBaseURL = cfg.Default.BaseURL
cfg.JWKSURL = cfg.Default.JWKSURL
} else if len(cfg.AuthorizationServers) > 0 {
cfg.AuthServerBaseURL = cfg.AuthorizationServers[0]
cfg.JWKSURL = cfg.JwksURI
}
return authz.NewDefaultProvider(cfg)
}
}

View file

@ -1,6 +1,11 @@
package authz package authz
import "net/http" import (
"net/http"
"github.com/golang-jwt/jwt/v4"
"github.com/wso2/open-mcp-auth-proxy/internal/config"
)
type Decision int type Decision int
@ -15,5 +20,5 @@ type AccessControlResult struct {
} }
type AccessControl interface { type AccessControl interface {
ValidateAccess(r *http.Request, claims *TokenClaims, requiredScopes any) AccessControlResult ValidateAccess(r *http.Request, claims *jwt.MapClaims, config *config.Config) AccessControlResult
} }

View file

@ -4,54 +4,68 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
)
type TokenClaims struct { "github.com/golang-jwt/jwt/v4"
Scopes []string "github.com/wso2/open-mcp-auth-proxy/internal/config"
} "github.com/wso2/open-mcp-auth-proxy/internal/util"
)
type ScopeValidator struct{} type ScopeValidator struct{}
// Evaluate and checks the token claims against one or more required scopes. // Evaluate and checks the token claims against one or more required scopes.
func (d *ScopeValidator) ValidateAccess( func (d *ScopeValidator) ValidateAccess(
_ *http.Request, r *http.Request,
claims *TokenClaims, claims *jwt.MapClaims,
requiredScopes any, config *config.Config,
) AccessControlResult { ) AccessControlResult {
var scopeStr string env, err := util.ParseRPCRequest(r)
switch v := requiredScopes.(type) { if err != nil {
case string: return AccessControlResult{DecisionDeny, "bad JSON-RPC request"}
scopeStr = v
case []string:
scopeStr = strings.Join(v, " ")
} }
requiredScopes := util.GetRequiredScopes(config, env.Method)
if strings.TrimSpace(scopeStr) == "" { if len(requiredScopes) == 0 {
return AccessControlResult{DecisionAllow, ""} return AccessControlResult{DecisionAllow, ""}
} }
scopes := strings.FieldsFunc(scopeStr, func(r rune) bool { required := make(map[string]struct{}, len(requiredScopes))
return r == ' ' || r == ',' for _, s := range requiredScopes {
}) s = strings.TrimSpace(s)
required := make(map[string]struct{}, len(scopes)) if s != "" {
for _, s := range scopes {
if s = strings.TrimSpace(s); s != "" {
required[s] = struct{}{} required[s] = struct{}{}
} }
} }
for _, tokenScope := range claims.Scopes { var tokenScopes []string
if _, ok := required[tokenScope]; ok { if claims, ok := (*claims)["scope"]; ok {
return AccessControlResult{DecisionAllow, ""} switch v := claims.(type) {
case string:
tokenScopes = strings.Fields(v)
case []interface{}:
for _, x := range v {
if s, ok := x.(string); ok && s != "" {
tokenScopes = append(tokenScopes, s)
}
}
} }
} }
var list []string tokenScopeSet := make(map[string]struct{}, len(tokenScopes))
for _, s := range tokenScopes {
tokenScopeSet[s] = struct{}{}
}
var missing []string
for s := range required { for s := range required {
list = append(list, s) if _, ok := tokenScopeSet[s]; !ok {
missing = append(missing, s)
}
}
if len(missing) == 0 {
return AccessControlResult{DecisionAllow, ""}
} }
return AccessControlResult{ return AccessControlResult{
DecisionDeny, DecisionDeny,
fmt.Sprintf("missing required scope(s): %s", strings.Join(list, ", ")), fmt.Sprintf("missing required scope(s): %s", strings.Join(missing, ", ")),
} }
} }

View file

@ -302,6 +302,7 @@ func authorizeSSE(w http.ResponseWriter, r *http.Request, isLatestSpec bool, res
// Handles both v1 (just signature) and v2 (aud + scope) flows // Handles both v1 (just signature) and v2 (aud + scope) flows
func authorizeMCP(w http.ResponseWriter, r *http.Request, isLatestSpec bool, cfg *config.Config, accessController authz.AccessControl) error { func authorizeMCP(w http.ResponseWriter, r *http.Request, isLatestSpec bool, cfg *config.Config, accessController authz.AccessControl) error {
authzHeader := r.Header.Get("Authorization") authzHeader := r.Header.Get("Authorization")
accessToken, _ := util.ExtractAccessToken(authzHeader)
if !strings.HasPrefix(authzHeader, "Bearer ") { if !strings.HasPrefix(authzHeader, "Bearer ") {
if isLatestSpec { if isLatestSpec {
realm := cfg.ResourceIdentifier + "/.well-known/oauth-protected-resource" realm := cfg.ResourceIdentifier + "/.well-known/oauth-protected-resource"
@ -314,7 +315,7 @@ func authorizeMCP(w http.ResponseWriter, r *http.Request, isLatestSpec bool, cfg
return fmt.Errorf("missing or invalid Authorization header") return fmt.Errorf("missing or invalid Authorization header")
} }
claims, err := util.ValidateJWT(isLatestSpec, authzHeader, cfg.Audience) err := util.ValidateJWT(isLatestSpec, accessToken, cfg.Audience)
if err != nil { if err != nil {
if isLatestSpec { if isLatestSpec {
realm := cfg.ResourceIdentifier + "/.well-known/oauth-protected-resource" realm := cfg.ResourceIdentifier + "/.well-known/oauth-protected-resource"
@ -331,16 +332,19 @@ func authorizeMCP(w http.ResponseWriter, r *http.Request, isLatestSpec bool, cfg
} }
if isLatestSpec { if isLatestSpec {
env, err := util.ParseRPCRequest(r) _, err := util.ParseRPCRequest(r)
if err != nil { if err != nil {
http.Error(w, "Bad request", http.StatusBadRequest) http.Error(w, "Bad request", http.StatusBadRequest)
return err return err
} }
requiredScopes := util.GetRequiredScopes(cfg, env.Method)
if len(requiredScopes) == 0 { claimsMap, err := util.ParseJWT(accessToken)
return nil if err != nil {
http.Error(w, "Invalid token claims", http.StatusUnauthorized)
return fmt.Errorf("invalid token claims")
} }
pr := accessController.ValidateAccess(r, claims, requiredScopes)
pr := accessController.ValidateAccess(r, &claimsMap, cfg)
if pr.Decision == authz.DecisionDeny { if pr.Decision == authz.DecisionDeny {
http.Error(w, "Forbidden: "+pr.Message, http.StatusForbidden) http.Error(w, "Forbidden: "+pr.Message, http.StatusForbidden)
return fmt.Errorf("forbidden — %s", pr.Message) return fmt.Errorf("forbidden — %s", pr.Message)

View file

@ -10,7 +10,6 @@ import (
"strings" "strings"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
"github.com/wso2/open-mcp-auth-proxy/internal/authz"
"github.com/wso2/open-mcp-auth-proxy/internal/config" "github.com/wso2/open-mcp-auth-proxy/internal/config"
"github.com/wso2/open-mcp-auth-proxy/internal/logging" "github.com/wso2/open-mcp-auth-proxy/internal/logging"
) )
@ -83,15 +82,12 @@ func parseRSAPublicKey(nStr, eStr string) (*rsa.PublicKey, error) {
// ValidateJWT checks the Bearer token according to the Mcp-Protocol-Version. // ValidateJWT checks the Bearer token according to the Mcp-Protocol-Version.
func ValidateJWT( func ValidateJWT(
isLatestSpec bool, isLatestSpec bool,
authHeader, audience string, accessToken string,
) (*authz.TokenClaims, error) { audience string,
tokenStr := strings.TrimPrefix(authHeader, "Bearer ") ) error {
if tokenStr == "" { logger.Warn("isLatestSpec: %s", isLatestSpec)
return nil, errors.New("empty bearer token")
}
// Parse & verify the signature // Parse & verify the signature
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) { token, err := jwt.Parse(accessToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
} }
@ -106,29 +102,31 @@ func ValidateJWT(
return key, nil return key, nil
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid token: %w", err) logger.Warn("Error detected, returning early")
return fmt.Errorf("invalid token: %w", err)
} }
if !token.Valid { if !token.Valid {
return nil, errors.New("token not valid") logger.Warn("Token invalid, returning early")
return errors.New("token not valid")
} }
claimsMap, ok := token.Claims.(jwt.MapClaims) claimsMap, ok := token.Claims.(jwt.MapClaims)
if !ok { if !ok {
return nil, errors.New("unexpected claim type") return errors.New("unexpected claim type")
} }
if !isLatestSpec { if !isLatestSpec {
return &authz.TokenClaims{Scopes: nil}, nil return nil
} }
audRaw, exists := claimsMap["aud"] audRaw, exists := claimsMap["aud"]
if !exists { if !exists {
return nil, errors.New("aud claim missing") return errors.New("aud claim missing")
} }
switch v := audRaw.(type) { switch v := audRaw.(type) {
case string: case string:
if v != audience { if v != audience {
return nil, fmt.Errorf("aud %q does not match %q", v, audience) return fmt.Errorf("aud %q does not match %q", v, audience)
} }
case []interface{}: case []interface{}:
var found bool var found bool
@ -139,38 +137,72 @@ func ValidateJWT(
} }
} }
if !found { if !found {
return nil, fmt.Errorf("audience %v does not include %q", v, audience) return fmt.Errorf("audience %v does not include %q", v, audience)
} }
default: default:
return nil, errors.New("aud claim has unexpected type") return errors.New("aud claim has unexpected type")
} }
rawScope := claimsMap["scope"] return nil
scopeList := []string{} }
if s, ok := rawScope.(string); ok {
scopeList = strings.Fields(s) // Parses the JWT token and returns the claims
func ParseJWT(tokenStr string) (jwt.MapClaims, error) {
if tokenStr == "" {
return nil, fmt.Errorf("empty JWT")
} }
return &authz.TokenClaims{Scopes: scopeList}, nil var claims jwt.MapClaims
_, _, err := jwt.NewParser().ParseUnverified(tokenStr, &claims)
if err != nil {
return nil, fmt.Errorf("failed to parse JWT: %w", err)
}
return claims, nil
} }
// Process the required scopes // Process the required scopes
func GetRequiredScopes(cfg *config.Config, method string) []string { func GetRequiredScopes(cfg *config.Config, method string) []string {
if scopes, ok := cfg.ScopesSupported.(map[string]string); ok && len(scopes) > 0 { switch raw := cfg.ScopesSupported.(type) {
if scope, ok := scopes[method]; ok { case map[string]string:
if scope, ok := raw[method]; ok {
return []string{scope} return []string{scope}
} }
if parts := strings.SplitN(method, "/", 2); len(parts) > 0 { parts := strings.SplitN(method, "/", 2)
if scope, ok := scopes[parts[0]]; ok { if len(parts) > 0 {
if scope, ok := raw[parts[0]]; ok {
return []string{scope} return []string{scope}
} }
} }
return nil return nil
case []interface{}:
out := make([]string, 0, len(raw))
for _, v := range raw {
if s, ok := v.(string); ok && s != "" {
out = append(out, s)
}
}
return out
case []string:
return raw
} }
if scopes, ok := cfg.ScopesSupported.([]string); ok && len(scopes) > 0 { return nil
return scopes }
}
// Extracts the Bearer token from the Authorization header
return []string{} func ExtractAccessToken(authHeader string) (string, error) {
if authHeader == "" {
return "", errors.New("empty authorization header")
}
if !strings.HasPrefix(authHeader, "Bearer ") {
return "", fmt.Errorf("invalid authorization header format: %s", authHeader)
}
tokenStr := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
if tokenStr == "" {
return "", errors.New("empty bearer token")
}
return tokenStr, nil
} }