Sign-in hardening: lockout, stronger passwords, authenticator codes

- 10 failed sign-ins in a row (password, authenticator code, or password
  at signing) lock an account for 15 minutes from any address; the user
  is emailed; admins can unlock. Same message as a wrong password.
- Passwords: at least 12 characters (max 72), refused if found in Have I
  Been Pwned (k-anonymity range API; fails open; PWNED_PASSWORDS_CHECK=false)
- Optional TOTP (authenticator app) with 10 recovery codes for password
  and emailed-link sign-in, and at signing (auth method password_totp);
  codes accepted once; admins can reset; SSO sign-in unaffected
- Demo/test passwords updated; guide, README and procedures document

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-07 15:17:56 -05:00
1 parent a6bfe922be
commit 14316bb60f
41 files changed
+600 -45

No files matched your search

+2
View File
@@ -84,3 +84,5 @@ gem "omniauth_openid_connect", "~> 0.8"
gem "omniauth-rails_csrf_protection", "~> 2.0"
gem "prawn", "~> 2.5" # printable logbook entries
gem "rotp", "~> 6.3" # authenticator app (TOTP) codes
gem "rqrcode", "~> 3.1" # QR code for setting up the authenticator
+12
View File
@@ -115,6 +115,7 @@ GEM
nokogiri (~> 1.10, >= 1.10.4)
rubyzip (>= 2.4, < 4)
chartkick (5.3.0)
chunky_png (1.4.0)
commonmarker (2.10.1-aarch64-linux)
commonmarker (2.10.1-aarch64-linux-musl)
commonmarker (2.10.1-arm-linux-gnu)
@@ -367,6 +368,11 @@ GEM
logger (~> 1)
nokogiri (~> 1)
rubyzip (>= 3.0.0, < 4.0.0)
rotp (6.4.0)
rqrcode (3.2.0)
chunky_png (~> 1.0)
rqrcode_core (~> 2.0)
rqrcode_core (2.1.0)
rubocop (1.92.2)
json (>= 2.3)
language_server-protocol (~> 3.17.0.2)
@@ -530,6 +536,8 @@ DEPENDENCIES
puma (>= 5.0)
rails (~> 8.1.0)
roo (~> 4.0)
rotp (~> 6.3)
rqrcode (~> 3.1)
rubocop-rails-omakase
rubyzip (~> 3.7)
selenium-webdriver
@@ -579,6 +587,7 @@ CHECKSUMS
capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef
caxlsx (4.5.0) sha256=e3d98d859f148df05d5462086b5079b523f29c1766b569535f1d68629ce743ff
chartkick (5.3.0) sha256=19a2bba39decf54c4939d3f31460535f8814c85045672ba2ed616c6897325b00
chunky_png (1.4.0) sha256=89d5b31b55c0cf4da3cf89a2b4ebc3178d8abe8cbaf116a1dba95668502fdcfe
commonmarker (2.10.1-aarch64-linux) sha256=3ab9e7027d2350364bdc541680cc28e21011b2950abf7d08ac29093fa691bdc3
commonmarker (2.10.1-aarch64-linux-musl) sha256=98e6d1a03ba708438d804702e3c25f3423bff21a1e9975280eb265d889677dfc
commonmarker (2.10.1-arm-linux-gnu) sha256=dc1ce6cfe5547d2814351ef306d5d1dd05f9c08ad405c76baa94748326c83b7f
@@ -680,6 +689,9 @@ CHECKSUMS
reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d
rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142
roo (4.0.0) sha256=83e25e85add9313fcf9d1e6c88720ce2bba2fa22590375eca23092be1d0690e8
rotp (6.4.0) sha256=e2de8e0dfda5729b430f384e6233432bf0402c4f57ca270fa0cc1b5a42ed49f2
rqrcode (3.2.0) sha256=64c1494ca6bb67d731330f38b50e3fd09eeab4f5dcd04b608e21218d1d0b9542
rqrcode_core (2.1.0) sha256=f303b85df89c1b8fc5ee8dc19808c9dc4330e6329b660d99d4a8cbb36ca13051
rubocop (1.92.2) sha256=14fb31eed143a0dc6f78186c550c1715e81cd38f59d05d1165050e445c1f5382
rubocop-ast (1.50.0) sha256=b9ca88300da0803ee222ad20cdb30494c0a784eed06fdc35d254b06d662788db
rubocop-performance (1.27.0) sha256=eeeb1374d062a368ee1c787b70eb0b0cc4b184cb1f8565f424760946146d61ce
+3 -1
View File
@@ -26,7 +26,7 @@ DEMO=1 bin/rails db:seed # optional: demo aircraft N12345
bin/dev # http://localhost:3000
```
With demo data, sign in as `admin@example.com` / `password123` (admin, owner of N12345) or `pilot@example.com` / `password123` (pilot).
With demo data, sign in as `admin@example.com` / `demo-password-123` (admin, owner of N12345) or `pilot@example.com` / `demo-password-123` (pilot).
Without demo data, the first visit asks you to create the admin account.
Run the tests: `bin/rails test`
@@ -69,6 +69,7 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in. New accounts start with no aircraft. Default off: an admin adds users first. |
| `OIDC_TRUST_EMAIL` | `true` links existing accounts by email even if the provider doesn't mark it verified. Only use it if users can't edit their own email at the provider. |
| `OIDC_ADMIN_GROUP` | Optional. Members of this provider group become admins and others lose admin, synced at each sign-in. |
| `PWNED_PASSWORDS_CHECK` | `false` turns off the check of new passwords against Have I Been Pwned (only the first 5 characters of the password's SHA-1 are sent). Use it if the server has no outbound internet access; the check also allows the password if the service can't be reached. |
| `PASSWORD_LOGIN` | `false` hides email/password sign-in, emailed sign-in links and password resets once SSO works. It's ignored while SSO isn't configured, so you can't lock yourself out. |
| `APP_REPOSITORY_URL` | Optional. The source code link on Admin → About, for a fork. |
| `APP_REVISION`, `APP_BUILT_AT` | Set as Docker build arguments (see the `Dockerfile`) so Admin → About shows the version and the records keep a software version history. |
@@ -129,6 +130,7 @@ To back up or move a single aircraft with all its files, use **Access & Sharing
| Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). |
| Activity log | Every write is recorded as an `AircraftEvent`. |
| Access | Admin, owner, and pilot roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
| Sign-in security | Passwords of at least 12 characters, checked against known breaches (Have I Been Pwned, k-anonymity). 10 failed sign-ins in a row lock an account for 15 minutes from any address, and the user is emailed; admins can unlock. Optional authenticator-app (TOTP) codes with recovery codes for password and emailed-link sign-in and for signing entries; admins can reset them. Rate limits per address on every sign-in form. |
| Help | The [user guide](docs/guide/README.md), shown in the app under **Help**. |
### Roles
+14 -1
View File
@@ -1,6 +1,6 @@
class Admin::UsersController < ApplicationController
before_action :require_admin!
before_action :set_user, only: %i[edit update destroy disable enable]
before_action :set_user, only: %i[edit update destroy disable enable unlock reset_two_factor]
def index
@users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft)
@@ -39,6 +39,19 @@ class Admin::UsersController < ApplicationController
# Ends their access and their ability to sign (AC 120-78B 2.2.6.4) while
# keeping their account, so the signatures they made stay attributed.
def unlock
@user.unlock!
redirect_to admin_users_path, notice: "#{@user.email_address} unlocked."
end
# For a user who lost their authenticator: they sign in with their password
# alone and can set it up again.
def reset_two_factor
@user.disable_otp!
Rails.logger.info("[auth] #{current_user.email_address} turned off two-factor for #{@user.email_address}")
redirect_to admin_users_path, notice: "Two-factor turned off for #{@user.email_address}. Ask them to set it up again from their profile."
end
def disable
return redirect_to admin_users_path, alert: "You can't disable yourself." if @user == current_user
@user.update!(disabled_at: Time.current)
@@ -58,6 +58,29 @@ module Authentication
end
end
# Password or emailed-link sign-in: straight in, or first the
# authenticator code if the user has one set up (SSO skips this; the
# provider handles its own second factor).
OTP_PENDING_FOR = 5.minutes
def begin_sign_in(user, return_to:, notice: nil)
reset_session # fresh session id after signing in
if user.otp_enabled?
session[:otp_user_id] = user.id
session[:otp_started_at] = Time.current.to_i
session[:return_to_after_authenticating] = return_to
redirect_to two_factor_session_path
else
start_new_session_for user
redirect_to return_to, notice: notice
end
end
def pending_otp_user
return unless (id = session[:otp_user_id]) && Time.zone.at(session[:otp_started_at].to_i) > OTP_PENDING_FOR.ago
User.active.find_by(id: id)
end
def terminate_session
Current.session.destroy
cookies.delete(:session_id)
+17 -3
View File
@@ -11,10 +11,20 @@ module EntrySigning
session[:after_reauth] = signing_page_path # where single sign-on returns after signing in again
end
# Password re-entered now, or single sign-on completed in the last few minutes.
# Password re-entered now (with an authenticator code too, if the user has
# one), or single sign-on completed in the last few minutes. Wrong
# passwords and codes count toward the account lockout.
def reauthenticated_method
if params[:password].present?
return "password" if current_user.authenticate_password(params[:password])
return if current_user.locked?
unless current_user.authenticate_password(params[:password])
current_user.register_failed_sign_in!
return
end
return "password" unless current_user.otp_enabled?
return "password_totp" if current_user.verify_second_factor(params[:otp_code])
current_user.register_failed_sign_in!
return
elsif current_user.sso_uid? && (at = session[:reauthenticated_at]) && Time.zone.at(at) > EntrySigner::REAUTH_WINDOW.ago
return "sso"
end
@@ -27,7 +37,11 @@ module EntrySigning
unless params[:confirm] == "1"
return signing_failed(entry, "Tick the box to confirm you're signing this entry.")
end
return signing_failed(entry, "Re-enter your password (or sign in again with #{Sso.label}) to sign.") unless method
unless method
return signing_failed(entry, "This account is locked for a few minutes after too many failed tries.") if current_user.reload.locked?
return signing_failed(entry, "Re-enter your password#{' and a current authenticator code' if current_user.otp_enabled?} (or sign in again with #{Sso.label}) to sign.")
end
current_user.clear_failed_sign_ins!
signature = EntrySigner.new(entry, user: current_user, certificate: certificate, auth_method: method, request: request).sign!
session.delete(:reauthenticated_at)
+1 -1
View File
@@ -24,7 +24,7 @@ class PasswordsController < ApplicationController
@user.sessions.destroy_all # a reset signs out every device
redirect_to new_session_path, notice: "Password has been reset."
else
redirect_to edit_password_path(params[:token]), alert: "Passwords did not match."
redirect_to edit_password_path(params[:token]), alert: @user.errors.full_messages.to_sentence.presence || "Enter a new password."
end
end
+31 -8
View File
@@ -1,6 +1,8 @@
class SessionsController < ApplicationController
allow_unauthenticated_access only: %i[ new create ]
rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_url, alert: "Try again later." }
allow_unauthenticated_access only: %i[new create two_factor verify_two_factor]
rate_limit to: 10, within: 3.minutes, only: %i[create verify_two_factor], with: -> { redirect_to new_session_url, alert: "Try again later." }
FAILED = "Try another email address or password. After #{User::LOCK_AFTER} failed tries in a row an account is locked for #{User::LOCK_FOR.inspect}.".freeze
def new
end
@@ -8,15 +10,36 @@ class SessionsController < ApplicationController
def create
return redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login?
if (user = User.authenticate_by(params.permit(:email_address, :password))) && user.disabled?
if (user = User.authenticate_with_lockout(email_address: params[:email_address], password: params[:password])) && user.disabled?
redirect_to new_session_path, alert: "This account is disabled."
elsif user
return_to = after_authentication_url
reset_session # fresh session id after signing in
start_new_session_for user
redirect_to return_to
begin_sign_in user, return_to: after_authentication_url
else
redirect_to new_session_path, alert: "Try another email address or password."
redirect_to new_session_path(email_address: params[:email_address].to_s.first(200)), alert: FAILED
end
end
# Second step for accounts with an authenticator app.
def two_factor
redirect_to new_session_path, alert: "Sign in again." unless pending_otp_user
end
def verify_two_factor
user = pending_otp_user
return redirect_to(new_session_path, alert: "That took too long. Sign in again.") unless user
if user.locked?
reset_session
redirect_to new_session_path, alert: FAILED
elsif user.verify_second_factor(params[:code])
user.clear_failed_sign_ins!
return_to = after_authentication_url
reset_session
start_new_session_for user
notice = user.recovery_codes_left < 3 ? "Signed in. You have #{user.recovery_codes_left} recovery codes left: make new ones on your profile." : nil
redirect_to return_to, notice: notice
else
user.register_failed_sign_in!
redirect_to two_factor_session_path, alert: "That code didn't match. Try the current code from your authenticator app, or a recovery code."
end
end
+1 -3
View File
@@ -26,9 +26,7 @@ class SignInLinksController < ApplicationController
def consume
return redirect_to new_session_path, alert: "This account is disabled." if @user.disabled?
reset_session # fresh session id after signing in
start_new_session_for @user # also spends the link
redirect_to root_path, notice: "Signed in."
begin_sign_in @user, return_to: root_path, notice: "Signed in." # signing in also spends the link
end
private
+48
View File
@@ -0,0 +1,48 @@
# Profile → Two-factor: set up an authenticator app (TOTP) for password and
# emailed-link sign-in, turn it off, or make new recovery codes.
class TwoFactorsController < ApplicationController
rate_limit to: 10, within: 5.minutes, only: %i[create destroy recovery_codes], with: -> { redirect_to edit_profile_path(anchor: "two-factor"), alert: "Try again later." }
def new
return redirect_to(back_path, notice: "Two-factor is already on.") if current_user.otp_enabled?
session[:pending_otp_secret] ||= User.new_otp_secret
@secret = session[:pending_otp_secret]
svg = RQRCode::QRCode.new(User.otp_uri(@secret, current_user.email_address)).as_svg(module_size: 4, use_path: true, viewbox: true)
@qr_data_uri = "data:image/svg+xml;base64,#{Base64.strict_encode64(svg)}"
end
def create
secret = session[:pending_otp_secret]
return redirect_to(new_two_factor_path(return_to: params[:return_to])) unless secret
if User.valid_otp?(secret, params[:code])
session.delete(:pending_otp_secret)
@codes = current_user.enable_otp!(secret)
log_security("turned on two-factor")
render :codes
else
redirect_to new_two_factor_path(return_to: params[:return_to]), alert: "That code didn't match. Check the time on your phone and try the current code."
end
end
def recovery_codes
return redirect_to(edit_profile_path(anchor: "two-factor"), alert: "That code didn't match.") unless current_user.verify_second_factor(params[:code])
@codes = current_user.enable_otp!(current_user.otp_secret)
log_security("made new recovery codes")
render :codes
end
def destroy
return redirect_to(edit_profile_path(anchor: "two-factor"), alert: "That code didn't match.") unless current_user.verify_second_factor(params[:code])
current_user.disable_otp!
log_security("turned off two-factor")
redirect_to edit_profile_path(anchor: "two-factor"), notice: "Two-factor is off."
end
private
# Back to a signing invitation the user came from, else the profile.
def back_path = params[:return_to].to_s.match?(%r{\A/sign/[\w-]+\z}) ? params[:return_to] : edit_profile_path(anchor: "two-factor")
helper_method :back_path
def log_security(what) = Rails.logger.info("[auth] #{current_user.email_address} #{what}")
end
+5
View File
@@ -4,4 +4,9 @@ class SessionsMailer < ApplicationMailer
@token = user.generate_token_for(:email_sign_in)
mail subject: "Your sign-in link", to: user.email_address
end
def locked(user)
@user = user
mail subject: "Your account was locked after failed sign-ins", to: user.email_address
end
end
+2 -1
View File
@@ -7,7 +7,8 @@
# by this server, so the signature record can't be altered unnoticed either.
class EntrySignature < ApplicationRecord
include Versioned
AUTH_METHODS = { "password" => "password re-entered", "sso" => "single sign-on, signed in again" }.freeze
AUTH_METHODS = { "password" => "password re-entered", "password_totp" => "password and authenticator code re-entered",
"sso" => "single sign-on, signed in again" }.freeze
# "Certified by" conveys the intent to sign (2.2.2).
LABEL = "Certified by".freeze
+89 -1
View File
@@ -22,7 +22,86 @@ class User < ApplicationRecord
validates :email_address, presence: true, uniqueness: true,
format: { with: URI::MailTo::EMAIL_REGEXP }
validates :password, length: { minimum: 8 }, allow_nil: true
PASSWORD_MIN = 12
validates :password, length: { minimum: PASSWORD_MIN, maximum: 72 }, allow_nil: true
validate :password_not_breached
# Lockout: this many failed sign-ins in a row (password, authenticator
# code, or password at signing) locks the account for a while, from
# whatever address they come. The user is emailed.
LOCK_AFTER = 10
LOCK_FOR = 15.minutes
encrypts :otp_secret
OTP_ISSUER = "Simple Aircraft Manager".freeze
RECOVERY_CODES = 10
# Password sign-in with lockout. Returns the user, or nil (wrong details,
# or locked: the same answer, so it doesn't reveal which).
def self.authenticate_with_lockout(email_address:, password:)
user = find_by(email_address: email_address.to_s.strip.downcase)
return if user&.locked?
authed = authenticate_by(email_address: email_address.to_s, password: password.to_s)
authed ? authed.tap(&:clear_failed_sign_ins!) : user&.register_failed_sign_in!
end
def locked? = locked_until&.future?
# Counts a failed attempt; locks the account (and returns nil) at the limit.
def register_failed_sign_in!
self.class.where(id: id).update_all("failed_sign_ins = failed_sign_ins + 1")
reload
if failed_sign_ins >= LOCK_AFTER
update_columns(failed_sign_ins: 0, locked_until: LOCK_FOR.from_now)
SessionsMailer.locked(self).deliver_later if MailSettings.configured?
Rails.logger.warn("[auth] #{email_address} locked after #{LOCK_AFTER} failed sign-ins")
end
nil
end
def clear_failed_sign_ins!
update_columns(failed_sign_ins: 0, locked_until: nil) if failed_sign_ins.positive? || locked_until
end
def unlock! = update_columns(failed_sign_ins: 0, locked_until: nil)
# --- Authenticator app (TOTP) ---
def otp_enabled? = otp_enabled_at.present? && otp_secret.present?
def self.new_otp_secret = ROTP::Base32.random
def self.otp_uri(secret, email) = ROTP::TOTP.new(secret, issuer: OTP_ISSUER).provisioning_uri(email)
# A code from the authenticator for this secret, allowing 30 s of clock drift.
def self.valid_otp?(secret, code, after: nil)
ROTP::TOTP.new(secret, issuer: OTP_ISSUER).verify(code.to_s.gsub(/\s/, ""), drift_behind: 30, drift_ahead: 30, after: after)
end
# Turns it on with a confirmed secret; returns the recovery codes to show once.
def enable_otp!(secret)
codes = Array.new(RECOVERY_CODES) { SecureRandom.alphanumeric(10).downcase.scan(/.{5}/).join("-") }
update!(otp_secret: secret, otp_enabled_at: Time.current, otp_last_used_at: nil, otp_recovery_codes: codes.map { recovery_digest(_1) })
codes
end
def disable_otp! = update!(otp_secret: nil, otp_enabled_at: nil, otp_last_used_at: nil, otp_recovery_codes: nil)
# An authenticator code (each accepted once) or an unused recovery code.
def verify_second_factor(code)
return false unless otp_enabled?
code = code.to_s.strip.downcase
if code.gsub(/\s/, "").match?(/\A\d{6}\z/)
step = self.class.valid_otp?(otp_secret, code, after: otp_last_used_at)
step ? update_columns(otp_last_used_at: step) && true : false
else
digests = Array(otp_recovery_codes)
match = digests.find { ActiveSupport::SecurityUtils.secure_compare(_1, recovery_digest(code)) }
match ? update_columns(otp_recovery_codes: digests - [ match ]) && true : false
end
end
def recovery_codes_left = Array(otp_recovery_codes).size
# Aircraft visible to this user: admins see the whole fleet.
def accessible_aircraft
@@ -38,4 +117,13 @@ class User < ApplicationRecord
def display_name
name.presence || email_address
end
private
def recovery_digest(code) = OpenSSL::HMAC.hexdigest("SHA256", Rails.application.key_generator.generate_key("otp-recovery", 32), code.to_s.strip.downcase)
def password_not_breached
return if password.blank? || errors.include?(:password)
errors.add(:password, "has appeared in a data breach (Have I Been Pwned); choose a different one") if PwnedPasswords.breached?(password)
end
end
+33
View File
@@ -0,0 +1,33 @@
require "net/http"
# Checks a password against the Have I Been Pwned breach corpus with the
# k-anonymity range API: only the first 5 characters of its SHA-1 are sent,
# never the password. If the service can't be reached the password is
# allowed (logged), so an outage doesn't stop anyone changing a password.
# PWNED_PASSWORDS_CHECK=false turns it off (e.g. no outbound internet).
module PwnedPasswords
API = "https://api.pwnedpasswords.com/range/".freeze
mattr_accessor :checker, default: ->(password) { lookup(password) }
def self.enabled? = ENV["PWNED_PASSWORDS_CHECK"] != "false"
def self.breached?(password) = enabled? && password.present? && checker.call(password)
def self.lookup(password)
sha1 = Digest::SHA1.hexdigest(password).upcase
prefix, suffix = sha1[0, 5], sha1[5..]
uri = URI("#{API}#{prefix}")
req = Net::HTTP::Get.new(uri)
req["Add-Padding"] = "true"
req["User-Agent"] = "Simple-Aircraft-Manager"
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 3, read_timeout: 3) { _1.request(req) }
return false unless res.is_a?(Net::HTTPSuccess)
res.body.each_line.any? do |line|
hash, count = line.strip.split(":")
hash == suffix && count.to_i.positive?
end
rescue StandardError => e
Rails.logger.warn("[pwned passwords] check skipped: #{e.class}: #{e.message}")
false
end
end
@@ -62,7 +62,7 @@
<ol class="<%= p_ %> list-decimal pl-5">
<li>The signer opens the entry and chooses Sign. The entry is shown in full exactly as it will be certified (AC 2.2.4).</li>
<li>They choose one of their own current certificates. The statement they will certify is shown with it, under the heading “Certified by” (2.2.2): for maintenance, “I certify that the work described in this entry was performed in accordance with 14 CFR Part 43, and I approve it for return to service with respect to that work”; for inspections, the 43.11(a)(5) statement; for preventive maintenance by a pilot, the corresponding statement.</li>
<li>They prove who they are again: their password, or signing in again with single sign-on within the last five minutes (2.2.6), and confirm that they are signing with intent to sign (2.1.2.4–5).</li>
<li>They prove who they are again: their password (with a code from their authenticator app, if they use one), or signing in again with single sign-on within the last five minutes (2.2.6), and confirm that they are signing with intent to sign (2.1.2.4–5).</li>
<li>The system records the signer, the certificate (kind and number), the statement, the time (UTC), how they authenticated, their network address and browser, a SHA-256 fingerprint of the entry's content and a readable copy of it, and a server seal (HMAC) over the signature record (2.1.2.6, 2.2.5). The signer is told on screen and by email (2.2.3).</li>
<li>Once signed, the entry and its components can't be edited or deleted (2.1.2.7–8, 2.2.7). A correction is made as a new entry that, once signed, supersedes the original; the original and its signature are kept and marked superseded (2.2.8).</li>
<li>When someone no longer needs access, the responsible person disables their account: they can no longer sign in or sign, and their past signatures stay valid (2.2.6.4).</li>
@@ -71,7 +71,7 @@
<h2 class="<%= h2 %>">7. Recordkeeping system controls</h2>
<ul class="<%= p_ %> list-disc pl-5">
<li><strong>Controlled access (3.2.1):</strong> personal accounts; roles per aircraft; sessions end after 30 days unused; rate-limited sign-in; changing an email or password needs the current password.</li>
<li><strong>Controlled access (3.2.1):</strong> personal accounts; roles per aircraft; passwords of at least 12 characters, refused if known from a data breach; optional authenticator-app codes; accounts locked for 15 minutes after 10 failed sign-ins (the user is emailed); rate-limited sign-in; sessions end after 30 days unused; changing an email or password needs the current password.</li>
<li><strong>Record preservation (3.2.2):</strong> every change to a maintenance record is kept with who, when and what changed, in a hash chain per aircraft that can't be edited; signed entries are locked.</li>
<li><strong>Confidential information (3.2.3):</strong> records are visible only to the aircraft's users, and to share links an owner creates (scoped and optionally expiring).</li>
<li><strong>Data corruption (3.2.4):</strong> nightly, the history chains and every signature's seal and fingerprint are checked; administrators are emailed on any problem.</li>
+1 -1
View File
@@ -2,7 +2,7 @@
<%= f.errors_summary %>
<%= f.field :name %>
<%= f.field :email_address, as: :email, label: "Email", required: true %>
<%= f.field :password, as: :password, hint: (user.persisted? ? "Leave blank to keep current password." : "At least 8 characters."), autocomplete: "new-password" %>
<%= f.field :password, as: :password, hint: (user.persisted? ? "Leave blank to keep current password." : "At least #{User::PASSWORD_MIN} characters; not one known from a data breach."), autocomplete: "new-password" %>
<%= f.field :password_confirmation, as: :password %>
<%= f.field :admin, as: :checkbox, label: "Administrator", hint: "Admins can see and edit every aircraft and manage users." %>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", admin_users_path, class: "btn-secondary" %></div>
+3 -1
View File
@@ -3,13 +3,15 @@
<section class="card"><table class="table">
<thead><tr><th>Name</th><th>Email</th><th>Aircraft</th><th>Last sign-in</th><th></th></tr></thead>
<tbody><% @users.each do |u| %><tr>
<td><%= u.name %> <% if u.admin? %><span class="badge-blue">Admin</span><% end %><% if u.sso_uid? %> <span class="badge-gray" title="Signs in with <%= Sso.label %>"><%= Sso.label %></span><% end %></td>
<td><%= u.name %> <% if u.admin? %><span class="badge-blue">Admin</span><% end %><% if u.sso_uid? %> <span class="badge-gray" title="Signs in with <%= Sso.label %>"><%= Sso.label %></span><% end %><% if u.otp_enabled? %> <span class="badge-green" title="Authenticator app on">2FA</span><% end %><% if u.locked? %> <span class="badge-red" title="Too many failed sign-ins">Locked</span><% end %></td>
<td><%= u.email_address %><% if u.certificates.any? %><div class="text-xs text-slate-500"><%= u.certificates.map { "#{_1.short_label} #{_1.number}" }.join(", ") %></div><% end %></td>
<td class="text-xs"><%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %></td>
<td class="text-xs text-slate-500"><%= u.last_signed_in_at ? "#{time_ago_in_words(u.last_signed_in_at)} ago" : "never" %></td>
<td class="whitespace-nowrap text-right">
<% if u.disabled? %><span class="badge-red mr-1">Disabled</span><%= button_to "Enable", enable_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %>
<% elsif u != current_user %><%= button_to "Disable", disable_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline", data: { turbo_confirm: "Disable #{u.email_address}? They'll be signed out and can't sign in or sign entries. Their past signatures are kept." } } %><% end %>
<% if u.locked? %><%= button_to "Unlock", unlock_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %><% end %>
<% if u.otp_enabled? %><%= button_to "Reset 2FA", reset_two_factor_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", title: "Turn off their authenticator app (lost phone)", form: { class: "inline", data: { turbo_confirm: "Turn off two-factor for #{u.email_address}? Only do this after confirming it's really them." } } %><% end %>
<%= link_to "Edit", edit_admin_user_path(u), class: "btn-secondary btn-sm" %></td>
</tr><% end %></tbody>
</table></section>
@@ -32,6 +32,12 @@
<%= password_field_tag :password, nil, class: "input", autocomplete: "current-password" %>
<p class="hint">Proves it's you signing, not someone at your keyboard.<%= " Or sign in again with #{Sso.label} below." if Sso.enabled? && current_user.sso_uid? %></p>
</div>
<% if current_user.otp_enabled? %>
<div class="max-w-xs">
<%= label_tag :otp_code, "Authenticator code", class: "label" %>
<%= text_field_tag :otp_code, nil, class: "input w-32 tracking-widest", autocomplete: "one-time-code", inputmode: "numeric", maxlength: 20 %>
</div>
<% end %>
<% end %>
<% if Sso.enabled? && current_user.sso_uid? %>
<% fresh = session[:reauthenticated_at] && Time.zone.at(session[:reauthenticated_at]) > EntrySigner::REAUTH_WINDOW.ago %>
+3
View File
@@ -10,3 +10,6 @@
</section>
<% end %>
<%= render "entry_signatures/form", entry: @entry, url: invited_signing_path(params[:token]), cancel_path: root_path %>
<% unless current_user.otp_enabled? %>
<p class="mx-auto mt-4 max-w-3xl text-sm text-slate-600">Recommended: <%= link_to "add an authenticator app", new_two_factor_path(return_to: request.path), class: "link" %> to your account, so your signature can't be made with a stolen password alone.</p>
<% end %>
+1 -1
View File
@@ -11,7 +11,7 @@
<% if @account_errors.present? %><div class="rounded-md bg-red-50 p-2 text-sm text-red-700"><%= @account_errors.to_sentence %></div><% end %>
<div><label class="label">Email</label><input class="input" value="<%= @invitation.email %>" disabled></div>
<div><%= label_tag :name, "Your name", class: "label" %><%= text_field_tag :name, params[:name], class: "input", required: true %></div>
<div><%= label_tag :password, "Password", class: "label" %><%= password_field_tag :password, nil, class: "input", required: true, autocomplete: "new-password" %></div>
<div><%= label_tag :password, "Password", class: "label" %><%= password_field_tag :password, nil, class: "input", required: true, autocomplete: "new-password", minlength: User::PASSWORD_MIN, maxlength: 72 %><p class="hint">At least <%= User::PASSWORD_MIN %> characters; not one known from a data breach.</p></div>
<div><%= label_tag :password_confirmation, "Confirm password", class: "label" %><%= password_field_tag :password_confirmation, nil, class: "input", required: true, autocomplete: "new-password" %></div>
<%= submit_tag "Create account", class: "btn-secondary" %>
<% end %>
+16 -1
View File
@@ -5,7 +5,7 @@
<%= f.field :email_address, as: :email, label: "Email" %>
<%= f.field :reminder_emails, as: :checkbox, label: "Weekly maintenance reminders",
hint: "A Monday email about overdue and upcoming inspections, ADs, parts and documents on aircraft you own, and certificates of yours about to expire. Only sent when something needs attention#{' (once email is set up)' unless MailSettings.configured?}." %>
<%= f.field :password, as: :password, label: "New password", hint: "Leave blank to keep your current password.", autocomplete: "new-password" %>
<%= f.field :password, as: :password, label: "New password", hint: "Leave blank to keep your current password. At least #{User::PASSWORD_MIN} characters; not one known from a data breach.", autocomplete: "new-password" %>
<%= f.field :password_confirmation, as: :password, label: "Confirm new password", autocomplete: "new-password" %>
<div>
<%= label_tag "user[current_password]", "Current password", class: "label" %>
@@ -31,6 +31,21 @@
</section>
<% end %>
<section class="card card-body mt-5 max-w-md" id="two-factor">
<h2 class="card-title">Two-factor sign-in</h2>
<% if @user.otp_enabled? %>
<p class="mt-1 text-sm text-slate-600"><span class="badge-green">On</span> since <%= @user.otp_enabled_at.to_date %>: signing in with your password or an emailed link also asks for a code from your authenticator app. <%= @user.recovery_codes_left %> recovery codes left.</p>
<%= form_with url: two_factor_path, class: "mt-3 flex flex-wrap items-end gap-2" do |f| %>
<div><%= label_tag :code, "Current code or a recovery code", class: "label" %><%= text_field_tag :code, nil, required: true, autocomplete: "one-time-code", class: "input w-44" %></div>
<%= button_tag "New recovery codes", type: "submit", formaction: recovery_codes_two_factor_path, class: "btn-secondary btn-sm" %>
<%= button_tag "Turn off", type: "submit", name: "_method", value: "delete", class: "btn-secondary btn-sm", data: { turbo_confirm: "Turn off two-factor sign-in?" } %>
<% end %>
<% else %>
<p class="mt-1 text-sm text-slate-600">Add a code from an authenticator app on your phone to password and emailed-link sign-in, so a stolen password alone can't get in.<%= " (Signing in with #{Sso.label} uses its own second factor.)" if Sso.enabled? %></p>
<div class="mt-3"><%= link_to "Set up", new_two_factor_path, class: "btn-secondary btn-sm" %></div>
<% end %>
</section>
<section class="card card-body mt-5 max-w-md" id="certificates">
<h2 class="card-title">Certificates</h2>
<p class="mt-1 text-sm text-slate-600">Your FAA certificates, for signing logbook entries: “Sign as” fills in your name, the kind of certificate and its number.</p>
+11
View File
@@ -0,0 +1,11 @@
<% content_for :title, "Sign in" %>
<div class="mx-auto max-w-sm">
<h1 class="mb-4 text-2xl font-bold">Authenticator code</h1>
<%= form_with url: two_factor_session_path, class: "card card-body space-y-4" do |form| %>
<p class="text-sm text-slate-600">Enter the 6-digit code from your authenticator app. Lost your phone? Enter one of your recovery codes instead.</p>
<div><%= form.label :code, "Code", class: "label" %>
<%= form.text_field :code, required: true, autofocus: true, autocomplete: "one-time-code", inputmode: "text", maxlength: 20, class: "input text-lg tracking-widest" %></div>
<%= form.submit "Continue", class: "btn-primary w-full justify-center" %>
<p class="text-center text-sm"><%= link_to "Start again", new_session_path, class: "link" %></p>
<% end %>
</div>
@@ -0,0 +1,2 @@
<p>Your Simple Aircraft Manager account (<%= @user.email_address %>) was locked for <%= User::LOCK_FOR.inspect %> after <%= User::LOCK_AFTER %> failed sign-in attempts in a row.</p>
<p>If that was you, wait and try again. If it wasn't, someone may be guessing your password: change it once you're back in (Profile), turn on an authenticator app, and tell your administrator.</p>
@@ -0,0 +1,3 @@
Your Simple Aircraft Manager account (<%= @user.email_address %>) was locked for <%= User::LOCK_FOR.inspect %> after <%= User::LOCK_AFTER %> failed sign-in attempts in a row.
If that was you, wait and try again. If it wasn't, someone may be guessing your password: change it once you're back in (Profile), turn on an authenticator app, and tell your administrator.
+1 -1
View File
@@ -5,7 +5,7 @@
<%= f.errors_summary %>
<%= f.field :name %>
<%= f.field :email_address, as: :email, label: "Email", required: true %>
<%= f.field :password, as: :password, required: true, hint: "At least 8 characters." %>
<%= f.field :password, as: :password, required: true, hint: "At least #{User::PASSWORD_MIN} characters; not one known from a data breach." %>
<%= f.field :password_confirmation, as: :password, required: true %>
<%= f.submit "Create Admin Account", class: "btn-primary w-full justify-center" %>
<% end %>
+9
View File
@@ -0,0 +1,9 @@
<% content_for :title, "Recovery codes" %>
<section class="card card-body mx-auto max-w-md space-y-4">
<h1 class="text-2xl font-bold">Save your recovery codes</h1>
<p class="text-sm text-slate-600">Two-factor is on. If you lose your phone, each of these codes signs you in once in place of an authenticator code. Print them or keep them in a password manager: they won't be shown again.</p>
<ul class="grid grid-cols-2 gap-2 rounded-md bg-slate-50 p-4 font-mono text-sm ring-1 ring-slate-200">
<% @codes.each do |c| %><li><%= c %></li><% end %>
</ul>
<%= link_to "Done", back_path, class: "btn-primary self-start" %>
</section>
+17
View File
@@ -0,0 +1,17 @@
<% content_for :title, "Set up two-factor" %>
<section class="card card-body mx-auto max-w-md space-y-4">
<h1 class="text-2xl font-bold">Set up an authenticator app</h1>
<p class="text-sm text-slate-600">After your password (or an emailed sign-in link) you'll also enter a 6-digit code from an app on your phone, so a stolen password alone can't get in. Any authenticator app works: Google Authenticator, Microsoft Authenticator, 1Password, Authy…</p>
<ol class="list-decimal space-y-3 pl-5 text-sm">
<li>In the app, add an account and scan this code:
<div class="mt-2 inline-block rounded bg-white p-2"><%= image_tag @qr_data_uri, alt: "QR code for your authenticator app", class: "h-48 w-48" %></div>
<p class="mt-1 text-xs text-slate-500">Can't scan it? Enter this key instead: <code class="break-all"><%= @secret.scan(/.{4}/).join(" ") %></code></p></li>
<li>Enter the code the app shows:
<%= form_with url: two_factor_path, class: "mt-2 flex flex-wrap items-end gap-2" do |f| %>
<%= hidden_field_tag :return_to, params[:return_to] %>
<%= f.text_field :code, required: true, autocomplete: "one-time-code", inputmode: "numeric", maxlength: 7, class: "input w-32 text-lg tracking-widest", "aria-label": "Code" %>
<%= f.submit "Turn on", class: "btn-primary" %>
<% end %></li>
</ol>
<p class="text-sm"><%= link_to "Not now", back_path, class: "link" %></p>
</section>
+9 -1
View File
@@ -3,7 +3,13 @@ Rails.application.routes.draw do
# (overrides Active Storage's open endpoint at the same path).
post "rails/active_storage/direct_uploads", to: "direct_uploads#create"
resource :session
resource :session do
get :two_factor
post :two_factor, action: :verify_two_factor
end
resource :two_factor, path: "profile/two_factor", only: %i[new create destroy] do
post :recovery_codes
end
resources :sign_in_links, path: "session/link", param: :token, only: %i[new create show] do
post :consume, on: :member
end
@@ -126,6 +132,8 @@ Rails.application.routes.draw do
member do
patch :disable
patch :enable
patch :unlock
patch :reset_two_factor
end
end
get "about", to: "about#show"
@@ -0,0 +1,12 @@
class AddSignInHardening < ActiveRecord::Migration[8.1]
def change
# Account lockout after repeated failed sign-ins (from any address).
add_column :users, :failed_sign_ins, :integer, null: false, default: 0
add_column :users, :locked_until, :datetime
# Authenticator app (TOTP) as a second factor for password sign-in.
add_column :users, :otp_secret, :text
add_column :users, :otp_enabled_at, :datetime
add_column :users, :otp_last_used_at, :integer # last accepted time step (no replays)
add_column :users, :otp_recovery_codes, :json
end
end
Generated
+7 -1
View File
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2026_11_08_040000) do
ActiveRecord::Schema[8.1].define(version: 2026_11_08_050000) do
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
@@ -792,6 +792,12 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_040000) do
t.datetime "last_signed_in_at"
t.boolean "reminder_emails", default: true, null: false
t.datetime "disabled_at"
t.integer "failed_sign_ins", default: 0, null: false
t.datetime "locked_until"
t.text "otp_secret"
t.datetime "otp_enabled_at"
t.integer "otp_last_used_at"
t.json "otp_recovery_codes"
t.index ["email_address"], name: "index_users_on_email_address", unique: true
t.index ["sso_uid"], name: "index_users_on_sso_uid", unique: true
end
+3 -3
View File
@@ -12,12 +12,12 @@ end
if ENV["DEMO"].present?
admin = User.find_or_create_by!(email_address: "admin@example.com") do |u|
u.name = "Demo Admin"
u.password = "password123"
u.password = "demo-password-123"
u.admin = true
end
pilot = User.find_or_create_by!(email_address: "pilot@example.com") do |u|
u.name = "Demo Pilot"
u.password = "password123"
u.password = "demo-password-123"
end
Current.session = admin.sessions.first_or_create!(user_agent: "seed", ip_address: "127.0.0.1")
@@ -87,5 +87,5 @@ if ENV["DEMO"].present?
e.signoff_person = "J. Mechanic A&P/IA 1234567"
end
puts "Demo data loaded. Sign in as admin@example.com / password123 (or pilot@example.com)."
puts "Demo data loaded. Sign in as admin@example.com / demo-password-123 (or pilot@example.com)."
end
+2
View File
@@ -8,6 +8,8 @@ Admins see the **Admin** menu (on a phone, under ☰). Admins can see and edit e
- **+ New User**: name, email and a starting password. Tick **Administrator** to make them an admin. Then add them to aircraft from each aircraft's **Access & Sharing** tab (or they add their own aircraft).
- **Edit** to change details or reset a password when email isn't set up.
- **Locked** marks an account locked for 15 minutes after 10 failed sign-ins in a row (the user is emailed). **Unlock** clears it straight away, once you know it was really them.
- **2FA** marks someone using an authenticator app. **Reset 2FA** turns it off for a user who lost their phone and recovery codes. Confirm it's really them first (call them); they can then set it up again.
- **Disable** someone who no longer needs access: they're signed out and can't sign in or sign entries, and their past signatures stay. **Enable** reverses it. Users who have signed entries can't be deleted, only disabled.
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).
+4
View File
@@ -8,6 +8,10 @@ Depending on how the app is set up, you can sign in with:
- **Email me a sign-in link.** Enter your email and use the link sent to you. It works once, for a short time.
- **Single sign-on** (for example *Sign in with Authentik*), if your organization uses it.
If you've set up an authenticator app (see [Your profile](profile.md#two-factor-sign-in)), signing in with a password or an emailed link then asks for its 6-digit code.
After 10 failed tries in a row (wrong passwords or codes), an account is locked for 15 minutes and its owner is emailed. Wait, or ask the administrator to unlock it.
The very first visit to a new installation asks for the administrator account instead.
## Roles
+13 -1
View File
@@ -4,10 +4,22 @@ Open your name in the top bar (☰ → **Profile** on a phone).
## Details and password
Change your name, email and password. Leave the password blank to keep the current one.
Change your name, email and password. Leave the password blank to keep the current one. A password needs at least 12 characters, and one that has appeared in a known data breach is refused (checked with Have I Been Pwned, which never receives the password itself).
**Weekly maintenance reminders**: on Mondays the app emails owners about anything overdue or coming due on their aircraft, and certificates about to expire. Untick it to stop them. (Emails need the administrator to have set up email.)
## Two-factor sign-in
**Set up** adds a code from an authenticator app on your phone (Google Authenticator, Microsoft Authenticator, 1Password, Authy…) to password and emailed-link sign-in, so a stolen password alone can't get in. It also asks for the code when you sign a logbook entry with your password.
1. Scan the QR code with the app (or type in the key shown under it).
2. Enter the code the app shows and choose **Turn on**.
3. Save the **recovery codes**: each one signs you in once if you lose your phone. They're shown only once.
To make new recovery codes or turn it off, enter a current code (or a recovery code) on your profile. If you've lost both your phone and your recovery codes, ask the administrator to reset it.
Signing in with single sign-on doesn't ask for this code: the sign-on provider handles its own second factor.
## Certificates
Add each certificate you sign maintenance records with: its kind (A&P, IA, airframe, powerplant, repairman, repair station, pilot…), its number, and for an IA, its expiry. You need one to sign a logbook entry, and the entry records which one you used. An IA expires on March 31 of each odd-numbered year unless renewed; you're reminded 60 days ahead.
+1 -1
View File
@@ -11,7 +11,7 @@ On the aircraft's **Logbook** tab, choose **+ New Entry** (owners). Give the dat
1. Add your certificate (kind and number) once, on your [profile](profile.md).
2. Open the entry and choose **Sign**. Read the entry as shown: your signature covers exactly that.
3. Pick the certificate you're signing with. The statement you'll certify is shown with it (return to service, or the inspection statement).
4. Re-enter your password, or sign in again with single sign-on, tick the confirmation and choose **Sign entry**. You'll see a confirmation and get an email.
4. Re-enter your password (and your authenticator code, if you've set one up), or sign in again with single sign-on, tick the confirmation and choose **Sign entry**. You'll see a confirmation and get an email.
Never share your password or let someone else sign while you're signed in: a signature is yours alone. If you think someone has, tell the administrator straight away.
@@ -15,7 +15,7 @@ class ElectronicSignaturesTest < ActionDispatch::IntegrationTest
end
def sign(entry = @entry, **params)
post aircraft_logbook_entry_signature_path(@a, entry), params: { certificate_id: @ap.id, password: "password123", confirm: "1" }.merge(params)
post aircraft_logbook_entry_signature_path(@a, entry), params: { certificate_id: @ap.id, password: "test-password-123", confirm: "1" }.merge(params)
end
test "signing: review, certificate, password, confirmation; then the record shows who certified what and when" do
@@ -114,14 +114,14 @@ class ElectronicSignaturesTest < ActionDispatch::IntegrationTest
assert_match "preventive maintenance", @entry.certification_statement("PILOT")
sign_in @owner # signing with someone else's certificate
post aircraft_logbook_entry_signature_path(@a, @entry), params: { certificate_id: @ap.id, password: "password123", confirm: "1" }
post aircraft_logbook_entry_signature_path(@a, @entry), params: { certificate_id: @ap.id, password: "test-password-123", confirm: "1" }
assert_includes response.body, "That certificate isn&#39;t yours"
get new_aircraft_logbook_entry_signature_path(@a, @entry)
assert_select "input[type=radio][value='#{pilot_cert.id}']:not([disabled])"
@mech.update!(disabled_at: Time.current)
assert_raises(EntrySigner::Error) { EntrySigner.new(@entry, user: @mech, certificate: @ap, auth_method: "password").sign! }
post session_path, params: { email_address: "mech@example.com", password: "password123" }
post session_path, params: { email_address: "mech@example.com", password: "test-password-123" }
assert_equal "This account is disabled.", flash[:alert]
end
+5 -5
View File
@@ -14,24 +14,24 @@ class SecurityHardeningTest < ActionDispatch::IntegrationTest
patch profile_path, params: { user: { password: "newpassword1", password_confirmation: "newpassword1", current_password: "wrong" } }
assert_response :unprocessable_entity
assert @user.reload.authenticate("password123")
assert @user.reload.authenticate("test-password-123")
patch profile_path, params: { user: { name: "Jane Pilot", email_address: "jane@example.com" } } # no sensitive change
assert_redirected_to root_path
assert_equal "Jane Pilot", @user.reload.name
patch profile_path, params: { user: { email_address: "jane2@example.com", current_password: "password123" } }
patch profile_path, params: { user: { email_address: "jane2@example.com", current_password: "test-password-123" } }
assert_redirected_to root_path
assert_equal "jane2@example.com", @user.reload.email_address
end
test "a new password signs out other sessions; so does the button" do
other = open_session
other.post session_path, params: { email_address: @user.email_address, password: "password123" }
other.post session_path, params: { email_address: @user.email_address, password: "test-password-123" }
sign_in @user
assert_equal 2, @user.sessions.count
patch profile_path, params: { user: { password: "newpassword1", password_confirmation: "newpassword1", current_password: "password123" } }
patch profile_path, params: { user: { password: "newpassword1", password_confirmation: "newpassword1", current_password: "test-password-123" } }
assert_redirected_to root_path
assert_equal 1, @user.sessions.count
other.get root_path
@@ -48,7 +48,7 @@ class SecurityHardeningTest < ActionDispatch::IntegrationTest
test "a password reset signs out every session; a blank password is refused" do
sign_in @user
token = @user.password_reset_token
put password_path(token), params: { password: "brandnew99", password_confirmation: "brandnew99" }
put password_path(token), params: { password: "brandnew9999", password_confirmation: "brandnew9999" }
assert_redirected_to new_session_path
assert_equal 0, @user.sessions.count
+1 -1
View File
@@ -4,7 +4,7 @@ class SetupTest < ActionDispatch::IntegrationTest
test "first run creates admin, then setup is closed" do
get root_path
assert_redirected_to new_setup_path
post setup_path, params: { user: { name: "Ricky", email_address: "a@b.com", password: "password123", password_confirmation: "password123" } }
post setup_path, params: { user: { name: "Ricky", email_address: "a@b.com", password: "test-password-123", password_confirmation: "test-password-123" } }
assert_redirected_to root_path
assert User.last.admin?
get new_setup_path
+180
View File
@@ -0,0 +1,180 @@
require "test_helper"
# Account lockout, password rules, and authenticator-app two-factor.
class SignInHardeningTest < ActionDispatch::IntegrationTest
include ActionMailer::TestHelper
PASSWORD = "test-password-123"
setup do
@user = create_user("jane@example.com")
end
def attempt(password, email: @user.email_address)
post session_path, params: { email_address: email, password: password }
end
def totp(user, at: Time.current) = ROTP::TOTP.new(user.reload.otp_secret).at(at)
def enable_two_factor(user)
user.enable_otp!(User.new_otp_secret)
end
test "ten failed sign-ins lock the account for 15 minutes, even with the right password, and email the user" do
assert_enqueued_emails(1) { 10.times { attempt("wrong-password") } }
assert @user.reload.locked?
attempt(PASSWORD)
assert_redirected_to new_session_path(email_address: @user.email_address)
assert_includes flash[:alert], "locked for 15 minutes"
attempt("whatever", email: "nobody@example.com")
assert_includes flash[:alert], "Try another email address or password" # same answer for unknown accounts
travel 16.minutes do
attempt(PASSWORD)
assert_redirected_to root_url
assert_equal 0, @user.reload.failed_sign_ins
end
end
test "a successful sign-in resets the count; admins can unlock" do
5.times { attempt("wrong-password") }
attempt(PASSWORD)
assert_equal 0, @user.reload.failed_sign_ins
@user.update_columns(locked_until: 10.minutes.from_now)
admin = create_user("admin@example.com", admin: true)
sign_in admin
get admin_users_path
assert_select ".badge-red", "Locked"
patch unlock_admin_user_path(@user)
refute @user.reload.locked?
end
test "passwords need 12 characters and mustn't be known from a breach" do
sign_in @user
patch profile_path, params: { user: { password: "short-pw1", password_confirmation: "short-pw1", current_password: PASSWORD } }
assert_response :unprocessable_entity
assert_includes response.body, "too short (minimum is 12 characters)"
patch profile_path, params: { user: { password: "breached-password-1", password_confirmation: "breached-password-1", current_password: PASSWORD } }
assert_response :unprocessable_entity
assert_includes response.body, "data breach"
patch profile_path, params: { user: { password: "a-good-new-password", password_confirmation: "a-good-new-password", current_password: PASSWORD } }
assert_redirected_to root_path
assert @user.reload.authenticate("a-good-new-password")
end
test "the breach check sends only a hash prefix and allows the password if the service is down" do
checker = PwnedPasswords.checker
PwnedPasswords.checker = ->(pw) { PwnedPasswords.lookup(pw) }
sha1 = Digest::SHA1.hexdigest("correct horse battery").upcase
stub_request(:get, "https://api.pwnedpasswords.com/range/#{sha1[0, 5]}").with(headers: { "Add-Padding" => "true" })
.to_return(body: "0000000000000000000000000000000000A:0\r\n#{sha1[5..]}:42\r\n")
assert PwnedPasswords.breached?("correct horse battery")
stub_request(:get, %r{api\.pwnedpasswords\.com}).to_timeout
refute PwnedPasswords.breached?("another long password")
ensure
PwnedPasswords.checker = checker
end
test "setting up an authenticator: scan, confirm with a code, get recovery codes" do
sign_in @user
get new_two_factor_path
assert_select "img[src^='data:image/svg+xml;base64,']"
secret = response.body[%r{<code class="break-all">([A-Z2-7 ]+)</code>}, 1].delete(" ")
post two_factor_path, params: { code: "000000" }
assert_redirected_to new_two_factor_path
refute @user.reload.otp_enabled?
post two_factor_path, params: { code: ROTP::TOTP.new(secret).now }
assert_response :success
assert_select "ul li", User::RECOVERY_CODES
assert @user.reload.otp_enabled?
assert_equal secret, @user.otp_secret
assert_not_equal secret, @user.read_attribute_before_type_cast(:otp_secret) # encrypted
end
test "with two-factor on, sign-in asks for a code; codes work once; recovery codes work once" do
codes = enable_two_factor(@user)
attempt(PASSWORD)
assert_redirected_to two_factor_session_path
get root_path
assert_redirected_to new_session_path # not signed in yet
post two_factor_session_path, params: { code: "123456" }
assert_redirected_to two_factor_session_path
assert_equal 1, @user.reload.failed_sign_ins
code = totp(@user)
post two_factor_session_path, params: { code: code }
assert_redirected_to root_url
get root_path
assert_response :success
delete session_path
attempt(PASSWORD)
post two_factor_session_path, params: { code: code } # same code again: refused
assert_redirected_to two_factor_session_path
post two_factor_session_path, params: { code: codes.first.upcase }
assert_redirected_to root_url
assert_equal User::RECOVERY_CODES - 1, @user.reload.recovery_codes_left
delete session_path
attempt(PASSWORD)
post two_factor_session_path, params: { code: codes.first }
assert_redirected_to two_factor_session_path
end
test "the code step expires, and an emailed sign-in link also needs the code" do
enable_two_factor(@user)
attempt(PASSWORD)
travel 6.minutes do
post two_factor_session_path, params: { code: totp(@user) }
assert_redirected_to new_session_path
end
token = @user.generate_token_for(:email_sign_in)
post consume_sign_in_link_path(token)
assert_redirected_to two_factor_session_path
post two_factor_session_path, params: { code: totp(@user) }
assert_redirected_to root_url
end
test "turning it off or making new recovery codes needs a code; admins can reset it" do
enable_two_factor(@user)
attempt(PASSWORD)
post two_factor_session_path, params: { code: totp(@user) }
delete two_factor_path, params: { code: "000000" }
assert @user.reload.otp_enabled?
travel 31.seconds do
post recovery_codes_two_factor_path, params: { code: totp(@user) }
assert_select "ul li", User::RECOVERY_CODES
end
travel 61.seconds do
delete two_factor_path, params: { code: totp(@user) }
refute @user.reload.otp_enabled?
end
enable_two_factor(@user)
admin = create_user("admin@example.com", admin: true)
sign_in admin
patch reset_two_factor_admin_user_path(@user)
refute @user.reload.otp_enabled?
end
test "signing an entry also needs the authenticator code, and wrong passwords count toward the lockout" do
a = create_aircraft(owner: @user)
entry = a.logbook_entries.create!(date: Date.current, entry_type: "MAINTENANCE", text: "Changed oil", aircraft_hours_at_entry: 1000)
cert = @user.certificates.create!(kind: "AP", number: "7654321")
enable_two_factor(@user)
attempt(PASSWORD)
post two_factor_session_path, params: { code: totp(@user) }
post aircraft_logbook_entry_signature_path(a, entry), params: { certificate_id: cert.id, password: PASSWORD, confirm: "1" }
assert_response :unprocessable_entity
assert_includes response.body, "authenticator code"
post aircraft_logbook_entry_signature_path(a, entry), params: { certificate_id: cert.id, password: "wrong-password", confirm: "1" }
assert_equal 2, @user.reload.failed_sign_ins
travel 31.seconds do
post aircraft_logbook_entry_signature_path(a, entry), params: { certificate_id: cert.id, password: PASSWORD, otp_code: totp(@user), confirm: "1" }
assert_equal "password_totp", entry.reload.signature.auth_method
assert_equal 0, @user.reload.failed_sign_ins
end
end
end
+1 -1
View File
@@ -105,7 +105,7 @@ class SsoTest < ActionDispatch::IntegrationTest
ENV["PASSWORD_LOGIN"] = "false"
get new_session_path
assert_select "input[name=password]", 0
post session_path, params: { email_address: "jane@example.com", password: "password123" }
post session_path, params: { email_address: "jane@example.com", password: "test-password-123" }
assert_redirected_to new_session_path
assert_match "Sign in with Authentik", flash[:alert]
post passwords_path, params: { email_address: "jane@example.com" }
+3 -2
View File
@@ -4,13 +4,14 @@ require "rails/test_help"
require "webmock/minitest"
WebMock.disable_net_connect!(allow_localhost: true)
Dir[File.expand_path("support/**/*.rb", __dir__)].each { require _1 }
PwnedPasswords.checker = ->(password) { password == "breached-password-1" } # no network in tests
module ActiveSupport
class TestCase
parallelize(workers: :number_of_processors)
def create_user(email = "user#{SecureRandom.hex(3)}@example.com", admin: false)
User.create!(email_address: email, password: "password123", name: email.split("@").first, admin: admin)
User.create!(email_address: email, password: "test-password-123", name: email.split("@").first, admin: admin)
end
def create_aircraft(owner: nil, pilot: nil, **attrs)
@@ -33,7 +34,7 @@ end
class ActionDispatch::IntegrationTest
def sign_in(user)
post session_path, params: { email_address: user.email_address, password: "password123" }
post session_path, params: { email_address: user.email_address, password: "test-password-123" }
follow_redirect!
end
end