diff --git a/config/config.exs b/config/config.exs index 8b26f70..feea72e 100644 --- a/config/config.exs +++ b/config/config.exs @@ -39,6 +39,16 @@ config :chesstrainer, ecto_repos: [Chesstrainer.Repo], generators: [timestamp_type: :utc_datetime] +# Password-login throttle. Failures are counted in fixed windows for each +# client address and each normalised login. The address bucket is deliberately +# wider so one account stays protected from distributed guessing while one +# address cannot spray many accounts. +config :chesstrainer, ChesstrainerWeb.LoginThrottle, + window_ms: :timer.minutes(15), + max_per_login: 5, + max_per_ip: 10, + confirmation_cooldown_ms: :timer.minutes(15) + # Glicko rating system. # # `system_constant` is the volatility constraint passed through to the Glicko diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 2d0ff03..a05ff61 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -3,13 +3,36 @@ # This file is not installed automatically. On the shared VPS, add this block # to the existing Caddy config by hand, then validate and reload Caddy. # -# The app listens on loopback only; Caddy is the public entry point. +# Cloudflare sits in front of Caddy. Two things matter here: +# +# 1. Only accept requests from Cloudflare's published edge ranges. +# 2. Replace X-Forwarded-For with Cloudflare's single-value CF-Connecting-IP +# header, so the app's TRUST_FORWARDED_FOR=true path sees the visitor, not a +# Cloudflare edge address. +# +# The ranges live in cloudflare-ranges.caddy next to this file. A systemd +# timer refreshes them from https://www.cloudflare.com/ips-v4 and /ips-v6; +# see deploy/update-cloudflare-ranges.sh and deploy/README.md. innersquare.app { - encode zstd gzip - reverse_proxy 127.0.0.1:4100 + encode zstd gzip + + @cloudflare { + import cloudflare-ranges.caddy + } + + handle @cloudflare { + reverse_proxy 127.0.0.1:4100 { + header_up X-Forwarded-For {http.request.header.CF-Connecting-IP} + } + } + + # Direct-to-origin requests cannot spoof Cloudflare's client-IP header. + handle { + respond "Access Denied" 403 + } } www.innersquare.app { - redir https://innersquare.app{uri} permanent + redir https://innersquare.app{uri} permanent } diff --git a/deploy/README.md b/deploy/README.md index 8772c5b..7c8d3d7 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -4,9 +4,10 @@ Phoenix release on the shared Ubuntu VPS, behind Caddy, with Postgres in Docker. ```text Internet - └─ Caddy :443 - └─ Phoenix release 127.0.0.1:4100 - └─ Postgres 127.0.0.1:5432 + └─ Cloudflare (TLS, WAF, edge rate limiting) + └─ Caddy :443 (cloudflare ranges only) + └─ Phoenix release 127.0.0.1:4100 + └─ Postgres 127.0.0.1:5432 ``` ## Pinned versions @@ -442,13 +443,30 @@ is in place. ## Caddy -On the current VPS the Caddyfile is a single file with no imports. Add the block -from `deploy/Caddyfile` by hand: +Add the site block from `deploy/Caddyfile` by hand. It imports +`cloudflare-ranges.caddy`, which is generated by +`deploy/update-cloudflare-ranges.sh` and refreshed by a systemd timer. + +Caddy must only accept Cloudflare traffic and must replace `X-Forwarded-For` +with Cloudflare's `CF-Connecting-IP` value: ```caddy innersquare.app { encode zstd gzip - reverse_proxy 127.0.0.1:4100 + + @cloudflare { + import cloudflare-ranges.caddy + } + + handle @cloudflare { + reverse_proxy 127.0.0.1:4100 { + header_up X-Forwarded-For {http.request.header.CF-Connecting-IP} + } + } + + handle { + respond "Access Denied" 403 + } } www.innersquare.app { @@ -456,7 +474,72 @@ www.innersquare.app { } ``` -If a new VPS uses imports, put the block in its own site file instead. +Install the range file and the hourly refresh timer: + +```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 +``` + +The installed pieces are: + +| Path | Mode | Purpose | +|---|---|---| +| `/usr/local/sbin/chesstrainer-update-cloudflare-ranges` | `0755` | fetch/validate/reload script | +| `/etc/caddy/cloudflare-ranges.caddy` | `0644` | generated `remote_ip` list | +| `/etc/systemd/system/chesstrainer-cloudflare-ranges.service` | `0644` | oneshot service | +| `/etc/systemd/system/chesstrainer-cloudflare-ranges.timer` | `0644` | hourly timer | + +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 depends on the installed copies; it does not read the repo. + +Run it once manually and enable the timer: + +```sh +sudo systemctl daemon-reload +sudo systemctl enable --now chesstrainer-cloudflare-ranges.timer +sudo systemctl start chesstrainer-cloudflare-ranges.service +sudo journalctl -u chesstrainer-cloudflare-ranges.service -n 50 --no-pager +``` + +The script fetches and +, validates the result, and reloads Caddy +only when the ranges actually changed. If the download, Caddy validation or +reload fails, it keeps or restores the previous file. + +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" +``` + +Do not edit `/etc/caddy/cloudflare-ranges.caddy` by hand; the next timer run +overwrites it. + +To update the refresher itself, replace the installed script or unit files from +the deploy directory, then: + +```sh +sudo systemctl daemon-reload +sudo systemctl restart chesstrainer-cloudflare-ranges.timer +sudo systemctl start chesstrainer-cloudflare-ranges.service +``` + +Without this, `TRUST_FORWARDED_FOR=true` records a Cloudflare edge address +instead of the visitor, and the login throttle and guest puzzle limit bucket +whole Cloudflare POPs together. + +If a new VPS uses imports, put the site block in its own file instead; keep the +`import cloudflare-ranges.caddy` path next to the Caddyfile. Do **not** switch Caddy until a release is running and verified on `127.0.0.1:4100`. Before that, keep the static coming-soon site live. @@ -468,8 +551,16 @@ sudo caddy validate --config /etc/caddy/Caddyfile sudo systemctl reload caddy ``` +A direct request to the origin with a forged `CF-Connecting-IP` header should +receive `403 Access Denied`. + Do not let a deploy overwrite the shared Caddyfile. +See `docs/security.md` for the application throttle, real-IP setup and the +Cloudflare edge controls. Production currently has Bot Fight Mode enabled and +the free-plan login flood rule: 10 POSTs per 10 seconds per IP, blocked for 10 +seconds. + ## Building a release Build on a machine matching Ubuntu 24.04 / glibc 2.39, or let CI do it. @@ -694,6 +785,75 @@ Set `Storage=persistent` and a `SystemMaxUse=` value in rate-limits bursts; if a crash storm drops lines, raise `RateLimitBurst` or `RateLimitIntervalSec` there. +## Interactive shell and user management + +Attach an IEx shell to the **running** release. This does not restart the +service and does not require direct database access: + +```sh +sudo /opt/chesstrainer/current/bin/chesstrainer remote +``` + +You should get a prompt like `iex(chesstrainer@)1>`. Exit with **Ctrl-C +twice**. Never call `System.halt/0`, `:init.stop/0`, or +`Application.stop(:chesstrainer)` from this shell — those stop production. + +Use it for account and role management. Go through the application contexts +(not SQL) so changesets, bcrypt hashing, timestamps, and token bookkeeping stay +consistent: + +```elixir +# Look up by email or username +u = Chesstrainer.Accounts.get_user_by_login("owen") + +# Promote or demote +{:ok, u} = Chesstrainer.Accounts.update_user_role(u, :super_admin) + +# Confirm an account without sending email +{:ok, u} = Chesstrainer.Repo.update(Chesstrainer.Accounts.User.confirm_changeset(u)) + +# Create an account, generating its password server-side +pw = :crypto.strong_rand_bytes(18) |> Base.url_encode64(padding: false) + +{:ok, u} = + Chesstrainer.Accounts.register_user(%{ + email: "you@example.com", + username: "owen", + password: pw + }) + +{:ok, u} = Chesstrainer.Repo.update(Chesstrainer.Accounts.User.confirm_changeset(u)) +pw +``` + +Notes: + +- `register_user/1` hashes the password with bcrypt; `password` is virtual and + is never written to the database. +- Do not type passwords into the shell if you can avoid it — IEx may keep a + history file — and never paste a password from shell history. Generate one as + above and change it later at `/users/profile/settings`. +- `mix accounts.promote` still works when a compiled source checkout is present + on the host, but the release shell is the supported production path. +- There is no guard against demoting the last `super_admin` outside the future + admin UI, so check the result before demoting. + +If `remote` fails while booting its client VM (for example +`Kernel pid terminated (logger)` with `code_server`/`persistent_term` in the +trace), the deployed release is stale, mixed, or missing IEx: rebuild and +redeploy it. To attach in the meantime, use the release's own ERTS: + +```sh +sudo bash -c ' + COOKIE=$(cat /opt/chesstrainer/current/releases/COOKIE) + exec /opt/chesstrainer/current/erts-*/bin/erl \ + -sname debug -setcookie "$COOKIE" -remsh chesstrainer +' +``` + +That shell speaks Erlang syntax, so quote Elixir module atoms, e.g. +`'Elixir.Chesstrainer.Accounts':register_user(...)`. + ## Backups `docker exec` connects over the container's Unix socket, which the Postgres @@ -753,6 +913,9 @@ the VPS regularly. A backup that is only on the VPS is not a backup. until a release exists. 6. Release built on a matching Ubuntu runner and activated. 7. `/health` and `/` verified on `127.0.0.1:4100`. -8. Caddy block added, validated, reloaded. +8. Caddy block, `cloudflare-ranges.caddy`, and the CIDR refresh timer added; + validated and reloaded. 9. Public `/`, `/privacy`, `/terms-conditions`, and `/health` verified. 10. Read-only role created, tunnel verified, backups scheduled and tested. +11. Remote shell attaches and exits cleanly: + `sudo /opt/chesstrainer/current/bin/chesstrainer remote` (Ctrl-C twice). diff --git a/deploy/chesstrainer-cloudflare-ranges.service b/deploy/chesstrainer-cloudflare-ranges.service new file mode 100644 index 0000000..ab2cc43 --- /dev/null +++ b/deploy/chesstrainer-cloudflare-ranges.service @@ -0,0 +1,11 @@ +[Unit] +Description=Refresh Cloudflare CIDRs for Caddy +Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/docs/security.md +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/chesstrainer-update-cloudflare-ranges +TimeoutStartSec=2min +Nice=10 diff --git a/deploy/chesstrainer-cloudflare-ranges.timer b/deploy/chesstrainer-cloudflare-ranges.timer new file mode 100644 index 0000000..1e47a6d --- /dev/null +++ b/deploy/chesstrainer-cloudflare-ranges.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Hourly refresh of Cloudflare CIDRs for Caddy + +[Timer] +OnCalendar=hourly +RandomizedDelaySec=10m +Persistent=true +Unit=chesstrainer-cloudflare-ranges.service + +[Install] +WantedBy=timers.target diff --git a/deploy/cloudflare-ranges.caddy b/deploy/cloudflare-ranges.caddy new file mode 100644 index 0000000..178bed5 --- /dev/null +++ b/deploy/cloudflare-ranges.caddy @@ -0,0 +1,3 @@ +# Generated by deploy/update-cloudflare-ranges.sh. +# Source: https://www.cloudflare.com/ips-v4 and /ips-v6 +remote_ip 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32 diff --git a/deploy/update-cloudflare-ranges.sh b/deploy/update-cloudflare-ranges.sh new file mode 100755 index 0000000..4e1505a --- /dev/null +++ b/deploy/update-cloudflare-ranges.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# +# Refresh Caddy's Cloudflare origin allowlist from Cloudflare's published +# ranges. Called by chesstrainer-cloudflare-ranges.timer. +# +# The generated file is imported by /etc/caddy/Caddyfile: +# +# @cloudflare { +# import cloudflare-ranges.caddy +# } +# +# The script validates the candidate Caddyfile before reloading Caddy. If the +# download or validation fails, the previous ranges stay in place. + +set -euo pipefail + +CADDYFILE="${CADDYFILE:-/etc/caddy/Caddyfile}" +RANGES_FILE="${RANGES_FILE:-/etc/caddy/cloudflare-ranges.caddy}" +CADDY_BIN="${CADDY_BIN:-caddy}" +RELOAD_CMD="${RELOAD_CMD:-systemctl reload caddy}" +LOCK_FILE="${LOCK_FILE:-/run/lock/chesstrainer-cloudflare-ranges.lock}" + +tmpdir="$(mktemp -d)" +trap 'rm -rf "$tmpdir"' EXIT + +exec 9>"$LOCK_FILE" +if ! flock -n 9; then + echo "another Cloudflare range update is already running" >&2 + exit 0 +fi + +fetch() { + local url="$1" + local output="$2" + + curl --fail --silent --show-error --location \ + --proto '=https' \ + --retry 3 --retry-delay 2 --connect-timeout 10 \ + "$url" --output "$output" +} + +validate_download() { + local file="$1" + + [[ -s "$file" ]] || return 1 + + # One CIDR per line. Caddy performs the real validation; this prevents + # obviously malformed or injected content from being written. + if grep -Evq '^[0-9A-Fa-f:.]+/[0-9]{1,3}$' "$file"; then + return 1 + fi +} + +fetch "https://www.cloudflare.com/ips-v4" "$tmpdir/ips-v4" +fetch "https://www.cloudflare.com/ips-v6" "$tmpdir/ips-v6" + +validate_download "$tmpdir/ips-v4" +validate_download "$tmpdir/ips-v6" + +ranges="$(awk 'NF { printf "%s ", $0 }' "$tmpdir/ips-v4" "$tmpdir/ips-v6" | sed -e 's/[[:space:]]*$//')" + +if [[ -z "$ranges" ]]; then + echo "Cloudflare returned an empty CIDR list" >&2 + exit 1 +fi + +candidate="$tmpdir/cloudflare-ranges.caddy" + +{ + echo "# Generated by deploy/update-cloudflare-ranges.sh." + echo "# Source: https://www.cloudflare.com/ips-v4 and /ips-v6" + echo "remote_ip $ranges" +} >"$candidate" + +if cmp -s "$candidate" "$RANGES_FILE"; then + echo "Cloudflare ranges are unchanged" + exit 0 +fi + +install -d -m 0755 "$(dirname "$RANGES_FILE")" + +backup="$tmpdir/previous-ranges.caddy" +if [[ -e "$RANGES_FILE" ]]; then + cp -a "$RANGES_FILE" "$backup" +fi + +install -m 0644 "$candidate" "$RANGES_FILE" + +if ! "$CADDY_BIN" validate --config "$CADDYFILE" --adapter caddyfile; then + echo "Caddy rejected the new Cloudflare ranges; restoring the previous file" >&2 + + if [[ -e "$backup" ]]; then + install -m 0644 "$backup" "$RANGES_FILE" + else + rm -f "$RANGES_FILE" + fi + + exit 1 +fi + +read -r -a reload_command <<<"$RELOAD_CMD" + +if ! "${reload_command[@]}"; then + echo "Caddy reload failed; restoring the previous ranges" >&2 + + if [[ -e "$backup" ]]; then + install -m 0644 "$backup" "$RANGES_FILE" + else + rm -f "$RANGES_FILE" + fi + + exit 1 +fi + +echo "Cloudflare ranges updated and Caddy reloaded" diff --git a/docs/logging.md b/docs/logging.md index 22a9fc5..7be6193 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -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 diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..d77b596 --- /dev/null +++ b/docs/security.md @@ -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 and + , +- 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. diff --git a/lib/chesstrainer/accounts.ex b/lib/chesstrainer/accounts.ex index eb3fcc7..a47de36 100644 --- a/lib/chesstrainer/accounts.ex +++ b/lib/chesstrainer/accounts.ex @@ -4,11 +4,14 @@ defmodule Chesstrainer.Accounts do """ import Ecto.Query, warn: false + require Logger alias Chesstrainer.Repo - alias Chesstrainer.Accounts.{User, UserToken, UserNotifier} + alias Chesstrainer.Accounts.{Policy, Role, Scope, User, UserToken, UserNotifier} alias Chesstrainer.MailingList + @admin_users_per_page 25 + ## Database getters @doc """ @@ -165,6 +168,308 @@ defmodule Chesstrainer.Accounts do |> Repo.update() end + ## Admin user management + + @doc """ + Returns a page of users the scope may administer, newest first. + + Options: + + * `:search` - case-insensitive match on email or username + * `:page` - 1-based page number (defaults to 1) + * `:per_page` - page size (defaults to 25, capped at 100) + + Admins only see members and moderators; super admins see every role. + Returns `{:error, :unauthorized}` when the scope lacks user management. + """ + def list_users_for_admin(scope, opts \\ []) do + with :ok <- ensure_manage_users(scope) do + page = normalize_page(Keyword.get(opts, :page, 1)) + per_page = normalize_per_page(Keyword.get(opts, :per_page, @admin_users_per_page)) + offset = (page - 1) * per_page + + users = + scope + |> admin_users_query(opts) + |> order_by([u], desc: u.inserted_at, desc: u.id) + |> limit(^per_page) + |> offset(^offset) + |> Repo.all() + + {:ok, users} + end + end + + @doc """ + Counts the users visible to the scope, using the same filters as + `list_users_for_admin/2`. + """ + def count_users_for_admin(scope, opts \\ []) do + with :ok <- ensure_manage_users(scope) do + count = + scope + |> admin_users_query(opts) + |> select([u], count(u.id)) + |> Repo.one() + + {:ok, count} + end + end + + @doc """ + Fetches a user for the admin detail page. + + Returns `{:error, :unauthorized}` when the scope may not view the target and + `{:error, :not_found}` for an unknown id. + """ + def get_user_for_admin(scope, id) do + with :ok <- ensure_manage_users(scope) do + case fetch_user(id) do + nil -> + {:error, :not_found} + + %User{} = user -> + if Policy.can_view_user?(scope, user) do + {:ok, user} + else + {:error, :unauthorized} + end + end + end + end + + @doc """ + Returns an `%Ecto.Changeset{}` for the admin-editable fields (role and plan). + """ + def change_user_as_admin(%User{} = user, attrs \\ %{}) do + User.admin_changeset(user, attrs) + end + + @doc """ + Updates a user's role and plan after enforcing the admin capability matrix. + + The last-super-admin check runs inside the update transaction with a row lock, + so concurrent demotions cannot remove the final super admin. + + Returns `{:error, :unauthorized}`, `{:error, :own_role}`, + `{:error, :last_super_admin}` or `{:error, %Ecto.Changeset{}}` instead of + raising. + """ + def update_user_as_admin(scope, %User{} = user, attrs) do + changeset = User.admin_changeset(user, attrs) + role_change = Ecto.Changeset.get_change(changeset, :role) + + with :ok <- ensure_manage_users(scope), + :ok <- ensure_not_own_role_change(scope, user, role_change), + :ok <- ensure_can_manage_user(scope, user), + :ok <- ensure_can_assign_role(scope, role_change), + {:ok, updated} <- persist_user_changes(user, changeset) do + log_user_update(scope, user, changeset) + {:ok, updated} + end + end + + @doc """ + Creates an invitation and emails the recipient a link to choose a password. + + The account is confirmed but has no password until the invitee follows the + link. `invite_url_fun` receives the encoded token and must return a URL. + """ + def invite_user_as_admin(scope, attrs, invite_url_fun) + when is_function(invite_url_fun, 1) do + role = normalize_role(role_param(attrs) || :member) + + with :ok <- ensure_manage_users(scope), + :ok <- ensure_can_assign_role(scope, role) do + changeset = + %User{} + |> User.invite_changeset(attrs) + |> User.admin_changeset(attrs) + + case Repo.insert(changeset) do + {:ok, user} -> + Logger.info("admin.user.invited", + actor_id: scope.user.id, + target_id: user.id, + fields: [:invite] + ) + + case deliver_invite_instructions(user, invite_url_fun) do + {:ok, _email} -> {:ok, user} + {:error, reason} -> {:error, reason} + end + + {:error, changeset} -> + {:error, changeset} + end + end + end + + @doc """ + Sends a password-reset email on behalf of an administrator. + + Uses the same policy as the editable user screen: an admin cannot trigger a + reset for another admin or a super admin. + """ + def send_user_reset_password_instructions_as_admin(scope, %User{} = user, reset_url_fun) + when is_function(reset_url_fun, 1) do + with :ok <- ensure_manage_users(scope), + :ok <- ensure_can_manage_user(scope, user) do + case deliver_user_reset_password_instructions(user, reset_url_fun) do + {:ok, email} -> + Logger.info("admin.user.password_reset_sent", + actor_id: scope.user.id, + target_id: user.id + ) + + {:ok, email} + + error -> + error + end + end + end + + @doc """ + Resends the account-confirmation email on behalf of an administrator. + """ + def resend_user_confirmation_instructions_as_admin(scope, %User{} = user, confirmation_url_fun) + when is_function(confirmation_url_fun, 1) do + with :ok <- ensure_manage_users(scope), + :ok <- ensure_can_manage_user(scope, user) do + case deliver_user_confirmation_instructions(user, confirmation_url_fun) do + {:ok, email} -> + Logger.info("admin.user.confirmation_resent", + actor_id: scope.user.id, + target_id: user.id + ) + + {:ok, email} + + error -> + error + end + end + end + + defp admin_users_query(scope, opts) do + roles = Policy.visible_roles(scope) + search = opts |> Keyword.get(:search, "") |> to_string() |> String.trim() + + query = from(u in User, where: u.role in ^roles) + + if search == "" do + query + else + pattern = "%#{search}%" + + where( + query, + [u], + ilike(u.email, ^pattern) or ilike(u.username, ^pattern) + ) + end + end + + defp persist_user_changes(user, changeset) do + Repo.transact(fn -> + with :ok <- ensure_not_last_super_admin(user, changeset), + {:ok, updated} <- Repo.update(changeset) do + {:ok, updated} + end + end) + end + + defp ensure_not_last_super_admin(%User{role: :super_admin}, changeset) do + case Ecto.Changeset.get_change(changeset, :role) do + role when role in [nil, :super_admin] -> + :ok + + _role -> + super_admins = + Repo.all(from(u in User, where: u.role == :super_admin, lock: "FOR UPDATE")) + + if length(super_admins) <= 1 do + {:error, :last_super_admin} + else + :ok + end + end + end + + defp ensure_not_last_super_admin(_user, _changeset), do: :ok + + defp log_user_update(scope, user, changeset) do + fields = changeset.changes |> Map.keys() |> Enum.sort() + + if fields != [] do + Logger.info("admin.user.updated", + actor_id: scope.user.id, + target_id: user.id, + fields: fields + ) + end + end + + defp deliver_invite_instructions(user, invite_url_fun) do + {encoded_token, user_token} = UserToken.build_email_token(user, "reset_password") + Repo.insert!(user_token) + UserNotifier.deliver_invite_instructions(user, invite_url_fun.(encoded_token)) + end + + defp ensure_manage_users(scope) do + if Policy.can?(scope, :manage_users), do: :ok, else: {:error, :unauthorized} + end + + defp ensure_can_manage_user(scope, user) do + if Policy.can_manage_user?(scope, user), do: :ok, else: {:error, :unauthorized} + end + + defp ensure_can_assign_role(_scope, nil), do: :ok + + defp ensure_can_assign_role(scope, role) do + if Policy.can_assign_role?(scope, role), do: :ok, else: {:error, :unauthorized} + end + + defp ensure_not_own_role_change(%Scope{user: %User{id: id}}, %User{id: id}, role) + when not is_nil(role), + do: {:error, :own_role} + + defp ensure_not_own_role_change(_scope, _user, _role), do: :ok + + defp fetch_user(id) do + Repo.get(User, id) + rescue + Ecto.Query.CastError -> nil + end + + defp role_param(attrs), do: Map.get(attrs, "role") || Map.get(attrs, :role) + + defp normalize_role(role) do + cond do + role in Role.values() -> role + is_binary(role) -> Enum.find(Role.values(), &(Atom.to_string(&1) == role)) + true -> nil + end + end + + defp normalize_page(page) when is_integer(page) and page > 0, do: page + + defp normalize_page(page) when is_binary(page) do + case Integer.parse(page) do + {number, ""} when number > 0 -> number + _ -> 1 + end + end + + defp normalize_page(_page), do: 1 + + defp normalize_per_page(per_page) when is_integer(per_page) and per_page > 0 do + min(per_page, 100) + end + + defp normalize_per_page(_per_page), do: @admin_users_per_page + ## Settings @doc """ diff --git a/lib/chesstrainer/accounts/policy.ex b/lib/chesstrainer/accounts/policy.ex new file mode 100644 index 0000000..3fd8bab --- /dev/null +++ b/lib/chesstrainer/accounts/policy.ex @@ -0,0 +1,100 @@ +defmodule Chesstrainer.Accounts.Policy do + @moduledoc """ + The single source of truth for administrator capabilities. + + Roles are ordered by `Chesstrainer.Accounts.Role`. An administrator may only + manage users below their own rank; a `super_admin` may also manage admins and + other super admins, but never changes their own role. + + The router uses `can?/2` to gate the admin area, and every mutating admin + LiveView calls back into this module or into the scoped `Accounts` functions + so hidden buttons are never the only protection. + """ + + alias Chesstrainer.Accounts.{Role, Scope, User} + + @capabilities %{ + manage_endgames: [:admin, :super_admin], + manage_themes: [:admin, :super_admin], + manage_users: [:admin, :super_admin] + } + + @doc "All admin capabilities." + @spec capabilities() :: [atom()] + def capabilities, do: Map.keys(@capabilities) + + @doc """ + Returns true when the scope may perform the given admin capability. + + A nil scope or a member/moderator never satisfies an admin capability. + """ + @spec can?(Scope.t() | nil, atom()) :: boolean() + def can?(%Scope{user: %User{role: role}}, capability) when is_atom(capability) do + role in Map.get(@capabilities, capability, []) + end + + def can?(_scope, _capability), do: false + + @doc """ + Returns true when the scope may edit the target user's role and plan. + + An actor may only modify a user whose role rank is strictly lower, except a + `super_admin`, who may also modify admins and other super admins. Nobody may + modify themselves through the admin area. + """ + @spec can_manage_user?(Scope.t() | nil, User.t()) :: boolean() + def can_manage_user?(%Scope{user: %User{} = actor} = scope, %User{} = target) do + cond do + not can?(scope, :manage_users) -> false + actor.id == target.id -> false + actor.role == :super_admin -> true + Role.rank(actor.role) > Role.rank(target.role) -> true + true -> false + end + end + + def can_manage_user?(_scope, _target), do: false + + @doc """ + Returns true when the scope may view the target user in the admin area. + + Admins can see themselves and lower-ranked users read-only; super admins can + see everyone. This is deliberately wider than `can_manage_user?/2`, which + controls the editable form. + """ + @spec can_view_user?(Scope.t() | nil, User.t()) :: boolean() + def can_view_user?(%Scope{user: %User{} = actor} = scope, %User{} = target) do + can?(scope, :manage_users) and + (actor.id == target.id or actor.role == :super_admin or + Role.rank(actor.role) > Role.rank(target.role)) + end + + def can_view_user?(_scope, _target), do: false + + @doc """ + Returns true when the scope may assign the given role. + + Admins can only assign member or moderator. Super admins can assign any role. + """ + @spec can_assign_role?(Scope.t() | nil, Role.value()) :: boolean() + def can_assign_role?(%Scope{user: %User{role: :super_admin}}, role) do + role in Role.values() + end + + def can_assign_role?(%Scope{user: %User{role: actor_role}}, role) do + role in Role.values() and Role.rank(actor_role) > Role.rank(role) + end + + def can_assign_role?(_scope, _role), do: false + + @doc """ + Returns the roles whose users the scope may see in the admin user list. + + Admins only see members and moderators; super admins see every role. + """ + @spec visible_roles(Scope.t() | nil) :: [Role.value()] + def visible_roles(%Scope{user: %User{role: :super_admin}}), do: Role.values() + + def visible_roles(%Scope{user: %User{role: :admin}}), do: [:member, :moderator] + def visible_roles(_scope), do: [] +end diff --git a/lib/chesstrainer/accounts/role.ex b/lib/chesstrainer/accounts/role.ex index e10433b..715b24c 100644 --- a/lib/chesstrainer/accounts/role.ex +++ b/lib/chesstrainer/accounts/role.ex @@ -6,6 +6,8 @@ defmodule Chesstrainer.Accounts.Role do should ask for the minimum tier they need via `at_least?/2`. """ + @type value :: :member | :moderator | :admin | :super_admin + @values [:member, :moderator, :admin, :super_admin] @ranks %{ diff --git a/lib/chesstrainer/accounts/scope.ex b/lib/chesstrainer/accounts/scope.ex index 9cd0a09..4878b78 100644 --- a/lib/chesstrainer/accounts/scope.ex +++ b/lib/chesstrainer/accounts/scope.ex @@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.Scope do defstruct user: nil + @type t :: %__MODULE__{user: User.t() | nil} + @doc """ Creates a scope for the given user. diff --git a/lib/chesstrainer/accounts/user.ex b/lib/chesstrainer/accounts/user.ex index 97eb410..2af41d2 100644 --- a/lib/chesstrainer/accounts/user.ex +++ b/lib/chesstrainer/accounts/user.ex @@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.User do timestamps(type: :utc_datetime) end + @type t :: %__MODULE__{} + @doc """ A user changeset for registration. @@ -53,6 +55,32 @@ defmodule Chesstrainer.Accounts.User do |> validate_required([:role]) end + @doc """ + A user changeset for an admin-created invitation. + + The account is created without a password and marked confirmed, so the + recipient can choose a password from the emailed invitation link and log in + immediately afterwards. Role and plan are applied separately by + `admin_changeset/2` after the caller has checked the policy. + """ + def invite_changeset(user, attrs) do + user + |> cast(attrs, [:email, :username]) + |> validate_email([]) + |> validate_username([]) + |> put_change(:confirmed_at, DateTime.utc_now(:second)) + end + + @doc """ + A user changeset for the fields an administrator may edit. + + These values are programmatic, so this changeset is only used by the scoped + admin functions in `Chesstrainer.Accounts`. + """ + def admin_changeset(user, attrs) do + cast(user, attrs, [:role, :plan]) + end + @doc """ A user changeset for registering or changing the email. diff --git a/lib/chesstrainer/accounts/user_notifier.ex b/lib/chesstrainer/accounts/user_notifier.ex index db555e6..83d3bcb 100644 --- a/lib/chesstrainer/accounts/user_notifier.ex +++ b/lib/chesstrainer/accounts/user_notifier.ex @@ -38,6 +38,31 @@ defmodule Chesstrainer.Accounts.UserNotifier do """) end + @doc """ + Deliver an invitation to choose a password. + + Admins create the account without a password; the invitation link uses the + same reset-password token flow so the recipient can set one. + """ + def deliver_invite_instructions(user, url) do + deliver(user.email, "You're invited to #{Branding.name()}", """ + + ============================== + + Hi #{user.username}, + + An administrator has created an account for you on #{Branding.name()}. + + Choose your password by visiting the URL below: + + #{url} + + If you weren't expecting this invitation, please ignore this email. + + ============================== + """) + end + @doc """ Deliver instructions to reset a user password. """ diff --git a/lib/chesstrainer/application.ex b/lib/chesstrainer/application.ex index 4cbf3bf..e3ea21f 100644 --- a/lib/chesstrainer/application.ex +++ b/lib/chesstrainer/application.ex @@ -17,6 +17,7 @@ defmodule Chesstrainer.Application do # Start a worker by calling: Chesstrainer.Worker.start_link(arg) # {Chesstrainer.Worker, arg}, Chesstrainer.GuestLimits, + ChesstrainerWeb.LoginThrottle, # Start to serve requests, typically the last entry ChesstrainerWeb.Endpoint, {Registry, keys: :unique, name: Chesstrainer.CacheRegistry}, diff --git a/lib/chesstrainer/themes.ex b/lib/chesstrainer/themes.ex index 81789b9..d1cc8f7 100644 --- a/lib/chesstrainer/themes.ex +++ b/lib/chesstrainer/themes.ex @@ -21,6 +21,43 @@ defmodule Chesstrainer.Themes do Repo.all(Theme) end + @doc """ + Lists themes for the admin index with their endgame usage count. + + Options: + + * `:search` - case-insensitive match on the theme name + * `:category` - one of `:endgame`, `:opening`, `:tactic`, or blank for all + + Returns `{theme, usage_count}` tuples sorted by name. + """ + def list_themes_for_admin(opts \\ []) do + search = opts |> Keyword.get(:search, "") |> to_string() |> String.trim() + category = normalize_category(Keyword.get(opts, :category, "")) + + query = from(t in Theme, order_by: [asc: t.name]) + + query = + if search == "" do + query + else + where(query, [t], ilike(t.name, ^"%#{search}%")) + end + + query = + if category do + where(query, [t], t.category == ^category) + else + query + end + + query + |> join(:left, [t], j in "endgames_themes", on: j.theme_id == t.id) + |> group_by([t], t.id) + |> select([t, j], {t, count(j.endgame_id)}) + |> Repo.all() + end + @doc """ Gets a single theme. @@ -153,4 +190,13 @@ defmodule Chesstrainer.Themes do def names(themes) when is_list(themes) do themes |> Enum.map(& &1.name) |> Enum.sort() end + + defp normalize_category(category) when category in [:endgame, :opening, :tactic], + do: category + + defp normalize_category(category) when is_binary(category) do + Enum.find([:endgame, :opening, :tactic], &(Atom.to_string(&1) == category)) + end + + defp normalize_category(_category), do: nil end diff --git a/lib/chesstrainer_web/client_address.ex b/lib/chesstrainer_web/client_address.ex new file mode 100644 index 0000000..ce80906 --- /dev/null +++ b/lib/chesstrainer_web/client_address.ex @@ -0,0 +1,84 @@ +defmodule ChesstrainerWeb.ClientAddress do + @moduledoc """ + Resolves the client's IP address from either a controller connection or a + LiveView socket. + + `X-Forwarded-For` is only read when + `Chesstrainer.GuestLimits.trust_forwarded_for?/0` is enabled. In that case the + rightmost entry is used, because that is the value our own proxy appended. + Invalid or missing headers fall back to the peer address. + + Production is Cloudflare -> Caddy -> Phoenix. `deploy/Caddyfile` makes Caddy + overwrite `X-Forwarded-For` with Cloudflare's `CF-Connecting-IP` and rejects + direct-to-origin requests, so the rightmost value is the real visitor rather + than a Cloudflare edge address. + """ + + alias Chesstrainer.GuestLimits + + @typedoc "An IPv4/IPv6 address, or `nil` when no peer data is available." + @type address :: :inet.ip_address() | nil + + @doc "Returns the client address for a controller connection." + @spec from_conn(Plug.Conn.t()) :: address() + def from_conn(conn) do + if GuestLimits.trust_forwarded_for?() do + conn + |> Plug.Conn.get_req_header("x-forwarded-for") + |> parse_forwarded_header() + |> fallback(conn.remote_ip) + else + conn.remote_ip + end + end + + @doc "Returns the client address for a connected LiveView socket." + @spec from_socket(Phoenix.LiveView.Socket.t()) :: address() + def from_socket(socket) do + if GuestLimits.trust_forwarded_for?() do + socket + |> Phoenix.LiveView.get_connect_info(:x_headers) + |> parse_x_headers() + |> fallback(peer_address(socket)) + else + peer_address(socket) + end + end + + defp peer_address(socket) do + case Phoenix.LiveView.get_connect_info(socket, :peer_data) do + %{address: address} -> address + _ -> nil + end + end + + defp parse_forwarded_header([value | _]) when is_binary(value), do: parse_address(value) + defp parse_forwarded_header(_headers), do: nil + + defp parse_x_headers(headers) when is_list(headers) do + case List.keyfind(headers, "x-forwarded-for", 0) do + {_, value} when is_binary(value) -> parse_address(value) + _ -> nil + end + end + + defp parse_x_headers(_headers), do: nil + + # The rightmost entry is the one our own proxy appended. + defp parse_address(value) do + value + |> String.split(",") + |> List.last() + |> to_string() + |> String.trim() + |> String.to_charlist() + |> :inet.parse_address() + |> case do + {:ok, address} -> address + {:error, _} -> nil + end + end + + defp fallback(nil, fallback), do: fallback + defp fallback(address, _fallback), do: address +end diff --git a/lib/chesstrainer_web/components/layouts.ex b/lib/chesstrainer_web/components/layouts.ex index c40518f..5b43e59 100644 --- a/lib/chesstrainer_web/components/layouts.ex +++ b/lib/chesstrainer_web/components/layouts.ex @@ -5,6 +5,7 @@ defmodule ChesstrainerWeb.Layouts do """ use ChesstrainerWeb, :html + alias Chesstrainer.Accounts.Policy alias Chesstrainer.Accounts.Role alias Chesstrainer.Accounts.Scope @@ -133,6 +134,42 @@ defmodule ChesstrainerWeb.Layouts do """ end + @doc """ + Renders the shared sub-navigation for admin pages. + + Items are filtered by capability, so the same component is safe to render on + every admin screen. + """ + attr :current_scope, :map, default: nil + + def admin_nav(assigns) do + links = + for {capability, label, href} <- [ + {:manage_endgames, "Endgames", ~p"/admin/endgames"}, + {:manage_themes, "Themes", ~p"/admin/themes"}, + {:manage_users, "Users", ~p"/admin/users"} + ], + Policy.can?(assigns.current_scope, capability), + do: %{label: label, href: href} + + assigns = assign(assigns, :links, links) + + ~H""" + + """ + end + defp nav_links(scope) do marketing = if Scope.premium?(scope) do @@ -187,6 +224,7 @@ defmodule ChesstrainerWeb.Layouts do Privacy Policy Terms & Conditions Mentions légales + Sitemap © {@year} {Branding.name()} diff --git a/lib/chesstrainer_web/controllers/user_session_controller.ex b/lib/chesstrainer_web/controllers/user_session_controller.ex index def9622..f4f3f1f 100644 --- a/lib/chesstrainer_web/controllers/user_session_controller.ex +++ b/lib/chesstrainer_web/controllers/user_session_controller.ex @@ -1,7 +1,11 @@ defmodule ChesstrainerWeb.UserSessionController do use ChesstrainerWeb, :controller + require Logger + alias Chesstrainer.Accounts + alias ChesstrainerWeb.ClientAddress + alias ChesstrainerWeb.LoginThrottle alias ChesstrainerWeb.UserAuth def create(conn, %{"user" => user_params}) do @@ -17,32 +21,78 @@ defmodule ChesstrainerWeb.UserSessionController do end defp authenticate(conn, user_params, failure_path, success_path) do + %{"email" => login} = user_params + address = ClientAddress.from_conn(conn) + + case LoginThrottle.check(address, login) do + :ok -> + attempt_login(conn, address, user_params, failure_path, success_path) + + {:throttled, bucket, retry_in_ms} -> + log_auth_event("auth.login.throttled", address, reason: bucket) + + conn + |> put_flash(:error, throttle_message(retry_in_ms)) + |> redirect(to: failure_path) + end + end + + defp attempt_login(conn, address, user_params, failure_path, success_path) do %{"email" => login, "password" => password} = user_params case Accounts.get_user_by_login_and_password(login, password) do nil -> - invalid_credentials(conn, login, failure_path) + authentication_failed(conn, address, login, :invalid_credentials, failure_path) user -> if user.confirmed_at do + LoginThrottle.record_success(login) + conn |> maybe_put_return_to(success_path) |> put_flash(:info, "Welcome back!") |> UserAuth.log_in_user(user, user_params) else - {:ok, _} = - Accounts.deliver_user_confirmation_instructions( - user, - &url(~p"/users/confirm/#{&1}") - ) - - # In order to prevent user enumeration attacks, report the same error - # as invalid credentials. - invalid_credentials(conn, login, failure_path) + maybe_resend_confirmation(user, login) + authentication_failed(conn, address, login, :unconfirmed, failure_path) end end end + defp maybe_resend_confirmation(user, login) do + if LoginThrottle.claim_confirmation_resend(login) do + case Accounts.deliver_user_confirmation_instructions( + user, + &url(~p"/users/confirm/#{&1}") + ) do + {:ok, _email} -> :ok + {:error, _reason} -> Logger.warning("auth.confirmation.resend_failed") + end + end + + :ok + end + + defp authentication_failed(conn, address, login, reason, failure_path) do + LoginThrottle.record_failure(address, login) + log_auth_event("auth.login.failed", address, reason: reason) + + # In order to prevent user enumeration attacks, report the same error as + # invalid credentials. + invalid_credentials(conn, login, failure_path) + end + + defp log_auth_event(message, address, metadata) do + Logger.warning(message, Keyword.put(metadata, :ip, LoginThrottle.fingerprint(address))) + end + + defp throttle_message(retry_in_ms) do + minutes = max(div(retry_in_ms + 59_999, 60_000), 1) + unit = if minutes == 1, do: "minute", else: "minutes" + + "Too many attempts. Try again in #{minutes} #{unit}." + end + defp invalid_credentials(conn, login, path) do conn |> put_flash(:error, "Invalid email, username or password") diff --git a/lib/chesstrainer_web/live/admin/theme_live/form.ex b/lib/chesstrainer_web/live/admin/theme_live/form.ex new file mode 100644 index 0000000..403effb --- /dev/null +++ b/lib/chesstrainer_web/live/admin/theme_live/form.ex @@ -0,0 +1,114 @@ +defmodule ChesstrainerWeb.Admin.ThemeLive.Form do + use ChesstrainerWeb, :live_view + + alias Chesstrainer.Accounts.Policy + alias Chesstrainer.Themes + alias Chesstrainer.Themes.Theme + + @category_options [ + {"Endgame", "endgame"}, + {"Opening", "opening"}, + {"Tactic", "tactic"} + ] + + @impl true + def render(assigns) do + ~H""" + + + + <.header> + {@page_title} + <:subtitle> + Themes group endgames for filtering. Names must be unique within a category, + ignoring case. + + + + <.form for={@form} id="theme-form" phx-change="validate" phx-submit="save"> + <.input field={@form[:name]} type="text" label="Name" autocomplete="off" required /> + <.input + field={@form[:category]} + type="select" + label="Category" + options={@category_options} + /> + +
+ <.button phx-disable-with="Saving..." variant="primary">Save theme + <.button navigate={~p"/admin/themes"}>Cancel +
+ +
+ """ + end + + @impl true + def mount(params, _session, socket) do + {:ok, apply_action(socket, socket.assigns.live_action, params)} + end + + defp apply_action(socket, :new, _params) do + theme = %Theme{} + + socket + |> assign(:page_title, "New theme") + |> assign(:theme, theme) + |> assign(:category_options, @category_options) + |> assign(:form, to_form(Themes.change_theme(theme))) + end + + defp apply_action(socket, :edit, %{"id" => id}) do + theme = Themes.get_theme!(id) + + socket + |> assign(:page_title, "Edit theme") + |> assign(:theme, theme) + |> assign(:category_options, @category_options) + |> assign(:form, to_form(Themes.change_theme(theme))) + end + + @impl true + def handle_event("validate", %{"theme" => theme_params}, socket) do + changeset = + socket.assigns.theme + |> Themes.change_theme(theme_params) + |> Map.put(:action, :validate) + + {:noreply, assign(socket, :form, to_form(changeset, action: :validate))} + end + + def handle_event("save", %{"theme" => theme_params}, socket) do + if Policy.can?(socket.assigns.current_scope, :manage_themes) do + save_theme(socket, socket.assigns.live_action, theme_params) + else + {:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")} + end + end + + defp save_theme(socket, :new, theme_params) do + case Themes.create_theme(theme_params) do + {:ok, _theme} -> + {:noreply, + socket + |> put_flash(:info, "Theme created successfully.") + |> push_navigate(to: ~p"/admin/themes")} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, :form, to_form(changeset, action: :insert))} + end + end + + defp save_theme(socket, :edit, theme_params) do + case Themes.update_theme(socket.assigns.theme, theme_params) do + {:ok, _theme} -> + {:noreply, + socket + |> put_flash(:info, "Theme updated successfully.") + |> push_navigate(to: ~p"/admin/themes")} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, :form, to_form(changeset, action: :insert))} + end + end +end diff --git a/lib/chesstrainer_web/live/admin/theme_live/index.ex b/lib/chesstrainer_web/live/admin/theme_live/index.ex new file mode 100644 index 0000000..0e73d3a --- /dev/null +++ b/lib/chesstrainer_web/live/admin/theme_live/index.ex @@ -0,0 +1,160 @@ +defmodule ChesstrainerWeb.Admin.ThemeLive.Index do + use ChesstrainerWeb, :live_view + + alias Chesstrainer.Accounts.Policy + alias Chesstrainer.Themes + + @category_options [ + {"All categories", ""}, + {"Endgame", "endgame"}, + {"Opening", "opening"}, + {"Tactic", "tactic"} + ] + + @impl true + def render(assigns) do + ~H""" + + + + <.header> + Themes + <:subtitle> + Themes group endgames for filtering and puzzle selection. Deleting a theme detaches + it from every endgame and leaves the endgames intact. + + <:actions> + <.button variant="primary" navigate={~p"/admin/themes/new"}> + <.icon name="hero-plus" /> New theme + + + + + <.form + for={@filter_form} + id="theme-admin-filter-form" + phx-change="filter" + class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-end" + > +
+ <.input + field={@filter_form[:search]} + type="text" + label="Search by name" + autocomplete="off" + phx-debounce="200" + placeholder="Theme name…" + /> +
+
+ <.input + field={@filter_form[:category]} + type="select" + label="Category" + options={@category_options} + /> +
+ + +

