-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
302 lines (276 loc) · 8.59 KB
/
Copy pathmain.go
File metadata and controls
302 lines (276 loc) · 8.59 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
// Command mcpproxyd is the standalone MCP gateway daemon: one process
// serving one or many MCP backends behind /mcp with inbound auth, policy
// checks, approvals, telemetry, and session recording.
//
// Usage:
//
// mcpproxyd -config config.yaml
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/hoophq/mcpproxy/approval"
"github.com/hoophq/mcpproxy/audit"
"github.com/hoophq/mcpproxy/auth/authserver"
"github.com/hoophq/mcpproxy/auth/inbound"
"github.com/hoophq/mcpproxy/auth/outbound"
"github.com/hoophq/mcpproxy/backend"
"github.com/hoophq/mcpproxy/checks"
"github.com/hoophq/mcpproxy/config"
"github.com/hoophq/mcpproxy/gateway"
"github.com/hoophq/mcpproxy/inspect"
"github.com/hoophq/mcpproxy/optimizer"
"github.com/hoophq/mcpproxy/telemetry"
"github.com/hoophq/mcpproxy/wal"
)
// version is the released build's tag, set by the release build with
// -ldflags "-X main.version=vX.Y.Z". A build from source reports "dev".
var version = "dev"
func main() {
cfgPath := flag.String("config", "config.yaml", "path to YAML config")
debug := flag.Bool("debug", false, "debug logging")
showVersion := flag.Bool("version", false, "print version and exit")
flag.Parse()
if *showVersion {
fmt.Println("mcpproxyd", version)
return
}
lvl := slog.LevelInfo
if *debug {
lvl = slog.LevelDebug
}
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lvl}))
slog.SetDefault(log)
if err := run(*cfgPath, log); err != nil {
log.Error("fatal", "err", err)
os.Exit(1)
}
}
func run(cfgPath string, log *slog.Logger) error {
cfg, err := config.Load(cfgPath)
if err != nil {
return fmt.Errorf("loading config: %w", err)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// ---- audit sinks --------------------------------------------------
sinks := audit.MultiSink{newLogSink(log)}
if cfg.WALDir != "" {
w, err := wal.New(cfg.WALDir)
if err != nil {
return fmt.Errorf("wal: %w", err)
}
sinks = append(sinks, w)
}
var sink audit.Sink = sinks
// ---- telemetry ----------------------------------------------------
tel, err := telemetry.New(cfg.Telemetry)
if err != nil {
return fmt.Errorf("telemetry: %w", err)
}
defer func() {
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = tel.Shutdown(sctx)
}()
// ---- embedded auth server (optional) -------------------------------
var authSrv *authserver.Server
if cfg.AuthServer != nil {
var fed authserver.UpstreamFederator
if cfg.AuthServer.Upstream != nil {
fed, err = authserver.NewOIDCFederator(ctx, *cfg.AuthServer.Upstream,
cfg.AuthServer.Issuer+"/callback", nil)
if err != nil {
return fmt.Errorf("auth server upstream: %w", err)
}
}
authSrv, err = authserver.New(*cfg.AuthServer, fed)
if err != nil {
return fmt.Errorf("auth server: %w", err)
}
}
// ---- inbound auth ---------------------------------------------------
resolver, err := buildResolver(cfg, authSrv)
if err != nil {
return fmt.Errorf("inbound auth: %w", err)
}
// ---- outbound auth + backends ---------------------------------------
tokenDeps, err := buildOutboundDeps(cfg, authSrv, log)
if err != nil {
return fmt.Errorf("outbound auth: %w", err)
}
factories := map[string]backend.Factory{}
for name, bcfg := range cfg.Backends {
ts, err := outbound.Resolve(ctx, name, bcfg, tokenDeps)
if err != nil {
return fmt.Errorf("backend %s auth: %w", name, err)
}
factories[name] = backend.NewFactory(name, bcfg, ts)
}
// ---- approvals -------------------------------------------------------
heldStore := approval.New(cfg.Approvals.Timeout, sink)
// ---- pipeline ---------------------------------------------------------
hooks := inspect.Hooks{} // standalone: guardrails/redaction via future plugins
pipeline := checks.Assemble(cfg.Policy, hooks, sink, true)
if cfg.Optimizer != nil && cfg.Optimizer.TopK > 0 {
pipeline = append(pipeline, optimizer.New(*cfg.Optimizer, sink, nil))
}
// ---- gateway ----------------------------------------------------------
gw, err := gateway.New(gateway.Options{
Backends: factories,
Pipeline: pipeline,
Resolver: resolver,
Sink: sink,
Held: heldStore,
Observer: tel,
Logger: log,
})
if err != nil {
return err
}
defer gw.Close()
// ---- HTTP mux -----------------------------------------------------------
mux := http.NewServeMux()
mux.Handle("/mcp", gw.Handler())
mux.Handle("/approvals/", http.StripPrefix("/approvals",
approval.NewAPI(heldStore, cfg.Approvals.APIToken)))
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
if h := tel.Handler(); h != nil && cfg.Telemetry.PrometheusPath != "" {
mux.Handle(cfg.Telemetry.PrometheusPath, h)
}
if authSrv != nil {
mux.Handle("/.well-known/", authSrv.Routes())
mux.Handle("/authorize", authSrv.Routes())
mux.Handle("/token", authSrv.Routes())
mux.Handle("/register", authSrv.Routes())
mux.Handle("/callback", authSrv.Routes())
} else if cfg.Inbound.Mode == "oidc" {
// Serve RFC 9728 protected-resource metadata pointing at the
// external issuer, so MCP clients can discover where to
// authenticate.
mux.Handle("/.well-known/oauth-protected-resource",
inbound.WellKnownHandler("http://"+cfg.Listen, cfg.Inbound.Issuer))
}
srv := &http.Server{
Addr: cfg.Listen,
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
errCh := make(chan error, 1)
go func() { errCh <- srv.ListenAndServe() }()
log.Info("mcpproxyd listening", "addr", cfg.Listen, "backends", len(cfg.Backends))
select {
case <-ctx.Done():
log.Info("shutting down")
sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(sctx)
return nil
case err := <-errCh:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}
}
// buildResolver wires inbound auth. An embedded auth server validates its
// own tokens; otherwise the configured inbound mode decides.
func buildResolver(cfg *config.Config, authSrv *authserver.Server) (gateway.IdentityResolver, error) {
if authSrv != nil {
return func(r *http.Request) (inspect.Identity, error) {
tok := bearerToken(r)
if tok == "" {
return inspect.Identity{}, fmt.Errorf("missing bearer token")
}
return authSrv.ValidateToken(r.Context(), tok)
}, nil
}
res, err := inbound.New(cfg.Inbound)
if err != nil {
return nil, err
}
// Stash the raw bearer and the upstream passthrough header in the
// context for outbound passthrough and exchange sources.
return func(r *http.Request) (inspect.Identity, error) {
id, err := res(r)
if err != nil {
return id, err
}
ctx := r.Context()
if up := r.Header.Get(outbound.UpstreamAuthHeader); up != "" {
ctx = outbound.WithClientToken(ctx, up)
}
if tok := bearerToken(r); tok != "" {
ctx = outbound.WithInboundToken(ctx, tok)
}
ctx = outbound.WithUser(ctx, id.Subject)
*r = *r.WithContext(ctx)
return id, nil
}, nil
}
func buildOutboundDeps(cfg *config.Config, authSrv *authserver.Server, log *slog.Logger) (outbound.Deps, error) {
stateDir := os.Getenv("MCPPROXY_STATE_DIR")
if stateDir == "" {
home, _ := os.UserHomeDir()
stateDir = home + "/.mcpproxy"
}
if err := os.MkdirAll(stateDir, 0o700); err != nil {
return outbound.Deps{}, err
}
store, err := outbound.NewFileStore(stateDir+"/tokens.enc", stateDir+"/tokens.key")
if err != nil {
return outbound.Deps{}, err
}
deps := outbound.Deps{
Store: store,
Authorizer: outbound.NewLoopbackAuthorizer(log),
}
if authSrv != nil {
deps.UpstreamSwap = authserver.NewUpstreamSwapSource(authSrv)
}
return deps, nil
}
func bearerToken(r *http.Request) string {
const p = "Bearer "
h := r.Header.Get("Authorization")
if len(h) > len(p) && h[:len(p)] == p {
return h[len(p):]
}
return ""
}
// logSink logs audit events as structured slog records.
type logSink struct{ log *slog.Logger }
func newLogSink(log *slog.Logger) audit.Sink { return &logSink{log: log} }
func (s *logSink) Emit(_ context.Context, ev audit.Event) {
attrs := []any{"sid", ev.Session}
if ev.User != "" {
attrs = append(attrs, "user", ev.User)
}
if ev.Backend != "" {
attrs = append(attrs, "backend", ev.Backend)
}
if ev.Tool != "" {
attrs = append(attrs, "tool", ev.Tool)
}
if ev.Rule != "" {
attrs = append(attrs, "rule", ev.Rule)
}
if ev.Reason != "" {
attrs = append(attrs, "reason", ev.Reason)
}
for k, v := range ev.Fields {
attrs = append(attrs, k, v)
}
s.log.Info(string(ev.Type), attrs...)
}