Files
scrabble-game/gateway/internal/connectsrv/metrics.go
T
Ilia Denisov 041106d623
CI / changes (pull_request) Successful in 3s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 17s
CI / ui (pull_request) Successful in 53s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m11s
feat(gateway): temporary IP ban (fail2ban) fed by rejections + honeypot/honeytoken
Add a prod-only, in-memory IP ban enforced at the edge, fed by three signals:
sustained rate-limiter rejections (the IP-keyed public/email/admin classes — the
user class stays the backend soft-flag's concern), a honeypot decoy-path hit (the
contour caddy tags decoys with X-Scrabble-Honeypot and routes them to the gateway),
and a honeytoken (a planted bearer, GATEWAY_HONEYTOKEN). A banned IP is refused with
429 by the abuseGuard middleware before any work — covering the Connect edge, the
live stream and the static SPA/landing the per-op limiter never gated.

The ban is off by default: it keys by the real client IP the shared-NAT test contour
does not expose, so a ban there would be self-inflicted; detection still logs in the
contour, only the ban action is gated (GATEWAY_ABUSE_BAN_ENABLED). Rejection bans last
GATEWAY_ABUSE_BAN_DURATION; tripwire/honeytoken hits are near-zero-false-positive and
earn longer fixed bans. Each ban increments gateway_abuse_banned_total{reason}.

Operators see and lift active bans on the admin console's Throttled page; the gateway
syncs its active set to the backend every 30s (POST /api/v1/internal/bans/sync,
backend/internal/banview) and applies the operator unbans the response returns.

PRERELEASE phase AG. Docs baked into ARCHITECTURE / FUNCTIONAL (+ru) / both READMEs.
2026-06-21 08:54:20 +02:00

101 lines
3.8 KiB
Go

package connectsrv
import (
"context"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/metric/noop"
)
// meterName scopes the gateway edge's OpenTelemetry instruments.
const meterName = "scrabble/gateway/edge"
// activeUserWindows are the rolling windows the active_users gauge reports.
var activeUserWindows = []struct {
label string
dur time.Duration
}{
{label: "24h", dur: 24 * time.Hour},
{label: "7d", dur: 7 * 24 * time.Hour},
}
// serverMetrics holds the edge's operational instruments. It defaults to no-ops;
// NewServer installs the real meter when one is supplied in Deps.
type serverMetrics struct {
edge metric.Float64Histogram
rateLimited metric.Int64Counter
banned metric.Int64Counter
active *activeUsers
}
// newServerMetrics builds the instruments on meter (nil selects a no-op meter),
// falling back to a no-op histogram on the (rare) construction error. The
// active_users gauge is registered as an observable callback over the in-memory
// tracker.
func newServerMetrics(meter metric.Meter) *serverMetrics {
if meter == nil {
meter = noop.NewMeterProvider().Meter(meterName)
}
h, err := meter.Float64Histogram("edge_request_duration",
metric.WithUnit("s"),
metric.WithDescription("Seconds to serve one Connect Execute call, by message type and result."))
if err != nil {
h, _ = noop.NewMeterProvider().Meter(meterName).Float64Histogram("edge_request_duration")
}
c, err := meter.Int64Counter("gateway_rate_limited_total",
metric.WithDescription("Rate-limiter rejections at the edge, by limiter class (user, public, email or admin) — aggregate only, no per-user attributes."))
if err != nil {
c, _ = noop.NewMeterProvider().Meter(meterName).Int64Counter("gateway_rate_limited_total")
}
b, err := meter.Int64Counter("gateway_abuse_banned_total",
metric.WithDescription("Temporary IP bans applied at the edge, by reason (rejections, tripwire or honeytoken)."))
if err != nil {
b, _ = noop.NewMeterProvider().Meter(meterName).Int64Counter("gateway_abuse_banned_total")
}
m := &serverMetrics{edge: h, rateLimited: c, banned: b, active: newActiveUsers()}
gauge, err := meter.Int64ObservableGauge("active_users",
metric.WithDescription("Distinct accounts that performed an authenticated action within the window (in-memory, single gateway instance)."))
if err == nil {
windows := make([]time.Duration, len(activeUserWindows))
for i, w := range activeUserWindows {
windows[i] = w.dur
}
_, _ = meter.RegisterCallback(func(_ context.Context, o metric.Observer) error {
counts := m.active.counts(windows)
for i, w := range activeUserWindows {
o.ObserveInt64(gauge, int64(counts[i]), metric.WithAttributes(attribute.String("window", w.label)))
}
return nil
}, gauge)
}
return m
}
// recordEdge records the duration of one Execute call labelled by message type and
// outcome (ok, domain, unauthenticated, rate_limited, unknown_type or internal).
func (m *serverMetrics) recordEdge(ctx context.Context, msgType, result string, start time.Time) {
m.edge.Record(ctx, time.Since(start).Seconds(), metric.WithAttributes(
attribute.String("message_type", msgType),
attribute.String("result", result),
))
}
// recordActive marks account uid active now, feeding the active_users gauge.
func (m *serverMetrics) recordActive(uid string) {
m.active.seen(uid)
}
// recordRateLimited counts one limiter rejection under class.
func (m *serverMetrics) recordRateLimited(ctx context.Context, class string) {
m.rateLimited.Add(ctx, 1, metric.WithAttributes(attribute.String("class", class)))
}
// recordBan counts one temporary IP ban under reason (rejections, tripwire or
// honeytoken).
func (m *serverMetrics) recordBan(ctx context.Context, reason string) {
m.banned.Add(ctx, 1, metric.WithAttributes(attribute.String("reason", reason)))
}