package httpapi import ( "crypto/rand" "crypto/sha256" "encoding/hex" "fmt" "log/slog" "net/http" "net/url" "strings" "sync" "time" "github.com/gin-gonic/gin" ) type operationSample struct { Count uint64 Seconds float64 } type Operations struct { mu sync.Mutex samples map[string]operationSample buckets map[string]rateBucket now func() time.Time logger *slog.Logger nextSweep time.Time limiter EntryLimiter } type rateBucket struct { start time.Time count int } func NewOperations(logger *slog.Logger) *Operations { return &Operations{samples: make(map[string]operationSample), buckets: make(map[string]rateBucket), now: time.Now, logger: logger} } func operation(path string) string { switch path { case "/api/v1/payments/checkout": return "payment_checkout" case "/api/v1/payments/:channel/notify": return "payment_notify" case "/api/v1/client/plans", "/api/v1/client/purchases", "/api/v1/client/purchases/status", "/api/v1/client/purchases/claim": return "client_purchase" case "/api/v1/portal/snapshot": return "login" case "/api/v1/auth/login": return "login" case "/api/v1/activation/instances/:instance_id": return "activation" case "/api/v1/instances/:instance_id/heartbeat": return "heartbeat" case "/api/v1/customers/:customer_id/releases/:id/download": return "download" } if strings.HasPrefix(path, "/api/v1/licenses") { return "authorization" } return "other" } // Local fixed-window limits are deliberately per process, never a distributed guarantee. func (o *Operations) allow(key string, limit int) bool { o.mu.Lock() defer o.mu.Unlock() now := o.now() if !now.Before(o.nextSweep) { for k, b := range o.buckets { if now.Sub(b.start) >= time.Minute { delete(o.buckets, k) } } o.nextSweep = now.Add(time.Minute) } b, exists := o.buckets[key] if !exists && len(o.buckets) >= 10000 { return false } if !exists || now.Sub(b.start) >= time.Minute { b = rateBucket{start: now} } if b.count >= limit { return false } b.count++ o.buckets[key] = b return true } func (o *Operations) Middleware() gin.HandlerFunc { return func(c *gin.Context) { raw := make([]byte, 16) if _, err := rand.Read(raw); err != nil { c.AbortWithStatus(http.StatusServiceUnavailable) return } id := hex.EncodeToString(raw) c.Set("request_id", id) c.Header("X-Request-ID", id) started := time.Now() path := c.FullPath() op := operation(path) defer func() { elapsed := time.Since(started).Seconds() outcome := "success" if c.Writer.Status() >= 400 { outcome = "failure" } key := op + "/" + outcome o.mu.Lock() sample := o.samples[key] sample.Count++ sample.Seconds += elapsed o.samples[key] = sample o.mu.Unlock() // No bodies, query strings, raw paths, IPs, cookies, headers, SQL errors or panic values. o.logger.Info("http_request", "request_id", id, "trace_id", id, "route", path, "operation", op, "status", c.Writer.Status(), "error_code", c.GetString("error_code"), "duration_seconds", elapsed) }() defer func() { if recover() != nil { apiError(c, 500, "internal_error", "Service unavailable") c.Abort() } }() if op == "login" || op == "activation" || op == "heartbeat" || op == "download" || op == "payment_checkout" || op == "payment_notify" || op == "client_purchase" { limit := 60 if op == "payment_notify" { limit = 600 } if op == "client_purchase" { limit = 60 } if op == "login" { limit = 10 } sum := sha256.Sum256([]byte(c.ClientIP())) key := op + hex.EncodeToString(sum[:]) allowed := false if o.limiter != nil { var err error allowed, err = o.limiter.Allow(c.Request.Context(), key, limit) if err != nil { apiError(c, 503, "rate_limit_unavailable", "Service unavailable") c.Abort() return } } else { allowed = o.allow(key, limit) } if !allowed { c.Header("Retry-After", "60") apiError(c, 429, "rate_limited", "Too many requests") c.Abort() return } } if c.Request.Method != "GET" && c.Request.Method != "HEAD" && c.Request.Method != "OPTIONS" { origin := c.GetHeader("Origin") if origin != "" { u, err := url.Parse(origin) scheme := "http" if secureSessionCookie(c) { scheme = "https" } if err != nil || u.Host != c.Request.Host || u.Scheme != scheme || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { apiError(c, 403, "origin_forbidden", "Cross-origin request denied") c.Abort() return } } if c.GetHeader("Sec-Fetch-Site") == "cross-site" { apiError(c, 403, "origin_forbidden", "Cross-site request denied") c.Abort() return } } // Uploads have their own streaming bounds (releases 64 MiB; suffix templates // bound in their handler); other JSON routes get a 64 KiB ceiling. if !(path == "/api/v1/products/:id/releases" && c.Request.Method == "POST") && !(path == "/api/v1/suffix-admin/suffixes/:id/files" && c.Request.Method == "POST") { if c.Request.ContentLength > 64<<10 { apiError(c, 413, "body_too_large", "Request body too large") c.Abort() return } c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<10) } c.Next() } } // Expose only on a separate loopback/private monitoring listener, never the public router. func (o *Operations) Metrics(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; version=0.0.4") o.mu.Lock() defer o.mu.Unlock() fmt.Fprintln(w, "# TYPE license_requests_total counter\n# TYPE license_request_duration_seconds_sum counter") for key, s := range o.samples { parts := strings.Split(key, "/") fmt.Fprintf(w, "license_requests_total{operation=%q,outcome=%q} %d\nlicense_request_duration_seconds_sum{operation=%q,outcome=%q} %g\n", parts[0], parts[1], s.Count, parts[0], parts[1], s.Seconds) } }