diff --git a/.forgejo/workflows/deploy.yaml b/.forgejo/workflows/deploy.yaml index 161f978..e4551b9 100644 --- a/.forgejo/workflows/deploy.yaml +++ b/.forgejo/workflows/deploy.yaml @@ -153,6 +153,8 @@ jobs: MAIL_TO=ie@asxp.io ADMIN_USER=${ADMIN_USER} ADMIN_PASSWORD=${ADMIN_PASSWORD} + SUPERUSER_HOST=admin.asxp.io + SITE_URL=https://asxp.io DATABASE_URL=postgres://asxpio:${ASXPIO_DB_PASSWORD}@postgres:5432/asxpio S3_ENDPOINT=http://garage:3900 S3_PUBLIC_ENDPOINT=https://s3.asxp.io diff --git a/CLAUDE.md b/CLAUDE.md index b9571fa..040bd99 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,6 +37,7 @@ Banking details and registration number are deliberately not on the public page - In-memory `RateLimit` (5 req/hour/IP) — see `lib/rate_limit.rb` - `Rack::Protection::AuthenticityToken` for CSRF (uses session-stored token) - `AdminAuth` (`lib/admin_auth.rb`, a Sinatra extension): session login at `/admin/login` against the `users` table (`lib/user.rb`, scrypt via OpenSSL, no gem). Session holds user id + `session_version` (bump = logged out everywhere). `ADMIN_USER`/`ADMIN_PASSWORD` bootstrap the first superuser on an empty table and otherwise work only while no active superuser exists (recovery; it re-creates that superuser). Login is rate-limited per IP (`LOGIN_RATE_LIMIT`, default 10/15 min). +- Superusers authenticate only on `SUPERUSER_HOST` (`admin.asxp.io`; Traefik allows WireGuard 10.20.0.0/24 + VPC 10.10.0.0/20 only). Elsewhere their correct password gets the normal "Wrong username or password", their session counts as logged out, a reset request sends nothing, and the env recovery login is off. The check reads `HTTP_HOST`, not `request.host` (which trusts `X-Forwarded-Host`). Account links for non-superusers use `SITE_URL` so they work off WireGuard. Unset = no restriction (dev, tests). - Permissions (`lib/admin_acl.rb`): areas `invoices`, `bingo`, `files`, `users` × independent flags read/write/delete in `user_permissions` (read + delete without write is valid); superusers bypass. GET → read (…/new, …/duplicate → write), POST …/delete|…/disable → delete, other POST → write. Unmapped /admin paths are superuser-only, and `test/admin_acl_test.rb` fails if a registered admin route isn't mapped — add new admin routes to `AdminACL::RULES`. Views hide forms via `can?(area, perm)`; the server check is the real gate. - Users UI (`lib/users_admin.rb`): `/admin/users` create/edit/disable/delete (superusers can also rename; sessions key on id, the audit log keeps old names), permission grid (you can only grant flags you hold; flags you can't grant keep their value; only superusers touch superuser accounts; no self-lockout; last active superuser can't be deleted). New users get a one-time invite link (48 h) by email via `Mailer.account_link`, also shown once to the admin. `/admin/reset` emails a 1 h reset link (same answer for unknown accounts). Tokens are stored as SHA-256 only (`user_tokens`). `/admin/audit` lists `audit_log` (logins, user changes, bingo and invoice actions) — call `audit!(action, target, detail)` in new admin actions. - Timestamps: `Sequel.default_timezone = :utc` (lib/db.rb); always write `Time.now.utc`. diff --git a/asxpio.rb b/asxpio.rb index 21a9934..f4975d5 100644 --- a/asxpio.rb +++ b/asxpio.rb @@ -62,7 +62,7 @@ class AsxpioWeb < Sinatra::Base # 127.0.0.1 is the Docker HEALTHCHECK. Empty list (= check disabled) # outside production so dev and rack-test hosts keep working. set :host_authorization, - { permitted_hosts: $env == 'production' ? ['asxp.io', 'www.asxp.io', '127.0.0.1'] : [] } + { permitted_hosts: $env == 'production' ? ['asxp.io', 'www.asxp.io', 'admin.asxp.io', '127.0.0.1'] : [] } end use Rack::Session::Cookie, diff --git a/docker-compose.yml b/docker-compose.yml index 24243a8..190b932 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -18,6 +18,14 @@ services: - "traefik.http.routers.asxpio.tls.certresolver=letsencrypt" - "traefik.http.routers.asxpio.service=asxpio" - "traefik.http.services.asxpio.loadbalancer.server.port=3000" + # Superuser logins only work here (SUPERUSER_HOST): WireGuard + VPC. + - "traefik.http.routers.asxpio-admin.rule=Host(`admin.asxp.io`)" + - "traefik.http.routers.asxpio-admin.entrypoints=websecure" + - "traefik.http.routers.asxpio-admin.tls=true" + - "traefik.http.routers.asxpio-admin.tls.certresolver=letsencrypt" + - "traefik.http.routers.asxpio-admin.service=asxpio" + - "traefik.http.routers.asxpio-admin.middlewares=asxpio-admin-private" + - "traefik.http.middlewares.asxpio-admin-private.ipallowlist.sourcerange=10.10.0.0/20,10.20.0.0/24" # Reachability worker for datacenterbingo's status page (bin/monitor). # Same image; the deploy's sed sets both image lines. diff --git a/lib/admin_auth.rb b/lib/admin_auth.rb index c464e88..ab11aa1 100644 --- a/lib/admin_auth.rb +++ b/lib/admin_auth.rb @@ -27,7 +27,27 @@ module AdminAuth return @current_user if defined?(@current_user) uid = session[:uid] user = uid && User[uid] - @current_user = user if user&.active && user.session_version == session[:uv] + @current_user = user if user&.active && user.session_version == session[:uv] && superuser_allowed?(user) + end + + # SUPERUSER_HOST (admin.asxp.io, reachable over WireGuard/VPC only): + # superusers authenticate there and nowhere else. Elsewhere their + # login fails like a wrong password and their session counts as none. + # Unset = no restriction (dev, tests). HTTP_HOST, not request.host: + # the latter would believe a client-sent X-Forwarded-Host. + def superuser_host? + want = ENV['SUPERUSER_HOST'].to_s.strip.downcase + want.empty? || request.env['HTTP_HOST'].to_s.downcase.sub(/:\d+\z/, '') == want + end + + def superuser_allowed?(user) + !user&.superuser || superuser_host? + end + + # Account links for non-superusers must work off the WireGuard host. + def account_link_base(user) + site = ENV['SITE_URL'].to_s + user.superuser || site.empty? ? request.base_url : site end # For views: show a form/button only if the user may use it. @@ -102,7 +122,8 @@ module AdminAuth return erb :'admin/login' end user = User.authenticate(params[:username], params[:password]) - if !user && !User.active_superuser? && env_credentials?(params[:username], params[:password]) + user = nil unless superuser_allowed?(user) + if !user && superuser_host? && !User.active_superuser? && env_credentials?(params[:username], params[:password]) # Recovery: no usable superuser left, so the env credentials restore one. name = ENV['ADMIN_USER'].strip.downcase user = User[username: name] || User.new(username: name) diff --git a/lib/users_admin.rb b/lib/users_admin.rb index dac0423..92d5e61 100644 --- a/lib/users_admin.rb +++ b/lib/users_admin.rb @@ -37,7 +37,7 @@ module UsersAdmin # account without email (or a failed send) can still be onboarded. def send_account_link(user, kind) raw = UserToken.issue!(user, kind) - url = "#{request.base_url}/admin/#{kind}/#{raw}" + url = "#{account_link_base(user)}/admin/#{kind}/#{raw}" sent = false if user.email begin @@ -229,8 +229,9 @@ module UsersAdmin if AdminAuth.login_limit.allow?(client_ip) q = params[:login].to_s.strip.downcase user = User.where(active: true).where(Sequel.|({ username: q }, { email: q })).first - if user&.email && user.password_digest - url = "#{request.base_url}/admin/reset/#{UserToken.issue!(user, 'reset')}" + # A superuser resets on SUPERUSER_HOST only; elsewhere: same silence. + if user&.email && user.password_digest && superuser_allowed?(user) + url = "#{account_link_base(user)}/admin/reset/#{UserToken.issue!(user, 'reset')}" begin Mailer.account_link(to: user.email, username: user.username, url: url, kind: 'reset') rescue StandardError => e diff --git a/test/admin_auth_test.rb b/test/admin_auth_test.rb index 2e711cd..556f090 100644 --- a/test/admin_auth_test.rb +++ b/test/admin_auth_test.rb @@ -133,6 +133,68 @@ class AdminAuthTest < Minitest::Test assert_equal '/admin', URI(last_response.location).path end + def with_superuser_host(host = 'admin.example.org') + old = ENV['SUPERUSER_HOST'] + ENV['SUPERUSER_HOST'] = host + yield + ensure + ENV['SUPERUSER_HOST'] = old + end + + def login_at(base, username, password, extra = {}) + get "#{base}/admin/login" + token = last_response.body[/name="authenticity_token" value="([^"]+)"/, 1] + post "#{base}/admin/login", { authenticity_token: token, username: username, password: password }, extra + end + + def test_superuser_login_only_on_superuser_host + User.create(username: 'root', superuser: true, password: 'root-password-1') + User.create(username: 'staff', password: 'staff-password-1') + with_superuser_host do + login_at('http://example.org', 'root', 'root-password-1') + assert_equal 401, last_response.status + assert_includes last_response.body, 'Wrong username or password.' + + # A forged X-Forwarded-Host does not count + login_at('http://example.org', 'root', 'root-password-1', 'HTTP_X_FORWARDED_HOST' => 'admin.example.org') + assert_equal 401, last_response.status + + login_at('http://example.org', 'staff', 'staff-password-1') + assert_equal 302, last_response.status + + login_at('http://admin.example.org', 'root', 'root-password-1') + assert_equal 302, last_response.status + get 'http://admin.example.org/admin' + assert last_response.ok? + end + end + + def test_superuser_session_ignored_off_host + User.create(username: 'root', superuser: true, password: 'root-password-1') + login('root', 'root-password-1') # no restriction yet + get '/admin' + assert last_response.ok? + with_superuser_host do + get '/admin' + assert_equal 302, last_response.status + assert_match %r{/admin/login}, last_response.location + end + end + + def test_emergency_login_only_on_superuser_host + old = [ENV['ADMIN_USER'], ENV['ADMIN_PASSWORD']] + ENV['ADMIN_USER'], ENV['ADMIN_PASSWORD'] = 'rescue', 'rescue-password-1' + with_superuser_host do + login_at('http://example.org', 'rescue', 'rescue-password-1') + assert_equal 401, last_response.status + assert_nil User[username: 'rescue'] + login_at('http://admin.example.org', 'rescue', 'rescue-password-1') + assert_equal 302, last_response.status + end + ensure + ENV['ADMIN_USER'], ENV['ADMIN_PASSWORD'] = old + end + def test_login_rate_limited AdminAuth.login_limit = RateLimit.new(limit: 2, window: 900) 3.times { login('x', 'y') } diff --git a/test/users_admin_test.rb b/test/users_admin_test.rb index d9c240a..94270be 100644 --- a/test/users_admin_test.rb +++ b/test/users_admin_test.rb @@ -124,6 +124,24 @@ class UsersAdminTest < Minitest::Test assert last_response.ok?, "#{url.inspect} -> #{last_response.status} #{last_response.body[0, 200]}" end + def test_superuser_reset_only_on_superuser_host + User.create(username: 'root', email: 'root@example.com', superuser: true, password: 'root-password-1') + old = ENV['SUPERUSER_HOST'] + ENV['SUPERUSER_HOST'] = 'admin.example.org' + get '/admin/reset' + tok = last_response.body[/name="authenticity_token" value="([^"]+)"/, 1] + post '/admin/reset', { authenticity_token: tok, login: 'root' } + assert last_response.ok? + assert_empty Mail::TestMailer.deliveries + get 'http://admin.example.org/admin/reset' + tok = last_response.body[/name="authenticity_token" value="([^"]+)"/, 1] + post 'http://admin.example.org/admin/reset', { authenticity_token: tok, login: 'root' } + assert_equal 1, Mail::TestMailer.deliveries.size + assert_match %r{http://admin\.example\.org/admin/reset/}, Mail::TestMailer.deliveries.last.body.to_s + ensure + ENV['SUPERUSER_HOST'] = old + end + def test_no_escalation_by_user_manager boss = User.create(username: 'manager', password: 'manager-pass-1') UserPermission.create(user_id: boss.id, area: 'users', can_read: true, can_write: true)