From 20fe485f102ebee32cbbcd7f1e8012043ae6ad49 Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Sat, 7 Nov 2026 16:36:58 -0500 Subject: [PATCH] Account recovery from the command line (bin/rails users:*) list, reset_password (generated, shown once; unlocks and signs out), sign_in_link (one-time, 15 min), unlock, reset_two_factor, enable, disable, make_admin, create_admin. Logged; documented in the admin guide and README. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++ app/services/account_recovery.rb | 71 +++++++++++++++++++++ docs/guide/administration.md | 19 ++++++ lib/tasks/users.rake | 66 +++++++++++++++++++ test/integration/account_recovery_test.rb | 78 +++++++++++++++++++++++ 5 files changed, 238 insertions(+) create mode 100644 app/services/account_recovery.rb create mode 100644 lib/tasks/users.rake create mode 100644 test/integration/account_recovery_test.rb diff --git a/README.md b/README.md index 4153556..33cd1fd 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,10 @@ Other OIDC providers (Keycloak, Google, Entra ID…) work the same way. To keep the whole app behind Authentik's forward auth (proxy provider) while share links and outside mechanics' signing invitations still work, see [Running behind Authentik](docs/authentik.md): it has the unauthenticated URL list and what each one exposes. +### Account recovery + +Locked out of the admin account? On the server, `bin/rails users:list`, then for example `bin/rails "users:reset_password[admin@example.com]"` (a new password, shown once) or `bin/rails "users:sign_in_link[admin@example.com]"` (a one-time link). With Docker: `docker compose exec web bin/rails …`. All commands (unlock, two-factor reset, enable, make or create an admin) are listed in the [administration guide](docs/guide/administration.md#account-recovery-from-the-command-line). + ### Backups SQLite runs in WAL mode, so a plain file copy taken while the app is running can be inconsistent. Use the SQLite backup command instead: diff --git a/app/services/account_recovery.rb b/app/services/account_recovery.rb new file mode 100644 index 0000000..633df2d --- /dev/null +++ b/app/services/account_recovery.rb @@ -0,0 +1,71 @@ +# Account recovery from the server's command line (lib/tasks/users.rake), +# for when nobody can sign in to fix things in the app: a forgotten admin +# password, a lockout, a lost authenticator, a disabled or demoted admin. +# Whoever can run commands on the server already controls the data, so +# these need no other proof. Every action is logged. +class AccountRecovery + class Error < StandardError; end + + def self.find!(email) + User.find_by(email_address: email.to_s.strip.downcase) or raise Error, "No account with the email #{email.inspect}. List them with: bin/rails users:list" + end + + def self.list + User.order(:email_address).map do |u| + flags = [ ("admin" if u.admin?), ("DISABLED" if u.disabled?), ("LOCKED" if u.locked?), ("2FA" if u.otp_enabled?), ("SSO" if u.sso_uid?) ].compact + "#{u.email_address.ljust(36)} #{u.name.to_s.truncate(24).ljust(24)} #{flags.join(' ').ljust(26)} last sign-in: #{u.last_signed_in_at&.to_date || 'never'}" + end + end + + # Sets a new password (the one given, or a generated one, returned so it can + # be shown once), unlocks the account and signs out its sessions. + def self.reset_password!(email, password: nil) + user = find!(email) + password = password.presence || generate_password + user.password = user.password_confirmation = password + raise Error, "Password not accepted: #{user.errors.full_messages.to_sentence}" unless user.save + user.unlock! + user.sessions.destroy_all + log(user, "password reset") + password + end + + # A one-time sign-in link (15 minutes), as the "Email me a sign-in link" + # email would contain, for when email isn't working. + def self.sign_in_link(email) + user = find!(email) + raise Error, "That account is disabled: enable it first (bin/rails \"users:enable[#{user.email_address}]\")" if user.disabled? + raise Error, "Password sign-in is turned off (PASSWORD_LOGIN=false), so sign-in links don't work: unset it and restart, or fix single sign-on" unless Sso.password_login? + log(user, "sign-in link made") + "#{Sso.app_url}#{Rails.application.routes.url_helpers.sign_in_link_path(user.generate_token_for(:email_sign_in))}" + end + + def self.unlock!(email) = find!(email).tap { _1.unlock!; log(_1, "unlocked") } + def self.reset_two_factor!(email) = find!(email).tap { _1.disable_otp!; log(_1, "two-factor turned off") } + + def self.enable!(email) = find!(email).tap { _1.update!(disabled_at: nil); log(_1, "enabled") } + + def self.disable!(email) + find!(email).tap do |user| + user.update!(disabled_at: Time.current) + user.sessions.destroy_all + log(user, "disabled") + end + end + + def self.make_admin!(email) = find!(email).tap { _1.update!(admin: true); log(_1, "made an admin") } + + # A new admin account, for when there's none left to sign in with. + def self.create_admin!(email, name: nil, password: nil) + raise Error, "#{email} already has an account: use users:reset_password and users:make_admin" if User.exists?(email_address: email.to_s.strip.downcase) + password = password.presence || generate_password + user = User.new(email_address: email, name: name.presence, password: password, password_confirmation: password, admin: true) + raise Error, "Account not created: #{user.errors.full_messages.to_sentence}" unless user.save + log(user, "admin account created") + [ user, password ] + end + + def self.generate_password = SecureRandom.alphanumeric(20).scan(/.{5}/).join("-") + + def self.log(user, what) = Rails.logger.warn("[account recovery] #{user.email_address}: #{what} from the command line") +end diff --git a/docs/guide/administration.md b/docs/guide/administration.md index 01601ce..2717077 100644 --- a/docs/guide/administration.md +++ b/docs/guide/administration.md @@ -14,6 +14,25 @@ Admins see the **Admin** menu (on a phone, under ☰). Admins can see and edit e With single sign-on, accounts can be created automatically at first sign-in, and admin rights can follow a group at the provider (see the main README). +## Account recovery from the command line + +If nobody can sign in to fix an account in the app (a forgotten admin password, a lockout, a lost phone with no recovery codes, the only admin disabled), run these on the server. With Docker Compose, put `docker compose exec web` in front; in Portainer, open the container's **Console** and run them there. Anyone who can run commands on the server already has the data, so they ask for nothing else. Each one is written to the log. + +| Command | What it does | +|---|---| +| `bin/rails users:list` | Lists accounts, with admin, disabled, locked, 2FA and SSO status | +| `bin/rails "users:reset_password[jane@example.com]"` | Sets a new generated password and shows it once; also unlocks the account and signs it out everywhere. `PASSWORD=...` in front sets your own instead (it then stays in your shell history) | +| `bin/rails "users:sign_in_link[jane@example.com]"` | Prints a one-time sign-in link (15 minutes), for when email isn't working. Two-factor still asks for the code | +| `bin/rails "users:unlock[jane@example.com]"` | Clears a lockout after failed sign-ins | +| `bin/rails "users:reset_two_factor[jane@example.com]"` | Turns off the authenticator app | +| `bin/rails "users:enable[jane@example.com]"` / `users:disable[…]` | Enables or disables an account | +| `bin/rails "users:make_admin[jane@example.com]"` | Makes an existing account an admin (with `OIDC_ADMIN_GROUP` set, the next single sign-on sets it from the group again) | +| `bin/rails "users:create_admin[jane@example.com,Jane Pilot]"` | Creates a new admin account with a generated password | + +Keep the quotes around commands with brackets: some shells treat `[` specially. + +If single sign-on is broken and `PASSWORD_LOGIN=false` is set, remove that setting and restart first, so password sign-in (and sign-in links) work again. + ## Component Types, Airports, Logbook Templates - **Component Types**: the list of types used for components (owners can also add new types while adding a component). diff --git a/lib/tasks/users.rake b/lib/tasks/users.rake new file mode 100644 index 0000000..e6c3c37 --- /dev/null +++ b/lib/tasks/users.rake @@ -0,0 +1,66 @@ +# Account recovery from the command line (see AccountRecovery). In Docker: +# docker compose exec web bin/rails users:list +# docker compose exec web bin/rails "users:reset_password[jane@example.com]" +namespace :users do + run = lambda do |&block| + block.call + rescue AccountRecovery::Error => e + abort "Error: #{e.message}" + end + + desc "List accounts with their admin, disabled, locked, 2FA and SSO status" + task list: :environment do + puts AccountRecovery.list + end + + desc "Set a new password (PASSWORD=... or a generated one, shown once), unlock, and sign out everywhere" + task :reset_password, [ :email ] => :environment do |_, args| + run.call do + password = AccountRecovery.reset_password!(args[:email], password: ENV["PASSWORD"]) + puts "New password for #{args[:email]}: #{password}" + puts "Signed out everywhere and unlocked. Change it after signing in (Profile)." unless ENV["PASSWORD"].present? + end + end + + desc "Print a one-time sign-in link (15 minutes), for when email isn't working" + task :sign_in_link, [ :email ] => :environment do |_, args| + run.call { puts AccountRecovery.sign_in_link(args[:email]), "Works once, for 15 minutes. If the account has two-factor on, it still asks for the code." } + end + + desc "Clear a lockout after failed sign-ins" + task :unlock, [ :email ] => :environment do |_, args| + run.call { AccountRecovery.unlock!(args[:email]) && puts("Unlocked #{args[:email]}.") } + end + + desc "Turn off the authenticator app (lost phone and recovery codes)" + task :reset_two_factor, [ :email ] => :environment do |_, args| + run.call { AccountRecovery.reset_two_factor!(args[:email]) && puts("Two-factor turned off for #{args[:email]}. They can set it up again from their profile.") } + end + + desc "Enable a disabled account" + task :enable, [ :email ] => :environment do |_, args| + run.call { AccountRecovery.enable!(args[:email]) && puts("Enabled #{args[:email]}.") } + end + + desc "Disable an account and sign it out everywhere" + task :disable, [ :email ] => :environment do |_, args| + run.call { AccountRecovery.disable!(args[:email]) && puts("Disabled #{args[:email]}.") } + end + + desc "Make an existing account an admin" + task :make_admin, [ :email ] => :environment do |_, args| + run.call do + AccountRecovery.make_admin!(args[:email]) + puts "#{args[:email]} is now an admin." + puts "Note: OIDC_ADMIN_GROUP is set, so their next single sign-on sign-in sets admin from the group again." if Sso.admin_group + end + end + + desc "Create a new admin account (PASSWORD=... or a generated one)" + task :create_admin, [ :email, :name ] => :environment do |_, args| + run.call do + user, password = AccountRecovery.create_admin!(args[:email], name: args[:name], password: ENV["PASSWORD"]) + puts "Created admin #{user.email_address} with password: #{password}" + end + end +end diff --git a/test/integration/account_recovery_test.rb b/test/integration/account_recovery_test.rb new file mode 100644 index 0000000..0398b51 --- /dev/null +++ b/test/integration/account_recovery_test.rb @@ -0,0 +1,78 @@ +require "test_helper" +require "rake" + +# Account recovery from the command line (bin/rails users:*). +class AccountRecoveryTest < ActionDispatch::IntegrationTest + setup do + @admin = create_user("admin@example.com", admin: true) + Rails.application.load_tasks if Rake::Task.tasks.none? { _1.name == "users:list" } + end + + def rake(name, *args, env: {}) + Rake::Task[name].reenable + old = env.to_h { |k, _| [ k, ENV[k] ] } + env.each { ENV[_1] = _2 } + out, = capture_io { Rake::Task[name].invoke(*args) } + out + ensure + old&.each { ENV[_1] = _2 } + end + + test "reset a forgotten password: generated, shown once, unlocks and signs out" do + sign_in @admin + @admin.update_columns(locked_until: 10.minutes.from_now, failed_sign_ins: 3) + out = rake("users:reset_password", "Admin@Example.com") + password = out[/New password for \S+: (\S+)/, 1] + assert_equal 23, password.size + @admin.reload + assert @admin.authenticate(password) + refute @admin.locked? + assert_equal 0, @admin.sessions.count + + rake("users:reset_password", "admin@example.com", env: { "PASSWORD" => "chosen-password-99" }) + assert @admin.reload.authenticate("chosen-password-99") + assert_raises(AccountRecovery::Error) { AccountRecovery.reset_password!("admin@example.com", password: "short") } + assert_raises(AccountRecovery::Error) { AccountRecovery.reset_password!("nobody@example.com") } + end + + test "a printed sign-in link signs in once" do + link = rake("users:sign_in_link", "admin@example.com").lines.first.strip + path = URI(link).path + assert_match %r{/session/link/}, path + post "#{path}/consume" + assert_redirected_to root_path + post "#{path}/consume" + assert_redirected_to new_sign_in_link_path # spent + + @admin.update!(disabled_at: Time.current) + assert_raises(AccountRecovery::Error) { AccountRecovery.sign_in_link("admin@example.com") } + end + + test "unlock, reset two-factor, enable, disable, make admin, list" do + user = create_user("jane@example.com") + user.update_columns(locked_until: 10.minutes.from_now) + user.enable_otp!(User.new_otp_secret) + listing = rake("users:list") + assert_match(/jane@example\.com .*LOCKED 2FA/, listing) + + rake("users:unlock", "jane@example.com") + refute user.reload.locked? + rake("users:reset_two_factor", "jane@example.com") + refute user.reload.otp_enabled? + rake("users:disable", "jane@example.com") + assert user.reload.disabled? + rake("users:enable", "jane@example.com") + refute user.reload.disabled? + rake("users:make_admin", "jane@example.com") + assert user.reload.admin? + end + + test "create a new admin when none can sign in" do + out = rake("users:create_admin", "new-admin@example.com", "Jane Pilot") + user = User.find_by!(email_address: "new-admin@example.com") + assert user.admin? + assert_equal "Jane Pilot", user.name + assert user.authenticate(out[/password: (\S+)/, 1]) + assert_raises(AccountRecovery::Error) { AccountRecovery.create_admin!("admin@example.com") } + end +end