mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 03:32:06 +00:00
Admin panel, login throttling, and Cloudflare edge hardening (#150)
* Document the remote shell for production user management * add sitemap to footer links * remove border under theme selection * Add admin theme and user management (#144) Add /admin/themes CRUD and /admin/users list/detail with role and plan editing, guarded by a shared Policy module. Include last-super-admin and self-role protections plus structured id-only admin logs. Also add admin invitations, confirmation resends and password-reset emails, which work in development through the Swoosh mailbox before SES is configured. * Rate-limit password logins and emit auth events (#142) Add a two-bucket login throttle (5 failures per login, 10 per IP in a 15-minute window) and a shared client-address helper for controllers and LiveViews. Blocked attempts skip the database and bcrypt. Log auth.login.failed and auth.login.throttled warnings with boot-scoped HMAC addresses only, and stop repeated confirmation emails on unconfirmed login attempts. * Harden the production login edge for Cloudflare Document the layered login defence: the app throttle is primary, Caddy must pass Cloudflare's CF-Connecting-IP to the app, and Cloudflare edge rate limiting covers request floods. Update the reference Caddyfile to accept only Cloudflare ranges and reject direct-to-origin traffic, and document the exact Cloudflare dashboard rules. * Document 10-second Cloudflare rate-limit window Cloudflare may only offer a 10-second period. Keep the edge rule at 10 login POSTs per 10 seconds per IP and rely on the app's 15-minute login/address throttle for credential guessing. * Document Cloudflare limits for LiveView registration Registration submits over the shared LiveView socket, so a Cloudflare rule on POST /users/register will not count account creations. Note the app-level throttle/Turnstile options instead. * Document current Cloudflare free-plan edge controls Record the production setup: Cloudflare-only Caddy origins, Bot Fight Mode, and the 10-second login flood rule (10 POSTs per 10 seconds, 10-second block). Clarify that the application's 15-minute throttle remains the real credential lockout. * Auto-refresh Cloudflare CIDRs for Caddy Move the origin allowlist into a generated cloudflare-ranges.caddy imported by Caddy. Add an hourly systemd timer and script that fetch Cloudflare's v4/v6 lists, reject malformed responses, validate the candidate Caddyfile, and reload Caddy only when the ranges change. Restore the previous file on validation or reload failure. * Document Cloudflare CIDR refresher setup and operations Record the installed paths, permissions, timer checks, manual run, update procedure, and the direct-on-VPS setup fallback when the deploy directory is absent.
This commit is contained in:
@@ -115,6 +115,21 @@ Prefer identifiers such as `user_id` or `table` over emails, and never log
|
||||
params or request bodies. The formatter is a safety net, not a licence to log
|
||||
PII.
|
||||
|
||||
## Authentication events
|
||||
|
||||
`ChesstrainerWeb.UserSessionController` emits warning lines consumed by
|
||||
host-level tooling such as fail2ban:
|
||||
|
||||
| Message | Metadata | Meaning |
|
||||
|---|---|---|
|
||||
| `auth.login.failed` | `reason` (`invalid_credentials` / `unconfirmed`), `ip` | A password login failed. |
|
||||
| `auth.login.throttled` | `reason` (`ip` / `login`), `ip` | The address or login bucket blocked the attempt before bcrypt. |
|
||||
|
||||
`ip` is a boot-scoped HMAC of the client address, not the address itself. The
|
||||
raw login identifier and password are never included. The login throttle is
|
||||
configured in `config/config.exs` and defaults to five failures per login and
|
||||
ten per address in a fifteen-minute window.
|
||||
|
||||
## Querying logs
|
||||
|
||||
`journalctl` prints the raw line only with `-o cat`; the default output wraps it
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
# Login and edge security
|
||||
|
||||
The login surface is protected in layers. The application throttle is the
|
||||
primary control; Cloudflare is the edge backstop for volume. There is no
|
||||
origin-level fail2ban for HTTP logins, because it would require storing raw IP
|
||||
addresses and would ban Cloudflare edge addresses on this deployment.
|
||||
|
||||
## Current production configuration
|
||||
|
||||
- Caddy accepts only Cloudflare's published ranges and forwards
|
||||
`CF-Connecting-IP` as `X-Forwarded-For`. The ranges are refreshed hourly by
|
||||
`chesstrainer-cloudflare-ranges.timer`.
|
||||
- `TRUST_FORWARDED_FOR=true`, so the app throttles by the real visitor address.
|
||||
- Cloudflare Bot Fight Mode is enabled.
|
||||
- The free-plan login flood rule allows 10 login POSTs per 10 seconds per IP and
|
||||
blocks for 10 seconds.
|
||||
|
||||
The short Cloudflare block is rate smoothing, not a credential lockout. The
|
||||
application's 5-per-login and 10-per-address failures in a 15-minute window are
|
||||
the real control.
|
||||
|
||||
## 1. Application login throttle
|
||||
|
||||
`ChesstrainerWeb.LoginThrottle` counts failures in two buckets:
|
||||
|
||||
| Bucket | Limit | Window |
|
||||
|---|---|---|
|
||||
| Normalised login (email or username) | 5 failures | 15 minutes |
|
||||
| Client address | 10 failures | 15 minutes |
|
||||
|
||||
Blocked attempts are rejected before the database lookup and bcrypt, so they do
|
||||
not consume password-hashing CPU. A successful login clears the login bucket
|
||||
only, keeping the address bucket in place so one address cannot spray many
|
||||
accounts.
|
||||
|
||||
The bucket keys are boot-scoped HMACs. Raw addresses and raw login identifiers
|
||||
are never stored in ETS or written to the application logs. The login form
|
||||
returns the same generic error for unknown accounts, bad passwords and
|
||||
unconfirmed accounts.
|
||||
|
||||
Configured in `config/config.exs`:
|
||||
|
||||
```elixir
|
||||
config :chesstrainer, ChesstrainerWeb.LoginThrottle,
|
||||
window_ms: :timer.minutes(15),
|
||||
max_per_login: 5,
|
||||
max_per_ip: 10,
|
||||
confirmation_cooldown_ms: :timer.minutes(15)
|
||||
```
|
||||
|
||||
`auth.login.failed` and `auth.login.throttled` are documented in
|
||||
`docs/logging.md`.
|
||||
|
||||
## 2. Real client IPs behind Cloudflare and Caddy
|
||||
|
||||
The production chain is:
|
||||
|
||||
```text
|
||||
Internet
|
||||
└─ Cloudflare
|
||||
└─ Caddy :443
|
||||
└─ Phoenix 127.0.0.1:4100
|
||||
```
|
||||
|
||||
Caddy ignores incoming `X-Forwarded-*` values by default and replaces them with
|
||||
the immediate peer address. Behind Cloudflare that peer is a Cloudflare edge
|
||||
node, so without configuration the app would throttle whole Cloudflare POPs
|
||||
rather than individual visitors.
|
||||
|
||||
`deploy/Caddyfile` fixes this by:
|
||||
|
||||
1. accepting only Cloudflare's published ranges, and
|
||||
2. setting `X-Forwarded-For` from Cloudflare's single-value `CF-Connecting-IP`
|
||||
header.
|
||||
|
||||
That keeps `TRUST_FORWARDED_FOR=true` safe: direct clients cannot reach the app
|
||||
through Caddy, so they cannot forge the header.
|
||||
|
||||
`deploy/Caddyfile` imports `cloudflare-ranges.caddy`. The file is generated by
|
||||
`deploy/update-cloudflare-ranges.sh`; do not edit it by hand.
|
||||
|
||||
The script is run hourly by `chesstrainer-cloudflare-ranges.timer`. It:
|
||||
|
||||
- downloads <https://www.cloudflare.com/ips-v4> and
|
||||
<https://www.cloudflare.com/ips-v6>,
|
||||
- rejects empty or malformed responses,
|
||||
- validates the candidate Caddyfile,
|
||||
- reloads Caddy only when the ranges changed.
|
||||
|
||||
If the download, validation or Caddy reload fails, the previous ranges stay in
|
||||
place.
|
||||
|
||||
Install and run it:
|
||||
|
||||
```sh
|
||||
sudo install -m 0755 /opt/chesstrainer/src/deploy/update-cloudflare-ranges.sh \
|
||||
/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/cloudflare-ranges.caddy \
|
||||
/etc/caddy/cloudflare-ranges.caddy
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.service \
|
||||
/etc/systemd/system/chesstrainer-cloudflare-ranges.service
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.timer \
|
||||
/etc/systemd/system/chesstrainer-cloudflare-ranges.timer
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now chesstrainer-cloudflare-ranges.timer
|
||||
sudo systemctl start chesstrainer-cloudflare-ranges.service
|
||||
```
|
||||
|
||||
If `/opt/chesstrainer/src/deploy` is not present on the VPS, create the same
|
||||
four files directly with `sudo tee` from the canonical contents in `deploy/`.
|
||||
The timer only uses the installed copies.
|
||||
|
||||
Check the timer and last run:
|
||||
|
||||
```sh
|
||||
systemctl list-timers chesstrainer-cloudflare-ranges.timer
|
||||
systemctl status chesstrainer-cloudflare-ranges.service
|
||||
journalctl -u chesstrainer-cloudflare-ranges.service --since "24 hours ago"
|
||||
```
|
||||
|
||||
Apply the site block by hand on the shared Caddy host, then validate and
|
||||
reload:
|
||||
|
||||
```sh
|
||||
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||
sudo systemctl reload caddy
|
||||
```
|
||||
|
||||
Direct requests to the origin with a spoofed `CF-Connecting-IP` must receive
|
||||
`403 Access Denied`; only Cloudflare's ranges should reach the Phoenix app. A
|
||||
host firewall allowlist for Cloudflare on ports 80 and 443 is a useful
|
||||
defence-in-depth addition.
|
||||
|
||||
## 3. Cloudflare edge rate limiting
|
||||
|
||||
This is for connection and request floods, not credential guessing. The
|
||||
application already stops password attempts cheaply.
|
||||
|
||||
The production rule is the free-plan version:
|
||||
|
||||
| Setting | Value |
|
||||
|---|---|
|
||||
| Name | Login POST flood |
|
||||
| Expression | `(http.request.method eq "POST" and http.request.uri.path in {"/admin/log-in" "/users/log-in"})` |
|
||||
| Characteristic | IP |
|
||||
| Period | 10 seconds |
|
||||
| Requests | 10 |
|
||||
| Action | Block |
|
||||
| Duration | 10 seconds |
|
||||
|
||||
Because the free plan only offers a 10-second period and a 10-second block, this
|
||||
is a burst limiter rather than a lasting ban. An attacker can retry after ten
|
||||
seconds, but the application still stops that login after five failures and that
|
||||
address after ten failures within fifteen minutes. A slow attacker staying under
|
||||
10 requests per 10 seconds never gets to make useful guesses because of the app
|
||||
throttle.
|
||||
|
||||
Bot Fight Mode is enabled as the plan-level bot control. If the plan later gains
|
||||
longer rate-limit windows or managed WAF rules, raise the block duration and
|
||||
consider a broader site-wide rule, such as 100 requests per 10 seconds per IP
|
||||
with a managed challenge. Use Under Attack Mode during an active incident.
|
||||
|
||||
### Registration cannot be limited this way
|
||||
|
||||
`/users/register` is a LiveView. The form submit is a LiveView event sent over
|
||||
the shared `/live/websocket` connection, not a `POST /users/register` request.
|
||||
Cloudflare therefore cannot count account creations with a rule on the
|
||||
registration path.
|
||||
|
||||
A Cloudflare rule on `GET /users/register` only limits page opens; a bot can
|
||||
open one page and submit many registrations over the socket. If registration
|
||||
spam becomes a problem, add an application-level registration throttle keyed by
|
||||
`ChesstrainerWeb.ClientAddress.from_socket/1`, and/or add Cloudflare Turnstile
|
||||
to the form.
|
||||
|
||||
While `PRELAUNCH=true`, registration is blocked entirely by the prelaunch plug
|
||||
and LiveView mount redirect.
|
||||
|
||||
## 4. Why not fail2ban for HTTP?
|
||||
|
||||
fail2ban needs the raw client address to build a firewall rule. The application
|
||||
deliberately logs only a boot-scoped HMAC, and this deployment sits behind
|
||||
Cloudflare. Banning the address that reaches the origin would ban Cloudflare
|
||||
edges, not attackers.
|
||||
|
||||
fail2ban remains useful for services that terminate connections directly on the
|
||||
VPS, such as SSH. It is not part of the HTTP login defence.
|
||||
Reference in New Issue
Block a user