feat(mcp): origin allowlist middleware

This commit is contained in:
Mathias Bergqvist
2026-05-04 20:41:21 +02:00
parent cf2017e687
commit ea19516109
2 changed files with 72 additions and 0 deletions

27
internal/mcp/origin.go Normal file
View File

@@ -0,0 +1,27 @@
package mcp
import "net/http"
// OriginAllowlist returns middleware that rejects requests whose Origin header
// is not in the allowlist. Empty Origin (e.g. server-side curl) is allowed
// because Origin is browser-only by design.
func OriginAllowlist(allowed []string) func(http.Handler) http.Handler {
set := make(map[string]struct{}, len(allowed))
for _, a := range allowed {
set[a] = struct{}{}
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
next.ServeHTTP(w, r)
return
}
if _, ok := set[origin]; !ok {
http.Error(w, "origin not allowed", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}