Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion apps/api/cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
8 changes: 8 additions & 0 deletions apps/api/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
}
Expand Down
22 changes: 22 additions & 0 deletions apps/api/internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand Down
24 changes: 21 additions & 3 deletions apps/api/internal/realtime/httpapi/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
66 changes: 64 additions & 2 deletions apps/api/internal/realtime/httpapi/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand All @@ -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))
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
}
}
46 changes: 46 additions & 0 deletions apps/api/internal/realtime/httpapi/limiter.go
Original file line number Diff line number Diff line change
@@ -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]
}
60 changes: 60 additions & 0 deletions apps/api/internal/realtime/httpapi/limiter_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
8 changes: 7 additions & 1 deletion contracts/asyncapi.yaml
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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).

Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion docs/architecture/container-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ operators.
- **`/ws` endpoint** (`internal/realtime/httpapi`): the access token travels as
the `bearer.<token>` 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
Expand Down
8 changes: 6 additions & 2 deletions docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Loading