Security hardening and OpenID Connect single sign-on

- SSO via OmniAuth OpenID Connect (Authentik, Keycloak, …): link by stable
  subject, by verified email, or from the profile; optional auto-create,
  admin-group sync, and turning password sign-in off
- Current password required to change email or password; password changes
  and resets sign out other sessions; idle sessions expire after 30 days;
  "sign out everywhere else"; session reset on sign-in
- Rate-limit password resets; scope squawk components to the aircraft
- Strict Content Security Policy with nonces (inline handlers removed),
  Permissions-Policy and COOP headers; file links expire after an hour

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-07 08:38:25 -05:00
1 parent 2bfcb845ca
commit ac4da93aaf
27 files changed
+708 -47

No files matched your search

@@ -30,6 +30,7 @@ class Admin::UsersController < ApplicationController
end
@user.admin = admin_flag
if @user.update(attrs)
@user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) # new password signs them out
redirect_to admin_users_path, notice: "User updated."
else
render :edit, status: :unprocessable_entity
+12 -1
View File
@@ -1,6 +1,9 @@
module Authentication
extend ActiveSupport::Concern
# A session unused for this long is signed out.
SESSION_IDLE_TIMEOUT = 30.days
included do
before_action :require_authentication
helper_method :authenticated?
@@ -26,7 +29,15 @@ module Authentication
end
def find_session_by_cookie
Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id]
session = Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id]
return unless session
if session.updated_at < SESSION_IDLE_TIMEOUT.ago
session.destroy
cookies.delete(:session_id)
return
end
session.touch if session.updated_at < 1.hour.ago # last-active time, without a write per request
session
end
def request_authentication
+9 -1
View File
@@ -1,6 +1,9 @@
class PasswordsController < ApplicationController
allow_unauthenticated_access
before_action :require_password_login
before_action :set_user_by_token, only: %i[ edit update ]
rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." }
rate_limit to: 10, within: 15.minutes, only: :update, with: -> { redirect_to new_session_path, alert: "Try again later." }
def new
end
@@ -17,7 +20,8 @@ class PasswordsController < ApplicationController
end
def update
if @user.update(params.permit(:password, :password_confirmation))
if params[:password].present? && @user.update(params.permit(:password, :password_confirmation))
@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."
@@ -25,6 +29,10 @@ class PasswordsController < ApplicationController
end
private
def require_password_login
redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login?
end
def set_user_by_token
@user = User.find_by_password_reset_token!(params[:token])
rescue ActiveSupport::MessageVerifier::InvalidSignature
+18 -1
View File
@@ -3,14 +3,31 @@ class ProfilesController < ApplicationController
@user = current_user
end
# Changing the email or password needs the current password, so a session
# left open somewhere can't be turned into a takeover of the account.
def update
@user = current_user
attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation)
attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank?
if @user.update(attrs)
new_email = User.normalize_value_for(:email_address, attrs[:email_address].to_s) if attrs.key?(:email_address)
sensitive = (new_email && new_email != @user.email_address) || attrs.key?(:password)
# Checked before assigning: setting a new password replaces the digest at once.
if sensitive && !@user.authenticate_password(params.dig(:user, :current_password).to_s)
@user.assign_attributes(attrs.except(:password, :password_confirmation))
@user.errors.add(:base, "Enter your current password to change your email or password")
return render :edit, status: :unprocessable_entity
end
@user.assign_attributes(attrs)
if @user.save
@user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password)
redirect_to root_path, notice: "Profile updated."
else
render :edit, status: :unprocessable_entity
end
end
def sign_out_others
count = current_user.sessions.where.not(id: Current.session.id).destroy_all.size
redirect_to edit_profile_path, notice: "Signed out #{helpers.pluralize(count, 'other session')}."
end
end
+5 -1
View File
@@ -6,9 +6,13 @@ class SessionsController < ApplicationController
end
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))
return_to = after_authentication_url
reset_session # fresh session id after signing in
start_new_session_for user
redirect_to after_authentication_url
redirect_to return_to
else
redirect_to new_session_path, alert: "Try another email address or password."
end
+1
View File
@@ -70,5 +70,6 @@ class SquawksController < ApplicationController
def squawk_params
params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, attachments: [])
.tap { |p| p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) if p.key?(:component_id) }
end
end
+100
View File
@@ -0,0 +1,100 @@
# Finishes an OpenID Connect sign-in (OmniAuth runs the redirect dance) and
# links or unlinks a signed-in user's account. See Sso for the settings.
#
# Accounts are matched by the provider's stable subject id. The first time,
# an existing account is linked by email only when the provider says the
# email is verified (or OIDC_TRUST_EMAIL is on), since some providers let
# users edit their email. Otherwise, sign in with a password once and link
# from the profile page.
class SsoController < ApplicationController
allow_unauthenticated_access only: %i[callback failure]
before_action :require_sso
rate_limit to: 20, within: 3.minutes, only: :callback, with: -> { redirect_to new_session_path, alert: "Try again later." }
def callback
auth = request.env["omniauth.auth"]
return failure unless auth && auth.provider.to_s == Sso::PROVIDER.to_s && auth.uid.present?
return link(auth) if authenticated?
user = User.find_by(sso_uid: auth.uid) || link_by_email(auth) || create_user(auth)
unless user
email = auth.info&.email.presence
return redirect_to new_session_path, alert: "There's no account for #{email || 'that sign-in'} here yet. " \
"Ask an administrator to add you, or sign in with your password and link #{Sso.label} from your profile."
end
sync_admin(user, auth)
return_to = session[:return_to_after_authenticating]
reset_session # fresh session id after signing in
start_new_session_for user
redirect_to return_to || root_url
end
# OmniAuth's error codes; anything else (network errors…) is logged, not shown.
FAILURES = { "invalid_credentials" => "invalid credentials", "csrf_detected" => "the sign-in expired, try again",
"access_denied" => "access denied", "timeout" => "timed out" }.freeze
def failure
reason = FAILURES[params[:message].to_s]
Rails.logger.warn("[sso] sign-in failed: #{params[:message].to_s.truncate(300)}") unless reason
redirect_to(authenticated? ? edit_profile_path : new_session_path,
alert: "#{Sso.label} sign-in failed (#{reason || "couldn't reach or verify #{Sso.label}; see the server log"}).")
end
def destroy
unless Sso.password_login?
return redirect_to edit_profile_path, alert: "Password sign-in is off, so unlinking #{Sso.label} would lock you out."
end
current_user.update!(sso_uid: nil)
redirect_to edit_profile_path, notice: "#{Sso.label} unlinked. Sign in with your email and password from now on."
end
private
def require_sso
raise ActiveRecord::RecordNotFound unless Sso.enabled?
end
def link(auth)
owner = User.find_by(sso_uid: auth.uid)
if owner && owner != current_user
redirect_to edit_profile_path, alert: "That #{Sso.label} account is already linked to another user."
else
current_user.update!(sso_uid: auth.uid)
redirect_to edit_profile_path, notice: "#{Sso.label} linked. You can now sign in with it."
end
end
def link_by_email(auth)
email = auth.info&.email.to_s.strip.downcase
return if email.blank? || !(email_verified?(auth) || Sso.trust_email?)
user = User.find_by(email_address: email, sso_uid: nil)
user&.update!(sso_uid: auth.uid)
user
end
def create_user(auth)
return unless Sso.auto_create_users?
email = auth.info&.email.to_s.strip.downcase
return if email.blank? || User.exists?(email_address: email)
# The random password is never shown; a password reset can set a real one.
User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
rescue ActiveRecord::RecordInvalid
nil
end
def email_verified?(auth)
[ true, "true" ].include?(raw_info(auth)["email_verified"])
end
# With OIDC_ADMIN_GROUP set, the provider decides who's an admin. Skipped
# when the token carries no groups claim, so a missing scope can't demote.
def sync_admin(user, auth)
return unless Sso.admin_group && raw_info(auth).key?("groups")
user.update!(admin: Array(raw_info(auth)["groups"]).map(&:to_s).include?(Sso.admin_group))
end
def raw_info(auth)
(auth.extra&.raw_info || {}).to_h.stringify_keys
end
end
+14
View File
@@ -42,3 +42,17 @@ function labelTableCells(root = document) {
}
document.addEventListener("turbo:load", () => labelTableCells())
document.addEventListener("turbo:frame-load", (event) => labelTableCells(event.target))
// Small behaviours that used to be inline onclick handlers (blocked by the CSP).
document.addEventListener("click", (event) => {
const target = event.target
if (!(target instanceof HTMLInputElement)) return
if (target.matches("[data-select-on-click]")) target.select()
if (target.matches("[data-check-all]")) {
target.closest("table")?.querySelectorAll("tbody input[type=checkbox]").forEach((box) => { box.checked = target.checked })
}
})
document.addEventListener("change", (event) => {
if (event.target.matches?.("[data-submit-on-change]")) event.target.form?.requestSubmit()
})
+45
View File
@@ -0,0 +1,45 @@
# Single sign-on through an OpenID Connect provider (Authentik, Keycloak,
# Google…), configured with environment variables:
#
# OIDC_ISSUER issuer URL, e.g. https://auth.example.com/application/o/sam/
# OIDC_CLIENT_ID client ID
# OIDC_CLIENT_SECRET client secret
# OIDC_PROVIDER_NAME button label (default "SSO")
# OIDC_AUTO_CREATE_USERS "true" to create an account for anyone the
# provider lets through (they start with no aircraft)
# OIDC_TRUST_EMAIL "true" to link existing accounts by email even when
# the provider doesn't mark the email verified. Only
# for providers where users can't change their email.
# OIDC_ADMIN_GROUP members of this group are admins, others aren't
# (synced at each sign-in; needs a "groups" claim)
# PASSWORD_LOGIN "false" to turn off email/password sign-in once SSO works
# APP_URL public base URL (default https://APP_HOST)
module Sso
PROVIDER = :oidc
module_function
def enabled? = ENV["OIDC_ISSUER"].present? && ENV["OIDC_CLIENT_ID"].present?
def label = ENV["OIDC_PROVIDER_NAME"].presence || "SSO"
def auto_create_users? = ENV["OIDC_AUTO_CREATE_USERS"] == "true"
def trust_email? = ENV["OIDC_TRUST_EMAIL"] == "true"
def admin_group = ENV["OIDC_ADMIN_GROUP"].presence
# Password sign-in stays on unless SSO is set up and it's switched off, so
# a broken SSO setup can't lock everyone out.
def password_login? = !enabled? || ENV["PASSWORD_LOGIN"] != "false"
def app_url
ENV["APP_URL"].presence&.chomp("/") ||
"#{ENV.fetch('FORCE_SSL', 'true') == 'true' ? 'https' : 'http'}://#{ENV.fetch('APP_HOST', 'localhost:3000')}"
end
# Origin of the provider, for the CSP form-action list (the sign-in POST
# redirects there).
def issuer_origin
uri = URI.parse(ENV["OIDC_ISSUER"].to_s)
uri.host && "#{uri.scheme}://#{uri.host}#{":#{uri.port}" unless uri.port == uri.default_port}"
rescue URI::InvalidURIError
nil
end
end
+1 -1
View File
@@ -3,7 +3,7 @@
<section class="card"><table class="table">
<thead><tr><th>Name</th><th>Email</th><th>Aircraft</th><th></th></tr></thead>
<tbody><% @users.each do |u| %><tr>
<td><%= u.name %> <% if u.admin? %><span class="badge-blue">Admin</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 %></td>
<td><%= u.email_address %></td>
<td class="text-xs"><%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %></td>
<td class="text-right"><%= link_to "Edit", edit_admin_user_path(u), class: "btn-secondary btn-sm" %></td>
+2 -2
View File
@@ -10,7 +10,7 @@
<td><%= r.user.display_name %><div class="text-xs text-slate-500"><%= r.user.email_address %></div></td>
<td>
<%= form_with url: aircraft_aircraft_role_path(@aircraft, r), method: :patch do |f| %>
<%= f.select :role, AircraftRole::ROLES.invert, { selected: r.role }, class: "input w-28", onchange: "this.form.requestSubmit()" %>
<%= f.select :role, AircraftRole::ROLES.invert, { selected: r.role }, class: "input w-28", data: { submit_on_change: true } %>
<% end %>
</td>
<td class="text-right"><% unless r.user == current_user %><%= delete_button "Remove", aircraft_aircraft_role_path(@aircraft, r), confirm: "Remove #{r.user.display_name}'s access?" %><% end %></td>
@@ -40,7 +40,7 @@
</div>
<%= delete_button "Revoke", aircraft_share_token_path(@aircraft, t), confirm: "Revoke this link? Anyone using it will lose access." %>
</div>
<input type="text" readonly value="<%= shared_url(t.token) %>" class="input mt-2 font-mono text-xs" onclick="this.select()">
<input type="text" readonly value="<%= shared_url(t.token) %>" class="input mt-2 font-mono text-xs" data-select-on-click>
<div class="mt-1 text-xs text-slate-500">Created <%= t.created_at.to_date %><%= " by #{t.created_by.display_name}" if t.created_by %> · <%= t.expires_at ? "expires #{l t.expires_at, format: :short}" : "never expires" %></div>
</li>
<% end %>
+1 -1
View File
@@ -12,7 +12,7 @@
</div>
<% if changes.any? %>
<table class="table">
<thead><tr><th class="w-8"><input type="checkbox" checked aria-label="Select all" onclick="this.closest('table').querySelectorAll('tbody input[type=checkbox]').forEach(c => c.checked = this.checked)"></th><th>Logged</th><th>Standard</th><th>Airport</th><th class="text-right">Entries</th></tr></thead>
<thead><tr><th class="w-8"><input type="checkbox" checked aria-label="Select all" data-check-all></th><th>Logged</th><th>Standard</th><th>Airport</th><th class="text-right">Entries</th></tr></thead>
<tbody>
<% changes.each do |c| %>
<tr>
+1 -1
View File
@@ -4,7 +4,7 @@
<div class="card-header">
<h2 class="card-title">Activity Log</h2>
<%= form_with url: aircraft_events_path(@aircraft), method: :get, class: "flex gap-2" do |f| %>
<%= f.select :category, AircraftEvent::CATEGORIES.invert, { include_blank: "All categories", selected: @category }, class: "input", onchange: "this.form.requestSubmit()" %>
<%= f.select :category, AircraftEvent::CATEGORIES.invert, { include_blank: "All categories", selected: @category }, class: "input", data: { submit_on_change: true } %>
<% end %>
</div>
<%= render "events/list", events: @events, full: true %>
+34 -1
View File
@@ -4,10 +4,43 @@
<%= f.field :name %>
<%= f.field :email_address, as: :email, label: "Email" %>
<%= f.field :password, as: :password, label: "New password", hint: "Leave blank to keep your current password.", autocomplete: "new-password" %>
<%= f.field :password_confirmation, as: :password, label: "Confirm 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" %>
<%= password_field_tag "user[current_password]", nil, id: "user_current_password", class: "input", autocomplete: "current-password" %>
<p class="hint">Needed to change your email or password.<%= " Signed up with #{Sso.label} and never set one? Use “Forgot password?” on the sign-in page." if Sso.enabled? && @user.sso_uid? %></p>
</div>
<%= f.submit "Save" %>
<% end %>
<% if Sso.enabled? %>
<section class="card card-body mt-5 max-w-md">
<h2 class="card-title">Single sign-on</h2>
<% if @user.sso_uid? %>
<p class="mt-1 text-sm text-slate-600">Your account is linked to <%= Sso.label %>; you can sign in with it.</p>
<% if Sso.password_login? %>
<div class="mt-3"><%= button_to "Unlink #{Sso.label}", sso_link_path, method: :delete, class: "btn-secondary btn-sm",
form: { data: { turbo_confirm: "Unlink #{Sso.label}? You'll sign in with your email and password." } } %></div>
<% end %>
<% else %>
<p class="mt-1 text-sm text-slate-600">Link your <%= Sso.label %> account to sign in with it.</p>
<div class="mt-3"><%= button_to "Link #{Sso.label}", "/auth/#{Sso::PROVIDER}", class: "btn-secondary btn-sm", data: { turbo: false } %></div>
<% end %>
</section>
<% end %>
<section class="card card-body mt-5 max-w-md">
<h2 class="card-title">Sessions</h2>
<% others = @user.sessions.where.not(id: Current.session.id).count %>
<p class="mt-1 text-sm text-slate-600">
You're signed in on <%= pluralize(others, "other device or browser", plural: "other devices or browsers") %>.
Sessions unused for <%= Authentication::SESSION_IDLE_TIMEOUT.inspect %> sign out on their own.
</p>
<% if others.positive? %>
<div class="mt-3"><%= button_to "Sign out everywhere else", other_sessions_path, method: :delete, class: "btn-secondary btn-sm" %></div>
<% end %>
</section>
<section class="card card-body mt-5 max-w-md">
<h2 class="card-title">Integrations</h2>
<p class="mt-1 text-sm text-slate-600">
+18 -8
View File
@@ -1,12 +1,22 @@
<% content_for :title, "Sign in" %>
<div class="mx-auto max-w-sm">
<h1 class="mb-4 text-2xl font-bold">Sign in</h1>
<%= form_with url: session_path, class: "card card-body space-y-4" do |form| %>
<div><%= form.label :email_address, "Email", class: "label" %>
<%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username", value: params[:email_address], class: "input" %></div>
<div><%= form.label :password, class: "label" %>
<%= form.password_field :password, required: true, autocomplete: "current-password", maxlength: 72, class: "input" %></div>
<%= form.submit "Sign in", class: "btn-primary w-full justify-center" %>
<p class="text-center text-sm"><%= link_to "Forgot password?", new_password_path, class: "link" %></p>
<% end %>
<div class="card card-body space-y-4">
<% if Sso.enabled? %>
<%= button_to "Sign in with #{Sso.label}", "/auth/#{Sso::PROVIDER}", class: "btn-primary w-full justify-center", data: { turbo: false } %>
<% end %>
<% if Sso.password_login? %>
<% if Sso.enabled? %>
<div class="flex items-center gap-3 text-xs text-slate-400"><span class="h-px flex-1 bg-slate-200"></span>or<span class="h-px flex-1 bg-slate-200"></span></div>
<% end %>
<%= form_with url: session_path, class: "space-y-4" do |form| %>
<div><%= form.label :email_address, "Email", class: "label" %>
<%= form.email_field :email_address, required: true, autofocus: !Sso.enabled?, autocomplete: "username", value: params[:email_address], class: "input" %></div>
<div><%= form.label :password, class: "label" %>
<%= form.password_field :password, required: true, autocomplete: "current-password", maxlength: 72, class: "input" %></div>
<%= form.submit "Sign in", class: (Sso.enabled? ? "btn-secondary" : "btn-primary") + " w-full justify-center" %>
<p class="text-center text-sm"><%= link_to "Forgot password?", new_password_path, class: "link" %></p>
<% end %>
<% end %>
</div>
</div>
+1 -1
View File
@@ -1,6 +1,6 @@
<%# Applies the saved theme before the page paints (no light flash in dark mode).
"system" (default) follows the OS setting. Set by theme_controller.js. %>
<script>
<script nonce="<%= content_security_policy_nonce %>">
(function () {
try {
var choice = localStorage.getItem("theme") || "system";