diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..109a9b9 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,93 @@ +# Builds the image on CI to prove the Dockerfile still works. +# +# This never pushes anywhere. There is no registry, no credentials and no tag to +# manage: the only output is a build that either succeeds or fails, which is the +# thing that was previously unverified. The xray download and its checksum are +# the fragile part -- a moved release URL, a re-signed artifact or a changed +# base image breaks the build -- and none of that shows up in `go test`. +# +# Single architecture on purpose. The Dockerfile resolves a different xray per +# TARGETARCH, and verifying both on every run would double the build time to +# re-check something that changes only when the pin does. Change the pin and +# both paths are exercised by the local build on the target machine. + +name: Docker + +on: + push: + branches: ["main"] + paths: + - "Dockerfile" + - ".dockerignore" + - "go.mod" + - "go.sum" + - "*.go" + - "web/**" + - ".github/workflows/docker.yml" + pull_request: + paths: + - "Dockerfile" + - ".dockerignore" + - "go.mod" + - "go.sum" + - "*.go" + - "web/**" + - ".github/workflows/docker.yml" + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@v4 + + - name: Set up Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build the image + uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/amd64 + # load, not push: the image has to land in the local daemon so the + # smoke test below can run it. Nothing leaves the runner. + load: true + push: false + tags: socks5-proxy:ci + cache-from: type=gha + cache-to: type=gha,mode=max + + # A successful build says the image assembles. This says it runs: the + # health endpoint answers, and the diagnostics that used to identify a + # deployment are behind auth. + - name: Smoke test the image + run: | + set -euo pipefail + docker run -d --name ci-test -p 18080:8080 socks5-proxy:ci + for i in $(seq 1 30); do + if curl -fsS http://127.0.0.1:18080/health >/dev/null 2>&1; then break; fi + if [ "$i" = "30" ]; then + echo "server never became healthy; container log:" + docker logs ci-test + exit 1 + fi + sleep 1 + done + echo " /health: $(curl -fsS http://127.0.0.1:18080/health)" + health=$(curl -fsS http://127.0.0.1:18080/health) + case "$health" in + *version*|*uptime*) echo "FAIL: /health leaks version or uptime: $health"; exit 1 ;; + esac + code=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:18080/metrics) + echo " /metrics: $code (want 401 without credentials)" + if [ "$code" != "401" ]; then + echo "FAIL: the metrics dashboard is reachable without credentials" + exit 1 + fi + # xray must be present in the image even with REALITY disabled, + # otherwise enabling it on a real host fails at startup. + docker exec ci-test xray version | head -1 + docker rm -f ci-test \ No newline at end of file diff --git a/README.md b/README.md index 276cf1c..edb5a3c 100644 --- a/README.md +++ b/README.md @@ -95,32 +95,31 @@ docker run --rm --entrypoint xray socks5-proxy x25519 # Password (PublicKey): ... -> what clients configure as "public key" ``` -**Precedence gotcha worth knowing.** The server resolves configuration in this -order, last one winning: +**How precedence actually resolves**, last one winning: ``` -built-in defaults < config.json < environment < database +built-in defaults < config.json < database < environment ``` -The database is last because the admin dashboard saves settings from the UI, and -it only ever holds those 10 keys: `max_connections`, `proxy_user`, `proxy_pass`, -`auth_enabled`, `admin_username`, `admin_pass`, `admin_auth_enabled`, -`security_headers_enabled`, `rate_limit_enabled`, `rate_limit_rps`. So on an -install where somebody has already saved settings in the dashboard, **a new -`PROXY_PASS` in `.env` is silently ignored on restart** — the stored value wins. -Either change the password from the dashboard, or clear the stored keys once: +The database holds only the 10 settings the dashboard can save: `max_connections`, +`proxy_user`, `proxy_pass`, `auth_enabled`, `admin_username`, `admin_pass`, +`admin_auth_enabled`, `security_headers_enabled`, `rate_limit_enabled` and +`rate_limit_rps`. The environment sits above it, so an explicit `.env` value is +never quietly overwritten by something saved from the browser three weeks ago — +that used to happen, and it made editing `.env` look broken. + +To hand a setting back to the database instead, unset it from `.env` and change +it in the dashboard. To clear stored settings entirely, stop the container first +and remove all three files, since SQLite runs in WAL mode: ```bash -docker exec -it sh -c 'rm -f /app/data/socks5.db /app/data/socks5.db-wal /app/data/socks5.db-shm && echo cleared' +docker compose down +rm -f data/socks5.db data/socks5.db-wal data/socks5.db-shm ``` -All three files matter: SQLite runs in WAL mode, so deleting only `socks5.db` -leaves a write-ahead log that gets replayed on the next open and puts your saved -settings straight back. - -That also drops users and usage history, so copy `data/socks5.db` out first if -you want them. `TUNNEL_*`, `REALITY_*`, timeouts and limits are never stored, so -those always come from your file or environment. +That also drops users and usage history, so copy `data/socks5.db` out first if you +want them. `TUNNEL_*`, `REALITY_*`, timeouts and limits are never stored, so they +always come from your file or environment. ### Docker Compose @@ -292,6 +291,9 @@ other REALITY-capable client can import the same parameters instead: Give each device its own UUID (`xray uuid`, then list them in `REALITY_CLIENT_IDS`) so one can be revoked without disturbing the others. +`REALITY_BIND` defaults to `0.0.0.0:443`, which is IPv4 only. On an IPv6-only +host set it to `[::]:443`. + Pick the camouflage site with care: it must speak TLS 1.3 with X25519, be reachable from the server, and resolve to a real CDN. Xray itself warns against apple/icloud targets, and a target that is an obvious outlier can get your IP @@ -351,7 +353,7 @@ Edit `config.json` or use environment variables (env vars override config file): | `IDLE_TIMEOUT_SECONDS` | 300 | Deadline on an **established** proxy session. Raise it if clients idle longer | | `SECURITY_HEADERS_ENABLED` | true | Enable security headers | | `RATE_LIMIT_ENABLED` | true | Enable rate limiting on admin endpoints | -| `RATE_LIMIT_RPS` | 30 | Admin requests per second per client | +| `RATE_LIMIT_RPS` | 30 | Admin requests per second **per client**, keyed by IP. One client cannot spend another's budget. Clients behind one carrier NAT share a bucket | | `TUNNEL_ENABLED` | false | Enable the WebSocket tunnel. Refused at startup without a token | | `TUNNEL_TOKEN` | empty | Shared secret for the tunnel path and the client | | `TUNNEL_PATH` | /api/v1/tunnel | Tunnel URL path | @@ -471,6 +473,13 @@ go test -run TestRealityEndToEnd -v ./... # needs xray on PATH | Pro | 20 | 50 Mbps | Unlimited | 90 days | | Unlimited | Unlimited | Unlimited | Unlimited | Never | +Bandwidth is enforced per direction on every session: a Free-tier session moves +at most 1 Mbps each way, with a one-second burst allowance so short transfers +are not penalised. A user's limit is captured when the account is created, so +changing a tier later does not retroactively re-rate existing accounts. Sessions +authenticated with the single `PROXY_USER`/`PROXY_PASS` pair, and the HTTP proxy +paths that share it, run unrestricted — there is no per-user tier to apply. + ## API Endpoints Reachable in both modes; in single-port mode they are all on the one port. diff --git a/limits_test.go b/limits_test.go new file mode 100644 index 0000000..ccc7cb1 --- /dev/null +++ b/limits_test.go @@ -0,0 +1,454 @@ +package main + +import ( + "bytes" + "io" + "log/slog" + "net" + "path/filepath" + "strconv" + "testing" + "time" +) + +// ─── Per-client rate limiting ─────────────────────────────────────────────── + +// The documented behaviour is per client. Under the single shared bucket this +// used to be, one address could spend everyone's budget. +func TestRateLimiterSetIsolatesClients(t *testing.T) { + set := newRateLimiterSet(5) + + for range 5 { + if !set.allow("10.0.0.1") { + t.Fatal("first client's fifth request was refused") + } + } + if set.allow("10.0.0.1") { + t.Error("sixth request for the same client should be refused at 5 rps") + } + + // The whole point: a different client is unaffected by the first one's burst. + for i := range 5 { + if !set.allow("10.0.0.2") { + t.Fatalf("second client refused on request %d while another client was flooding", i+1) + } + } +} + +func TestRateLimiterSetRefillsOverTime(t *testing.T) { + set := newRateLimiterSet(5) + for range 5 { + set.allow("10.0.0.1") + } + if set.allow("10.0.0.1") { + t.Fatal("bucket should be empty") + } + // Refill is time-based, not reset-on-use: nudge the clock rather than sleep. + set.mu.Lock() + set.buckets["10.0.0.1"].last = time.Now().Add(-time.Second) + set.mu.Unlock() + + if !set.allow("10.0.0.1") { + t.Error("bucket did not refill after a second") + } +} + +// Buckets must not accumulate for every address the proxy has ever seen. +func TestRateLimiterSetSweepsIdleBuckets(t *testing.T) { + set := newRateLimiterSet(5) + for i := range 10 { + set.allow(strconv.Itoa(i)) + } + if len(set.buckets) != 10 { + t.Fatalf("got %d buckets, want 10", len(set.buckets)) + } + + set.mu.Lock() + // Pretend the last sweep was long ago and nobody has been back since. + set.lastSweep = time.Now().Add(-time.Hour) + for _, b := range set.buckets { + b.lastSeen = time.Now().Add(-rateLimiterIdle - time.Minute) + } + set.mu.Unlock() + + // The sweep happens inside allow(). The returning client gets a fresh, + // full bucket, which is the point of sweeping rather than deleting on use. + if !set.allow("10.0.0.9") { + t.Fatal("a client returning after a sweep should start with a full budget") + } + if got := len(set.buckets); got != 1 { + t.Errorf("got %d buckets after a sweep, want only the client that just came back", got) + } +} + +// A change in the dashboard must reach the limiter without a restart. +func TestRateLimiterSetRPSChangeApplies(t *testing.T) { + set := newRateLimiterSet(2) + for range 2 { + set.allow("10.0.0.1") + } + if set.allow("10.0.0.1") { + t.Fatal("third request should be refused at 2 rps") + } + + // The drained client keeps its debt: a higher limit is not a free refill. + if set.allow("10.0.0.1") { + t.Error("raising the limit should not hand the drained client free tokens") + } + + // A client that has not spent anything now gets the new rate. + set.setRPS(10) + allowed := 0 + for range 10 { + if set.allow("10.0.0.3") { + allowed++ + } + } + if allowed != 10 { + t.Errorf("new client got %d of 10 immediate requests after setRPS(10)", allowed) + } +} + +// ─── Configuration precedence ─────────────────────────────────────────────── + +// Editing .env and restarting used to change nothing whenever the dashboard had +// ever saved that setting. +func TestApplyDBOverridesEnvironmentWins(t *testing.T) { + cfg := DefaultConfig() + cfg.Username = "env-user" + cfg.Password = "env-pass" + cfg.envSet = map[string]bool{"proxy_user": true, "proxy_pass": true} + + dbCfg := map[string]string{ + "proxy_user": "db-user", + "proxy_pass": "db-pass", + "admin_username": "db-admin", + "max_connections": "500", + } + + applied := applyDBOverrides(&cfg, dbCfg) + + if cfg.Username != "env-user" || cfg.Password != "env-pass" { + t.Errorf("environment was overwritten by the database: %s/%s", cfg.Username, cfg.Password) + } + // Keys the environment did not mention still come from the database. + if cfg.AdminUser != "db-admin" { + t.Errorf("admin_username = %q, want the stored value", cfg.AdminUser) + } + if cfg.MaxConns != 500 { + t.Errorf("max_connections = %d, want the stored 500", cfg.MaxConns) + } + for _, key := range []string{"proxy_user", "proxy_pass"} { + if contains(applied, key) { + t.Errorf("%s was reported as applied from the database, but the environment set it", key) + } + } + if !contains(applied, "admin_username") || !contains(applied, "max_connections") { + t.Errorf("applied = %v, want the keys that were not set in the environment", applied) + } +} + +func TestApplyDBOverridesDatabaseWinsWhenEnvUnset(t *testing.T) { + cfg := DefaultConfig() + dbCfg := map[string]string{"proxy_pass": "db-pass", "auth_enabled": "false", "rate_limit_rps": "99"} + + applyDBOverrides(&cfg, dbCfg) + + if cfg.Password != "db-pass" { + t.Errorf("password = %q, want the stored value when the environment is silent", cfg.Password) + } + if cfg.AuthEnabled { + t.Error("auth_enabled = true, want the stored false") + } + if cfg.RateLimitRPS != 99 { + t.Errorf("rate_limit_rps = %d, want the stored 99", cfg.RateLimitRPS) + } +} + +// Every documented setting must be tracked, or the precedence rule has a hole. +func TestEveryDatabaseOverridableKeyIsTrackedFromEnv(t *testing.T) { + envFor := map[string]string{ + "max_connections": "MAX_CONNECTIONS", + "proxy_user": "PROXY_USER", + "proxy_pass": "PROXY_PASS", + "auth_enabled": "AUTH_ENABLED", + "admin_auth_enabled": "ADMIN_AUTH_ENABLED", + "admin_username": "ADMIN_USER", + "admin_pass": "ADMIN_PASS", + "security_headers_enabled": "SECURITY_HEADERS_ENABLED", + "rate_limit_enabled": "RATE_LIMIT_ENABLED", + "rate_limit_rps": "RATE_LIMIT_RPS", + } + for _, env := range envFor { + t.Setenv(env, "1") + } + cfgFile := writeTempConfig(t, `{}`) + cfg, err := LoadConfig(cfgFile) + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + for key := range envFor { + if !cfg.envSet[key] { + t.Errorf("%s is overridable from the database but its environment variable was not recorded", key) + } + } +} + +// ─── Bandwidth pacing ─────────────────────────────────────────────────────── + +func TestPacerCapsThroughput(t *testing.T) { + payload := bytes.Repeat([]byte("x"), 256<<10) // 256 KiB + var sink bytes.Buffer + + start := time.Now() + n, err := copyPaced(&sink, bytes.NewReader(payload), newPacer(1)) + if err != nil { + t.Fatalf("copyPaced: %v", err) + } + elapsed := time.Since(start) + + if n != int64(len(payload)) { + t.Fatalf("copied %d bytes, want %d", n, len(payload)) + } + if !bytes.Equal(sink.Bytes(), payload) { + t.Fatal("pacing changed the byte stream, which must stay transparent") + } + + // 256 KiB at 1 Mbps is 2.05s of transfer time. The first second comes from + // the burst allowance, so the floor is a little under that. + floor := 900 * time.Millisecond + if elapsed < floor { + t.Errorf("256 KiB through a 1 Mbps pacer took %s, want at least %s: the limit is not being applied", elapsed, floor) + } +} + +func TestPacerNilMeansUnlimited(t *testing.T) { + payload := bytes.Repeat([]byte("x"), 512<<10) + var sink bytes.Buffer + + start := time.Now() + if _, err := copyPaced(&sink, bytes.NewReader(payload), newPacer(-1)); err != nil { + t.Fatalf("copyPaced: %v", err) + } + // The Unlimited tier must not pay for a limit that does not exist. Half a + // megabyte at 1 Mbps would be four seconds; allow a very generous margin and + // still catch an accidentally applied pacer. + if elapsed := time.Since(start); elapsed > 500*time.Millisecond { + t.Errorf("unlimited transfer took %s, want well under 500ms: a pacer is active", elapsed) + } + if sink.Len() != len(payload) { + t.Errorf("copied %d bytes, want %d", sink.Len(), len(payload)) + } +} + +// The tier table advertises bandwidth; this proves a Free-tier session is +// actually held to it, through the real SOCKS5 path. +func TestFreeTierSessionIsPaced(t *testing.T) { + store, err := NewStore(filepath.Join(t.TempDir(), "pace.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatalf("NewStore: %v", err) + } + defer store.Close() + + user, err := store.CreateUser("pu", "pp", "free") + if err != nil { + t.Fatalf("CreateUser: %v", err) + } + if user.BandwidthMbps != 1 { + t.Fatalf("free tier bandwidth = %d, want 1", user.BandwidthMbps) + } + + // Origin: hands out a fixed payload and nothing else. + payload := bytes.Repeat([]byte("y"), 256<<10) + origin, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("origin listen: %v", err) + } + defer origin.Close() + go func() { + for { + conn, aerr := origin.Accept() + if aerr != nil { + return + } + go func(c net.Conn) { + defer c.Close() + buf := make([]byte, len(payload)) + if _, rerr := io.ReadFull(c, buf); rerr != nil { + return + } + c.Write(payload) + }(conn) + } + }() + + cfg := DefaultConfig() + cfg.AuthEnabled = true + cfg.Username = "pu" + cfg.Password = "pp" + cfg.AdminEnabled = false + cfg.SecurityHeadersEnabled = false + cfg.RateLimitEnabled = false + + proxy := NewProxyServer(cfg) + proxy.store = store + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("proxy listen: %v", err) + } + defer ln.Close() + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go proxy.handleClient(conn, "") + } + }() + + host, portStr, _ := net.SplitHostPort(origin.Addr().String()) + port64, err := strconv.ParseUint(portStr, 10, 16) + if err != nil { + t.Fatalf("origin port %q: %v", portStr, err) + } + port := uint16(port64) + + client, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("dial proxy: %v", err) + } + defer client.Close() + if err := socks5ConnectAndAuth(t, client, "pu", "pp", host, port); err != nil { + t.Fatalf("socks5 handshake: %v", err) + } + if _, err := client.Write(payload); err != nil { + t.Fatalf("write payload: %v", err) + } + + got := make([]byte, len(payload)) + start := time.Now() + if _, err := io.ReadFull(client, got); err != nil { + t.Fatalf("read through proxy: %v", err) + } + elapsed := time.Since(start) + + if !bytes.Equal(got, payload) { + t.Fatal("payload changed in transit") + } + if elapsed < 900*time.Millisecond { + t.Errorf("free tier moved 256 KiB in %s: BandwidthMbps is still not enforced", elapsed) + } +} + +// socks5ConnectAndAuth performs greeting, username/password auth and CONNECT. +// Written out rather than reusing the e2e helper because that one assumes +// no-auth and lives in a different test file's style. +func socks5ConnectAndAuth(t *testing.T, conn net.Conn, user, pass, host string, port uint16) error { + t.Helper() + if _, err := conn.Write([]byte{0x05, 0x01, 0x02}); err != nil { + return err + } + sel := make([]byte, 2) + if _, err := io.ReadFull(conn, sel); err != nil { + return err + } + if sel[1] != 0x02 { + return errAuthNotOffered + } + if _, err := conn.Write([]byte{0x01, byte(len(user))}); err != nil { + return err + } + if _, err := conn.Write([]byte(user)); err != nil { + return err + } + if _, err := conn.Write([]byte{byte(len(pass))}); err != nil { + return err + } + if _, err := conn.Write([]byte(pass)); err != nil { + return err + } + status := make([]byte, 2) + if _, err := io.ReadFull(conn, status); err != nil { + return err + } + if status[1] != 0x00 { + return errAuthRejected + } + + req := []byte{0x05, 0x01, 0x00, 0x03, byte(len(host))} + req = append(req, host...) + req = append(req, byte(port>>8), byte(port)) + if _, err := conn.Write(req); err != nil { + return err + } + head := make([]byte, 4) + if _, err := io.ReadFull(conn, head); err != nil { + return err + } + if head[1] != 0x00 { + return errConnectRefused + } + switch head[3] { + case 0x01: + _, err := io.ReadFull(conn, make([]byte, 6)) + return err + case 0x03: + var l [1]byte + if _, err := io.ReadFull(conn, l[:]); err != nil { + return err + } + _, err := io.ReadFull(conn, make([]byte, int(l[0])+2)) + return err + case 0x04: + _, err := io.ReadFull(conn, make([]byte, 18)) + return err + default: + return errBadAddrType + } +} + +var ( + errAuthNotOffered = errorString("server did not offer username/password auth") + errAuthRejected = errorString("server rejected the credentials") + errConnectRefused = errorString("server refused the CONNECT") + errBadAddrType = errorString("server replied with an unknown bound address type") +) + +type errorString string + +func (e errorString) Error() string { return string(e) } + +func contains(haystack []string, needle string) bool { + for _, v := range haystack { + if v == needle { + return true + } + } + return false +} + +func TestPacerHonoursSmallerLimits(t *testing.T) { + // 4 Mbps over 512 KiB is ~1s, against a burst of 512 KiB, so the floor sits + // just under the non-burst transfer time. This catches a pacer that only + // ever applies its ceiling once. + p := newPacer(4) + if p == nil { + t.Fatal("newPacer(4) returned nil, want a pacer") + } + if p.bytesPerSec != 512*1024 { + t.Errorf("bytesPerSec = %v, want 512KiB/s for 4 Mbps", p.bytesPerSec) + } + + start := time.Now() + payload := bytes.Repeat([]byte("z"), 1<<20) // 1 MiB + var sink bytes.Buffer + if _, err := copyPaced(&sink, bytes.NewReader(payload), p); err != nil { + t.Fatalf("copyPaced: %v", err) + } + elapsed := time.Since(start) + if elapsed < 900*time.Millisecond { + t.Errorf("1 MiB at 4 Mbps took %s, want at least ~900ms", elapsed) + } +} diff --git a/main.go b/main.go index 0b00ba6..e3d2797 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,7 @@ import ( "net/http" "os" "os/signal" + "sort" "strconv" "strings" "sync" @@ -28,7 +29,7 @@ import ( // version is reported by the version subcommand, /health and /api/stats, so the // three can never disagree. -const version = "1.3.0" +const version = "1.3.1" type Config struct { ProxyPort int `json:"proxy_port"` @@ -88,10 +89,17 @@ type Config struct { RealityPublicHost string `json:"reality_public_host"` RealityXrayBin string `json:"reality_xray_bin"` RealityClientFile string `json:"reality_client_file"` + + // envSet records which settings were explicitly provided through the + // environment, so applyDBOverrides knows not to overwrite the operator's + // stated intent with a value saved from the dashboard months earlier. + // Unexported, so it never appears in JSON and never reaches an API. + envSet map[string]bool } func DefaultConfig() Config { return Config{ + envSet: make(map[string]bool), ProxyPort: 1080, AdminPort: 8080, MetricsPort: 9090, @@ -124,6 +132,9 @@ func LoadConfig(filename string) (Config, error) { if err != nil { return cfg, fmt.Errorf("read config %s: %w", filename, err) } + if cfg.envSet == nil { + cfg.envSet = make(map[string]bool) + } if err := json.Unmarshal(data, &cfg); err != nil { return cfg, fmt.Errorf("parse config: %w", err) } @@ -150,38 +161,48 @@ func LoadConfig(filename string) (Config, error) { } } if user := os.Getenv("PROXY_USER"); user != "" { + cfg.envSet["proxy_user"] = true cfg.Username = user } if pass := os.Getenv("PROXY_PASS"); pass != "" { + cfg.envSet["proxy_pass"] = true cfg.Password = pass } if max := os.Getenv("MAX_CONNECTIONS"); max != "" { + cfg.envSet["max_connections"] = true if m, err := strconv.Atoi(max); err == nil && m > 0 { cfg.MaxConns = m } } if v := os.Getenv("AUTH_ENABLED"); v != "" { + cfg.envSet["auth_enabled"] = true cfg.AuthEnabled = v == "true" || v == "1" } // Admin auth env vars if user := os.Getenv("ADMIN_USER"); user != "" { + cfg.envSet["admin_username"] = true cfg.AdminUser = user } if pass := os.Getenv("ADMIN_PASS"); pass != "" { + cfg.envSet["admin_pass"] = true cfg.AdminPass = pass } if v := os.Getenv("ADMIN_AUTH_ENABLED"); v != "" { + cfg.envSet["admin_auth_enabled"] = true cfg.AdminEnabled = v == "true" || v == "1" } if v := os.Getenv("SECURITY_HEADERS_ENABLED"); v != "" { + cfg.envSet["security_headers_enabled"] = true cfg.SecurityHeadersEnabled = v == "true" || v == "1" } if v := os.Getenv("RATE_LIMIT_ENABLED"); v != "" { + cfg.envSet["rate_limit_enabled"] = true cfg.RateLimitEnabled = v == "true" || v == "1" } if v := os.Getenv("RATE_LIMIT_RPS"); v != "" { + cfg.envSet["rate_limit_rps"] = true if r, err := strconv.Atoi(v); err == nil && r > 0 { cfg.RateLimitRPS = r } @@ -491,11 +512,11 @@ type ProxyServer struct { wg sync.WaitGroup // Rate limiter (shared reference for runtime updates) - limiter *rateLimiter + limiter *rateLimiterSet // Separate limiter for tunnel handshakes, so token brute-force cannot // exhaust the admin/dashboard budget (see multiplex.go) - tunnelLimiter *rateLimiter + tunnelLimiter *rateLimiterSet // Client used for absolute-URI forward-proxy requests (http:// targets). // Initialised with the mux; nil in multi-port mode, where forward proxying @@ -961,9 +982,18 @@ func (s *ProxyServer) relay(client, target net.Conn, log *slog.Logger, targetAdd var bytesUp, bytesDown atomic.Int64 wg.Add(2) + // The tier's bandwidth limit, one pacer per direction. A nil pacer (the + // Unlimited tier, or an unauthenticated session) means full speed and costs + // nothing to check. + var upPacer, downPacer *pacer + if user != nil { + upPacer = newPacer(user.BandwidthMbps) + downPacer = newPacer(user.BandwidthMbps) + } + go func() { defer wg.Done() - n, err := io.Copy(target, client) + n, err := copyPaced(target, client, upPacer) if err != nil && !isClosedConnError(err) { log.Debug("client->target copy error", "error", err) } @@ -973,7 +1003,7 @@ func (s *ProxyServer) relay(client, target net.Conn, log *slog.Logger, targetAdd go func() { defer wg.Done() - n, err := io.Copy(client, target) + n, err := copyPaced(client, target, downPacer) if err != nil && !isClosedConnError(err) { log.Debug("target->client copy error", "error", err) } @@ -1111,10 +1141,10 @@ func (rl *rateLimiter) allow() bool { return true } -func rateLimit(limiter *rateLimiter) func(http.Handler) http.Handler { +func rateLimit(limiter *rateLimiterSet) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !limiter.allow() { + if !limiter.allow(requestIP(r)) { http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests) return } @@ -1123,6 +1153,119 @@ func rateLimit(limiter *rateLimiter) func(http.Handler) http.Handler { } } +// ─── Per-client rate limiting ─────────────────────────────────────────────── + +// rateLimiterSet gives every client its own token bucket. +// +// A single shared bucket, which is what this used to be, means one noisy client +// spends everyone's budget: on a dashboard polled by two administrators, or on +// a tunnel shared by a dozen phones behind one carrier NAT, a flood from one +// address throttles all of them. That is also what the README claimed did not +// happen, so the docs and the code now agree in the direction of the code being +// useful. +// +// The cost is memory proportional to the number of distinct addresses seen in +// the last rateLimiterIdle window, which is why buckets are swept rather than +// kept forever. +type rateLimiterSet struct { + mu sync.Mutex + rps int + buckets map[string]*rateBucket + lastSweep time.Time +} + +type rateBucket struct { + tokens float64 + last time.Time + lastSeen time.Time +} + +const ( + // rateLimiterSweep is how often idle buckets are collected. + rateLimiterSweep = 5 * time.Minute + // rateLimiterIdle is how long a silent client's bucket is kept. Two sweeps, + // so a client that is quiet for one interval keeps its accumulated tokens. + rateLimiterIdle = 10 * time.Minute + // rateLimiterMaxBuckets bounds memory if a flood of distinct addresses + // arrives faster than the sweep removes them. + rateLimiterMaxBuckets = 100000 +) + +func newRateLimiterSet(rps int) *rateLimiterSet { + return &rateLimiterSet{ + rps: rps, + buckets: make(map[string]*rateBucket), + lastSweep: time.Now(), + } +} + +func (s *rateLimiterSet) allow(key string) bool { + now := time.Now() + + s.mu.Lock() + defer s.mu.Unlock() + + if now.Sub(s.lastSweep) >= rateLimiterSweep { + s.sweepLocked(now) + } + + b, ok := s.buckets[key] + if !ok { + b = &rateBucket{tokens: float64(s.rps), last: now} + s.buckets[key] = b + } + + elapsed := now.Sub(b.last).Seconds() + b.last = now + b.lastSeen = now + b.tokens += elapsed * float64(s.rps) + if b.tokens > float64(s.rps) { + b.tokens = float64(s.rps) + } + if b.tokens < 1 { + return false + } + b.tokens-- + return true +} + +func (s *rateLimiterSet) setRPS(rps int) { + s.mu.Lock() + defer s.mu.Unlock() + s.rps = rps + for _, b := range s.buckets { + if b.tokens > float64(rps) { + b.tokens = float64(rps) + } + } +} + +// sweepLocked drops buckets nobody has used, and if that is not enough, the +// least recently used half. Callers must hold the lock. +func (s *rateLimiterSet) sweepLocked(now time.Time) { + s.lastSweep = now + for key, b := range s.buckets { + if now.Sub(b.lastSeen) > rateLimiterIdle { + delete(s.buckets, key) + } + } + if len(s.buckets) <= rateLimiterMaxBuckets { + return + } + type entry struct { + key string + lastSeen time.Time + } + entries := make([]entry, 0, len(s.buckets)) + for key, b := range s.buckets { + entries = append(entries, entry{key, b.lastSeen}) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].lastSeen.Before(entries[j].lastSeen) }) + for _, e := range entries[:len(entries)/2] { + delete(s.buckets, e.key) + } +} + // ─── No-Directory-Listing File Server ────────────────────────────────────── func noDirListing(root http.FileSystem) http.Handler { @@ -1587,7 +1730,7 @@ func (s *ProxyServer) adminHandler() http.Handler { // Apply middleware stack (outermost first) if s.cfg.RateLimitEnabled { - s.limiter = newRateLimiter(s.cfg.RateLimitRPS) + s.limiter = newRateLimiterSet(s.cfg.RateLimitRPS) handler = rateLimit(s.limiter)(handler) } if s.cfg.AdminEnabled && s.cfg.AdminUser != "" && s.cfg.AdminPass != "" { @@ -1695,6 +1838,67 @@ func (s *ProxyServer) metricsHandler() http.Handler { return handler } +// applyDBOverrides applies settings saved from the admin dashboard. +// +// The environment wins. Both the docs and every deployment since the beginning +// have said "edit config.json or use environment variables", so a password +// edited in .env that silently kept working because a value happened to be +// stored in SQLite three weeks earlier is a trap, not a feature. The dashboard +// still wins over config.json, because the operator clicking "save" is stating +// intent right now; the environment wins over the dashboard because it is how a +// deployment is described at boot. +// +// Returns the keys that were actually applied, for the startup log. +func applyDBOverrides(cfg *Config, dbCfg map[string]string) []string { + if len(dbCfg) == 0 { + return nil + } + var applied []string + take := func(key string, ok bool) bool { + if !ok || cfg.envSet[key] { + return false + } + applied = append(applied, key) + return true + } + + if v, ok := dbCfg["max_connections"]; take("max_connections", ok) { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + cfg.MaxConns = n + } + } + if v, ok := dbCfg["proxy_user"]; take("proxy_user", ok) { + cfg.Username = v + } + if v, ok := dbCfg["proxy_pass"]; take("proxy_pass", ok) { + cfg.Password = v + } + if v, ok := dbCfg["auth_enabled"]; take("auth_enabled", ok) { + cfg.AuthEnabled = v == "true" + } + if v, ok := dbCfg["admin_auth_enabled"]; take("admin_auth_enabled", ok) { + cfg.AdminEnabled = v == "true" + } + if v, ok := dbCfg["admin_username"]; take("admin_username", ok) { + cfg.AdminUser = v + } + if v, ok := dbCfg["admin_pass"]; take("admin_pass", ok) { + cfg.AdminPass = v + } + if v, ok := dbCfg["security_headers_enabled"]; take("security_headers_enabled", ok) { + cfg.SecurityHeadersEnabled = v == "true" + } + if v, ok := dbCfg["rate_limit_enabled"]; take("rate_limit_enabled", ok) { + cfg.RateLimitEnabled = v == "true" + } + if v, ok := dbCfg["rate_limit_rps"]; take("rate_limit_rps", ok) { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + cfg.RateLimitRPS = n + } + } + return applied +} + // ─── Main ────────────────────────────────────────────────────────────────── func main() { @@ -1758,42 +1962,10 @@ func runServer(logger *slog.Logger, configFile string) { // Load persisted config overrides from DB dbCfg := store.LoadConfig() - if len(dbCfg) > 0 { - if v, ok := dbCfg["max_connections"]; ok { - if n, err := strconv.Atoi(v); err == nil && n > 0 { - cfg.MaxConns = n - } - } - if v, ok := dbCfg["proxy_user"]; ok { - cfg.Username = v - } - if v, ok := dbCfg["proxy_pass"]; ok { - cfg.Password = v - } - if v, ok := dbCfg["auth_enabled"]; ok { - cfg.AuthEnabled = v == "true" - } - if v, ok := dbCfg["admin_auth_enabled"]; ok { - cfg.AdminEnabled = v == "true" - } - if v, ok := dbCfg["admin_username"]; ok { - cfg.AdminUser = v - } - if v, ok := dbCfg["admin_pass"]; ok { - cfg.AdminPass = v - } - if v, ok := dbCfg["security_headers_enabled"]; ok { - cfg.SecurityHeadersEnabled = v == "true" - } - if v, ok := dbCfg["rate_limit_enabled"]; ok { - cfg.RateLimitEnabled = v == "true" - } - if v, ok := dbCfg["rate_limit_rps"]; ok { - if n, err := strconv.Atoi(v); err == nil && n > 0 { - cfg.RateLimitRPS = n - } - } - logger.Info("loaded config overrides from database") + if applied := applyDBOverrides(&cfg, dbCfg); len(applied) > 0 { + logger.Info("loaded config overrides from database", + "keys", strings.Join(applied, ","), + "note", "keys set in the environment were left alone") } server := NewProxyServer(cfg) diff --git a/multiplex.go b/multiplex.go index 3588e50..87baed0 100644 --- a/multiplex.go +++ b/multiplex.go @@ -401,7 +401,7 @@ func (s *ProxyServer) connectHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, "forbidden", http.StatusForbidden) return } - if !s.tunnelLimiter.allow() { + if !s.tunnelLimiter.allow(requestIP(r)) { http.Error(w, "too many requests", http.StatusTooManyRequests) return } @@ -519,7 +519,7 @@ func (s *ProxyServer) forwardProxyHandler(w http.ResponseWriter, r *http.Request http.Error(w, "forbidden", http.StatusForbidden) return } - if !s.tunnelLimiter.allow() { + if !s.tunnelLimiter.allow(requestIP(r)) { http.Error(w, "too many requests", http.StatusTooManyRequests) return } @@ -658,6 +658,8 @@ func validProxyAuth(r *http.Request, wantUser, wantPass string) bool { func (s *ProxyServer) tunnelHandler(w http.ResponseWriter, r *http.Request) { cfg := s.currentConfig() + clientIP := requestIP(r) + // Every refusal below is byte-identical, on purpose. A disabled tunnel, a // rate-limited attempt and a wrong token must be indistinguishable from a // path that does not exist, because "this path exists but I am not welcome" @@ -666,7 +668,7 @@ func (s *ProxyServer) tunnelHandler(w http.ResponseWriter, r *http.Request) { s.writeTunnelRefusal(w, r) return } - if !s.tunnelLimiter.allow() { + if !s.tunnelLimiter.allow(clientIP) { s.writeTunnelRefusal(w, r) return } @@ -708,7 +710,6 @@ func (s *ProxyServer) tunnelHandler(w http.ResponseWriter, r *http.Request) { conn = newPadConn(conn, cfg.TunnelPadding) } - clientIP := requestIP(r) s.logger.Info("tunnel session opened", "client", clientIP, "padding", cfg.TunnelPadding) s.handleClient(conn, clientIP) } @@ -812,7 +813,7 @@ func (s *ProxyServer) serveMultiplex(addr string) error { return err } - s.tunnelLimiter = newRateLimiter(cfg.TunnelRateRPS) + s.tunnelLimiter = newRateLimiterSet(cfg.TunnelRateRPS) tunnelPath := cfg.TunnelPath if tunnelPath == "" { diff --git a/multiplex_test.go b/multiplex_test.go index 8d47e03..3dc567a 100644 --- a/multiplex_test.go +++ b/multiplex_test.go @@ -1217,7 +1217,7 @@ func TestTunnelPathRejectsServeMuxPanics(t *testing.T) { for name, path := range bad { t.Run(name, func(t *testing.T) { srv := NewProxyServer(DefaultConfig()) - srv.tunnelLimiter = newRateLimiter(5) + srv.tunnelLimiter = newRateLimiterSet(5) srv.cfg.TunnelEnabled = true srv.cfg.TunnelPath = path @@ -1233,7 +1233,7 @@ func TestTunnelPathRejectsServeMuxPanics(t *testing.T) { // A valid path must still start. srv := NewProxyServer(DefaultConfig()) - srv.tunnelLimiter = newRateLimiter(5) + srv.tunnelLimiter = newRateLimiterSet(5) srv.cfg.TunnelEnabled = true srv.cfg.TunnelPath = "/api/v1/tunnel" if err := srv.serveMultiplex("127.0.0.1:0"); err != nil { @@ -1246,7 +1246,7 @@ func TestTunnelPathRejectsServeMuxPanics(t *testing.T) { // TUNNEL_ENABLED=false while leaving a stale TUNNEL_PATH behind. func TestDisabledTunnelIgnoresPath(t *testing.T) { srv := NewProxyServer(DefaultConfig()) - srv.tunnelLimiter = newRateLimiter(5) + srv.tunnelLimiter = newRateLimiterSet(5) srv.cfg.TunnelEnabled = false srv.cfg.TunnelPath = "not-even-a-path" diff --git a/pacer.go b/pacer.go new file mode 100644 index 0000000..3d7e149 --- /dev/null +++ b/pacer.go @@ -0,0 +1,110 @@ +package main + +import ( + "io" + "time" +) + +// ─── Bandwidth pacer ──────────────────────────────────────────────────────── + +// pacer keeps a stream under a bitrate. +// +// BandwidthMbps has been stored per user since the tier system landed and +// advertised in the README as "1 / 5 / 50 Mbps", but nothing ever read it: +// relay() was a plain io.Copy in both directions, so the Free tier ran at line +// speed like every other tier. This is where that column finally takes effect. +// +// A token bucket with a one-second burst, which is what a tier limit means in +// practice: sustained rate capped, short spikes allowed. Each direction gets its +// own pacer, so a tier's number is the rate in each direction rather than a +// shared budget -- the usual reading of a per-tier bandwidth figure, and the one +// that keeps a download from starving the upload that ACKs it. +type pacer struct { + bytesPerSec float64 + tokens float64 + last time.Time +} + +// pacerBurstSeconds is how much slack a client gets before the average rate +// kicks in. One second of traffic is enough to smooth a burst without letting a +// fast transfer spend its whole allowance at once. +const pacerBurstSeconds = 1.0 + +// newPacer returns nil when there is nothing to enforce, which is the -1 that +// the Unlimited tier uses. Callers treat a nil pacer as "copy at full speed", so +// the unlimited path keeps costing nothing. +func newPacer(mbps int) *pacer { + if mbps <= 0 { + return nil + } + rate := float64(mbps) * 1024 * 1024 / 8 // Mbit/s -> bytes/s + return &pacer{ + bytesPerSec: rate, + tokens: rate * pacerBurstSeconds, + last: time.Now(), + } +} + +// reserve asks for permission to move n bytes, sleeping if the allowance for +// this instant is not there yet. +func (p *pacer) reserve(n int) { + if p == nil || n <= 0 { + return + } + now := time.Now() + p.tokens += now.Sub(p.last).Seconds() * p.bytesPerSec + p.last = now + if p.tokens > p.bytesPerSec*pacerBurstSeconds { + p.tokens = p.bytesPerSec * pacerBurstSeconds + } + p.tokens -= float64(n) + if p.tokens >= 0 { + return + } + // Negative tokens are the debt: wait for the bucket to refill by that much. + debt := -p.tokens + p.tokens = 0 + time.Sleep(time.Duration(debt / p.bytesPerSec * float64(time.Second))) + // The clock has to be moved past the sleep. Without this the next call + // credits the sleeping interval as if it were idle time, so the debt is + // paid twice and the link runs at twice the configured rate. + p.last = time.Now() +} + +// copyPaced is io.Copy with a rate limit. The read/write loop replaces io.Copy +// because pacing needs to sit between the two, and because the chunk size is +// what the pacer reserves against. +func copyPaced(dst io.Writer, src io.Reader, p *pacer) (int64, error) { + if p == nil { + return io.Copy(dst, src) + } + buf := make([]byte, pacerChunkSize) + var total int64 + for { + nr, rerr := src.Read(buf) + if nr > 0 { + nw, werr := dst.Write(buf[:nr]) + if nw > 0 { + total += int64(nw) + p.reserve(nw) + } + if werr != nil { + return total, werr + } + if nw != nr { + return total, io.ErrShortWrite + } + } + if rerr != nil { + if rerr == io.EOF { + return total, nil + } + return total, rerr + } + } +} + +// pacerChunkSize is the read size for paced copies. 32KB keeps the sleep count +// low on a fast link while staying small enough that a rate limit of 1 Mbps +// still arrives in ~4 chunks a second instead of a single one-second stall. +const pacerChunkSize = 32 << 10