diff --git a/.env.example b/.env.example index 5b9cf96..3f530fb 100644 --- a/.env.example +++ b/.env.example @@ -23,6 +23,9 @@ JWT_ACCESS_TOKEN_TTL=15m # How often the realtime relay polls the transactional outbox. OUTBOX_POLL_INTERVAL=500ms +# Maximum concurrent /ws event streams per user (extra handshakes get 429). +WS_MAX_CONNECTIONS_PER_USER=5 + # Demo account passwords for `go run ./cmd/api seed-users` (operator@example.com, # admin@example.com). SAFE example dev values only. DEMO_OPERATOR_PASSWORD=operator_dev_password diff --git a/apps/api/cmd/api/main.go b/apps/api/cmd/api/main.go index deff9b1..92e7133 100644 --- a/apps/api/cmd/api/main.go +++ b/apps/api/cmd/api/main.go @@ -268,7 +268,7 @@ func run() error { PublicModules: []httpserver.RouteRegistrar{ httpserver.RegistrarFunc(authHandler.RegisterPublicRoutes), // /ws authenticates its own handshake (token in a subprotocol). - realtimehttp.NewHandler(hub, verifier, cfg.CORSAllowedOrigins, logger), + realtimehttp.NewHandler(hub, verifier, cfg.CORSAllowedOrigins, cfg.WSMaxConnectionsPerUser, logger), }, Modules: []httpserver.RouteRegistrar{ httpserver.RegistrarFunc(authHandler.RegisterProtectedRoutes), diff --git a/apps/api/internal/config/config.go b/apps/api/internal/config/config.go index 00e2d64..50539a6 100644 --- a/apps/api/internal/config/config.go +++ b/apps/api/internal/config/config.go @@ -48,6 +48,8 @@ type Config struct { // OutboxPollInterval is how often the realtime relay polls for unpublished // outbox events. OutboxPollInterval time.Duration + // WSMaxConnectionsPerUser caps each user's concurrent /ws streams. + WSMaxConnectionsPerUser int } // Addr returns the host:port the HTTP server should bind to. @@ -109,6 +111,9 @@ func Load(getenv func(string) string) (*Config, error) { if cfg.OutboxPollInterval, err = durationEnv(getenv, "OUTBOX_POLL_INTERVAL", 500*time.Millisecond); err != nil { return nil, err } + if cfg.WSMaxConnectionsPerUser, err = intEnv(getenv, "WS_MAX_CONNECTIONS_PER_USER", 5); err != nil { + return nil, err + } if err := cfg.Validate(); err != nil { return nil, err @@ -136,6 +141,9 @@ func (c Config) Validate() error { if !strings.HasPrefix(c.DatabaseURL, "postgres://") && !strings.HasPrefix(c.DatabaseURL, "postgresql://") { return fmt.Errorf("config: DATABASE_URL must be a postgres:// or postgresql:// connection string") } + if c.WSMaxConnectionsPerUser < 1 { + return fmt.Errorf("config: WS_MAX_CONNECTIONS_PER_USER %d must be at least 1", c.WSMaxConnectionsPerUser) + } if len(c.JWTSigningSecret) < 32 { return fmt.Errorf("config: JWT_SIGNING_SECRET must be at least 32 characters") } diff --git a/apps/api/internal/config/config_test.go b/apps/api/internal/config/config_test.go index da12270..d837a4f 100644 --- a/apps/api/internal/config/config_test.go +++ b/apps/api/internal/config/config_test.go @@ -98,6 +98,26 @@ func TestLoad_OutboxPollIntervalDefaultAndOverride(t *testing.T) { } } +func TestLoad_WSMaxConnectionsPerUser(t *testing.T) { + cfg, err := Load(envFunc(validEnv())) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if cfg.WSMaxConnectionsPerUser != 5 { + t.Errorf("WSMaxConnectionsPerUser = %d, want 5", cfg.WSMaxConnectionsPerUser) + } + + env := validEnv() + env["WS_MAX_CONNECTIONS_PER_USER"] = "2" + cfg, err = Load(envFunc(env)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if cfg.WSMaxConnectionsPerUser != 2 { + t.Errorf("WSMaxConnectionsPerUser = %d, want 2", cfg.WSMaxConnectionsPerUser) + } +} + func TestLoad_ValidationErrors(t *testing.T) { tests := []struct { name string @@ -117,6 +137,8 @@ func TestLoad_ValidationErrors(t *testing.T) { {"zero jwt ttl", func(m map[string]string) { m["JWT_ACCESS_TOKEN_TTL"] = "0s" }}, {"non-duration outbox poll interval", func(m map[string]string) { m["OUTBOX_POLL_INTERVAL"] = "often" }}, {"negative outbox poll interval", func(m map[string]string) { m["OUTBOX_POLL_INTERVAL"] = "-1s" }}, + {"zero ws connection cap", func(m map[string]string) { m["WS_MAX_CONNECTIONS_PER_USER"] = "0" }}, + {"non-integer ws connection cap", func(m map[string]string) { m["WS_MAX_CONNECTIONS_PER_USER"] = "many" }}, {"published example secret in staging", func(m map[string]string) { m["APP_ENV"] = "staging" m["JWT_SIGNING_SECRET"] = "dev_only_example_secret_change_me_32+chars" diff --git a/apps/api/internal/realtime/httpapi/handler.go b/apps/api/internal/realtime/httpapi/handler.go index cbe6b82..869d966 100644 --- a/apps/api/internal/realtime/httpapi/handler.go +++ b/apps/api/internal/realtime/httpapi/handler.go @@ -40,20 +40,28 @@ type Handler struct { hub *realtime.Hub verifier TokenVerifier originPatterns []string + limiter *connLimiter log *slog.Logger } // NewHandler constructs a Handler. allowedOrigins are the browser origins // (e.g. http://localhost:5173) permitted to open cross-origin connections; -// same-origin connections are always allowed. -func NewHandler(hub *realtime.Hub, verifier TokenVerifier, allowedOrigins []string, log *slog.Logger) *Handler { +// same-origin connections are always allowed. maxPerUser caps each user's +// concurrent streams and must be at least 1. +func NewHandler(hub *realtime.Hub, verifier TokenVerifier, allowedOrigins []string, maxPerUser int, log *slog.Logger) *Handler { patterns := make([]string, 0, len(allowedOrigins)) for _, o := range allowedOrigins { if u, err := url.Parse(o); err == nil && u.Host != "" { patterns = append(patterns, u.Host) } } - return &Handler{hub: hub, verifier: verifier, originPatterns: patterns, log: log} + return &Handler{ + hub: hub, + verifier: verifier, + originPatterns: patterns, + limiter: newConnLimiter(maxPerUser), + log: log, + } } // RegisterRoutes mounts /ws. It authenticates the handshake itself, so it must @@ -80,6 +88,16 @@ func (h *Handler) serve(w http.ResponseWriter, r *http.Request) { return } + // Reserve the user's slot before upgrading so a rejected handshake costs + // no WebSocket resources. The slot is held until the stream ends, however + // it ends, including a failed upgrade. + if !h.limiter.acquire(claims.UserID) { + h.log.WarnContext(r.Context(), "realtime: connection limit reached", slog.String("user_id", claims.UserID)) + web.WriteError(w, http.StatusTooManyRequests, "TOO_MANY_CONNECTIONS", "too many concurrent event streams for this user") + return + } + defer h.limiter.release(claims.UserID) + // The server's read/write timeouts are connection deadlines that survive // the upgrade; clear them so the stream outlives them. Pings and per-write // timeouts bound a dead peer instead. diff --git a/apps/api/internal/realtime/httpapi/handler_test.go b/apps/api/internal/realtime/httpapi/handler_test.go index b3d2642..1d417b8 100644 --- a/apps/api/internal/realtime/httpapi/handler_test.go +++ b/apps/api/internal/realtime/httpapi/handler_test.go @@ -31,6 +31,8 @@ func (fakeVerifier) Verify(token string) (auth.Claims, error) { return auth.Claims{UserID: "u1", Role: auth.RoleOperator, ExpiresAt: time.Now().Add(time.Hour)}, nil case "short": return auth.Claims{UserID: "u1", Role: auth.RoleOperator, ExpiresAt: time.Now().Add(150 * time.Millisecond)}, nil + case "other": + return auth.Claims{UserID: "u2", Role: auth.RoleOperator, ExpiresAt: time.Now().Add(time.Hour)}, nil default: return auth.Claims{}, errors.New("invalid token") } @@ -40,10 +42,16 @@ func (fakeVerifier) Verify(token string) (auth.Claims, error) { // server with deliberately short read/write timeouts, which the handler must // clear for long-lived streams. func newServer(t *testing.T) (*httptest.Server, *realtime.Hub) { + t.Helper() + srv, hub, _ := newServerWithLimit(t, 10) + return srv, hub +} + +func newServerWithLimit(t *testing.T, maxPerUser int) (*httptest.Server, *realtime.Hub, *Handler) { t.Helper() log := slog.New(slog.NewTextHandler(io.Discard, nil)) hub := realtime.NewHub(log) - h := NewHandler(hub, fakeVerifier{}, []string{"http://allowed.example"}, log) + h := NewHandler(hub, fakeVerifier{}, []string{"http://allowed.example"}, maxPerUser, log) r := chi.NewRouter() r.Use(httpserver.AccessLog(log)) @@ -54,7 +62,7 @@ func newServer(t *testing.T) (*httptest.Server, *realtime.Hub) { srv.Config.WriteTimeout = serverTimeout srv.Start() t.Cleanup(srv.Close) - return srv, hub + return srv, hub, h } func wsURL(srv *httptest.Server) string { @@ -277,3 +285,57 @@ func TestParseSubprotocols(t *testing.T) { t.Errorf("got (%q, %v), want (a.b-c_d, true)", token, ok) } } + +func TestServe_ConnectionLimitPerUser(t *testing.T) { + srv, _, h := newServerWithLimit(t, 2) + + first, _, err := dial(t, srv, "finwatch.v1", "bearer.valid") + if err != nil { + t.Fatalf("first dial: %v", err) + } + if _, _, err := dial(t, srv, "finwatch.v1", "bearer.valid"); err != nil { + t.Fatalf("second dial: %v", err) + } + + _, resp, err := dial(t, srv, "finwatch.v1", "bearer.valid") + if err == nil || resp == nil || resp.StatusCode != http.StatusTooManyRequests { + t.Fatalf("third dial: err=%v resp=%v, want 429", err, resp) + } + var env struct { + Error struct{ Code string } `json:"error"` + } + if err := json.NewDecoder(resp.Body).Decode(&env); err != nil || env.Error.Code != "TOO_MANY_CONNECTIONS" { + t.Errorf("error code = %q (decode err %v), want TOO_MANY_CONNECTIONS", env.Error.Code, err) + } + + // Another user has their own budget. + if _, _, err := dial(t, srv, "finwatch.v1", "bearer.other"); err != nil { + t.Fatalf("other user's dial: %v", err) + } + + // Closing a stream frees its slot. + _ = first.Close(websocket.StatusNormalClosure, "bye") + waitFor(t, func() bool { return h.limiter.count("u1") == 1 }) + if _, _, err := dial(t, srv, "finwatch.v1", "bearer.valid"); err != nil { + t.Fatalf("dial after a slot freed: %v", err) + } +} + +func TestServe_FailedUpgradeReleasesSlot(t *testing.T) { + srv, _, h := newServerWithLimit(t, 1) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _, resp, err := websocket.Dial(ctx, wsURL(srv), &websocket.DialOptions{ + Subprotocols: []string{"finwatch.v1", "bearer.valid"}, + HTTPHeader: http.Header{"Origin": []string{"http://evil.example"}}, + }) + if err == nil || resp == nil || resp.StatusCode != http.StatusForbidden { + t.Fatalf("err=%v resp=%v, want 403", err, resp) + } + waitFor(t, func() bool { return h.limiter.count("u1") == 0 }) + + if _, _, err := dial(t, srv, "finwatch.v1", "bearer.valid"); err != nil { + t.Fatalf("dial after a rejected upgrade: %v", err) + } +} diff --git a/apps/api/internal/realtime/httpapi/limiter.go b/apps/api/internal/realtime/httpapi/limiter.go new file mode 100644 index 0000000..4063a10 --- /dev/null +++ b/apps/api/internal/realtime/httpapi/limiter.go @@ -0,0 +1,46 @@ +package httpapi + +import "sync" + +// connLimiter caps concurrent streams per user. It is in-process, matching the +// single-instance deployment in ADR 0003. +type connLimiter struct { + max int + + mu sync.Mutex + active map[string]int +} + +func newConnLimiter(max int) *connLimiter { + return &connLimiter{max: max, active: make(map[string]int)} +} + +// acquire reserves a slot for user, reporting false when the user is already +// at the limit. Every successful acquire must be paired with one release. +func (l *connLimiter) acquire(user string) bool { + l.mu.Lock() + defer l.mu.Unlock() + if l.active[user] >= l.max { + return false + } + l.active[user]++ + return true +} + +// release frees a slot taken by acquire. +func (l *connLimiter) release(user string) { + l.mu.Lock() + defer l.mu.Unlock() + if l.active[user] <= 1 { + delete(l.active, user) + return + } + l.active[user]-- +} + +// count reports the user's active slots. +func (l *connLimiter) count(user string) int { + l.mu.Lock() + defer l.mu.Unlock() + return l.active[user] +} diff --git a/apps/api/internal/realtime/httpapi/limiter_test.go b/apps/api/internal/realtime/httpapi/limiter_test.go new file mode 100644 index 0000000..b6edd1a --- /dev/null +++ b/apps/api/internal/realtime/httpapi/limiter_test.go @@ -0,0 +1,60 @@ +package httpapi + +import ( + "sync" + "sync/atomic" + "testing" +) + +func TestConnLimiter_EnforcesPerUserMax(t *testing.T) { + l := newConnLimiter(2) + if !l.acquire("a") || !l.acquire("a") { + t.Fatal("first two acquires for a should succeed") + } + if l.acquire("a") { + t.Fatal("third acquire for a should fail") + } + if !l.acquire("b") { + t.Fatal("b has its own budget") + } + + l.release("a") + if !l.acquire("a") { + t.Fatal("acquire after release should succeed") + } + + l.release("a") + l.release("a") + l.release("b") + if len(l.active) != 0 { + t.Errorf("active = %v, want empty after releasing everything", l.active) + } +} + +func TestConnLimiter_ConcurrentAcquire(t *testing.T) { + const max, callers = 5, 100 + l := newConnLimiter(max) + + var granted atomic.Int32 + var wg sync.WaitGroup + for range callers { + wg.Add(1) + go func() { + defer wg.Done() + if l.acquire("u") { + granted.Add(1) + } + }() + } + wg.Wait() + + if got := granted.Load(); got != max { + t.Fatalf("granted %d slots, want %d", got, max) + } + for range max { + l.release("u") + } + if l.count("u") != 0 || len(l.active) != 0 { + t.Errorf("count = %d, active = %v, want all released", l.count("u"), l.active) + } +} diff --git a/contracts/asyncapi.yaml b/contracts/asyncapi.yaml index d6a0876..e7e3542 100644 --- a/contracts/asyncapi.yaml +++ b/contracts/asyncapi.yaml @@ -1,7 +1,7 @@ asyncapi: 3.0.0 info: title: FinWatch Realtime API - version: 0.2.0 + version: 0.3.0 description: | WebSocket/event contract for FinWatch. Real-time delivery uses a PostgreSQL transactional outbox relayed to an in-process WebSocket hub (no external @@ -20,6 +20,12 @@ info: server verifies the token before upgrading and selects `finwatch.v1`. A missing or invalid token is rejected with HTTP 401 and the canonical error envelope; the upgrade does not happen. + * Each user may hold at most `WS_MAX_CONNECTIONS_PER_USER` (default 5) + concurrent streams, counted by the token's subject. A handshake beyond + the limit is rejected before upgrading with HTTP 429 and the canonical + error envelope (`TOO_MANY_CONNECTIONS`). Browsers surface this only as + a failed connection (close 1006); retrying with backoff succeeds once + one of the user's other streams closes. * The stream is server-to-client only. A client data message closes the connection with 1008 (policy violation). diff --git a/docker-compose.yml b/docker-compose.yml index 4010769..8fbc81b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -38,6 +38,7 @@ services: JWT_SIGNING_SECRET: ${JWT_SIGNING_SECRET:-dev_only_example_secret_change_me_32+chars} JWT_ACCESS_TOKEN_TTL: ${JWT_ACCESS_TOKEN_TTL:-15m} OUTBOX_POLL_INTERVAL: ${OUTBOX_POLL_INTERVAL:-500ms} + WS_MAX_CONNECTIONS_PER_USER: ${WS_MAX_CONNECTIONS_PER_USER:-5} DEMO_OPERATOR_PASSWORD: ${DEMO_OPERATOR_PASSWORD:-operator_dev_password} DEMO_ADMIN_PASSWORD: ${DEMO_ADMIN_PASSWORD:-admin_dev_password} ports: diff --git a/docs/architecture/container-design.md b/docs/architecture/container-design.md index d90951e..b8f2af2 100644 --- a/docs/architecture/container-design.md +++ b/docs/architecture/container-design.md @@ -56,7 +56,8 @@ operators. - **`/ws` endpoint** (`internal/realtime/httpapi`): the access token travels as the `bearer.` subprotocol next to `finwatch.v1`, is verified before the upgrade, and the connection closes with 1008 when the token expires. - Cross-origin handshakes must come from `CORS_ALLOWED_ORIGINS`. + Cross-origin handshakes must come from `CORS_ALLOWED_ORIGINS`, and each + user may hold at most `WS_MAX_CONNECTIONS_PER_USER` streams (429 beyond it). - **Web app**: `useRealtimeEvents` keeps one socket open while signed in, de-duplicates on envelope `id`, and invalidates the `transactions` / `alerts` TanStack Query keys; every (re)connect invalidates both because there is no diff --git a/docs/threat-model.md b/docs/threat-model.md index fcfc12e..f831e03 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -27,7 +27,7 @@ and contribute to. | **Tampering** | Malformed/oversized requests | Bounded HTTP timeouts; input validated at handlers (per-feature) | Schema validation against OpenAPI | | **Repudiation** | No trace of actions | Per-request IDs + structured access logs; rule changes log `rule_id`, `enabled` and the acting `user_id` | Persistent audit log for state changes | | **Information disclosure** | Secrets/PII leakage | No secrets in repo; synthetic data only; logs exclude secrets/PII | Secret scanning, log review | -| **Denial of service** | Slow-client / resource exhaustion | Read/write/idle timeouts; panic recovery; graceful shutdown; WebSocket clients that fall behind are dropped instead of blocking fan-out, and dead peers are detected by pings and per-write timeouts | Rate limiting on `POST /login` (bcrypt cost makes it both a brute-force target and a CPU sink), connection caps | +| **Denial of service** | Slow-client / resource exhaustion | Read/write/idle timeouts; panic recovery; graceful shutdown; WebSocket clients that fall behind are dropped instead of blocking fan-out, and dead peers are detected by pings and per-write timeouts; at most `WS_MAX_CONNECTIONS_PER_USER` concurrent streams per user (429 before upgrade) | Rate limiting on `POST /login` (bcrypt cost makes it both a brute-force target and a CPU sink), global/per-IP connection caps | | **Elevation of privilege** | Acting beyond role | Role checked server-side from the verified token: `PATCH /rules/{id}` requires `admin` (`RequireRole`), operators get 403; reads and alert workflow stay open to both roles | Role-aware UI (hide admin actions from operators) | ## Supply chain @@ -60,4 +60,8 @@ model when implemented. browser, so a hostile page cannot ride an operator's session. - **Token lifetime:** an open stream is closed (1008) when its token expires, so a connection cannot outlive the credential that opened it. -- **Planned:** per-user connection caps. +- **Resource exhaustion:** each user may hold at most + `WS_MAX_CONNECTIONS_PER_USER` (default 5) concurrent streams, counted by + the verified token subject. Extra handshakes are rejected with 429 before + the upgrade, so they cost no WebSocket resources. +- **Planned:** global or per-IP connection caps.