Files
MrAlders0n d3e6cbd04c fix(mcp): charge every read, contain handler panics, keep cursors intact
Also sets a write deadline on MCP responses so a client that stops
reading cannot hold up change notices, and checks that an ID exists
before the find tool reports it.
2026-12-02 12:31:13 -05:00

166 lines
5.0 KiB
Go

// Copyright 2026 Beacon Contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
package mcp
import (
"crypto/sha256"
"crypto/subtle"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/go-chi/httprate"
"github.com/MeshCore-Beacon/beacon-server/internal/metrics"
)
// The access layer sets these on every request it lets through, after removing whatever the client
// sent, so handlers can trust them.
const (
headerCaller = "X-Beacon-Mcp-Caller" // key name, or "public"
headerClient = "X-Beacon-Mcp-Client" // limiter key: "key:<name>" or "ip:<addr>"
headerAddr = "X-Beacon-Mcp-Addr" // resolved client address, for the guards
)
// caller is who is behind one MCP request.
type caller struct {
name string // key name, or "public"
client string // what the limits count by
addr string
}
func callerFrom(h http.Header) caller {
c := caller{name: h.Get(headerCaller), client: h.Get(headerClient), addr: h.Get(headerAddr)}
if c.name == "" {
c.name = "public"
}
if c.client == "" {
c.client = "ip:" + c.addr
}
return c
}
type keyEntry struct {
name string
sum [sha256.Size]byte
rpm int
}
// access checks origin, key and request rate before a request reaches the MCP handler.
func (s *service) access(next http.Handler) http.Handler {
keys := make([]keyEntry, 0, len(s.cfg.Keys))
for _, k := range s.cfg.Keys {
keys = append(keys, keyEntry{name: k.Name, sum: sha256.Sum256([]byte(k.Key)), rpm: k.RequestsPerMinute})
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.originAllowed(r) {
metrics.MCPRejected.WithLabelValues("origin").Inc()
httpError(w, http.StatusForbidden, "forbidden_origin", "This origin may not call the MCP endpoint.")
return
}
addr := r.RemoteAddr
if ip, err := httprate.KeyByIP(r); err == nil {
addr = ip
}
c := caller{name: "public", client: "ip:" + addr, addr: r.RemoteAddr}
rpm := s.cfg.RequestsPerMinute
if len(keys) > 0 {
k, ok := matchKey(keys, r.Header.Get("Authorization"))
if !ok {
metrics.MCPRejected.WithLabelValues("key").Inc()
w.Header().Set("WWW-Authenticate", `Bearer realm="beacon-mcp"`)
httpError(w, http.StatusUnauthorized, "unauthorized", "A valid key is required.")
return
}
c.name, c.client, rpm = k.name, "key:"+k.name, k.rpm
}
if wait, ok := s.rate.take(c.client, rpm, 1); !ok {
metrics.MCPRejected.WithLabelValues("rate").Inc()
w.Header().Set("Retry-After", strconv.Itoa(wait))
httpError(w, http.StatusTooManyRequests, "rate_limited", "Request rate limit exceeded. Retry later.")
return
}
r.Header.Set(headerCaller, c.name)
r.Header.Set(headerClient, c.client)
r.Header.Set(headerAddr, c.addr)
// The key has done its job; keep it away from handlers and logs.
r.Header.Del("Authorization")
next.ServeHTTP(&deadlineWriter{ResponseWriter: w, rc: http.NewResponseController(w)}, r)
})
}
// matchKey compares digests in constant time so neither a key's content nor its length leaks.
func matchKey(keys []keyEntry, header string) (keyEntry, bool) {
scheme, token, ok := strings.Cut(header, " ")
if !ok || !strings.EqualFold(scheme, "Bearer") {
return keyEntry{}, false
}
sum := sha256.Sum256([]byte(strings.TrimSpace(token)))
var hit keyEntry
found := 0
for _, k := range keys {
if subtle.ConstantTimeCompare(sum[:], k.sum[:]) == 1 {
hit, found = k, 1
}
}
return hit, found == 1
}
// originAllowed passes requests with no Origin (anything that is not a browser), same-host ones, the
// web app's, and configured extras. It stops other sites' pages driving the endpoint from a browser.
func (s *service) originAllowed(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
u, err := url.Parse(origin)
if err != nil || u.Host == "" {
return false
}
if strings.EqualFold(u.Host, r.Host) {
return true
}
o := strings.ToLower(u.Scheme + "://" + u.Host)
if s.webURL != "" && o == strings.ToLower(s.webURL) {
return true
}
for _, allowed := range s.cfg.AllowedOrigins {
if o == allowed {
return true
}
}
return false
}
func httpError(w http.ResponseWriter, status int, code, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write([]byte(`{"error":{"code":"` + code + `","message":"` + message + `"}}`))
}
// writeStall is how long one write to a client may block. The HTTP server has no write timeout, so
// without this a client that stops reading a stream would hold its writer, and the notices queued
// behind it, for as long as the connection lasts.
const writeStall = 30 * time.Second
// deadlineWriter renews the connection's write deadline before every write.
type deadlineWriter struct {
http.ResponseWriter
rc *http.ResponseController
}
func (w *deadlineWriter) Write(p []byte) (int, error) {
_ = w.rc.SetWriteDeadline(time.Now().Add(writeStall))
return w.ResponseWriter.Write(p)
}
func (w *deadlineWriter) Flush() {
_ = w.rc.SetWriteDeadline(time.Now().Add(writeStall))
_ = w.rc.Flush()
}
func (w *deadlineWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }