feat(ops): protect metrics, rate-limit auth, agent secret timing, e2e smoke
Bearer для /metrics (EVOBGP_METRICS_TOKEN); rate limit /v1/auth/config; constant-time agent secret; OTel stub; Playwright smoke; HTTP_PROXY note; checklist обновлён. Co-authored-by: Cursor <[email protected]>
This commit is contained in:
@@ -2,6 +2,7 @@ package agentserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -157,7 +158,8 @@ func (s *Server) authorize(r *http.Request) bool {
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(h[len(prefix):]) == secret
|
||||
got := strings.TrimSpace(h[len(prefix):])
|
||||
return subtle.ConstantTimeCompare([]byte(got), []byte(secret)) == 1
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// authRateLimiter is a simple per-IP token bucket for public auth-ish endpoints.
|
||||
type authRateLimiter struct {
|
||||
mu sync.Mutex
|
||||
hits map[string][]time.Time
|
||||
limit int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func newAuthRateLimiter() *authRateLimiter {
|
||||
limit := 60
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(os.Getenv("EVOBGP_AUTH_RATE_LIMIT"))); err == nil && n > 0 {
|
||||
limit = n
|
||||
}
|
||||
return &authRateLimiter{
|
||||
hits: make(map[string][]time.Time),
|
||||
limit: limit,
|
||||
window: time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *authRateLimiter) allow(ip string) bool {
|
||||
if l == nil {
|
||||
return true
|
||||
}
|
||||
now := time.Now()
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
cut := now.Add(-l.window)
|
||||
arr := l.hits[ip]
|
||||
kept := arr[:0]
|
||||
for _, t := range arr {
|
||||
if t.After(cut) {
|
||||
kept = append(kept, t)
|
||||
}
|
||||
}
|
||||
if len(kept) >= l.limit {
|
||||
l.hits[ip] = kept
|
||||
return false
|
||||
}
|
||||
kept = append(kept, now)
|
||||
l.hits[ip] = kept
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) withAuthRateLimit(next http.HandlerFunc) http.HandlerFunc {
|
||||
if s.authLimiter == nil {
|
||||
s.authLimiter = newAuthRateLimiter()
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ip := clientIP(r)
|
||||
if !s.authLimiter.allow(ip) {
|
||||
writeProblem(w, http.StatusTooManyRequests, "Too Many Requests", "auth rate limit exceeded")
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
@@ -30,12 +30,12 @@ func (s *Server) Handler() http.Handler {
|
||||
s.registerV1(v1)
|
||||
wrappedV1 := http.StripPrefix("/v1", v1)
|
||||
|
||||
s.mux.Handle("GET /metrics", observability.MetricsHandler())
|
||||
s.mux.Handle("GET /metrics", observability.ProtectMetrics(observability.MetricsHandler()))
|
||||
s.mux.HandleFunc("GET /version", s.handleVersion)
|
||||
s.mux.HandleFunc("GET /v1/health", s.handleHealth)
|
||||
s.mux.HandleFunc("GET /v1/ready", s.handleReady)
|
||||
s.mux.HandleFunc("GET /v1/version", s.handleVersion)
|
||||
s.mux.HandleFunc("GET /v1/auth/config", s.handleAuthConfigPublic)
|
||||
s.mux.HandleFunc("GET /v1/auth/config", s.withAuthRateLimit(s.handleAuthConfigPublic))
|
||||
// Firewall subsystem moved to the standalone EvoFirewall service; see docs/firewall.md.
|
||||
// Registered on the public mux so it wins over the "/v1/" subtree below regardless of auth.
|
||||
s.mux.HandleFunc("/v1/firewall/", s.handleFirewallGone)
|
||||
|
||||
@@ -29,6 +29,7 @@ type Server struct {
|
||||
maintConfig *maintenance.ConfigProvider
|
||||
maintStats *maintenance.DBStatsProvider
|
||||
jobs *jobs.Registry
|
||||
authLimiter *authRateLimiter
|
||||
bundlePriv ed25519.PrivateKey
|
||||
keyResolver *apiKeyResolver
|
||||
firewallResolver *firewallTokenResolver
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
const DefaultTimeout = 45 * time.Second
|
||||
|
||||
// New returns an HTTP client with timeout and tuned idle connection pooling.
|
||||
// Standard proxy env (HTTP_PROXY / HTTPS_PROXY / NO_PROXY) is honored via the cloned DefaultTransport.
|
||||
func New(timeout time.Duration) *http.Client {
|
||||
if timeout <= 0 {
|
||||
timeout = DefaultTimeout
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ProtectMetrics wraps the Prometheus handler. When EVOBGP_METRICS_TOKEN is set,
|
||||
// scrapes must send Authorization: Bearer <token> (constant-time compare).
|
||||
// Empty token keeps /metrics open (dev / private network).
|
||||
func ProtectMetrics(next http.Handler) http.Handler {
|
||||
token := strings.TrimSpace(os.Getenv("EVOBGP_METRICS_TOKEN"))
|
||||
if token == "" {
|
||||
return next
|
||||
}
|
||||
want := []byte(token)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := r.Header.Get("Authorization")
|
||||
const p = "Bearer "
|
||||
got := ""
|
||||
if strings.HasPrefix(h, p) {
|
||||
got = strings.TrimSpace(h[len(p):])
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(got), want) != 1 {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"evobgp/internal/logging"
|
||||
)
|
||||
|
||||
// StartOTelIfEnabled is an opt-in stub for OpenTelemetry (EVOBGP_OTEL_ENDPOINT).
|
||||
// Full exporter wiring lands when the ops stack provides a collector; this logs intent only.
|
||||
func StartOTelIfEnabled(ctx context.Context) (shutdown func(context.Context) error) {
|
||||
ep := strings.TrimSpace(os.Getenv("EVOBGP_OTEL_ENDPOINT"))
|
||||
if ep == "" {
|
||||
return func(context.Context) error { return nil }
|
||||
}
|
||||
logging.Default().Info("otel opt-in enabled (stub; export not wired yet)", "endpoint", ep)
|
||||
_ = ctx
|
||||
return func(context.Context) error { return nil }
|
||||
}
|
||||
Reference in New Issue
Block a user