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)
})
}
}

View File

@@ -0,0 +1,45 @@
package mcp_test
import (
"net/http"
"net/http/httptest"
"testing"
"gitea.d-ma.be/mathias/gitea-mcp/internal/mcp"
"github.com/stretchr/testify/assert"
)
func TestOriginAllowlist(t *testing.T) {
allow := []string{"https://claude.ai", "https://api.anthropic.com"}
called := false
h := mcp.OriginAllowlist(allow)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
cases := []struct {
name string
origin string
wantCode int
wantCalled bool
}{
{"allowed", "https://claude.ai", 200, true},
{"allowed-2", "https://api.anthropic.com", 200, true},
{"forbidden", "https://evil.example", 403, false},
{"empty allowed (server-side caller)", "", 200, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
called = false
req := httptest.NewRequest(http.MethodPost, "/", nil)
if tc.origin != "" {
req.Header.Set("Origin", tc.origin)
}
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
assert.Equal(t, tc.wantCode, rr.Code)
assert.Equal(t, tc.wantCalled, called)
})
}
}