caelum0x 31be78e465 fix(gateway): REST facade's unscoped routes shared one rate-limit bucket across every caller
GetDashboardSnapshot and StreamActivity (empty tenant_id, the documented
"all tenants" mode) carry no tenant_id/card_id, so internal/ratelimit's
gRPC-layer interceptor falls back to peer-address keying. But the REST
facade reaches gateway's own gRPC server over one single, long-lived
self-dial connection (cmd/gateway/main.go's selfConn) — so every REST
caller of GET /v1/dashboard/snapshot, GET /v1/dashboard/activity/stream,
and GET /v1/activity (no tenant_id) collapsed into ONE shared token
bucket, the opposite of "one noisy caller can't starve every other
caller" that package promises. Most exposed on the dashboard: a public,
zero-login, judge-facing page explicitly designed for multiple
simultaneous viewers.

Add a second, HTTP-layer limiter keyed by the real client's remote
address, applied only to those three call sites — every tenant/card-
scoped route keeps its existing, already-correct gRPC-level protection
untouched.

Verified live against the real bare-metal stack: a concurrent burst of
40 connections to /v1/dashboard/activity/stream now correctly splits
30 (burst) succeed / 10 rejected with 429, keyed per real client IP;
confirmed tenant-scoped /v1/activity calls are unaffected (10/10 200s).
go build/vet/test clean for services/gateway, 0 regressions.
2026-10-29 15:35:47 +03:00

99 lines
3.0 KiB
Go

package httpapi
import (
"encoding/json"
"io"
"net/http"
gatewaypb "github.com/caelum0x/ration/pkg/pb/gateway"
)
type activityEventJSON struct {
ID string `json:"id"`
TenantID string `json:"tenant_id"`
Kind string `json:"kind"`
Summary string `json:"summary"`
AtUnix int64 `json:"at_unix"`
}
func newActivityEventJSON(e *gatewaypb.ActivityEvent) activityEventJSON {
return activityEventJSON{
ID: e.GetId(),
TenantID: e.GetTenantId(),
Kind: e.GetKind(),
Summary: e.GetSummary(),
AtUnix: e.GetAtUnix(),
}
}
// handleStreamActivity serves GET /v1/activity[?tenant_id=...] — the
// REST facade's equivalent of gateway.proto's server-streaming
// StreamActivity RPC. There is no REST/HTTP equivalent of gRPC
// streaming (see docs/adr/0003's "why gRPC first" section), so this
// handler approximates it with newline-delimited JSON
// (Content-Type: application/x-ndjson): one ActivityEvent JSON object
// per line, flushed as each event arrives, for as long as the HTTP
// client stays connected — curl -N, or any HTTP client that reads the
// response body incrementally rather than buffering it, sees events in
// real time.
func (h *Handler) handleStreamActivity(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
writeBadRequest(w, h.log, "streaming not supported by this response writer")
return
}
tenantID := r.URL.Query().Get("tenant_id")
// An empty tenant_id is the documented "all tenants" mode (this
// handler's own doc comment) — the one case where
// internal/ratelimit's gRPC-layer interceptor has no tenant_id/
// card_id to key on and falls back to "peer:<addr>", which is
// always the same collapsed loopback self-dial peer for every REST
// caller (see publiclimit.go). A non-empty tenant_id is already
// correctly per-tenant-scoped at the gRPC layer, so this check is
// skipped there to avoid double-limiting a legitimate caller.
if tenantID == "" && !h.allowPublicRoute(w, r) {
return
}
stream, err := h.client.StreamActivity(clientContext(r), &gatewaypb.StreamActivityRequest{TenantId: tenantID})
if err != nil {
writeGRPCError(w, h.log, err)
return
}
w.Header().Set("Content-Type", "application/x-ndjson")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
flusher.Flush()
enc := json.NewEncoder(w)
for {
event, err := stream.Recv()
if err == io.EOF {
return
}
if err != nil {
// Headers are already sent (streaming started) — the
// client's best signal at this point is the connection
// simply ending, so log and stop rather than attempting a
// second (invalid, after WriteHeader) status code.
h.log.Error("httpapi: StreamActivity recv failed", "error", err)
return
}
if err := enc.Encode(newActivityEventJSON(event)); err != nil {
h.log.Error("httpapi: failed encoding activity event", "error", err)
return
}
flusher.Flush()
select {
case <-r.Context().Done():
return
default:
}
}
}