-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmain.go
More file actions
355 lines (326 loc) · 9.9 KB
/
main.go
File metadata and controls
355 lines (326 loc) · 9.9 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package mcpproxy
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"path"
"strings"
"sync"
"time"
"github.com/blendle/zapdriver"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"github.com/sigbit/mcp-auth-proxy/pkg/auth"
"github.com/sigbit/mcp-auth-proxy/pkg/backend"
"github.com/sigbit/mcp-auth-proxy/pkg/idp"
"github.com/sigbit/mcp-auth-proxy/pkg/proxy"
"github.com/sigbit/mcp-auth-proxy/pkg/repository"
"github.com/sigbit/mcp-auth-proxy/pkg/utils"
"go.uber.org/zap"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/crypto/bcrypt"
)
var ServerShutdownTimeout = 5 * time.Second
func Run(
listen string,
listenTLS string,
autoTLS bool,
tlsHost string,
tlsDirectoryURL string,
tlsAcceptTOS bool,
dataPath string,
externalURL string,
googleClientID string,
googleClientSecret string,
googleAllowedUsers []string,
githubClientID string,
githubClientSecret string,
githubAllowedUsers []string,
oidcConfigurationURL string,
oidcClientID string,
oidcClientSecret string,
oidcScopes []string,
oidcUserIDField string,
oidcProviderName string,
oidcAllowedUsers []string,
password string,
passwordHash string,
proxyHeaders []string,
proxyBearerToken string,
proxyTarget []string,
) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
parsedExternalURL, err := url.Parse(externalURL)
if err != nil {
return fmt.Errorf("failed to parse external URL: %w", err)
}
if parsedExternalURL.Path != "" {
return fmt.Errorf("external URL must not have a path, got: %s", parsedExternalURL.Path)
}
secret, err := utils.LoadOrGenerateSecret(path.Join(dataPath, "secret"))
if err != nil {
return fmt.Errorf("failed to load or generate secret: %w", err)
}
var config zap.Config
if os.Getenv("MODE") == "debug" {
gin.SetMode(gin.DebugMode)
config = zap.NewDevelopmentConfig()
} else {
gin.SetMode(gin.ReleaseMode)
config = zapdriver.NewProductionConfig()
}
logger, err := config.Build()
if err != nil {
return fmt.Errorf("failed to build logger: %w", err)
}
if err := os.MkdirAll(dataPath, os.ModePerm); err != nil {
return fmt.Errorf("failed to create database directory: %w", err)
}
if len(proxyTarget) == 0 {
return fmt.Errorf("proxy target must be specified")
}
var be *backend.ProxyBackend
var beHandler http.Handler
if proxyURL, err := url.Parse(proxyTarget[0]); err == nil && (proxyURL.Scheme == "http" || proxyURL.Scheme == "https") {
beHandler = httputil.NewSingleHostReverseProxy(proxyURL)
} else {
be = backend.NewProxyBackend(logger, proxyTarget)
beHandler, err = be.Run(ctx)
if err != nil {
return fmt.Errorf("failed to create proxy backend: %w", err)
}
}
// Convert headers slice to map and integrate bearer token
proxyHeadersMap := http.Header{}
for _, header := range proxyHeaders {
parts := strings.SplitN(header, ":", 2)
if len(parts) != 2 || strings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[1]) == "" {
return fmt.Errorf("invalid proxy header format: %s", header)
}
proxyHeadersMap.Add(strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]))
}
// Add bearer token as Authorization header if provided
if proxyBearerToken != "" {
if proxyHeadersMap.Get("Authorization") != "" {
logger.Warn("Authorization header already set, overwriting with bearer token")
}
proxyHeadersMap.Set("Authorization", "Bearer "+proxyBearerToken)
}
repo, err := repository.NewKVSRepository(path.Join(dataPath, "db"), "mcp-oauth-proxy")
if err != nil {
return fmt.Errorf("failed to create repository: %w", err)
}
privKey, err := utils.LoadOrGeneratePrivateKey(path.Join(dataPath, "private_key.pem"))
if err != nil {
return fmt.Errorf("failed to load or generate private key: %w", err)
}
var providers []auth.Provider
// Add Google provider if configured
if googleClientID != "" && googleClientSecret != "" {
googleProvider, err := auth.NewGoogleProvider(externalURL, googleClientID, googleClientSecret, googleAllowedUsers)
if err != nil {
return fmt.Errorf("failed to create Google provider: %w", err)
}
providers = append(providers, googleProvider)
}
// Add GitHub provider if configured
if githubClientID != "" && githubClientSecret != "" {
githubProvider, err := auth.NewGithubProvider(githubClientID, githubClientSecret, externalURL, githubAllowedUsers)
if err != nil {
return fmt.Errorf("failed to create GitHub provider: %w", err)
}
providers = append(providers, githubProvider)
}
// Add OIDC provider if configured
if oidcConfigurationURL != "" && oidcClientID != "" && oidcClientSecret != "" {
oidcProvider, err := auth.NewOIDCProvider(
oidcConfigurationURL,
oidcScopes,
oidcUserIDField,
oidcProviderName,
externalURL,
oidcClientID,
oidcClientSecret,
oidcAllowedUsers,
)
if err != nil {
return fmt.Errorf("failed to create OIDC provider: %w", err)
}
providers = append(providers, oidcProvider)
}
var passwordHashes []string
// Handle password argument - generate bcrypt hash if provided
if password != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to generate password hash: %w", err)
}
passwordHashes = append(passwordHashes, string(hash))
}
// Handle password-hash argument - use directly if provided
if passwordHash != "" {
passwordHashes = append(passwordHashes, passwordHash)
}
authRouter, err := auth.NewAuthRouter(passwordHashes, providers...)
if err != nil {
return fmt.Errorf("failed to create auth router: %w", err)
}
idpRouter, err := idp.NewIDPRouter(repo, privKey, logger, externalURL, secret, authRouter)
if err != nil {
return fmt.Errorf("failed to create IDP router: %w", err)
}
proxyRouter, err := proxy.NewProxyRouter(externalURL, beHandler, &privKey.PublicKey, proxyHeadersMap)
if err != nil {
return fmt.Errorf("failed to create proxy router: %w", err)
}
router := gin.New()
router.Use(ginzap.Ginzap(logger, time.RFC3339, true))
router.Use(ginzap.RecoveryWithZap(logger, true))
store := cookie.NewStore(secret)
router.Use(sessions.Sessions("session", store))
authRouter.SetupRoutes(router)
idpRouter.SetupRoutes(router)
proxyRouter.SetupRoutes(router)
var tlsHostDetected bool
if autoTLS &&
tlsHost == "" &&
parsedExternalURL.Scheme == "https" &&
parsedExternalURL.Host != "localhost" {
tlsHost = parsedExternalURL.Host
tlsHostDetected = true
}
exit := make(chan struct{}, 3)
var wg sync.WaitGroup
errs := []error{}
lock := sync.Mutex{}
if tlsHost != "" {
if !tlsAcceptTOS {
if tlsHostDetected {
return errors.New("TLS host is auto-detected, but tlsAcceptTOS is not set to true. Please agree to the TOS or set autoTLS to false")
} else {
return errors.New("TLS is enabled, but tlsAcceptTOS is not set to true. Please explicitly agree to the TOS")
}
}
m := autocert.Manager{
Prompt: func(tosURL string) bool {
return tlsAcceptTOS
},
HostPolicy: autocert.HostWhitelist(tlsHost),
Cache: autocert.DirCache(path.Join(dataPath, "certs")),
Client: &acme.Client{
DirectoryURL: tlsDirectoryURL,
},
}
httpServer := &http.Server{
Addr: listen,
Handler: m.HTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host := r.Host
if host == "" {
host = r.URL.Host
}
target := "https://" + host + r.RequestURI
http.Redirect(w, r, target, http.StatusMovedPermanently)
})),
}
httpsServer := &http.Server{
Addr: listenTLS,
Handler: router,
TLSConfig: m.TLSConfig(),
}
wg.Add(1)
go func() {
defer wg.Done()
err := httpServer.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
}
logger.Debug("HTTP server closed")
exit <- struct{}{}
}()
go func() {
<-ctx.Done()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
defer shutdownCancel()
if shutdownErr := httpServer.Shutdown(shutdownCtx); shutdownErr != nil {
logger.Warn("HTTP server shutdown error", zap.Error(shutdownErr))
}
}()
wg.Add(1)
go func() {
defer wg.Done()
err := httpsServer.ListenAndServeTLS("", "")
if err != nil && !errors.Is(err, http.ErrServerClosed) {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
}
logger.Debug("HTTPS server closed")
exit <- struct{}{}
}()
go func() {
<-ctx.Done()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
defer shutdownCancel()
if shutdownErr := httpsServer.Shutdown(shutdownCtx); shutdownErr != nil {
logger.Warn("HTTPS server shutdown error", zap.Error(shutdownErr))
}
}()
} else {
httpServer := &http.Server{
Addr: listen,
Handler: router,
}
wg.Add(1)
go func() {
defer wg.Done()
err := httpServer.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
}
exit <- struct{}{}
}()
go func() {
<-ctx.Done()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
defer shutdownCancel()
if shutdownErr := httpServer.Shutdown(shutdownCtx); shutdownErr != nil {
logger.Warn("HTTP server shutdown error", zap.Error(shutdownErr))
}
}()
}
if be != nil {
wg.Add(1)
go func() {
defer wg.Done()
if err := be.Wait(); err != nil && !errors.Is(ctx.Err(), context.Canceled) {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
}
logger.Debug("proxy backend closed")
exit <- struct{}{}
}()
}
if tlsHost != "" {
logger.Info("Starting server", zap.Strings("listen", []string{listen, listenTLS}))
} else {
logger.Info("Starting server", zap.Strings("listen", []string{listen}))
}
<-exit
stop()
wg.Wait()
return errors.Join(errs...)
}