diff --git a/CLAUDE.md b/CLAUDE.md index 7eb7ed4..6894e93 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,6 +38,8 @@ Banking details and registration number are deliberately not on the public page - `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). - Permissions (`lib/admin_acl.rb`): areas `invoices`, `bingo`, `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, 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`. - Honeypot field named `website` for spam - Static assets in `public/`; views in `views/` - Deploy: `Dockerfile` + `docker-compose.yml` (Traefik labels for asxp.io / www.asxp.io). Container joins two external Docker networks: `traefik` (ingress) and `storage` (Postgres + MinIO). diff --git a/asxpio.rb b/asxpio.rb index 87b4761..5cf9bc3 100644 --- a/asxpio.rb +++ b/asxpio.rb @@ -24,6 +24,7 @@ require_relative 'lib/db' require_relative 'lib/admin_auth' require_relative 'lib/s3' require_relative 'lib/bingo_admin' +require_relative 'lib/users_admin' # Invoice model needs a live Sequel connection at class-definition time. if ENV['DATABASE_URL'] @@ -38,6 +39,7 @@ if ENV['DATABASE_URL'] require_relative 'lib/bingo' Bingo.seed! require_relative 'lib/user' + require_relative 'lib/audit' User.bootstrap!(ENV['ADMIN_USER'], ENV['ADMIN_PASSWORD']) else $logger.warn('DATABASE_URL not set — invoicing disabled') @@ -67,6 +69,7 @@ class AsxpioWeb < Sinatra::Base use Rack::Protection::AuthenticityToken register AdminAuth register BingoAdmin + register UsersAdmin Mailer.configure! @@ -288,6 +291,7 @@ class AsxpioWeb < Sinatra::Base retry end + audit!('invoice.create', invoice.number, "#{invoice.client_name}, #{invoice.currency} #{'%.2f' % invoice.total}") redirect "/admin/invoices/#{invoice.uuid}" end @@ -302,6 +306,7 @@ class AsxpioWeb < Sinatra::Base invoice = Invoice[uuid: params[:uuid]] or halt 404 invoice.paid_at = invoice.paid? ? nil : Time.now.utc invoice.save_changes + audit!(invoice.paid? ? 'invoice.paid' : 'invoice.unpaid', invoice.number) redirect "/admin/invoices/#{invoice.uuid}" end diff --git a/db/migrations/008_user_tokens_audit.rb b/db/migrations/008_user_tokens_audit.rb new file mode 100644 index 0000000..ba27d25 --- /dev/null +++ b/db/migrations/008_user_tokens_audit.rb @@ -0,0 +1,27 @@ +Sequel.migration do + change do + # One-time invite / password-reset links. Only a SHA-256 of the token + # is stored; the raw token exists in the email and the URL. + create_table(:user_tokens) do + primary_key :id + foreign_key :user_id, :users, null: false, on_delete: :cascade + String :purpose, null: false # invite | reset + String :token_digest, null: false, unique: true + DateTime :expires_at, null: false + DateTime :used_at + DateTime :created_at, null: false + end + + create_table(:audit_log) do + primary_key :id + foreign_key :user_id, :users, on_delete: :set_null + String :username # kept after the user is deleted + String :action, null: false + String :target + String :detail, text: true + String :ip + DateTime :created_at, null: false + index :created_at + end + end +end diff --git a/lib/admin_auth.rb b/lib/admin_auth.rb index 774c5a8..6de8ce7 100644 --- a/lib/admin_auth.rb +++ b/lib/admin_auth.rb @@ -54,6 +54,10 @@ module AdminAuth Rack::Utils.secure_compare(p, pass.to_s) end + def audit!(action, target = nil, detail = nil, user: current_user) + Audit.log(action: action, user: user, target: target, detail: detail, ip: client_ip) + end + def safe_next(target) target.to_s.match?(%r{\A/admin(/[\w\-/]*)?\z}) ? target : '/admin' end @@ -102,12 +106,15 @@ module AdminAuth user.password = ENV['ADMIN_PASSWORD'] user.save $logger.warn("users: emergency login restored superuser #{name} from #{client_ip}") + audit!('auth.emergency_login', name, user: user) end if user log_in!(user) + audit!('auth.login') redirect @next else $logger.info("users: failed login for #{params[:username].to_s[0, 64].inspect} from #{client_ip}") + Audit.log(action: 'auth.login_failed', username: params[:username].to_s[0, 64], ip: client_ip) @error = 'Wrong username or password.' status 401 erb :'admin/login' @@ -115,6 +122,7 @@ module AdminAuth end app.post '/admin/logout' do + audit!('auth.logout') if current_user session.clear redirect '/admin/login' end @@ -143,6 +151,7 @@ module AdminAuth u.session_version += 1 # other sessions out u.save log_in!(u) + audit!('auth.password_changed') redirect '/admin' end end diff --git a/lib/audit.rb b/lib/audit.rb new file mode 100644 index 0000000..7511881 --- /dev/null +++ b/lib/audit.rb @@ -0,0 +1,20 @@ +require 'sequel' + +# Append-only record of who changed what in the admin (/admin/audit). +module Audit + module_function + + def log(action:, user: nil, target: nil, detail: nil, ip: nil, username: nil) + DB.connection[:audit_log].insert( + user_id: user&.id, username: user&.username || username, action: action, + target: target&.to_s&.slice(0, 200), detail: detail&.to_s&.slice(0, 2000), + ip: ip, created_at: Time.now.utc + ) + rescue Sequel::Error => e + $logger.error("audit: #{action} not recorded: #{e.message}") # never break the action itself + end + + def recent(limit = 200) + DB.connection[:audit_log].order(Sequel.desc(:created_at), Sequel.desc(:id)).limit(limit).all + end +end diff --git a/lib/bingo_admin.rb b/lib/bingo_admin.rb index b8341bb..8d1ed85 100644 --- a/lib/bingo_admin.rb +++ b/lib/bingo_admin.rb @@ -72,6 +72,7 @@ module BingoAdmin @dc.position = Bingo::Datacenter.count + 1 @dc.save Bingo.place!(@dc, position_param) + audit!('bingo.dc_create', @dc.slug, "##{@dc.refresh.position} #{@dc.name_ru}") session[:bingo_flash] = "Added #{@dc.name_ru} at ##{@dc.refresh.position}." redirect "/admin/bingo/dc/#{@dc.id}" end @@ -90,6 +91,7 @@ module BingoAdmin if errs.empty? dc.save_changes Bingo.place!(dc, position_param) if position_param && position_param != dc.position + audit!('bingo.dc_update', dc.slug, dc.name_ru) session[:bingo_flash] = 'Saved.' else session[:bingo_flash] = errs.join('; ') @@ -106,12 +108,14 @@ module BingoAdmin dc.destroy Bingo.renumber! end + audit!('bingo.dc_delete', dc.slug, "#{dc.name_ru}, #{n} incident(s)") session[:bingo_flash] = "Deleted #{dc.name_ru}#{" and #{n} incident(s)" if n.positive?}." redirect '/admin/bingo' end app.post '/admin/bingo/sort' do Bingo.sort_by_mw! + audit!('bingo.sort_by_mw') session[:bingo_flash] = 'Sorted by MW (unknown last).' redirect '/admin/bingo' end @@ -130,6 +134,7 @@ module BingoAdmin end dc.save_changes Bingo::Photo.attach(dc, bytes) + audit!('bingo.photo_store', dc.slug, dc.photo_source_url) session[:bingo_flash] = dc.photo_variants ? 'Photo stored.' : 'Photo stored (no resized variants; check logs).' rescue Bingo::Photo::Error => e session[:bingo_flash] = "Photo failed: #{e.message}" @@ -140,6 +145,7 @@ module BingoAdmin app.post '/admin/bingo/dc/:id/photo/delete' do dc = Bingo::Datacenter[params[:id].to_i] or halt 404 dc.update(photo_key: nil, photo_variants: false) + audit!('bingo.photo_remove', dc.slug) session[:bingo_flash] = 'Photo removed from card (object kept in bucket).' redirect "/admin/bingo/dc/#{dc.id}" end @@ -156,6 +162,7 @@ module BingoAdmin rescue Bingo::Photo::Error => e failed << "#{dc.slug}: #{e.message}" end + audit!('bingo.photos_import', params[:all] == '1' ? 'all' : 'missing', "#{ok} ok, #{failed.size} failed") session[:bingo_flash] = (["Imported #{ok}."] + failed).join(' | ') redirect '/admin/bingo' end @@ -171,6 +178,7 @@ module BingoAdmin $logger.error("bingo: rebuild #{dc.slug}: #{e.class}: #{e.message}") end failed = dcs.reject(&:photo_variants).map { |dc| errors[dc.slug] ? "#{dc.slug} (#{errors[dc.slug]})" : dc.slug } + audit!('bingo.photos_rebuild', nil, "#{dcs.size - failed.size}/#{dcs.size}") session[:bingo_flash] = "Rebuilt #{dcs.size - failed.size}/#{dcs.size}.#{" Failed: #{failed.join(', ')}" if failed.any?}" redirect '/admin/bingo' end @@ -203,6 +211,7 @@ module BingoAdmin title_ru: params[:title_ru].strip, title_en: blank_nil(params[:title_en]), title_uk: blank_nil(params[:title_uk]), url: blank_nil(url) ) + audit!('bingo.incident_create', dc.slug, "#{date} #{params[:kind]}: #{params[:title_ru].strip}") session[:bingo_flash] = "Incident recorded for #{dc.name_ru}." else session[:bingo_flash] = errs.join('; ') @@ -211,7 +220,9 @@ module BingoAdmin end app.post '/admin/bingo/incidents/:id/delete' do + inc = Bingo::Incident[params[:id].to_i] Bingo::Incident.where(id: params[:id].to_i).delete + audit!('bingo.incident_delete', inc&.datacenter&.slug, inc && "#{inc.occurred_on} #{inc.title_ru}") session[:bingo_flash] = 'Incident deleted.' redirect '/admin/bingo' end diff --git a/lib/db.rb b/lib/db.rb index 7f87eeb..038e8bb 100644 --- a/lib/db.rb +++ b/lib/db.rb @@ -4,6 +4,9 @@ module DB module_function def connect! + # Every timestamp is written as Time.now.utc; read them back as UTC too + # (otherwise a host in UTC+4 sees a fresh 1 h token as already expired). + Sequel.default_timezone = :utc @connection ||= Sequel.connect( ENV.fetch('DATABASE_URL'), max_connections: 5, diff --git a/lib/mailer.rb b/lib/mailer.rb index 7ba21c2..325cb54 100644 --- a/lib/mailer.rb +++ b/lib/mailer.rb @@ -69,4 +69,33 @@ module Mailer body body end end + + # Invite / password-reset email with a one-time link. + def account_link(to:, username:, url:, kind:) + from = ENV.fetch('MAIL_FROM') + subj, intro, ttl = + if kind == 'invite' + ['Your asxp.io admin account', "An account \"#{username}\" was created for you on the asxp.io admin.\nSet your password here:", '48 hours'] + else + ['Reset your asxp.io admin password', "Someone (hopefully you) asked to reset the password for \"#{username}\".\nSet a new one here:", '1 hour'] + end + body = <<~BODY + #{intro} + + #{url} + + The link works once and expires in #{ttl}. If you didn't expect this + email, ignore it. + + -- + asxp.io + BODY + + Mail.deliver do + from from + to to + subject subj + body body + end + end end diff --git a/lib/user.rb b/lib/user.rb index 338dc18..08bf27f 100644 --- a/lib/user.rb +++ b/lib/user.rb @@ -85,3 +85,30 @@ class UserPermission < Sequel::Model(:user_permissions) unrestrict_primary_key many_to_one :user end + +# One-time invite / reset links; see migration 008. +class UserToken < Sequel::Model(:user_tokens) + TTL = { 'invite' => 48 * 3600, 'reset' => 3600 }.freeze + + many_to_one :user + + def self.digest(raw) = OpenSSL::Digest::SHA256.hexdigest(raw.to_s) + + # Returns the raw token; earlier unused tokens of the same purpose die. + def self.issue!(user, purpose) + where(user_id: user.id, purpose: purpose, used_at: nil).delete + raw = SecureRandom.urlsafe_base64(32) + create(user_id: user.id, purpose: purpose, token_digest: digest(raw), + expires_at: Time.now.utc + TTL.fetch(purpose), created_at: Time.now.utc) + raw + end + + def self.find_valid(raw, purpose) + t = self[token_digest: digest(raw), purpose: purpose] + t if t && t.used_at.nil? && t.expires_at > Time.now && t.user&.active + end + + def use! + update(used_at: Time.now.utc) + end +end diff --git a/lib/users_admin.rb b/lib/users_admin.rb new file mode 100644 index 0000000..0e7c659 --- /dev/null +++ b/lib/users_admin.rb @@ -0,0 +1,221 @@ +# /admin/users (manage accounts), /admin/audit, and the public one-time +# invite / password-reset pages. Registered into AsxpioWeb after AdminAuth. +module UsersAdmin + module Helpers + # Permission flags from the form. The acting user can only change flags + # they hold themselves (no escalation); any other flag keeps the target's + # current value. Ticking delete implies read. + def permission_params(target = nil) + User::AREAS.to_h do |area| + flags = User::PERMS.select do |f| + if current_user.can?(area, f) then params.dig('perm', area, f) == '1' + else target&.can?(area, f) || false + end + end + flags |= ['read'] if flags.include?('delete') + [area, flags] + end + end + + def save_permissions!(user, perms) + UserPermission.where(user_id: user.id).delete + perms.each do |area, flags| + next if flags.empty? + UserPermission.create(user_id: user.id, area: area, **flags.to_h { |f| [:"can_#{f}", true] }) + end + end + + def perm_summary(user) + return 'superuser' if user.superuser + user.permissions.map do |p| + f = User::PERMS.select { |x| p[:"can_#{x}"] }.map { |x| x[0] }.join + f.empty? ? nil : "#{p.area}: #{f}" + end.compact.join(' · ').then { |s| s.empty? ? 'no access' : s } + end + + # Email the link if possible; the acting admin also sees it once, so an + # 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}" + sent = false + if user.email + begin + Mailer.account_link(to: user.email, username: user.username, url: url, kind: kind) + sent = true + rescue StandardError => e + $logger.error("users: #{kind} mail to #{user.email} failed: #{e.class}: #{e.message}") + end + end + session[:users_link] = { 'url' => url, 'sent' => sent, 'to' => user.email, 'kind' => kind } + end + + def manageable!(user) + halt 403, 'Only superusers can change superuser accounts.' if user.superuser && !current_user.superuser + end + + def set_password_page(purpose) + @token = UserToken.find_valid(params[:token], purpose) or halt 404, 'This link is invalid or has expired.' + @purpose = purpose + @page_title = purpose == 'invite' ? 'Set your password' : 'Reset password' + @noindex = true + end + end + + def self.registered(app) + app.helpers Helpers + + app.get '/admin/users' do + @page_title = 'Users · admin' + @noindex = true + @users = User.order(:username).eager(:permissions).all + @flash = session.delete(:users_flash) + @link = session.delete(:users_link) + erb :'admin/users/index' + end + + app.get '/admin/users/new' do + @user = User.new + @page_title = 'New user · admin' + @noindex = true + erb :'admin/users/form' + end + + app.post '/admin/users' do + @user = User.new(username: params[:username].to_s.strip.downcase, name: params[:name].to_s.strip, + email: params[:email].to_s.strip.downcase.then { |e| e.empty? ? nil : e }) + @user.superuser = params[:superuser] == '1' if current_user.superuser + unless @user.valid? && !User[username: @user.username] && !(@user.email && User[email: @user.email]) + @error = @user.errors.full_messages.join('; ').then { |m| m.empty? ? 'Username or email already in use.' : m } + @page_title = 'New user · admin' + @noindex = true + status 422 + return erb :'admin/users/form' + end + @user.save + save_permissions!(@user, permission_params) unless @user.superuser + send_account_link(@user, 'invite') + audit!('user.create', @user.username, perm_summary(@user.refresh)) + redirect '/admin/users' + end + + app.get '/admin/users/:id' do + @user = User[params[:id].to_i] or halt 404 + @page_title = "#{@user.username} · admin" + @noindex = true + @flash = session.delete(:users_flash) + erb :'admin/users/form' + end + + app.post '/admin/users/:id' do + user = User[params[:id].to_i] or halt 404 + manageable!(user) + self_edit = user.id == current_user.id + before = perm_summary(user) + user.name = params[:name].to_s.strip + user.email = params[:email].to_s.strip.downcase.then { |e| e.empty? ? nil : e } + unless self_edit # you can't lock yourself out + active = params[:active] == '1' + user.session_version += 1 if user.active && !active + user.active = active + user.superuser = params[:superuser] == '1' if current_user.superuser + end + if !user.valid? || (user.email && User.exclude(id: user.id).where(email: user.email).any?) + session[:users_flash] = user.errors.full_messages.join('; ').then { |m| m.empty? ? 'Email already in use.' : m } + redirect "/admin/users/#{user.id}" + end + perms = permission_params(user) # read before saving changes + user.save + save_permissions!(user, perms) unless user.superuser + audit!('user.update', user.username, "#{before} → #{perm_summary(user.refresh)}#{' (disabled)' unless user.active}") + session[:users_flash] = 'Saved.' + redirect "/admin/users/#{user.id}" + end + + app.post '/admin/users/:id/invite' do + user = User[params[:id].to_i] or halt 404 + manageable!(user) + kind = user.password_digest ? 'reset' : 'invite' + send_account_link(user, kind) + audit!("user.#{kind}_link", user.username) + redirect '/admin/users' + end + + app.post '/admin/users/:id/delete' do + user = User[params[:id].to_i] or halt 404 + manageable!(user) + halt 422, "You can't delete yourself." if user.id == current_user.id + if user.superuser && User.where(superuser: true, active: true).exclude(id: user.id).empty? + halt 422, "Can't delete the last active superuser." + end + user.destroy + audit!('user.delete', user.username) + session[:users_flash] = "Deleted #{user.username}." + redirect '/admin/users' + end + + app.get '/admin/audit' do + @page_title = 'Audit log · admin' + @noindex = true + @entries = Audit.recent + erb :'admin/audit' + end + + # --- public: invite / reset links ----------------------------------- + + %w[invite reset].each do |purpose| + app.get "/admin/#{purpose}/:token" do + set_password_page(purpose) + erb :'admin/set_password' + end + + app.post "/admin/#{purpose}/:token" do + set_password_page(purpose) + @error = + if params[:password].to_s.length < User::MIN_PASS then "Password needs at least #{User::MIN_PASS} characters." + elsif params[:password] != params[:confirm] then 'Passwords do not match.' + end + if @error + status 422 + return erb :'admin/set_password' + end + user = @token.user + user.password = params[:password] + user.must_change_password = false + user.session_version += 1 + user.save + @token.use! + log_in!(user) + audit!("user.#{purpose}_accepted", user.username) + redirect '/admin' + end + end + + app.get '/admin/reset' do + @page_title = 'Reset password' + @noindex = true + erb :'admin/reset_request' + end + + # Same answer whether or not the account exists (no enumeration). + app.post '/admin/reset' do + @page_title = 'Reset password' + @noindex = true + 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')}" + begin + Mailer.account_link(to: user.email, username: user.username, url: url, kind: 'reset') + rescue StandardError => e + $logger.error("users: reset mail failed: #{e.class}: #{e.message}") + end + Audit.log(action: 'user.reset_requested', user: user, ip: client_ip) + end + end + @sent = true + erb :'admin/reset_request' + end + end +end diff --git a/test/users_admin_test.rb b/test/users_admin_test.rb new file mode 100644 index 0000000..ae86642 --- /dev/null +++ b/test/users_admin_test.rb @@ -0,0 +1,164 @@ +require_relative 'test_helper' + +class UsersAdminTest < Minitest::Test + include Rack::Test::Methods + include AdminLogin + + def app + AsxpioWeb + end + + def setup + skip 'TEST_DATABASE_URL not set' unless TestDb.available? + TestDb.clean_users! + DB.connection[:audit_log].delete + Mail::TestMailer.deliveries.clear + end + + def token(path = '/admin/users') + get path + last_response.body[/name="authenticity_token" value="([^"]+)"/, 1] + end + + def create_user(params) + post '/admin/users', { authenticity_token: token('/admin/users/new') }.merge(params) + end + + def invite_url + Mail::TestMailer.deliveries.last.body.to_s[%r{https?://\S+/admin/invite/\S+}] + end + + def test_superuser_creates_user_and_invite_is_emailed_and_shown + admin_login! + create_user(username: 'carol', email: 'carol@example.com', perm: { 'bingo' => { 'read' => '1', 'delete' => '1' } }) + assert_equal 302, last_response.status + carol = User[username: 'carol'] + assert carol.can?('bingo', 'read') + assert carol.can?('bingo', 'delete') + refute carol.can?('bingo', 'write') + assert_nil carol.password_digest + assert_equal ['carol@example.com'], Mail::TestMailer.deliveries.last.to + get '/admin/users' + assert_includes last_response.body, 'emailed to carol@example.com' + assert_includes last_response.body, '/admin/invite/' + get '/admin/users' + refute_includes last_response.body, '/admin/invite/' # shown once + end + + def test_delete_implies_read + admin_login! + create_user(username: 'dave', perm: { 'bingo' => { 'delete' => '1' } }) + assert User[username: 'dave'].can?('bingo', 'read') + end + + def test_invite_accept_sets_password_and_is_single_use + admin_login! + create_user(username: 'carol', email: 'carol@example.com') + path = URI(invite_url).path + clear_cookies + get path + assert last_response.ok? + assert_includes last_response.body, 'carol' + tok = last_response.body[/name="authenticity_token" value="([^"]+)"/, 1] + post path, { authenticity_token: tok, password: 'short', confirm: 'short' } + assert_equal 422, last_response.status + post path, { authenticity_token: tok, password: 'carol-password-1', confirm: 'carol-password-1' } + assert_equal 302, last_response.status + assert User[username: 'carol'].authenticate('carol-password-1') + get '/admin' + assert last_response.ok? # logged in + clear_cookies + get path + assert_equal 404, last_response.status # used + end + + def test_expired_invite_rejected + u = User.create(username: 'erin') + raw = UserToken.issue!(u, 'invite') + UserToken.where(user_id: u.id).update(expires_at: Time.now.utc - 1) + get "/admin/invite/#{raw}" + assert_equal 404, last_response.status + end + + def test_reset_request_same_answer_and_mails_only_real_accounts + User.create(username: 'frank', email: 'frank@example.com', password: 'frank-password-1') + get '/admin/reset' + tok = last_response.body[/name="authenticity_token" value="([^"]+)"/, 1] + post '/admin/reset', { authenticity_token: tok, login: 'nobody' } + nobody = last_response.body + post '/admin/reset', { authenticity_token: tok, login: 'frank@example.com' } + assert_equal nobody.scan(/reset link is on its way/), last_response.body.scan(/reset link is on its way/) + assert_equal 1, Mail::TestMailer.deliveries.size + url = Mail::TestMailer.deliveries.last.body.to_s[%r{https?://\S+/admin/reset/\S+}] + get URI(url).path + assert last_response.ok?, "#{url.inspect} -> #{last_response.status} #{last_response.body[0, 200]}" + 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) + UserPermission.create(user_id: boss.id, area: 'bingo', can_read: true) + target = User.create(username: 'grace', password: 'grace-password-1') + UserPermission.create(user_id: target.id, area: 'invoices', can_read: true) + admin_login!(username: 'manager', password: 'manager-pass-1') + + create_user(username: 'henry', superuser: '1', perm: { 'invoices' => { 'write' => '1' }, 'bingo' => { 'read' => '1' } }) + henry = User[username: 'henry'] + refute henry.superuser + refute henry.can?('invoices', 'write') # manager lacks it + assert henry.can?('bingo', 'read') + + post "/admin/users/#{target.id}", { authenticity_token: token, name: 'G', active: '1', perm: { 'bingo' => { 'read' => '1' } } } + target.refresh + assert target.can?('invoices', 'read') # kept: manager can't touch it + assert target.can?('bingo', 'read') + + root = User.create(username: 'root', superuser: true, password: 'root-password-11') + post "/admin/users/#{root.id}", { authenticity_token: token, name: 'x', active: '' } + assert_equal 403, last_response.status + end + + def test_cannot_delete_self_or_last_superuser + admin_login! + me = User[username: ENV['ADMIN_USER']] + post "/admin/users/#{me.id}/delete", { authenticity_token: token } + assert_equal 422, last_response.status + other = User.create(username: 'other', superuser: true, password: 'other-password-1') + post "/admin/users/#{other.id}/delete", { authenticity_token: token } + assert_equal 302, last_response.status + assert_nil User[other.id] + end + + def test_disabling_logs_user_out + admin_login! + u = User.create(username: 'ivan', password: 'ivan-password-12') + v = u.session_version + post "/admin/users/#{u.id}", { authenticity_token: token, name: '', email: '' } # active unticked + u.refresh + refute u.active + assert_equal v + 1, u.session_version + end + + def test_audit_log_records_and_lists + admin_login! + create_user(username: 'judy') + actions = DB.connection[:audit_log].select_map(:action) + assert_includes actions, 'auth.login' + assert_includes actions, 'user.create' + get '/admin/audit' + assert last_response.ok? + assert_includes last_response.body, 'user.create' + assert_includes last_response.body, 'judy' + end + + def test_users_read_only_cannot_create + u = User.create(username: 'viewer', password: 'viewer-password1') + UserPermission.create(user_id: u.id, area: 'users', can_read: true) + admin_login!(username: 'viewer', password: 'viewer-password1') + get '/admin/users' + assert last_response.ok? + refute_includes last_response.body, '+ New user' + get '/admin/users/new' + assert_equal 403, last_response.status + end +end diff --git a/views/admin/audit.erb b/views/admin/audit.erb new file mode 100644 index 0000000..243a5ab --- /dev/null +++ b/views/admin/audit.erb @@ -0,0 +1,23 @@ +<%== erb :'admin/_nav', layout: false %> +
← users · last <%= @entries.size %> entries
+| Time (UTC) | User | Action | Target | Detail | IP |
|---|---|---|---|---|---|
| <%= e[:created_at].strftime('%Y-%m-%d %H:%M') %> | +<%= e[:username] || '—' %> | +<%= e[:action] %> | +<%= e[:target] %> | +<%= e[:detail] %> | +<%= e[:ip] %> | +
If an account with an email address matches, a reset link is on its way. It works once and expires in 1 hour.
+ <% else %> + + <% end %> +Set a password for <%= @token.user.username %>
++ <% if can?('users', 'write') %>+ New user · <% end %>audit log +
+<%= @link['kind'] == 'invite' ? 'Invite' : 'Password reset' %> link<%= @link['sent'] ? " emailed to #{@link['to']}" : (@link['to'] ? " — email to #{@link['to']} FAILED, send it yourself" : ' (no email on file — send it yourself)') %>. + Shown once; it works once and expires in <%= @link['kind'] == 'invite' ? '48 hours' : '1 hour' %>:
+<%= @link['url'] %>
+| User | Access | Status | Last login | |
|---|---|---|---|---|
| <%= u.username %><% if u.name.to_s != '' %> <%= u.name %><% end %><% if u.email %> <%= u.email %><% end %> |
+ <%= perm_summary(u) %> | ++ <% if !u.active %>disabled + <% elsif !u.password_digest %>invited + <% else %>active<% end %> + | +<%= u.last_login_at&.strftime('%Y-%m-%d %H:%M') || '—' %> | +<%= can?('users', 'write') ? 'edit' : 'view' %> | +