feat(gateway): temporary IP ban (fail2ban) fed by rejections + honeypot/honeytoken
CI / changes (pull_request) Successful in 3s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 17s
CI / ui (pull_request) Successful in 53s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m11s

Add a prod-only, in-memory IP ban enforced at the edge, fed by three signals:
sustained rate-limiter rejections (the IP-keyed public/email/admin classes — the
user class stays the backend soft-flag's concern), a honeypot decoy-path hit (the
contour caddy tags decoys with X-Scrabble-Honeypot and routes them to the gateway),
and a honeytoken (a planted bearer, GATEWAY_HONEYTOKEN). A banned IP is refused with
429 by the abuseGuard middleware before any work — covering the Connect edge, the
live stream and the static SPA/landing the per-op limiter never gated.

The ban is off by default: it keys by the real client IP the shared-NAT test contour
does not expose, so a ban there would be self-inflicted; detection still logs in the
contour, only the ban action is gated (GATEWAY_ABUSE_BAN_ENABLED). Rejection bans last
GATEWAY_ABUSE_BAN_DURATION; tripwire/honeytoken hits are near-zero-false-positive and
earn longer fixed bans. Each ban increments gateway_abuse_banned_total{reason}.

Operators see and lift active bans on the admin console's Throttled page; the gateway
syncs its active set to the backend every 30s (POST /api/v1/internal/bans/sync,
backend/internal/banview) and applies the operator unbans the response returns.

