admin: allow superuser login only on admin.asxp.io
All checks were successful
Build and Deploy to Production / test (push) Successful in 21s
Build and Deploy to Production / build (push) Successful in 59s
Build and Deploy to Production / deploy (push) Successful in 40s

Superuser accounts can do everything, so their login should not be
exposed on the public site. With SUPERUSER_HOST set, a superuser's
correct password on any other host fails exactly like a wrong one, an
existing superuser session there counts as none, a password reset sends
nothing, and the env recovery login only works on that host.

admin.asxp.io is a second Traefik router to the same container, allowed
only from WireGuard and the VPC. The host comes from HTTP_HOST, since
Rack's request.host would trust a client-sent X-Forwarded-Host.
Invite and reset links for regular users use SITE_URL, so an invite
created on admin.asxp.io still opens for someone off WireGuard.

Assisted-by: Claude:opus-5-5
This commit is contained in:
Sergei Poljanski 2026-11-13 06:55:16 +04:00
commit 19cd0fb675
Signed by: asxpi
GPG key ID: 4F8851660FA4121B
8 changed files with 119 additions and 6 deletions

View file

@ -153,6 +153,8 @@ jobs:
MAIL_TO=ie@asxp.io MAIL_TO=ie@asxp.io
ADMIN_USER=${ADMIN_USER} ADMIN_USER=${ADMIN_USER}
ADMIN_PASSWORD=${ADMIN_PASSWORD} ADMIN_PASSWORD=${ADMIN_PASSWORD}
SUPERUSER_HOST=admin.asxp.io
SITE_URL=https://asxp.io
DATABASE_URL=postgres://asxpio:${ASXPIO_DB_PASSWORD}@postgres:5432/asxpio DATABASE_URL=postgres://asxpio:${ASXPIO_DB_PASSWORD}@postgres:5432/asxpio
S3_ENDPOINT=http://garage:3900 S3_ENDPOINT=http://garage:3900
S3_PUBLIC_ENDPOINT=https://s3.asxp.io S3_PUBLIC_ENDPOINT=https://s3.asxp.io

View file

@ -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` - In-memory `RateLimit` (5 req/hour/IP) — see `lib/rate_limit.rb`
- `Rack::Protection::AuthenticityToken` for CSRF (uses session-stored token) - `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). - `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. - 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. - 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`. - Timestamps: `Sequel.default_timezone = :utc` (lib/db.rb); always write `Time.now.utc`.

View file

@ -62,7 +62,7 @@ class AsxpioWeb < Sinatra::Base
# 127.0.0.1 is the Docker HEALTHCHECK. Empty list (= check disabled) # 127.0.0.1 is the Docker HEALTHCHECK. Empty list (= check disabled)
# outside production so dev and rack-test hosts keep working. # outside production so dev and rack-test hosts keep working.
set :host_authorization, 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 end
use Rack::Session::Cookie, use Rack::Session::Cookie,

View file

@ -18,6 +18,14 @@ services:
- "traefik.http.routers.asxpio.tls.certresolver=letsencrypt" - "traefik.http.routers.asxpio.tls.certresolver=letsencrypt"
- "traefik.http.routers.asxpio.service=asxpio" - "traefik.http.routers.asxpio.service=asxpio"
- "traefik.http.services.asxpio.loadbalancer.server.port=3000" - "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). # Reachability worker for datacenterbingo's status page (bin/monitor).
# Same image; the deploy's sed sets both image lines. # Same image; the deploy's sed sets both image lines.

View file

@ -27,7 +27,27 @@ module AdminAuth
return @current_user if defined?(@current_user) return @current_user if defined?(@current_user)
uid = session[:uid] uid = session[:uid]
user = uid && User[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 end
# For views: show a form/button only if the user may use it. # For views: show a form/button only if the user may use it.
@ -102,7 +122,8 @@ module AdminAuth
return erb :'admin/login' return erb :'admin/login'
end end
user = User.authenticate(params[:username], params[:password]) 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. # Recovery: no usable superuser left, so the env credentials restore one.
name = ENV['ADMIN_USER'].strip.downcase name = ENV['ADMIN_USER'].strip.downcase
user = User[username: name] || User.new(username: name) user = User[username: name] || User.new(username: name)

View file

@ -37,7 +37,7 @@ module UsersAdmin
# account without email (or a failed send) can still be onboarded. # account without email (or a failed send) can still be onboarded.
def send_account_link(user, kind) def send_account_link(user, kind)
raw = UserToken.issue!(user, kind) raw = UserToken.issue!(user, kind)
url = "#{request.base_url}/admin/#{kind}/#{raw}" url = "#{account_link_base(user)}/admin/#{kind}/#{raw}"
sent = false sent = false
if user.email if user.email
begin begin
@ -229,8 +229,9 @@ module UsersAdmin
if AdminAuth.login_limit.allow?(client_ip) if AdminAuth.login_limit.allow?(client_ip)
q = params[:login].to_s.strip.downcase q = params[:login].to_s.strip.downcase
user = User.where(active: true).where(Sequel.|({ username: q }, { email: q })).first user = User.where(active: true).where(Sequel.|({ username: q }, { email: q })).first
if user&.email && user.password_digest # A superuser resets on SUPERUSER_HOST only; elsewhere: same silence.
url = "#{request.base_url}/admin/reset/#{UserToken.issue!(user, 'reset')}" if user&.email && user.password_digest && superuser_allowed?(user)
url = "#{account_link_base(user)}/admin/reset/#{UserToken.issue!(user, 'reset')}"
begin begin
Mailer.account_link(to: user.email, username: user.username, url: url, kind: 'reset') Mailer.account_link(to: user.email, username: user.username, url: url, kind: 'reset')
rescue StandardError => e rescue StandardError => e

View file

@ -133,6 +133,68 @@ class AdminAuthTest < Minitest::Test
assert_equal '/admin', URI(last_response.location).path assert_equal '/admin', URI(last_response.location).path
end 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 def test_login_rate_limited
AdminAuth.login_limit = RateLimit.new(limit: 2, window: 900) AdminAuth.login_limit = RateLimit.new(limit: 2, window: 900)
3.times { login('x', 'y') } 3.times { login('x', 'y') }

View file

@ -124,6 +124,24 @@ class UsersAdminTest < Minitest::Test
assert last_response.ok?, "#{url.inspect} -> #{last_response.status} #{last_response.body[0, 200]}" assert last_response.ok?, "#{url.inspect} -> #{last_response.status} #{last_response.body[0, 200]}"
end 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 def test_no_escalation_by_user_manager
boss = User.create(username: 'manager', password: 'manager-pass-1') boss = User.create(username: 'manager', password: 'manager-pass-1')
UserPermission.create(user_id: boss.id, area: 'users', can_read: true, can_write: true) UserPermission.create(user_id: boss.id, area: 'users', can_read: true, can_write: true)