|
| 1 | +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package factory |
| 5 | + |
| 6 | +import ( |
| 7 | + "crypto/ecdsa" |
| 8 | + "crypto/elliptic" |
| 9 | + "crypto/rand" |
| 10 | + "net/http" |
| 11 | + "net/http/httptest" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/golang-jwt/jwt/v5" |
| 16 | + "github.com/stretchr/testify/assert" |
| 17 | + "github.com/stretchr/testify/require" |
| 18 | + "go.uber.org/mock/gomock" |
| 19 | + |
| 20 | + pkgauth "github.com/stacklok/toolhive/pkg/auth" |
| 21 | + "github.com/stacklok/toolhive/pkg/authserver/server/keys" |
| 22 | + keysmocks "github.com/stacklok/toolhive/pkg/authserver/server/keys/mocks" |
| 23 | + "github.com/stacklok/toolhive/pkg/vmcp/config" |
| 24 | +) |
| 25 | + |
| 26 | +// TestNewOIDCAuthMiddleware_KeyProvider_LocalResolution verifies that when a |
| 27 | +// PublicKeyProvider is wired in, key resolution happens in-process via the |
| 28 | +// local provider rather than through an HTTP JWKS fetch. |
| 29 | +func TestNewOIDCAuthMiddleware_KeyProvider_LocalResolution(t *testing.T) { |
| 30 | + t.Parallel() |
| 31 | + |
| 32 | + // Generate an ECDSA P-256 key pair (matching the embedded auth server's |
| 33 | + // default GeneratingProvider algorithm). |
| 34 | + privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 35 | + require.NoError(t, err) |
| 36 | + |
| 37 | + const ecdsaKeyID = "test-ecdsa-key-1" |
| 38 | + |
| 39 | + // Stand up a minimal OIDC discovery server so issuer validation passes. |
| 40 | + // The JWKS endpoint returns an empty key set — all key resolution should |
| 41 | + // happen through the local provider, not HTTP. |
| 42 | + server, _ := newTestOIDCServer(t) |
| 43 | + t.Cleanup(server.Close) |
| 44 | + |
| 45 | + issuer := server.URL |
| 46 | + |
| 47 | + oidcCfg := &config.OIDCConfig{ |
| 48 | + Issuer: issuer, |
| 49 | + ClientID: "test-client", |
| 50 | + Audience: "test-audience", |
| 51 | + InsecureAllowHTTP: true, |
| 52 | + JwksAllowPrivateIP: true, |
| 53 | + } |
| 54 | + |
| 55 | + ctrl := gomock.NewController(t) |
| 56 | + mockProvider := keysmocks.NewMockPublicKeyProvider(ctrl) |
| 57 | + mockProvider.EXPECT(). |
| 58 | + PublicKeys(gomock.Any()). |
| 59 | + Return([]*keys.PublicKeyData{{ |
| 60 | + KeyID: ecdsaKeyID, |
| 61 | + Algorithm: "ES256", |
| 62 | + PublicKey: &privateKey.PublicKey, |
| 63 | + CreatedAt: time.Now(), |
| 64 | + }}, nil). |
| 65 | + AnyTimes() |
| 66 | + |
| 67 | + authMw, _, err := newOIDCAuthMiddleware(t.Context(), oidcCfg, nil, mockProvider) |
| 68 | + require.NoError(t, err, "middleware creation should succeed with key provider") |
| 69 | + require.NotNil(t, authMw) |
| 70 | + |
| 71 | + var capturedIdentity *pkgauth.Identity |
| 72 | + handler := authMw(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 73 | + capturedIdentity, _ = pkgauth.IdentityFromContext(r.Context()) |
| 74 | + })) |
| 75 | + |
| 76 | + // Sign a JWT with the ECDSA private key — only the local provider |
| 77 | + // holds the matching public key. |
| 78 | + tok := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{ |
| 79 | + "iss": issuer, |
| 80 | + "aud": "test-audience", |
| 81 | + "sub": "test-user", |
| 82 | + "exp": time.Now().Add(time.Hour).Unix(), |
| 83 | + }) |
| 84 | + tok.Header["kid"] = ecdsaKeyID |
| 85 | + tokenString, err := tok.SignedString(privateKey) |
| 86 | + require.NoError(t, err) |
| 87 | + |
| 88 | + req := httptest.NewRequest(http.MethodGet, "/test", nil) |
| 89 | + req.Header.Set("Authorization", "Bearer "+tokenString) |
| 90 | + rr := httptest.NewRecorder() |
| 91 | + |
| 92 | + handler.ServeHTTP(rr, req) |
| 93 | + |
| 94 | + require.Equal(t, http.StatusOK, rr.Code, "request should succeed via local key provider") |
| 95 | + require.NotNil(t, capturedIdentity, "identity should be present in context") |
| 96 | + assert.Equal(t, "test-user", capturedIdentity.Subject) |
| 97 | +} |
| 98 | + |
| 99 | +// TestNewOIDCAuthMiddleware_KeyProvider_HTTPFallback verifies that when the |
| 100 | +// key provider is nil, key resolution falls back to an HTTP JWKS fetch. |
| 101 | +func TestNewOIDCAuthMiddleware_KeyProvider_HTTPFallback(t *testing.T) { |
| 102 | + t.Parallel() |
| 103 | + |
| 104 | + // Use the RSA key from the test OIDC server (served via HTTP JWKS). |
| 105 | + server, rsaPrivateKey := newTestOIDCServer(t) |
| 106 | + t.Cleanup(server.Close) |
| 107 | + |
| 108 | + issuer := server.URL |
| 109 | + oidcCfg := &config.OIDCConfig{ |
| 110 | + Issuer: issuer, |
| 111 | + ClientID: "test-client", |
| 112 | + Audience: "test-audience", |
| 113 | + InsecureAllowHTTP: true, |
| 114 | + JwksAllowPrivateIP: true, |
| 115 | + } |
| 116 | + |
| 117 | + authMw, _, err := newOIDCAuthMiddleware(t.Context(), oidcCfg, nil, nil) |
| 118 | + require.NoError(t, err) |
| 119 | + require.NotNil(t, authMw) |
| 120 | + |
| 121 | + var capturedIdentity *pkgauth.Identity |
| 122 | + handler := authMw(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 123 | + capturedIdentity, _ = pkgauth.IdentityFromContext(r.Context()) |
| 124 | + })) |
| 125 | + |
| 126 | + token := signJWT(t, rsaPrivateKey, jwt.MapClaims{ |
| 127 | + "iss": issuer, |
| 128 | + "aud": "test-audience", |
| 129 | + "sub": "test-user", |
| 130 | + "exp": time.Now().Add(time.Hour).Unix(), |
| 131 | + }) |
| 132 | + |
| 133 | + req := httptest.NewRequest(http.MethodGet, "/test", nil) |
| 134 | + req.Header.Set("Authorization", "Bearer "+token) |
| 135 | + rr := httptest.NewRecorder() |
| 136 | + |
| 137 | + handler.ServeHTTP(rr, req) |
| 138 | + |
| 139 | + require.Equal(t, http.StatusOK, rr.Code, "request should succeed via HTTP JWKS fallback") |
| 140 | + require.NotNil(t, capturedIdentity, "identity should be present in context") |
| 141 | + assert.Equal(t, "test-user", capturedIdentity.Subject) |
| 142 | +} |
| 143 | + |
| 144 | +// TestNewOIDCAuthMiddleware_KeyProvider_KidMissFallback verifies that when the |
| 145 | +// local PublicKeyProvider does not hold a key matching the JWT's kid, the |
| 146 | +// validator falls back to HTTP JWKS and the request still succeeds. This |
| 147 | +// confirms the end-to-end wiring for the kid-miss path at the factory level. |
| 148 | +func TestNewOIDCAuthMiddleware_KeyProvider_KidMissFallback(t *testing.T) { |
| 149 | + t.Parallel() |
| 150 | + |
| 151 | + // Stand up a real OIDC server that serves the RSA key via HTTP JWKS. |
| 152 | + server, rsaPrivateKey := newTestOIDCServer(t) |
| 153 | + t.Cleanup(server.Close) |
| 154 | + |
| 155 | + issuer := server.URL |
| 156 | + oidcCfg := &config.OIDCConfig{ |
| 157 | + Issuer: issuer, |
| 158 | + ClientID: "test-client", |
| 159 | + Audience: "test-audience", |
| 160 | + InsecureAllowHTTP: true, |
| 161 | + JwksAllowPrivateIP: true, |
| 162 | + } |
| 163 | + |
| 164 | + // Wire a mock provider that returns a key with a *different* kid than the |
| 165 | + // one in the JWT. The validator should call the local provider first, get a |
| 166 | + // kid-miss (nil key returned), and then fall back to HTTP JWKS. |
| 167 | + ctrl := gomock.NewController(t) |
| 168 | + mockProvider := keysmocks.NewMockPublicKeyProvider(ctrl) |
| 169 | + |
| 170 | + // Generate a throwaway ECDSA key so the mock returns a non-nil key list |
| 171 | + // with a different kid. |
| 172 | + throwawayKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 173 | + require.NoError(t, err) |
| 174 | + |
| 175 | + mockProvider.EXPECT(). |
| 176 | + PublicKeys(gomock.Any()). |
| 177 | + Return([]*keys.PublicKeyData{{ |
| 178 | + KeyID: "unrelated-key-id", // does NOT match testKeyID used by signJWT |
| 179 | + Algorithm: "ES256", |
| 180 | + PublicKey: &throwawayKey.PublicKey, |
| 181 | + CreatedAt: time.Now(), |
| 182 | + }}, nil). |
| 183 | + AnyTimes() |
| 184 | + |
| 185 | + authMw, _, err := newOIDCAuthMiddleware(t.Context(), oidcCfg, nil, mockProvider) |
| 186 | + require.NoError(t, err) |
| 187 | + require.NotNil(t, authMw) |
| 188 | + |
| 189 | + var capturedIdentity *pkgauth.Identity |
| 190 | + handler := authMw(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 191 | + capturedIdentity, _ = pkgauth.IdentityFromContext(r.Context()) |
| 192 | + })) |
| 193 | + |
| 194 | + // Sign the JWT with the RSA key from the test server (kid = testKeyID). |
| 195 | + // The mock provider holds a key with a different kid, so the validator must |
| 196 | + // fall back to HTTP JWKS to find the matching key. |
| 197 | + token := signJWT(t, rsaPrivateKey, jwt.MapClaims{ |
| 198 | + "iss": issuer, |
| 199 | + "aud": "test-audience", |
| 200 | + "sub": "test-user", |
| 201 | + "exp": time.Now().Add(time.Hour).Unix(), |
| 202 | + }) |
| 203 | + |
| 204 | + req := httptest.NewRequest(http.MethodGet, "/test", nil) |
| 205 | + req.Header.Set("Authorization", "Bearer "+token) |
| 206 | + rr := httptest.NewRecorder() |
| 207 | + |
| 208 | + handler.ServeHTTP(rr, req) |
| 209 | + |
| 210 | + require.Equal(t, http.StatusOK, rr.Code, "request should succeed via HTTP JWKS fallback on kid-miss") |
| 211 | + require.NotNil(t, capturedIdentity, "identity should be present in context") |
| 212 | + assert.Equal(t, "test-user", capturedIdentity.Subject) |
| 213 | +} |
0 commit comments