[PR #6966] feat(sub): opt-in per-client rate limit for the subscription server #6549

Open
opened 2026-11-02 04:09:33 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6966
Author: @amirim1
Created: 10/26/2026
Status: 🔄 Open

Base: main ← Head: feat/sub-rate-limit


📝 Commits (7)

  • 99d23cc feat(sub): add an opt-in per-client rate limit to the subscription server
  • a32d087 fix(sub): gofmt controller; frontend settings model fields
  • c1d0c51 fix(sub): address adversarial review of the rate limit branch
  • d028b0c test(sub): prime the limiter before asserting 429 in the controller test
  • e6a3639 test(sub): init the DB and assert exact codes in the controller rate limit test
  • 5cdc9ec docs(sub): note why static assets stay outside the rate limit guard
  • 250ff8e fix(sub): address the review bot's low findings

📊 Changes

29 files changed (+851 additions, -0 deletions)

View changed files

📝 docs/public/openapi.json (+20 -0)
📝 frontend/public/openapi.json (+20 -0)
📝 frontend/src/generated/examples.ts (+4 -0)
📝 frontend/src/generated/schemas.ts (+20 -0)
📝 frontend/src/generated/types.ts (+4 -0)
📝 frontend/src/generated/zod.ts (+4 -0)
📝 frontend/src/models/setting.ts (+2 -0)
📝 frontend/src/pages/settings/SubscriptionGeneralTab.tsx (+28 -0)
📝 frontend/src/schemas/setting.ts (+2 -0)
📝 internal/sub/controller.go (+20 -0)
➕ internal/sub/rate_limiter.go (+301 -0)
➕ internal/sub/rate_limiter_test.go (+340 -0)
📝 internal/sub/sub.go (+18 -0)
📝 internal/web/entity/entity.go (+2 -0)
📝 internal/web/service/setting.go (+10 -0)
📝 internal/web/translation/ar-EG.json (+4 -0)
📝 internal/web/translation/en-US.json (+4 -0)
📝 internal/web/translation/es-ES.json (+4 -0)
📝 internal/web/translation/fa-IR.json (+4 -0)
📝 internal/web/translation/id-ID.json (+4 -0)

...and 9 more files

📄 Description

Summary

Adds an opt-in per-client rate limit to the subscription server (subRateLimitEnable, subRateLimit requests/minute, default 60). When enabled, every subscription route (/sub/:id, /:id/hwid-status, JSON, Clash/Mihomo formats, the HTML sub page) passes through a bounded sliding-window limiter keyed by client identity. Over-limit requests get 429 Too Many Requests with a Retry-After header pointing at when the oldest hit in the window ages out.

Motivation: subscription bodies are cheap to serve but their reads are not free (inbounds join, per-email traffic loads, host rows), and subId is the only gate. A probe loop over guessed subscription IDs currently turns into a database load generator; this caps it at the configured rate.

Design notes:

  • Sliding window, bounded memory. One mutex-protected store holds at most 4096 client buckets (LRU eviction) with a 20-minute idle TTL; each bucket keeps at most limit timestamps, so the worst case stays proportional to the configured limit.
  • Client identity follows the panel's login-limiter semantics (internal/web/controller/util.go getRemoteIp): the peer address, unless the peer is a trusted proxy (shared trustedProxyCIDRs setting), in which case X-Forwarded-For is walked from the proxy end and a client-supplied X-Real-IP is only believed when it agrees with the forwarded chain. One deliberate deviation, documented in code: a partially invalid CIDR list fails closed to loopback instead of trusting the remaining entries, because a silently narrowed identity would lump every proxied client into one bucket.
  • Off by default. A nil limiter keeps the historical behavior; the guard degrades to a no-op, so existing embedders and tests are unaffected. subRateLimit is clamped to 1–1000 on the read path too, not only on panel writes.
  • Settings reuse the existing plumbing (AllSetting form fields → UpdateAllSetting reflection → defaultValueMap defaults); the subscription server builds the limiter and resolver once at initRouter, consistent with every other sub setting.
  • UI: two fields in Settings → Subscriptions → General (switch + requests/minute), all 14 locales translated; frontend/src/generated/ and both openapi.json files regenerated via npm run gen.
  • Static /assets are intentionally outside the guard (mounted on the engine before the controller; no database reads).

Why

No rate limiting exists on the subscription server today (checked against main and the issue tracker; the panel's login limiter covers only login). Large installations can see thousands of subscription fetches per minute from client apps plus scanners probing random subIds; both share the same database. A per-client ceiling with trusted-proxy awareness is the cheap first layer — an exact continuation of the subscription-body caching shipped in #6758.

Type

  • New feature
  • Bug fix
  • Refactor / code quality
  • Documentation
  • Other

Areas affected

  • Subscription (share links / Clash / JSON)
  • Panel UI (frontend)
  • Database / migrations
  • Nodes / remote runtime
  • Telegram bot
  • Build / CI / docs

(Settings UI + i18n touched, hence Panel UI.)

How tested

  • Unit tests for the limiter core: window sliding, Retry-After arithmetic, LRU + idle eviction, concurrent hammering under -race (injected clock, no sleeps).
  • Client-IP resolver: trusted-proxy walk, spoofed/mismatched X-Real-IP falls back to the proxy address, malformed headers, unparseable peer → unknown, wildcard CIDR refused.
  • Controller-level test through a real NewSUBController: with the limit on, every subscription format route returns 429 + Retry-After after the first request; with it off, handlers answer 404 (exact codes, so a vacuous pass is impossible). Runs in isolation and under -shuffle=on.
  • Verified locally on go1.27.3/linux: go build ./..., go vet, gofmt, full internal/sub and internal/web/service suites, -race, two shuffled seeds of internal/sub; frontend tsc --noEmit, oxlint; npm run gen produces a clean diff.
  • The branch passed two rounds of adversarial subagent review; findings (stale docs spec, missing read-path clamp, per-request resolver reparse, lockfile churn, a DB-less controller test that could panic in isolation / pass vacuously under shuffle) were fixed before opening this PR.

Breaking changes

None. The limiter is disabled by default and adds two settings keys with shipped defaults.

Checklist

  • Commits follow the <area>: summary convention
  • npm run gen run, no generated-file drift
  • Tests added/updated for the changed behavior
  • No secrets, tokens, or private URLs in the diff

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/6966 **Author:** [@amirim1](https://github.com/amirim1) **Created:** 10/26/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `feat/sub-rate-limit` --- ### 📝 Commits (7) - [`99d23cc`](https://github.com/MHSanaei/3x-ui/commit/99d23ccdead66931efbede54d8caa0766fe494e5) feat(sub): add an opt-in per-client rate limit to the subscription server - [`a32d087`](https://github.com/MHSanaei/3x-ui/commit/a32d087aad0bdd4e04347d49ba5ba1133ccc9736) fix(sub): gofmt controller; frontend settings model fields - [`c1d0c51`](https://github.com/MHSanaei/3x-ui/commit/c1d0c5162b7cc6a3d6dad8f5c1c4428bb9ba68bb) fix(sub): address adversarial review of the rate limit branch - [`d028b0c`](https://github.com/MHSanaei/3x-ui/commit/d028b0cf72cb947770da725107ad6b609dde0bc1) test(sub): prime the limiter before asserting 429 in the controller test - [`e6a3639`](https://github.com/MHSanaei/3x-ui/commit/e6a36390ddc8ebe8b736ed1c765cc9a85206f38b) test(sub): init the DB and assert exact codes in the controller rate limit test - [`5cdc9ec`](https://github.com/MHSanaei/3x-ui/commit/5cdc9eca9fb222b95c39f73ae40108759ad76cf6) docs(sub): note why static assets stay outside the rate limit guard - [`250ff8e`](https://github.com/MHSanaei/3x-ui/commit/250ff8e9271f813f2e770f26eeac3523d73818d0) fix(sub): address the review bot's low findings ### 📊 Changes **29 files changed** (+851 additions, -0 deletions) <details> <summary>View changed files</summary> 📝 `docs/public/openapi.json` (+20 -0) 📝 `frontend/public/openapi.json` (+20 -0) 📝 `frontend/src/generated/examples.ts` (+4 -0) 📝 `frontend/src/generated/schemas.ts` (+20 -0) 📝 `frontend/src/generated/types.ts` (+4 -0) 📝 `frontend/src/generated/zod.ts` (+4 -0) 📝 `frontend/src/models/setting.ts` (+2 -0) 📝 `frontend/src/pages/settings/SubscriptionGeneralTab.tsx` (+28 -0) 📝 `frontend/src/schemas/setting.ts` (+2 -0) 📝 `internal/sub/controller.go` (+20 -0) ➕ `internal/sub/rate_limiter.go` (+301 -0) ➕ `internal/sub/rate_limiter_test.go` (+340 -0) 📝 `internal/sub/sub.go` (+18 -0) 📝 `internal/web/entity/entity.go` (+2 -0) 📝 `internal/web/service/setting.go` (+10 -0) 📝 `internal/web/translation/ar-EG.json` (+4 -0) 📝 `internal/web/translation/en-US.json` (+4 -0) 📝 `internal/web/translation/es-ES.json` (+4 -0) 📝 `internal/web/translation/fa-IR.json` (+4 -0) 📝 `internal/web/translation/id-ID.json` (+4 -0) _...and 9 more files_ </details> ### 📄 Description ## Summary Adds an opt-in per-client rate limit to the subscription server (`subRateLimitEnable`, `subRateLimit` requests/minute, default 60). When enabled, every subscription route (`/sub/:id`, `/:id/hwid-status`, JSON, Clash/Mihomo formats, the HTML sub page) passes through a bounded sliding-window limiter keyed by client identity. Over-limit requests get `429 Too Many Requests` with a `Retry-After` header pointing at when the oldest hit in the window ages out. Motivation: subscription bodies are cheap to serve but their reads are not free (inbounds join, per-email traffic loads, host rows), and `subId` is the only gate. A probe loop over guessed subscription IDs currently turns into a database load generator; this caps it at the configured rate. Design notes: - **Sliding window, bounded memory.** One mutex-protected store holds at most 4096 client buckets (LRU eviction) with a 20-minute idle TTL; each bucket keeps at most `limit` timestamps, so the worst case stays proportional to the configured limit. - **Client identity follows the panel's login-limiter semantics** (`internal/web/controller/util.go getRemoteIp`): the peer address, unless the peer is a trusted proxy (shared `trustedProxyCIDRs` setting), in which case `X-Forwarded-For` is walked from the proxy end and a client-supplied `X-Real-IP` is only believed when it agrees with the forwarded chain. One deliberate deviation, documented in code: a partially invalid CIDR list fails closed to loopback instead of trusting the remaining entries, because a silently narrowed identity would lump every proxied client into one bucket. - **Off by default.** A nil limiter keeps the historical behavior; the guard degrades to a no-op, so existing embedders and tests are unaffected. `subRateLimit` is clamped to 1–1000 on the read path too, not only on panel writes. - **Settings reuse the existing plumbing** (`AllSetting` form fields → `UpdateAllSetting` reflection → `defaultValueMap` defaults); the subscription server builds the limiter and resolver once at `initRouter`, consistent with every other sub setting. - **UI:** two fields in Settings → Subscriptions → General (switch + requests/minute), all 14 locales translated; `frontend/src/generated/` and both `openapi.json` files regenerated via `npm run gen`. - Static `/assets` are intentionally outside the guard (mounted on the engine before the controller; no database reads). ## Why No rate limiting exists on the subscription server today (checked against `main` and the issue tracker; the panel's login limiter covers only login). Large installations can see thousands of subscription fetches per minute from client apps plus scanners probing random `subId`s; both share the same database. A per-client ceiling with trusted-proxy awareness is the cheap first layer — an exact continuation of the subscription-body caching shipped in #6758. ## Type - [x] New feature - [ ] Bug fix - [ ] Refactor / code quality - [ ] Documentation - [ ] Other ## Areas affected - [x] Subscription (share links / Clash / JSON) - [ ] Panel UI (frontend) - [ ] Database / migrations - [ ] Nodes / remote runtime - [ ] Telegram bot - [ ] Build / CI / docs (Settings UI + i18n touched, hence Panel UI.) ## How tested - Unit tests for the limiter core: window sliding, `Retry-After` arithmetic, LRU + idle eviction, concurrent hammering under `-race` (injected clock, no sleeps). - Client-IP resolver: trusted-proxy walk, spoofed/mismatched `X-Real-IP` falls back to the proxy address, malformed headers, unparseable peer → `unknown`, wildcard CIDR refused. - Controller-level test through a real `NewSUBController`: with the limit on, every subscription format route returns 429 + `Retry-After` after the first request; with it off, handlers answer 404 (exact codes, so a vacuous pass is impossible). Runs in isolation and under `-shuffle=on`. - Verified locally on go1.27.3/linux: `go build ./...`, `go vet`, `gofmt`, full `internal/sub` and `internal/web/service` suites, `-race`, two shuffled seeds of `internal/sub`; frontend `tsc --noEmit`, oxlint; `npm run gen` produces a clean diff. - The branch passed two rounds of adversarial subagent review; findings (stale docs spec, missing read-path clamp, per-request resolver reparse, lockfile churn, a DB-less controller test that could panic in isolation / pass vacuously under shuffle) were fixed before opening this PR. ## Breaking changes None. The limiter is disabled by default and adds two settings keys with shipped defaults. ## Checklist - [x] Commits follow the `<area>: summary` convention - [x] `npm run gen` run, no generated-file drift - [x] Tests added/updated for the changed behavior - [x] No secrets, tokens, or private URLs in the diff --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#6549
No description provided.