auth.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package mcp
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/gnacho/netpulse/server-go/internal/apitoken"
  9. "github.com/gnacho/netpulse/server-go/internal/auth"
  10. )
  11. // Handler devuelve el handler HTTP de /mcp: rate limit por IP → auth Bearer
  12. // por API token → servidor MCP streamable-HTTP. La cadena va en este orden
  13. // para que el brute-force de tokens también quede limitado.
  14. //
  15. // SOLO acepta API tokens (internal/apitoken): nunca la cookie de sesión, para
  16. // no mezclar superficies CSRF con clientes AI (spec fase 3.5). Cualquier scope
  17. // válido (read/write/admin) basta: la primera tanda de tools es solo lectura.
  18. func (s *Server) Handler(tokens *apitoken.Store) http.Handler {
  19. // Sin token store el endpoint NO se sirve sin auth: fail-closed (el MCP
  20. // nunca debe quedar abierto; main solo lo construye con tokenStore, pero
  21. // la defensa va aquí, en la última capa antes del handler).
  22. if tokens == nil {
  23. return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  24. w.Header().Set("Content-Type", "application/json")
  25. w.WriteHeader(http.StatusServiceUnavailable)
  26. _, _ = w.Write([]byte(`{"error":"mcp_auth_unavailable"}`))
  27. })
  28. }
  29. return rateLimit(s.ratePerMin, bearerOnly(tokens, http.Handler(s.http)))
  30. }
  31. // bearerOnly exige Authorization: Bearer <api token> válido. Sin token, con
  32. // token mal formado o inválido → 401 {error: unauthorized}.
  33. func bearerOnly(tokens *apitoken.Store, next http.Handler) http.Handler {
  34. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  35. raw := bearerToken(r)
  36. if raw == "" || tokens.Validate(raw) == nil {
  37. w.Header().Set("Content-Type", "application/json")
  38. w.WriteHeader(http.StatusUnauthorized)
  39. _, _ = w.Write([]byte(`{"error":"unauthorized"}`))
  40. return
  41. }
  42. next.ServeHTTP(w, r)
  43. })
  44. }
  45. func bearerToken(r *http.Request) string {
  46. v := r.Header.Get("Authorization")
  47. if !strings.HasPrefix(v, "Bearer ") {
  48. return ""
  49. }
  50. return strings.TrimPrefix(v, "Bearer ")
  51. }
  52. // rlBucket es la ventana deslizante de un cliente (por IP).
  53. type rlBucket struct {
  54. window time.Time
  55. count int
  56. }
  57. // rateLimit limita /mcp por IP (ventana fija de 1 minuto). Sin tokens ni
  58. // estado externo: brute-force de tokens queda acotado a ratePerMin intentos/min.
  59. func rateLimit(perMin int, next http.Handler) http.Handler {
  60. var mu sync.Mutex
  61. buckets := map[string]*rlBucket{}
  62. window := time.Minute
  63. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  64. ip := clientIP(r)
  65. now := time.Now()
  66. mu.Lock()
  67. b := buckets[ip]
  68. if b == nil || now.Sub(b.window) >= window {
  69. b = &rlBucket{window: now}
  70. buckets[ip] = b
  71. }
  72. b.count++
  73. full := b.count > perMin
  74. mu.Unlock()
  75. if full {
  76. w.Header().Set("Content-Type", "application/json")
  77. w.WriteHeader(http.StatusTooManyRequests)
  78. _ = json.NewEncoder(w).Encode(map[string]string{"error": "rate_limited"})
  79. return
  80. }
  81. next.ServeHTTP(w, r)
  82. })
  83. }
  84. // clientIP prefiere X-Forwarded-For solo si el proceso confía en proxy
  85. // (misma regla global que internal/auth: sin TRUST_PROXY el header no es
  86. // fiable y se usa RemoteAddr).
  87. func clientIP(r *http.Request) string {
  88. if auth.TrustProxy() {
  89. if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
  90. if first := strings.TrimSpace(strings.Split(xff, ",")[0]); first != "" {
  91. return first
  92. }
  93. }
  94. }
  95. host := r.RemoteAddr
  96. if i := strings.LastIndex(host, ":"); i > 0 {
  97. host = host[:i]
  98. }
  99. return host
  100. }