-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmain_test.go
More file actions
315 lines (269 loc) · 10.1 KB
/
main_test.go
File metadata and controls
315 lines (269 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package main
import (
"context"
"log"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/obot-platform/mcp-oauth-proxy/pkg/proxy"
"github.com/obot-platform/mcp-oauth-proxy/pkg/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIntegrationFlow(t *testing.T) {
// Skip if running in short mode
if testing.Short() {
t.Skip("Skipping integration tests in short mode")
}
// Create OAuth proxy
config := &types.Config{
Mode: proxy.ModeProxy,
MCPServerURL: "http://localhost:8081/",
OAuthClientID: "test_client_id",
OAuthClientSecret: "test_client_secret",
OAuthAuthorizeURL: "https://accounts.google.com",
ScopesSupported: "openid,profile,email",
}
_, err := proxy.NewOAuthProxy(config)
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
oauthProxy, err := proxy.NewOAuthProxy(config)
if err != nil {
t.Skipf("Skipping test due to database connection error: %v", err)
}
defer func() {
if err := oauthProxy.Close(); err != nil {
t.Logf("Error closing OAuth proxy: %v", err)
}
}()
// Get HTTP handler
handler := oauthProxy.GetHandler()
// Test health endpoint
t.Run("HealthEndpoint", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/health", nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "ok")
})
// Test OAuth metadata endpoints
t.Run("OAuthMetadata", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/.well-known/oauth-authorization-server", nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "authorization_endpoint")
assert.Contains(t, w.Body.String(), "token_endpoint")
})
// Test protected resource metadata
t.Run("ProtectedResourceMetadata", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/.well-known/oauth-protected-resource", nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "resource")
assert.Contains(t, w.Body.String(), "authorization_servers")
})
// Test MCP endpoint requires authorization
t.Run("MCPEndpointRequiresAuth", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/mcp", nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Contains(t, w.Header().Get("WWW-Authenticate"), "Bearer")
})
// Test protected resource metadata with path parameter
t.Run("ProtectedResourceMetadataWithPath", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/.well-known/oauth-protected-resource/test/path", nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "resource")
assert.Contains(t, w.Body.String(), "authorization_servers")
})
// Test authorization endpoint redirects (basic validation)
t.Run("AuthorizationEndpointRedirect", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/authorize?response_type=code&client_id=test&redirect_uri=http://localhost:8080/callback&scope=openid", nil)
handler.ServeHTTP(w, req)
// Should get a redirect to the OAuth provider or an error about invalid client
assert.True(t, w.Code == http.StatusFound || w.Code == http.StatusBadRequest)
})
}
func TestOAuthProxyCreation(t *testing.T) {
// Create OAuth proxy
config := &types.Config{
Mode: proxy.ModeProxy,
MCPServerURL: "http://localhost:8081/",
OAuthClientID: "test_client_id",
OAuthClientSecret: "test_client_secret",
OAuthAuthorizeURL: "https://accounts.google.com",
ScopesSupported: "openid,profile,email",
}
_, err := proxy.NewOAuthProxy(config)
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
oauthProxy, err := proxy.NewOAuthProxy(config)
require.NoError(t, err, "Should be able to create OAuth proxy with valid environment")
require.NotNil(t, oauthProxy, "OAuth proxy should not be nil")
// Test that we can get handler without error
require.NotPanics(t, func() {
handler := oauthProxy.GetHandler()
require.NotNil(t, handler)
}, "GetHandler should not panic and should return non-nil handler")
// Clean up
err = oauthProxy.Close()
assert.NoError(t, err, "Should be able to close OAuth proxy")
}
func TestOAuthProxyStart(t *testing.T) {
if testing.Short() {
t.Skip("Skipping OAuth proxy start test in short mode")
}
// Create OAuth proxy
config := &types.Config{
Mode: proxy.ModeProxy,
MCPServerURL: "http://localhost:8081/",
OAuthClientID: "test_client_id",
OAuthClientSecret: "test_client_secret",
OAuthAuthorizeURL: "https://accounts.google.com",
ScopesSupported: "openid,profile,email",
}
_, err := proxy.NewOAuthProxy(config)
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
oauthProxy, err := proxy.NewOAuthProxy(config)
require.NoError(t, err)
defer func() {
_ = oauthProxy.Close()
}()
// Test starting and stopping the proxy
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// Start the proxy in a goroutine
errCh := make(chan error, 1)
go func() {
errCh <- oauthProxy.Start(ctx)
}()
// Give it a moment to start
time.Sleep(100 * time.Millisecond)
// Cancel the context to stop the server
cancel()
// Wait for the server to stop
select {
case err := <-errCh:
// Server stopped, which is expected when context is cancelled
if err != nil {
assert.Contains(t, err.Error(), "context canceled", "Expected context cancellation error")
}
case <-time.After(3 * time.Second):
t.Fatal("Server did not stop within timeout")
}
}
func TestForwardAuthIntegrationFlow(t *testing.T) {
// Skip if running in short mode
if testing.Short() {
t.Skip("Skipping integration tests in short mode")
}
config := &types.Config{
Mode: proxy.ModeForwardAuth,
MCPServerURL: "http://localhost:8081/",
OAuthClientID: "test_client_id",
OAuthClientSecret: "test_client_secret",
OAuthAuthorizeURL: "https://accounts.google.com",
ScopesSupported: "openid,profile,email",
Port: "8082",
}
_, err := proxy.NewOAuthProxy(config)
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
require.Equal(t, "forward_auth", config.Mode)
require.Equal(t, "8082", config.Port)
oauthProxy, err := proxy.NewOAuthProxy(config)
if err != nil {
t.Skipf("Skipping test due to database connection error: %v", err)
}
defer func() {
if err := oauthProxy.Close(); err != nil {
t.Logf("Error closing OAuth proxy: %v", err)
}
}()
// Get HTTP handler
handler := oauthProxy.GetHandler()
// Test health endpoint works in forward auth mode
t.Run("ForwardAuthHealthEndpoint", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/health", nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "ok")
})
// Test OAuth metadata endpoints work in forward auth mode
t.Run("ForwardAuthOAuthMetadata", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/.well-known/oauth-authorization-server", nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "authorization_endpoint")
assert.Contains(t, w.Body.String(), "token_endpoint")
})
// Test protected resource metadata with path works in forward auth mode
t.Run("ForwardAuthProtectedResourceMetadataWithPath", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/.well-known/oauth-protected-resource/api/v1", nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "resource")
assert.Contains(t, w.Body.String(), "authorization_servers")
})
// Test that forward auth mode requires authorization for protected endpoints
t.Run("ForwardAuthRequiresAuth", func(t *testing.T) {
testPaths := []string{"/api", "/data", "/protected", "/mcp", "/test"}
for _, path := range testPaths {
t.Run("Path_"+path, func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", path, nil)
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Contains(t, w.Header().Get("WWW-Authenticate"), "Bearer")
})
}
})
// Test that forward auth mode doesn't proxy to MCP server (no proxying behavior)
t.Run("ForwardAuthNoProxying", func(t *testing.T) {
// In forward auth mode, there should be no attempt to proxy to an MCP server
// Instead, the proxy should validate tokens and set headers for downstream services
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/test", nil)
handler.ServeHTTP(w, req)
// Should get unauthorized (no proxying attempt)
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Contains(t, w.Header().Get("WWW-Authenticate"), "Bearer")
// Should not have any proxy-related error messages
assert.NotContains(t, w.Body.String(), "proxy")
assert.NotContains(t, w.Body.String(), "502")
assert.NotContains(t, w.Body.String(), "Bad Gateway")
})
// Test authorization endpoint redirects work in forward auth mode
t.Run("ForwardAuthAuthorizationEndpointRedirect", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/authorize?response_type=code&client_id=test&redirect_uri=http://localhost:8082/callback&scope=openid", nil)
handler.ServeHTTP(w, req)
// Should get a redirect to the OAuth provider or an error about invalid client
assert.True(t, w.Code == http.StatusFound || w.Code == http.StatusBadRequest)
})
// Test CORS headers work in forward auth mode
t.Run("ForwardAuthCORSHeaders", func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("OPTIONS", "/api", nil)
req.Header.Set("Origin", "https://example.com")
req.Header.Set("Access-Control-Request-Method", "GET")
handler.ServeHTTP(w, req)
// Should handle CORS preflight
assert.Contains(t, w.Header().Get("Access-Control-Allow-Origin"), "*")
})
}