+ <%= if @has_filters do %> + No themes match these filters. + <% else %> + No themes yet. Themes power endgame filtering and puzzle selection, so start by + creating one and attaching it to an endgame. + <% end %> +

+ + + + + + + + + + + + + + + + + + +
NameCategoryUsed byActions
{theme.name}{theme.category} + {usage_label(usage_count)} + +
+ <.link navigate={~p"/admin/themes/#{theme.id}/edit"}>Edit + <.link + phx-click="delete" + phx-value-id={theme.id} + data-confirm={ + "Delete #{theme.name}? Used by #{usage_label(usage_count)}. " <> + "The endgames will be kept and simply detached." + } + > + Delete + +
+
+
+ """ + end + + @impl true + def mount(_params, _session, socket) do + {:ok, + socket + |> assign(:page_title, "Themes") + |> assign(:search, "") + |> assign(:category, "") + |> assign(:has_filters, false) + |> assign(:category_options, @category_options) + |> assign(:filter_form, to_form(%{"search" => "", "category" => ""})) + |> load_themes()} + end + + @impl true + def handle_event("filter", params, socket) do + search = Map.get(params, "search", socket.assigns.search) + category = Map.get(params, "category", socket.assigns.category) + + {:noreply, + socket + |> assign(:search, search) + |> assign(:category, category) + |> assign(:has_filters, String.trim(search) != "" or category != "") + |> load_themes()} + end + + def handle_event("delete", %{"id" => id}, socket) do + if Policy.can?(socket.assigns.current_scope, :manage_themes) do + theme = Themes.get_theme!(id) + {:ok, _theme} = Themes.delete_theme(theme) + + socket = + socket + |> put_flash(:info, "Theme deleted. Attached endgames were kept.") + |> load_themes() + + {:noreply, socket} + else + {:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")} + end + end + + defp load_themes(socket) do + themes = + Themes.list_themes_for_admin( + search: socket.assigns.search, + category: socket.assigns.category + ) + + assign(socket, :themes, themes) + end + + defp usage_label(1), do: "1 endgame" + defp usage_label(count), do: "#{count} endgames" +end diff --git a/lib/chesstrainer_web/live/admin/user_live/index.ex b/lib/chesstrainer_web/live/admin/user_live/index.ex new file mode 100644 index 0000000..e051421 --- /dev/null +++ b/lib/chesstrainer_web/live/admin/user_live/index.ex @@ -0,0 +1,177 @@ +defmodule ChesstrainerWeb.Admin.UserLive.Index do + use ChesstrainerWeb, :live_view + + alias Chesstrainer.Accounts + + @per_page 25 + + @impl true + def render(assigns) do + ~H""" + + + + <.header> + Users + <:subtitle> + Search accounts, review their roles and plans, and open a user to edit them. + Admins only see members and moderators. + + <:actions> + <.button variant="primary" navigate={~p"/admin/users/new"}> + <.icon name="hero-plus" /> Invite user + + + + + <.form for={@filter_form} id="admin-user-search-form" phx-change="search" class="mb-6"> + <.input + field={@filter_form[:search]} + type="search" + label="Search by email or username" + autocomplete="off" + phx-debounce="200" + placeholder="email or username…" + /> + + +