PRERELEASE phase AG. Docs baked into ARCHITECTURE / FUNCTIONAL (+ru) / both READMEs.
This commit is contained in:
Ilia Denisov
2026-06-21 08:54:20 +02:00
parent 3fffee7817
commit 041106d623
28 changed files with 1295 additions and 19 deletions
+23 -1
View File
@@ -922,6 +922,28 @@ edits take effect on the next `profile.get` (open/reconnect/foreground), not mid
list/detail, cleared by the operator, **never an automatic ban** and never a request
gate. The Edge/UX dashboard graphs the aggregate request rate against the rejection
rate by class.
- **Temporary IP ban (prod-only):** with `GATEWAY_ABUSE_BAN_ENABLED` set, the gateway
enforces a fail2ban-style block keyed by client IP, fed by three signals: an IP that
sustains `GATEWAY_ABUSE_BAN_THRESHOLD` rate-limiter rejections within
`GATEWAY_ABUSE_BAN_WINDOW` (the IP-keyed public/email/admin classes — the user class
stays the soft-flag's concern, never the ban's), a **honeypot** decoy-path hit, and a
**honeytoken** (a planted bearer no real client holds, `GATEWAY_HONEYTOKEN`). A banned
IP is refused with **429** by an edge middleware (`abuseGuard`) before any work —
covering the Connect edge, the live stream and the static SPA/landing the per-op limiter
never gated. A rejection ban lasts `GATEWAY_ABUSE_BAN_DURATION`; a tripwire/honeytoken
hit is near-zero-false-positive and earns a longer fixed ban (1 h / 24 h). The ban is
**in-memory, single-instance and resets on restart**, like `ratewatch`; each ban
increments `gateway_abuse_banned_total` (`reason` = rejections/tripwire/honeytoken). The
decoy paths live only in the contour **caddy**, which tags them with `X-Scrabble-Honeypot`
(stripping any client-supplied value) and routes them to the gateway. It is **off by
default and only enabled in prod**: the ban keys by real client IP, which the shared-NAT
test contour does not expose (every client arrives as one address), so a ban there would
be self-inflicted — the honeypot/honeytoken still **log** in the contour, only the ban
*action* is gated. Operators see the active bans and lift them on the admin console's
**Throttled** page; the gateway syncs its active set to the backend every 30 s
(`POST /api/v1/internal/bans/sync`, network-trusted like the rejection report) and applies
the operator unbans the response returns, so a manual unban takes effect within the sync
interval.
- Unauthenticated `GET /healthz` (liveness) and `GET /readyz` (readiness — the
database answers a bounded ping and the session cache is warmed).
- The backend serves a **second listener** — a gRPC server
@@ -932,7 +954,7 @@ edits take effect on the next `profile.get` (open/reconnect/foreground), not mid
| Concern | Enforced by |
| --- | --- |
| Public rate limiting / anti-abuse | gateway (per-IP public/email/admin classes, per-user authenticated class; a request body cap of `GATEWAY_MAX_BODY_BYTES`; rejections are metered, summarised to the backend and surfaced in the admin console with a conservative reversible auto-flag — §11) |
| Public rate limiting / anti-abuse | gateway (per-IP public/email/admin classes, per-user authenticated class; a request body cap of `GATEWAY_MAX_BODY_BYTES`; rejections are metered, summarised to the backend and surfaced in the admin console with a conservative reversible auto-flag — §11). In prod a **temporary IP ban** (`GATEWAY_ABUSE_BAN_ENABLED`) blocks an IP that sustains rejections or trips a **honeypot** decoy path / **honeytoken**, refused with 429 before any work; operators lift bans from the console. Off in the shared-NAT test contour, where the client IP is not real (§11) |
| Telegram initData validation (bot-token HMAC) | the Telegram **validator**; the gateway delegates it over gRPC, so the bot token (the HMAC secret) lives only in the validator and the bot, never in the gateway |
| Session minting; email-code / guest validation | gateway (with backend) |
| Session → `user_id` resolution, `X-User-ID` injection | gateway |
+8 -2
View File
@@ -295,8 +295,14 @@ recently throttled users/IPs the gateway reported (an in-memory window — it re
a backend restart) and the accounts currently carrying the soft **high-rate flag**. An
account sustaining rejections past a tunable threshold is flagged automatically —
the marker is reversible, shown as a badge in the user list and on the user card, and
**never blocks play**; the operator reviews and clears it from the user card. There is
no automatic ban.
**never blocks play**; the operator reviews and clears it from the user card. The
account flag itself is never a ban. In **production** the same page also lists the
**active IP bans** the gateway is enforcing: a temporary block of a client IP that
floods the service past a threshold, or trips a hidden **honeypot** path or a planted
**honeytoken** — a high-confidence sign of a scanner or hostile bot, never a normal
player. Each ban shows its reason and expiry with an **Unban** action; bans auto-expire
and the operator can lift one early. IP bans are a production-only safeguard — the
shared test environment cannot tell its clients apart, so it does not enforce them.
The console also lets an operator **manually block** an account — the hard counterpart to the
soft high-rate flag. From the user card the operator blocks the account **permanently** or
+8 -1
View File
@@ -303,7 +303,14 @@ Telegram-identity) или **отправить пост в игровой кан
флагом**. Аккаунт, устойчиво превышающий настраиваемый порог отказов, помечается
автоматически — маркер обратим, виден бейджем в списке пользователей и на карточке
аккаунта и **никогда не блокирует игру**; оператор рассматривает и снимает его с
карточки пользователя. Автоматического бана нет.
карточки пользователя. Сам флаг аккаунта баном не является. В **проде** та же
страница дополнительно перечисляет **активные баны по IP**, которые применяет gateway:
временную блокировку IP клиента, превысившего порог наплыва, либо задевшего скрытую
**honeypot**-ловушку или подброшенный **honeytoken** — высокодостоверный признак
сканера или враждебного бота, но не нормального игрока. У каждого бана показаны причина
и срок, рядом действие **Unban**; баны истекают сами, а оператор может снять бан раньше.
Баны по IP — защита только для прода: общий тестовый контур не различает своих клиентов,
поэтому там не применяется.
Консоль также позволяет оператору **вручную заблокировать** аккаунт — жёсткий аналог мягкого
high-rate флага. С карточки пользователя оператор блокирует аккаунт **навсегда** или **до даты**