+ <%= if @search == "" do %> + No users are visible to you yet. + <% else %> + No users match “{@search}”. + <% end %> +

+ + + + + + + + + + + + + + + user.id}> + + + + + + + + + +
UsernameEmailRolePlanConfirmedCreatedActions
{user.username}{user.email}{user.role}{user.plan}{confirmed_label(user)}{format_date(user.inserted_at)} + <.link navigate={~p"/admin/users/#{user.id}"}>View +
+ +
+

+ Page {@page} of {@total_pages} · {@count} {if @count == 1, do: "user", else: "users"} +

+
+ <.button + :if={@page > 1} + variant="secondary" + phx-click="previous_page" + id="previous-page" + > + Previous + + <.button + :if={@page < @total_pages} + variant="secondary" + phx-click="next_page" + id="next-page" + > + Next + +
+
+
+ """ + end + + @impl true + def mount(_params, _session, socket) do + socket = + socket + |> assign(:page_title, "Users") + |> assign(:search, "") + |> assign(:page, 1) + |> assign(:users, []) + |> assign(:count, 0) + |> assign(:total_pages, 1) + |> assign(:filter_form, to_form(%{"search" => ""})) + + case load_users(socket) do + {:ok, socket} -> {:ok, socket} + {:error, :unauthorized} -> {:ok, redirect_unauthorized(socket)} + end + end + + @impl true + def handle_event("search", %{"search" => search}, socket) do + case load_users(assign(socket, search: search, page: 1)) do + {:ok, socket} -> {:noreply, socket} + {:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)} + end + end + + def handle_event("previous_page", _params, socket) do + case load_users(assign(socket, :page, max(socket.assigns.page - 1, 1))) do + {:ok, socket} -> {:noreply, socket} + {:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)} + end + end + + def handle_event("next_page", _params, socket) do + case load_users(assign(socket, :page, socket.assigns.page + 1)) do + {:ok, socket} -> {:noreply, socket} + {:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)} + end + end + + defp load_users(socket) do + scope = socket.assigns.current_scope + search = socket.assigns.search + + case Accounts.count_users_for_admin(scope, search: search) do + {:ok, count} -> + total_pages = max(div(count + @per_page - 1, @per_page), 1) + page = min(socket.assigns.page, total_pages) + + case Accounts.list_users_for_admin(scope, search: search, page: page) do + {:ok, users} -> + {:ok, + assign(socket, users: users, count: count, total_pages: total_pages, page: page)} + + {:error, :unauthorized} -> + {:error, :unauthorized} + end + + {:error, :unauthorized} -> + {:error, :unauthorized} + end + end + + defp redirect_unauthorized(socket) do + socket + |> put_flash(:error, "You are not authorized to manage users.") + |> push_navigate(to: ~p"/") + end + + defp confirmed_label(%{confirmed_at: nil}), do: "No" + defp confirmed_label(_user), do: "Yes" + + defp format_date(nil), do: "" + + defp format_date(%DateTime{} = datetime) do + Calendar.strftime(datetime, "%Y-%m-%d") + end +end diff --git a/lib/chesstrainer_web/live/admin/user_live/new.ex b/lib/chesstrainer_web/live/admin/user_live/new.ex new file mode 100644 index 0000000..0222363 --- /dev/null +++ b/lib/chesstrainer_web/live/admin/user_live/new.ex @@ -0,0 +1,120 @@ +defmodule ChesstrainerWeb.Admin.UserLive.New do + use ChesstrainerWeb, :live_view + + alias Chesstrainer.Accounts + alias Chesstrainer.Accounts.Policy + alias Chesstrainer.Accounts.Role + alias Chesstrainer.Accounts.User + + @plan_options [{"Free", "free"}, {"Premium", "premium"}] + + @impl true + def render(assigns) do + ~H""" + + + + <.header> + Invite user + <:subtitle> + We create the account and email a link so the recipient can choose a password. + The invite is confirmed immediately, so no separate confirmation step is needed. + + + + <.form for={@form} id="invite-user-form" phx-change="validate" phx-submit="save"> + <.input + field={@form[:email]} + type="email" + label="Email" + autocomplete="off" + required + /> + <.input + field={@form[:username]} + type="text" + label="Username" + autocomplete="off" + required + /> + <.input + field={@form[:role]} + type="select" + label="Role" + options={@role_options} + /> + <.input + field={@form[:plan]} + type="select" + label="Plan" + options={@plan_options} + /> + +
+ <.button phx-disable-with="Sending..." variant="primary">Send invitation + <.button navigate={~p"/admin/users"}>Cancel +
+ +
+ """ + end + + @impl true + def mount(_params, _session, socket) do + {:ok, + socket + |> assign(:page_title, "Invite user") + |> assign(:role_options, role_options(socket.assigns.current_scope)) + |> assign(:plan_options, @plan_options) + |> assign( + :form, + to_form(%{"email" => "", "username" => "", "role" => "member", "plan" => "free"}, + as: :user + ) + )} + end + + @impl true + def handle_event("validate", %{"user" => user_params}, socket) do + changeset = + %User{} + |> User.invite_changeset(user_params) + |> User.admin_changeset(user_params) + |> Map.put(:action, :validate) + + {:noreply, assign(socket, :form, to_form(changeset, action: :validate))} + end + + def handle_event("save", %{"user" => user_params}, socket) do + case Accounts.invite_user_as_admin( + socket.assigns.current_scope, + user_params, + &url(~p"/users/reset-password/#{&1}") + ) do + {:ok, user} -> + {:noreply, + socket + |> put_flash(:info, "Invitation sent to #{user.email}.") + |> push_navigate(to: ~p"/admin/users")} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, :form, to_form(changeset, action: :insert))} + + {:error, :unauthorized} -> + {:noreply, put_flash(socket, :error, "You are not authorized to assign that role.")} + + {:error, _reason} -> + {:noreply, + put_flash(socket, :error, "The invitation could not be sent. Please try again.")} + end + end + + defp role_options(scope) do + for role <- Role.values(), + Policy.can_assign_role?(scope, role), + do: {role_label(role), role} + end + + defp role_label(:super_admin), do: "Super admin" + defp role_label(role), do: role |> Atom.to_string() |> String.capitalize() +end diff --git a/lib/chesstrainer_web/live/admin/user_live/show.ex b/lib/chesstrainer_web/live/admin/user_live/show.ex new file mode 100644 index 0000000..b6a72ca --- /dev/null +++ b/lib/chesstrainer_web/live/admin/user_live/show.ex @@ -0,0 +1,228 @@ +defmodule ChesstrainerWeb.Admin.UserLive.Show do + use ChesstrainerWeb, :live_view + + alias Chesstrainer.Accounts + alias Chesstrainer.Accounts.Policy + alias Chesstrainer.Accounts.Role + + @plan_options [{"Free", "free"}, {"Premium", "premium"}] + + @impl true + def render(assigns) do + ~H""" + + + +
+ <.header> + {@user.username} + <:subtitle>Account details and administrator controls. + <:actions> + <.button navigate={~p"/admin/users"}> + <.icon name="hero-arrow-left" /> All users + + + + + <.list> + <:item title="Email">{@user.email} + <:item title="Username">{@user.username} + <:item title="Role">{@user.role} + <:item title="Plan">{@user.plan} + <:item title="Confirmed">{confirmed_label(@user)} + <:item title="Rating">{round(@user.rating)} + <:item title="Created">{format_datetime(@user.inserted_at)} + <:item title="Last updated">{format_datetime(@user.updated_at)} + + +
+

Role and plan

+ + <.form + :if={@can_manage} + for={@form} + id="admin-user-form" + phx-change="validate" + phx-submit="save" + class="mt-4" + > + <.input + field={@form[:role]} + type="select" + label="Role" + options={@role_options} + /> + <.input + field={@form[:plan]} + type="select" + label="Plan" + options={@plan_options} + /> + +
+ <.button phx-disable-with="Saving..." variant="primary">Save changes +
+ + +

+ You can view this account but not change its role or plan. +

+
+ +
+

Account emails

+

+ These actions send email through the configured mailer. In development the messages + appear in the Swoosh mailbox at /dev/mailbox. +

+ +
+ <.button + :if={is_nil(@user.confirmed_at)} + variant="secondary" + phx-click="resend_confirmation" + id="resend-confirmation" + > + Resend confirmation email + + <.button + variant="secondary" + phx-click="send_password_reset" + id="send-password-reset" + > + Send password reset email + +
+
+
+
+ """ + end + + @impl true + def mount(%{"id" => id}, _session, socket) do + case Accounts.get_user_for_admin(socket.assigns.current_scope, id) do + {:ok, user} -> + {:ok, assign_user(socket, user)} + + {:error, :unauthorized} -> + {:ok, + socket + |> put_flash(:error, "You are not authorized to view that user.") + |> push_navigate(to: ~p"/admin/users")} + + {:error, :not_found} -> + {:ok, + socket + |> put_flash(:error, "User not found.") + |> push_navigate(to: ~p"/admin/users")} + end + end + + @impl true + def handle_event("validate", %{"user" => user_params}, socket) do + if socket.assigns.can_manage do + changeset = + socket.assigns.user + |> Accounts.change_user_as_admin(user_params) + |> Map.put(:action, :validate) + + {:noreply, assign(socket, :form, to_form(changeset, action: :validate))} + else + {:noreply, put_flash(socket, :error, "You are not authorized to modify this user.")} + end + end + + def handle_event("save", %{"user" => user_params}, socket) do + case Accounts.update_user_as_admin( + socket.assigns.current_scope, + socket.assigns.user, + user_params + ) do + {:ok, user} -> + {:noreply, + socket + |> assign_user(user) + |> put_flash(:info, "User updated successfully.")} + + {:error, :unauthorized} -> + {:noreply, put_flash(socket, :error, "You are not authorized to modify this user.")} + + {:error, :own_role} -> + {:noreply, put_flash(socket, :error, "You cannot change your own role.")} + + {:error, :last_super_admin} -> + {:noreply, put_flash(socket, :error, "You cannot demote the last super admin.")} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, :form, to_form(changeset, action: :insert))} + end + end + + def handle_event("resend_confirmation", _params, socket) do + case Accounts.resend_user_confirmation_instructions_as_admin( + socket.assigns.current_scope, + socket.assigns.user, + &url(~p"/users/confirm/#{&1}") + ) do + {:ok, _email} -> + {:noreply, put_flash(socket, :info, "Confirmation email sent.")} + + {:error, :already_confirmed} -> + {:noreply, put_flash(socket, :error, "That account is already confirmed.")} + + {:error, :unauthorized} -> + {:noreply, put_flash(socket, :error, "You are not authorized to email this user.")} + + {:error, _reason} -> + {:noreply, put_flash(socket, :error, "The confirmation email could not be sent.")} + end + end + + def handle_event("send_password_reset", _params, socket) do + case Accounts.send_user_reset_password_instructions_as_admin( + socket.assigns.current_scope, + socket.assigns.user, + &url(~p"/users/reset-password/#{&1}") + ) do + {:ok, _email} -> + {:noreply, put_flash(socket, :info, "Password reset email sent.")} + + {:error, :unauthorized} -> + {:noreply, put_flash(socket, :error, "You are not authorized to email this user.")} + + {:error, _reason} -> + {:noreply, put_flash(socket, :error, "The password reset email could not be sent.")} + end + end + + defp assign_user(socket, user) do + can_manage = Policy.can_manage_user?(socket.assigns.current_scope, user) + + socket + |> assign(:page_title, user.username) + |> assign(:user, user) + |> assign(:can_manage, can_manage) + |> assign(:plan_options, @plan_options) + |> assign(:role_options, role_options(socket.assigns.current_scope)) + |> assign(:form, to_form(Accounts.change_user_as_admin(user))) + end + + defp role_options(scope) do + for role <- Role.values(), + Policy.can_assign_role?(scope, role), + do: {role_label(role), role} + end + + defp role_label(:super_admin), do: "Super admin" + defp role_label(role), do: role |> Atom.to_string() |> String.capitalize() + + defp confirmed_label(%{confirmed_at: nil}), do: "No" + defp confirmed_label(_user), do: "Yes" + + defp format_datetime(nil), do: "—" + + defp format_datetime(%DateTime{} = datetime) do + Calendar.strftime(datetime, "%Y-%m-%d %H:%M UTC") + end +end diff --git a/lib/chesstrainer_web/live/endgame_live/form.ex b/lib/chesstrainer_web/live/endgame_live/form.ex index 4ebb97d..50bb606 100644 --- a/lib/chesstrainer_web/live/endgame_live/form.ex +++ b/lib/chesstrainer_web/live/endgame_live/form.ex @@ -13,6 +13,8 @@ defmodule ChesstrainerWeb.EndgameLive.Form do def render(assigns) do ~H""" + + <.header> {@page_title} <:subtitle>Use this form to manage endgame records in your database. @@ -48,7 +50,7 @@ defmodule ChesstrainerWeb.EndgameLive.Form do placeholder="Search or create a theme…" /> -
    +