From d719f663bcdaa8dc5cf3b81a2e142f95b67ef143 Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Sat, 7 Nov 2026 13:12:04 -0500 Subject: [PATCH] Electronic signatures on logbook entries (AC 120-78B chapter 2) - Sign an entry: review exactly what's certified, choose a current certificate (eligibility checked: pilot only for preventive maintenance, inspections need their result and time), re-enter the password or sign in again with SSO (prompt=login, within 5 minutes), and confirm the "Certified by" statement (43.9 return to service, 43.11(a)(5) for inspections, preventive maintenance for pilots) - The signature stores signer, certificate, statement, UTC time, how they authenticated, IP/browser, a SHA-256 fingerprint of the entry's content and a readable snapshot; an HMAC seal covers the signature record. Status shows Valid / Superseded / Altered since signing. The signer is emailed - Signed entries (and their sub-components) can't be edited or deleted; a correction entry, once signed, supersedes the original (kept) - Owners invite an outside mechanic by email to sign one entry: one-time, 14-day link; they create or use their own account and certificate and see only that entry - Admins can disable accounts (signed out, can't sign in or sign; past signatures kept); users with signatures can't be deleted - Printouts show the electronic signature and fingerprint; archives carry signatures (marked imported, with their origin) and corrections Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + app/controllers/admin/users_controller.rb | 19 +- app/controllers/concerns/authentication.rb | 3 +- app/controllers/concerns/entry_signing.rb | 45 ++++ .../entry_signatures_controller.rb | 23 ++ .../invited_signings_controller.rb | 62 +++++ app/controllers/logbook_entries_controller.rb | 34 ++- app/controllers/logbook_prints_controller.rb | 2 +- app/controllers/sessions_controller.rb | 4 +- app/controllers/sign_in_links_controller.rb | 3 +- .../signing_invitations_controller.rb | 30 +++ app/controllers/sso_controller.rb | 9 + .../user_certificates_controller.rb | 8 +- app/mailers/signature_mailer.rb | 8 + app/mailers/signing_invitation_mailer.rb | 8 + app/models/entry_signature.rb | 47 ++++ app/models/logbook_entry.rb | 106 +++++++++ app/models/logbook_entry_part.rb | 4 + app/models/signing_invitation.rb | 25 ++ app/models/user.rb | 5 + app/services/aircraft_archive/exporter.rb | 14 +- app/services/aircraft_archive/importer.rb | 19 ++ app/services/entry_signer.rb | 41 ++++ app/services/logbook_entry_pdf.rb | 20 ++ app/views/admin/users/index.html.erb | 5 +- app/views/entry_signatures/_form.html.erb | 51 ++++ app/views/entry_signatures/new.html.erb | 4 + app/views/invited_signings/expired.html.erb | 5 + app/views/invited_signings/new.html.erb | 12 + app/views/invited_signings/signed.html.erb | 6 + app/views/invited_signings/welcome.html.erb | 19 ++ .../invited_signings/wrong_account.html.erb | 6 + app/views/logbook_entries/_content.html.erb | 19 ++ app/views/logbook_entries/_form.html.erb | 7 + app/views/logbook_entries/_signature.html.erb | 14 ++ app/views/logbook_entries/index.html.erb | 3 +- app/views/logbook_entries/show.html.erb | 14 +- app/views/signature_mailer/signed.html.erb | 8 + app/views/signature_mailer/signed.text.erb | 10 + .../signing_invitation_mailer/invite.html.erb | 4 + .../signing_invitation_mailer/invite.text.erb | 10 + app/views/signing_invitations/new.html.erb | 11 + config/initializers/omniauth.rb | 2 + config/routes.rb | 13 ++ .../20261108010000_create_entry_signatures.rb | 44 ++++ db/schema.rb | 52 ++++- .../integration/electronic_signatures_test.rb | 217 ++++++++++++++++++ 47 files changed, 1059 insertions(+), 17 deletions(-) create mode 100644 app/controllers/concerns/entry_signing.rb create mode 100644 app/controllers/entry_signatures_controller.rb create mode 100644 app/controllers/invited_signings_controller.rb create mode 100644 app/controllers/signing_invitations_controller.rb create mode 100644 app/mailers/signature_mailer.rb create mode 100644 app/mailers/signing_invitation_mailer.rb create mode 100644 app/models/entry_signature.rb create mode 100644 app/models/signing_invitation.rb create mode 100644 app/services/entry_signer.rb create mode 100644 app/views/entry_signatures/_form.html.erb create mode 100644 app/views/entry_signatures/new.html.erb create mode 100644 app/views/invited_signings/expired.html.erb create mode 100644 app/views/invited_signings/new.html.erb create mode 100644 app/views/invited_signings/signed.html.erb create mode 100644 app/views/invited_signings/welcome.html.erb create mode 100644 app/views/invited_signings/wrong_account.html.erb create mode 100644 app/views/logbook_entries/_content.html.erb create mode 100644 app/views/logbook_entries/_signature.html.erb create mode 100644 app/views/signature_mailer/signed.html.erb create mode 100644 app/views/signature_mailer/signed.text.erb create mode 100644 app/views/signing_invitation_mailer/invite.html.erb create mode 100644 app/views/signing_invitation_mailer/invite.text.erb create mode 100644 app/views/signing_invitations/new.html.erb create mode 100644 db/migrate/20261108010000_create_entry_signatures.rb create mode 100644 test/integration/electronic_signatures_test.rb diff --git a/README.md b/README.md index 62194a1..0d85050 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ To back up or move a single aircraft with all its files, use **Access & Sharing | Inspections | Shared inspection types with hour, month, and day recurrence, plus history. Each says what overdue means (grounded, no IFR, no transponder, advisory); an annual can also count as the 100-hour, and the 100-hour's 10-hour overrun is credited (91.409(b)). One click adds the standard Part 91 set. | | Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. Entries transcribed by Claude stay "unverified" until someone checks them against the scan. Entry templates (built-in pilot preventive maintenance per 43.3(g) and Part 43 Appendix A(c); admins add and edit their own under Admin → Logbook templates). Engine and propeller entries link the component and record its total time and time since overhaul (SMOH/SFOH/SNEW) at the entry, worked out from the entry's airframe total time; sub-components (an oil filter on the engine…) can be included with their own times. Print entries as a PDF on Avery 5163/5164 labels or half-letter/letter pages (boxed) to sign and put in the paper logbook. | | Documents | Collections, multi-file documents with a page viewer, per-document share visibility, bulk upload, and expiration dates (registration, insurance…). | +| Electronic signatures | Logbook entries can be signed electronically along the lines of AC 120-78B chapter 2: the signer reviews the entry, picks their certificate, re-enters their password (or signs in again with SSO) and confirms a "Certified by" statement. The signature records who, which certificate, the statement, the time and a SHA-256 fingerprint of the entry, sealed by the server; the signer gets an email. Signed entries are locked: a correction is a new signed entry that supersedes the original. Owners can invite an outside mechanic to sign one entry with their own account. Disabled accounts can't sign; their past signatures stay. | | Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. | | Weight & balance | History of empty weight and CG (linked to the alteration that changed them) and a loading calculator: takeoff and landing weight and CG against max gross and the CG envelope. | | Status report | A printable maintenance status (91.417(a)(2)): total times, life-limited parts, time since overhaul, inspections, ADs with method and revision, major alterations, open discrepancies. Also on maintenance share links. | diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index cfd7cd8..fc59d02 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -1,6 +1,6 @@ class Admin::UsersController < ApplicationController before_action :require_admin! - before_action :set_user, only: %i[edit update destroy] + before_action :set_user, only: %i[edit update destroy disable enable] def index @users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft) @@ -37,8 +37,25 @@ class Admin::UsersController < ApplicationController end end + # 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 disable + return redirect_to admin_users_path, alert: "You can't disable yourself." if @user == current_user + @user.update!(disabled_at: Time.current) + @user.sessions.destroy_all + redirect_to admin_users_path, notice: "#{@user.email_address} disabled: signed out, can't sign in or sign entries. Their past signatures are kept." + end + + def enable + @user.update!(disabled_at: nil) + redirect_to admin_users_path, notice: "#{@user.email_address} enabled." + end + def destroy return redirect_to admin_users_path, alert: "You can't delete yourself." if @user == current_user + if @user.entry_signatures.exists? + return redirect_to admin_users_path, alert: "#{@user.email_address} has signed logbook entries; disable the account instead of deleting it." + end @user.destroy! redirect_to admin_users_path, notice: "User deleted." end diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb index 09c410a..7adc300 100644 --- a/app/controllers/concerns/authentication.rb +++ b/app/controllers/concerns/authentication.rb @@ -31,7 +31,7 @@ module Authentication def find_session_by_cookie 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 + if session.updated_at < SESSION_IDLE_TIMEOUT.ago || session.user.disabled? session.destroy cookies.delete(:session_id) return @@ -50,6 +50,7 @@ module Authentication end def start_new_session_for(user) + raise ArgumentError, "disabled account" if user.disabled? user.update_column(:last_signed_in_at, Time.current) user.sessions.create!(user_agent: request.user_agent, ip_address: request.remote_ip).tap do |session| Current.session = session diff --git a/app/controllers/concerns/entry_signing.rb b/app/controllers/concerns/entry_signing.rb new file mode 100644 index 0000000..b3a0d65 --- /dev/null +++ b/app/controllers/concerns/entry_signing.rb @@ -0,0 +1,45 @@ +# The signing steps shared by aircraft users and invited signers. +module EntrySigning + extend ActiveSupport::Concern + + private + + def signing_certificates = current_user.certificates.reject(&:expired?) + + def prepare_signing(entry) + @certificates = signing_certificates + 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. + def reauthenticated_method + if params[:password].present? + return "password" if current_user.authenticate_password(params[:password]) + elsif current_user.sso_uid? && (at = session[:reauthenticated_at]) && Time.zone.at(at) > EntrySigner::REAUTH_WINDOW.ago + return "sso" + end + nil + end + + def sign_entry(entry) + certificate = current_user.certificates.find_by(id: params[:certificate_id]) + method = reauthenticated_method + 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 + + signature = EntrySigner.new(entry, user: current_user, certificate: certificate, auth_method: method, request: request).sign! + session.delete(:reauthenticated_at) + SignatureMailer.signed(signature).deliver_later if MailSettings.configured? + yield signature + rescue EntrySigner::Error => e + signing_failed(entry, e.message) + end + + def signing_failed(entry, message) + prepare_signing(entry) + @signing_error = message + render :new, status: :unprocessable_entity + end +end diff --git a/app/controllers/entry_signatures_controller.rb b/app/controllers/entry_signatures_controller.rb new file mode 100644 index 0000000..0864e4c --- /dev/null +++ b/app/controllers/entry_signatures_controller.rb @@ -0,0 +1,23 @@ +# Signing a logbook entry electronically (AC 120-78B chapter 2): the signer +# reviews exactly what they're certifying, chooses their certificate, proves +# who they are again (password, or single sign-on just now), and confirms. +class EntrySignaturesController < ApplicationController + include AircraftScoped + include EntrySigning + before_action :set_entry + + def new + prepare_signing(@entry) + end + + def create + sign_entry(@entry) do |signature| + redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Signed. #{EntrySignature::LABEL} #{signature.signer_name}, #{signature.certificate_label} #{signature.certificate_number}." + end + end + + private + + def set_entry = @entry = @aircraft.logbook_entries.find(params[:logbook_entry_id]) + def signing_page_path = new_aircraft_logbook_entry_signature_path(@aircraft, @entry) +end diff --git a/app/controllers/invited_signings_controller.rb b/app/controllers/invited_signings_controller.rb new file mode 100644 index 0000000..6b092b5 --- /dev/null +++ b/app/controllers/invited_signings_controller.rb @@ -0,0 +1,62 @@ +# The invited signer's side: sign in (or create an account for the invited +# address), add a certificate if needed, review the entry and sign it. The +# invitation gives access to that one entry only. +class InvitedSigningsController < ApplicationController + include EntrySigning + allow_unauthenticated_access only: %i[show account] + before_action :set_invitation + rate_limit to: 10, within: 15.minutes, only: :account, with: -> { redirect_to new_session_path, alert: "Try again later." } + + def show + @entry = @invitation.logbook_entry + @aircraft = @entry.aircraft + unless authenticated? + session[:return_to_after_authenticating] = request.url + return render(:welcome) + end + return render(:wrong_account) unless current_user.email_address == @invitation.email + return render(:signed) if @entry.signed? + prepare_signing(@entry) + render :new + end + + # Creating an account for the invited email address. + def account + return redirect_to(invited_signing_path(params[:token])) if authenticated? + if User.exists?(email_address: @invitation.email) || !Sso.password_login? + return redirect_to invited_signing_path(params[:token]), alert: "Sign in to continue." + end + user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email)) + if user.save + reset_session + start_new_session_for user + redirect_to invited_signing_path(params[:token]), notice: "Account created. Add your certificate, then sign." + else + @entry = @invitation.logbook_entry + @account_errors = user.errors.full_messages + render :welcome, status: :unprocessable_entity + end + end + + def create + @entry = @invitation.logbook_entry + @aircraft = @entry.aircraft + return render(:wrong_account) unless current_user.email_address == @invitation.email + sign_entry(@entry) do |signature| + @invitation.update!(used_at: Time.current, user: current_user) + redirect_to invited_signing_path(params[:token]), notice: "Signed. #{EntrySignature::LABEL} #{signature.signer_name}, #{signature.certificate_label} #{signature.certificate_number}." + end + end + + private + + def set_invitation + @invitation = SigningInvitation.find_usable(params[:token]) + # Afterwards, the signer can still see what they signed. + @invitation ||= SigningInvitation.where.not(used_at: nil).find_by(token_digest: SigningInvitation.digest(params[:token]), user: current_user) if current_user + render(:expired, layout: "public", status: :not_found) unless @invitation + end + + def current_user = Current.user || (resume_session && Current.user) + def signing_page_path = invited_signing_path(params[:token]) +end diff --git a/app/controllers/logbook_entries_controller.rb b/app/controllers/logbook_entries_controller.rb index 7626d0c..c087c35 100644 --- a/app/controllers/logbook_entries_controller.rb +++ b/app/controllers/logbook_entries_controller.rb @@ -2,11 +2,12 @@ class LogbookEntriesController < ApplicationController include AircraftScoped before_action :require_owner!, except: %i[index show] before_action :set_entry, only: %i[show edit update destroy verify] + before_action :require_unsigned, only: %i[edit update destroy] def index @query = params[:q] @log_type = params[:log_type].presence - scope = @aircraft.logbook_entries.search(@query).recent_first.includes(:document) + scope = @aircraft.logbook_entries.search(@query).recent_first.includes(:document, :signature) scope = scope.where(log_type: @log_type) if @log_type @unverified_only = params[:unverified] == "1" scope = scope.unverified if @unverified_only @@ -27,15 +28,17 @@ class LogbookEntriesController < ApplicationController def new LogbookTemplate.ensure_defaults! - @entry = @aircraft.logbook_entries.new(date: Date.current, aircraft_hours_at_entry: @aircraft.current_hours) + @entry = (original = correctable(params[:supersedes])) ? correction_of(original) : @aircraft.logbook_entries.new(date: Date.current, aircraft_hours_at_entry: @aircraft.current_hours) end def create @entry = @aircraft.logbook_entries.new(entry_params) + @entry.supersedes = correctable(params.dig(:logbook_entry, :supersedes_id)) @entry.assign_parts(parts_params, @aircraft) if @entry.save - log_event("logbook", "Logbook entry added (#{@entry.date})") - redirect_to aircraft_logbook_entries_path(@aircraft), notice: "Logbook entry added." + log_event("logbook", "Logbook entry #{@entry.supersedes ? 'correction ' : ''}added (#{@entry.date})") + redirect_to aircraft_logbook_entry_path(@aircraft, @entry), + notice: @entry.supersedes ? "Correction saved. Sign it to supersede the original entry." : "Logbook entry added." else render :new, status: :unprocessable_entity end @@ -62,6 +65,29 @@ class LogbookEntriesController < ApplicationController private + # Signed entries are locked (AC 120-78B 2.1.2.8): changes go in a correction. + def require_unsigned + return unless @entry.signed? + redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: "This entry is signed, so it can't be changed or deleted. Make a correction entry instead." + end + + # A signed, not yet superseded entry of this aircraft. + def correctable(id) + return if id.blank? + entry = @aircraft.logbook_entries.find_by(id: id) + entry if entry&.signed? && !entry.superseded? + end + + # A new entry starting from the signed one it corrects; signed afresh. + def correction_of(original) + copy = @aircraft.logbook_entries.new(original.attributes.slice(*%w[date log_type entry_type text aircraft_hours_at_entry signoff_location + inspection_result component_id component_hours_at_entry + component_since_overhaul_at_entry document_id page_number])) + copy.supersedes = original + original.parts.each { copy.parts.build(component_id: _1.component_id, hours_at_entry: _1.hours_at_entry, since_overhaul_at_entry: _1.since_overhaul_at_entry) } + copy + end + # Sub-components ticked on the form: { component_id => { include, hours, since } }. def parts_params params.fetch(:logbook_entry, {}).permit(parts: {})[:parts]&.to_h || {} diff --git a/app/controllers/logbook_prints_controller.rb b/app/controllers/logbook_prints_controller.rb index ee5316b..691e83e 100644 --- a/app/controllers/logbook_prints_controller.rb +++ b/app/controllers/logbook_prints_controller.rb @@ -18,7 +18,7 @@ class LogbookPrintsController < ApplicationController def set_entries ids = Array(params[:ids]).map(&:to_i).first(200) - @entries = @aircraft.logbook_entries.where(id: ids).includes(:component, :parts, inspection_records: :inspection_type).order(:date, :id).to_a + @entries = @aircraft.logbook_entries.where(id: ids).includes(:component, :parts, :signature, inspection_records: :inspection_type).order(:date, :id).to_a redirect_to aircraft_logbook_entries_path(@aircraft), alert: "Choose the entries to print." if @entries.empty? end end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index c1d59de..dba5949 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -8,7 +8,9 @@ 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)) + if (user = User.authenticate_by(params.permit(:email_address, :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 diff --git a/app/controllers/sign_in_links_controller.rb b/app/controllers/sign_in_links_controller.rb index 67fc2dd..f4486c9 100644 --- a/app/controllers/sign_in_links_controller.rb +++ b/app/controllers/sign_in_links_controller.rb @@ -14,7 +14,7 @@ class SignInLinksController < ApplicationController end def create - if (user = User.find_by(email_address: params[:email_address].to_s)) + if (user = User.active.find_by(email_address: params[:email_address].to_s)) SessionsMailer.sign_in_link(user).deliver_later end # Same answer either way, so this can't be used to find accounts. @@ -25,6 +25,7 @@ class SignInLinksController < ApplicationController end 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." diff --git a/app/controllers/signing_invitations_controller.rb b/app/controllers/signing_invitations_controller.rb new file mode 100644 index 0000000..a74fa24 --- /dev/null +++ b/app/controllers/signing_invitations_controller.rb @@ -0,0 +1,30 @@ +# An owner asks someone outside the aircraft (a mechanic) to sign an entry. +class SigningInvitationsController < ApplicationController + include AircraftScoped + before_action :require_owner! + before_action :set_entry + rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: "Too many invitations; try again later." } + + def new + @invitation = @entry.signing_invitations.new + end + + def create + return redirect_to(aircraft_logbook_entry_path(@aircraft, @entry), alert: "This entry is already signed.") if @entry.signed? + unless MailSettings.configured? + return redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: "Email isn't set up, so invitations can't be sent (Admin → About)." + end + @invitation = @entry.signing_invitations.new(params.require(:signing_invitation).permit(:email, :message).merge(invited_by: current_user)) + if @invitation.save + SigningInvitationMailer.invite(@invitation, @invitation.token).deliver_later + log_event("logbook", "Signature requested from #{@invitation.email} (#{@entry.date} entry)") + redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Invitation sent to #{@invitation.email}. The link works once, for #{SigningInvitation::VALID_FOR.inspect}." + else + render :new, status: :unprocessable_entity + end + end + + private + + def set_entry = @entry = @aircraft.logbook_entries.find(params[:logbook_entry_id]) +end diff --git a/app/controllers/sso_controller.rb b/app/controllers/sso_controller.rb index 9f9002b..1e1fef9 100644 --- a/app/controllers/sso_controller.rb +++ b/app/controllers/sso_controller.rb @@ -14,6 +14,7 @@ class SsoController < ApplicationController def callback auth = request.env["omniauth.auth"] return failure unless auth && auth.provider.to_s == Sso::PROVIDER.to_s && auth.uid.present? + return reauthenticated(auth) if authenticated? && current_user.sso_uid.present? && current_user.sso_uid == auth.uid.to_s return link(auth) if authenticated? user = User.find_by(sso_uid: auth.uid) || link_by_email(auth) || create_user(auth) @@ -23,6 +24,8 @@ class SsoController < ApplicationController "Ask an administrator to add you, or sign in with your password and link #{Sso.label} from your profile." end + return redirect_to new_session_path, alert: "This account is disabled." if user.disabled? + sync_admin(user, auth) return_to = session[:return_to_after_authenticating] reset_session # fresh session id after signing in @@ -55,6 +58,12 @@ class SsoController < ApplicationController raise ActiveRecord::RecordNotFound unless Sso.enabled? end + # Signed in again (e.g. to sign a logbook entry): note when, and go back. + def reauthenticated(auth) + session[:reauthenticated_at] = Time.current.to_i + redirect_to session.delete(:after_reauth).presence || edit_profile_path, notice: "Signed in again with #{Sso.label}." + end + def link(auth) owner = User.find_by(sso_uid: auth.uid) if owner && owner != current_user diff --git a/app/controllers/user_certificates_controller.rb b/app/controllers/user_certificates_controller.rb index 21efa11..5fbc1b5 100644 --- a/app/controllers/user_certificates_controller.rb +++ b/app/controllers/user_certificates_controller.rb @@ -4,10 +4,11 @@ class UserCertificatesController < ApplicationController def create certificate = current_user.certificates.new(certificate_params) + back = safe_return_to || edit_profile_path(anchor: "certificates") if certificate.save - redirect_to edit_profile_path(anchor: "certificates"), notice: "#{certificate.kind_label} certificate added." + redirect_to back, notice: "#{certificate.kind_label} certificate added." else - redirect_to edit_profile_path(anchor: "certificates"), alert: "Certificate not added: #{certificate.errors.full_messages.to_sentence}." + redirect_to back, alert: "Certificate not added: #{certificate.errors.full_messages.to_sentence}." end end @@ -26,6 +27,9 @@ class UserCertificatesController < ApplicationController private + # Only back to a signing invitation page (no open redirects). + def safe_return_to = params[:return_to].to_s.match?(%r{\A/sign/[\w-]+\z}) ? params[:return_to] : nil + def set_certificate = @certificate = current_user.certificates.find(params[:id]) def certificate_params = params.require(:user_certificate).permit(:kind, :number, :expires_on) diff --git a/app/mailers/signature_mailer.rb b/app/mailers/signature_mailer.rb new file mode 100644 index 0000000..b9a230c --- /dev/null +++ b/app/mailers/signature_mailer.rb @@ -0,0 +1,8 @@ +# Tells the signer their signature was affixed (AC 120-78B 2.2.3). +class SignatureMailer < ApplicationMailer + def signed(signature) + @signature = signature + @entry = signature.logbook_entry + mail subject: "You signed a logbook entry for #{@entry.aircraft.tail_number}", to: signature.signer_email + end +end diff --git a/app/mailers/signing_invitation_mailer.rb b/app/mailers/signing_invitation_mailer.rb new file mode 100644 index 0000000..2a6f232 --- /dev/null +++ b/app/mailers/signing_invitation_mailer.rb @@ -0,0 +1,8 @@ +class SigningInvitationMailer < ApplicationMailer + def invite(invitation, token) + @invitation = invitation + @entry = invitation.logbook_entry + @url = invited_signing_url(token) + mail subject: "Please sign a logbook entry for #{@entry.aircraft.tail_number}", to: invitation.email + end +end diff --git a/app/models/entry_signature.rb b/app/models/entry_signature.rb new file mode 100644 index 0000000..f03b752 --- /dev/null +++ b/app/models/entry_signature.rb @@ -0,0 +1,47 @@ +# An electronic signature on a logbook entry (AC 120-78B chapter 2). +# +# It records the signer, the certificate they signed with, the statement they +# certified, when, and how they proved who they were. content_digest is a +# SHA-256 of the entry's content at signing (content_snapshot is that content), +# so any later change shows; seal is an HMAC over the signature itself, keyed +# by this server, so the signature record can't be altered unnoticed either. +class EntrySignature < ApplicationRecord + AUTH_METHODS = { "password" => "password re-entered", "sso" => "single sign-on, signed in again" }.freeze + # "Certified by" conveys the intent to sign (2.2.2). + LABEL = "Certified by".freeze + + belongs_to :logbook_entry + belongs_to :user, optional: true + + validates :signer_name, :certificate_kind, :certificate_number, :statement, :signed_at, :content_digest, :content_snapshot, presence: true + validates :auth_method, inclusion: { in: AUTH_METHODS.keys + [ "imported" ] } + validates :logbook_entry_id, uniqueness: true + before_create { self.seal ||= compute_seal unless imported? } + before_update { throw :abort } # signatures are permanent (2.1.2.7) + before_destroy { throw :abort unless destroyed_by_association } + + def self.seal_key = Rails.application.key_generator.generate_key("entry-signature-seal", 32) + + def imported? = origin.present? + def certificate_label = UserCertificate::SHORT_LABELS.fetch(certificate_kind, certificate_kind) + def short_id = content_digest.first(12) + + def compute_seal + payload = [ logbook_entry_id, user_id, signer_name, certificate_kind, certificate_number, statement, + signed_at.utc.iso8601(6), content_digest, auth_method ].join("\u001f") + OpenSSL::HMAC.hexdigest("SHA256", self.class.seal_key, payload) + end + + def seal_valid? = imported? || (seal.present? && ActiveSupport::SecurityUtils.secure_compare(seal, compute_seal)) + def content_matches? = content_digest == logbook_entry.content_digest + + # :valid, :superseded, :altered (content or signature changed since signing) + def status + return :altered unless seal_valid? && content_matches? + logbook_entry.superseded_at ? :superseded : :valid + end + + def status_label + { valid: "Valid", superseded: "Superseded by a correction", altered: "Altered since signing" }[status] + end +end diff --git a/app/models/logbook_entry.rb b/app/models/logbook_entry.rb index 8321448..cd69043 100644 --- a/app/models/logbook_entry.rb +++ b/app/models/logbook_entry.rb @@ -26,6 +26,12 @@ class LogbookEntry < ApplicationRecord # Sub-components it also covers (the oil filter on the engine…). has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart", dependent: :destroy, autosave: true + # Electronic signature (AC 120-78B): once signed the entry is locked; a + # correction is a new entry that supersedes it (2.2.8). + has_one :signature, class_name: "EntrySignature", dependent: :destroy + has_many :signing_invitations, dependent: :destroy + belongs_to :supersedes, class_name: "LogbookEntry", optional: true + has_one :superseded_by, class_name: "LogbookEntry", foreign_key: :supersedes_id, inverse_of: :supersedes, dependent: :nullify has_many :inspection_records, dependent: :nullify has_many :ad_compliances, dependent: :nullify has_many :squawks, dependent: :nullify @@ -38,6 +44,12 @@ class LogbookEntry < ApplicationRecord validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence } + # Fields that may still change on a signed entry: its link to a scanned + # page, the transcription check, and being superseded by a correction. + UNSIGNED_FIELDS = %w[document_id page_number verified superseded_at updated_at].freeze + before_update :keep_signed_content + before_destroy(prepend: true) { throw :abort if signed? && !destroyed_by_association } + scope :recent_first, -> { order(date: :desc, created_at: :desc) } scope :unverified, -> { where(verified: false) } @@ -49,6 +61,90 @@ class LogbookEntry < ApplicationRecord def to_s = "#{date} — #{LOG_TYPES[log_type]}" + def signed? = signature.present? + def superseded? = superseded_at.present? + + # What a signature covers: the entry's own content, in a fixed form, so + # the fingerprint changes if anything in it does. + def content_payload + num = ->(v) { v.nil? ? nil : format("%.1f", v) } + { + "v" => 1, "id" => id, "aircraft_id" => aircraft_id, "date" => date&.iso8601, "log_type" => log_type, "entry_type" => entry_type, + "text" => text.to_s, "airframe_hours" => num.(aircraft_hours_at_entry), "location" => signoff_location.to_s, + "signer" => [ signoff_person.to_s, signoff_certificate_type.to_s, signoff_certificate_number.to_s ], + "inspection_result" => inspection_result.to_s, "supersedes_id" => supersedes_id, + "component" => component_id && [ component_id, num.(component_hours_at_entry), num.(component_since_overhaul_at_entry) ], + "parts" => parts.reject(&:marked_for_destruction?).map { [ _1.component_id, num.(_1.hours_at_entry), num.(_1.since_overhaul_at_entry) ] }.sort_by { _1.first.to_i } + } + end + + def content_digest = OpenSSL::Digest::SHA256.hexdigest(content_payload.to_json) + + # Readable copy of what was signed, kept with the signature. + def content_snapshot + c = component + { + "aircraft" => { "tail_number" => aircraft.tail_number, "make" => aircraft.make, "model" => aircraft.model, "serial_number" => aircraft.serial_number }, + "date" => date&.iso8601, "log" => LOG_TYPES[log_type], "entry_type" => ENTRY_TYPES[entry_type], "text" => text, + "airframe_total_time" => aircraft_hours_at_entry&.to_s, "time_basis" => aircraft.time_basis, "location" => signoff_location, + "inspection_result" => inspection_result_label, + "component" => c && { "type" => c.component_type&.name, "make" => c.manufacturer, "model" => c.model, "serial_number" => c.serial_number, + "total_time" => component_hours_at_entry&.to_s, "since_overhaul" => component_since_overhaul_at_entry&.to_s, + "since_label" => c.since_overhaul_abbreviation }, + "parts" => parts.map { |p| { "type" => p.component.component_type&.name, "model" => p.component.model, "serial_number" => p.component.serial_number, + "total_time" => p.hours_at_entry&.to_s, "since" => p.since_overhaul_at_entry&.to_s } }, + "supersedes" => supersedes && { "date" => supersedes.date&.iso8601, "fingerprint" => supersedes.signature&.content_digest } + } + end + + # "an annual" / "a 100-hour": from a linked inspection record, else the text. + def inspection_kind_phrase + name = inspection_records.first&.inspection_type&.name.to_s.sub(/\s*\(.*\)\z/, "").sub(/\s*inspection\z/i, "").strip.downcase + name = "annual" if name.empty? && text.to_s.match?(/annual/i) + name = "100-hour" if name.empty? && text.to_s.match?(/100[- ]?h(ou)?r/i) + return "a ______________" if name.empty? + "#{name.match?(/\A[aeiou]/) ? 'an' : 'a'} #{name}" + end + + # What the signer certifies, by the kind of entry and certificate. + def certification_statement(certificate_kind) + if entry_type == "INSPECTION" + if inspection_result == "discrepancies" + "I certify that this aircraft has been inspected in accordance with #{inspection_kind_phrase} inspection and a list of discrepancies " \ + "and unairworthy items dated #{date&.strftime('%b %-d, %Y')} has been provided for the aircraft owner or operator." + else + "I certify that this aircraft has been inspected in accordance with #{inspection_kind_phrase} inspection and was determined to be in airworthy condition." + end + elsif certificate_kind == "PILOT" + "I certify that the preventive maintenance described in this entry was performed in accordance with 14 CFR Part 43, and I approve it for return to service." + elsif entry_type == "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." + else + "I certify that this entry is correct." + end + end + + # Why this certificate can't sign this entry ([] if it can). + def signing_problems(certificate) + problems = [] + problems << "it's already signed" if signed? + problems << "it has been superseded by a correction" if superseded? + problems << "it has no description" if text.blank? + problems << "it has no date" if date.blank? + if entry_type == "INSPECTION" + problems << "an inspection entry needs its result (airworthy, or discrepancy list)" if inspection_result.blank? + problems << "an inspection entry needs the aircraft's total time" if aircraft_hours_at_entry.blank? + end + if certificate + problems << "that certificate has expired" if certificate.expired? + problems << "a pilot certificate can sign preventive maintenance only" if certificate.kind == "PILOT" && entry_type != "MAINTENANCE" + problems << "\"Other\" certificates can't sign maintenance or inspections" if certificate.kind == "OTHER" && RECORD_TYPES.include?(entry_type) + else + problems << "choose a certificate to sign with" + end + problems + end + # From the form: { component_id => { "include" => "1", "hours" => …, "since" => … } }. # Only the aircraft's sub-components of the entry's component are kept. def assign_parts(params, aircraft) @@ -79,4 +175,14 @@ class LogbookEntry < ApplicationRecord end missing end + + private + + def keep_signed_content + return unless signed? && signature.persisted? + locked = changed - UNSIGNED_FIELDS + return if locked.empty? + errors.add(:base, "This entry is signed, so it can't be changed. Make a correction entry instead") + throw :abort + end end diff --git a/app/models/logbook_entry_part.rb b/app/models/logbook_entry_part.rb index f5b1396..01ba7bf 100644 --- a/app/models/logbook_entry_part.rb +++ b/app/models/logbook_entry_part.rb @@ -6,4 +6,8 @@ class LogbookEntryPart < ApplicationRecord validates :component_id, uniqueness: { scope: :logbook_entry_id } validates :hours_at_entry, :since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true + + # Part of a signed entry's content: locked with it. + before_save { throw :abort if logbook_entry&.signed? } + before_destroy { throw :abort if logbook_entry&.signed? && !destroyed_by_association } end diff --git a/app/models/signing_invitation.rb b/app/models/signing_invitation.rb new file mode 100644 index 0000000..c0f57ad --- /dev/null +++ b/app/models/signing_invitation.rb @@ -0,0 +1,25 @@ +# An invitation, by email, for someone outside the aircraft (a mechanic) to +# sign one logbook entry with their own account and certificate +# (AC 120-78B 3.2.8.11). The link works once and expires. +class SigningInvitation < ApplicationRecord + VALID_FOR = 14.days + + belongs_to :logbook_entry + belongs_to :invited_by, class_name: "User", optional: true + belongs_to :user, optional: true + + attr_reader :token + + normalizes :email, with: ->(e) { e.strip.downcase } + validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } + before_validation(on: :create) do + @token = SecureRandom.urlsafe_base64(32) + self.token_digest = self.class.digest(@token) + self.expires_at ||= VALID_FOR.from_now + end + + def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s) + def self.find_usable(token) = where(token_digest: digest(token), used_at: nil).where("expires_at > ?", Time.current).first + + def aircraft = logbook_entry.aircraft +end diff --git a/app/models/user.rb b/app/models/user.rb index 3d6736e..074db6a 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -5,6 +5,11 @@ class User < ApplicationRecord has_many :aircraft, through: :aircraft_roles has_one :air_trail_connection, dependent: :destroy has_many :certificates, -> { ordered }, class_name: "UserCertificate", dependent: :destroy + has_many :entry_signatures, dependent: :nullify + + scope :active, -> { where(disabled_at: nil) } + + def disabled? = disabled_at.present? # Emailed sign-in links: valid 15 minutes, and spent by the next sign-in of # any kind (or an email change), so each link works once. last_signed_in_at diff --git a/app/services/aircraft_archive/exporter.rb b/app/services/aircraft_archive/exporter.rb index 11bbe67..a2bced8 100644 --- a/app/services/aircraft_archive/exporter.rb +++ b/app/services/aircraft_archive/exporter.rb @@ -55,7 +55,7 @@ module AircraftArchive document_images: a.documents.includes(pages_attachments: :blob).flat_map do |d| d.pages.map { |page| { id: id(page), document_id: id(d), notes: "", image: file(page, "health/documents") } } end, - logbook_entries: a.logbook_entries.includes(:parts).map { logbook_hash(_1) }, + logbook_entries: a.logbook_entries.includes(:parts, :signature).map { logbook_hash(_1) }, squawks: a.squawks.includes(:reported_by, attachments_attachments: :blob).map { squawk_hash(_1) }, inspection_types: inspection_types.map { inspection_type_hash(_1, component_ids) }, inspection_records: a.inspection_records.map do |r| @@ -131,6 +131,15 @@ module AircraftArchive picture: file(a.picture, "aircraft_pictures"), icao_type: a.icao_type } end + # Carried as a record of the signature; the importing system can't re-check + # this server's seal, so it marks the signature as imported. + def signature_hash(sig) + { signer_name: sig.signer_name, signer_email: sig.signer_email, certificate_kind: sig.certificate_kind, + certificate_number: sig.certificate_number, statement: sig.statement, signed_at: sig.signed_at.utc.iso8601(6), + content_digest: sig.content_digest, content_snapshot: sig.content_snapshot, auth_method: sig.auth_method, + origin: sig.origin.presence || @source } + end + def component_hash(c) { id: id(c), aircraft_id: id(c.aircraft_id), parent_component_id: id(c.parent_component_id), component_type_id: id(c.component_type_id), manufacturer: c.manufacturer, model: c.model, serial_number: c.serial_number, install_location: c.install_location, @@ -153,7 +162,8 @@ module AircraftArchive .reject { |k, v| k.nil? || v.nil? }, component_since_overhaul: { id(e.component_id) => dec(e.component_since_overhaul_at_entry) } .merge(e.parts.to_h { [ id(_1.component_id), dec(_1.since_overhaul_at_entry) ] }).reject { |k, v| k.nil? || v.nil? }, - related_documents: [] } + related_documents: [], supersedes_id: id(e.supersedes_id), superseded_at: e.superseded_at&.iso8601, + signature: e.signature && signature_hash(e.signature) } end def squawk_hash(s) diff --git a/app/services/aircraft_archive/importer.rb b/app/services/aircraft_archive/importer.rb index 0fcf8d0..690a028 100644 --- a/app/services/aircraft_archive/importer.rb +++ b/app/services/aircraft_archive/importer.rb @@ -247,8 +247,11 @@ module AircraftArchive e.parts.build(component_id: @map[:component][r.to_s], hours_at_entry: num(hash_value(data["component_hours"], r)), since_overhaul_at_entry: num(hash_value(data["component_since_overhaul"], r))) end + e.superseded_at = time(data["superseded_at"]) e.save!(validate: false) @map[:logbook][data["id"].to_s] = e.id + (@supersedes ||= []) << [ e.id, data["supersedes_id"].to_s ] if data["supersedes_id"].present? + import_signature(e, data["signature"]) if data["signature"].is_a?(Hash) tick("logbook_entries") end @@ -383,6 +386,22 @@ module AircraftArchive tick("major_records") end import_weight_balance + Array(@supersedes).each do |entry_id, ref| + target = @map[:logbook][ref] + LogbookEntry.where(id: entry_id).update_all(supersedes_id: target) if target + end + end + + def import_signature(entry, sig) + kind = LogbookEntry::CERTIFICATE_TYPES.key?(sig["certificate_kind"]) ? sig["certificate_kind"] : "OTHER" + EntrySignature.new( + logbook_entry: entry, signer_name: sig["signer_name"].to_s.presence || "Unknown", signer_email: sig["signer_email"], + certificate_kind: kind, certificate_number: sig["certificate_number"].to_s.presence || "unknown", + statement: sig["statement"].to_s.presence || "—", signed_at: time(sig["signed_at"]) || Time.current, + content_digest: sig["content_digest"].to_s.presence || "unknown", content_snapshot: sig["content_snapshot"].to_s.presence || "{}", + auth_method: EntrySignature::AUTH_METHODS.key?(sig["auth_method"]) ? sig["auth_method"] : "imported", + origin: sig["origin"].to_s.presence || "another system" + ).save!(validate: false) end def import_weight_balance diff --git a/app/services/entry_signer.rb b/app/services/entry_signer.rb new file mode 100644 index 0000000..e27c80f --- /dev/null +++ b/app/services/entry_signer.rb @@ -0,0 +1,41 @@ +# Signs a logbook entry for a user with one of their certificates +# (AC 120-78B 2.1.2 / 2.2): the entry's signer fields are set from the +# certificate, then the signature records exactly what was signed. Signing a +# correction marks the entry it corrects as superseded (2.2.8). +class EntrySigner + REAUTH_WINDOW = 5.minutes + + class Error < StandardError; end + + def initialize(entry, user:, certificate:, auth_method:, request: nil) + @entry = entry + @user = user + @certificate = certificate + @auth_method = auth_method + @request = request + end + + def sign! + raise Error, "Your account is disabled" if @user.disabled? + raise Error, "That certificate isn't yours" unless @certificate && @certificate.user_id == @user.id + problems = @entry.signing_problems(@certificate) + raise Error, "This entry can't be signed: #{problems.to_sentence}" if problems.any? + + LogbookEntry.transaction do + @entry.update!(signoff_person: @user.display_name, signoff_certificate_type: @certificate.kind, + signoff_certificate_number: @certificate.number) + @entry.reload + signature = @entry.create_signature!( + user: @user, signer_name: @user.display_name, signer_email: @user.email_address, + certificate_kind: @certificate.kind, certificate_number: @certificate.number, + statement: @entry.certification_statement(@certificate.kind), signed_at: Time.current, + content_digest: @entry.content_digest, content_snapshot: @entry.content_snapshot.to_json, + auth_method: @auth_method, ip_address: @request&.remote_ip, user_agent: @request&.user_agent.to_s.first(255) + ) + @entry.supersedes&.update_column(:superseded_at, signature.signed_at) + @entry.aircraft.log_event!("logbook", "Logbook entry signed electronically (#{@entry.date})", + notes: "#{signature.signer_name}, #{signature.certificate_label} #{signature.certificate_number}", user: @user) + signature + end + end +end diff --git a/app/services/logbook_entry_pdf.rb b/app/services/logbook_entry_pdf.rb index 04f251d..fe18659 100644 --- a/app/services/logbook_entry_pdf.rb +++ b/app/services/logbook_entry_pdf.rb @@ -195,6 +195,7 @@ class LogbookEntryPdf def signature_block_height(small) = (small + 3) * 3 + 6 def signature_block(entry, w, height, small, more:) + return electronic_signature_block(entry, w, height, small, more: more) if entry.signature @pdf.bounding_box([ 0, height ], width: w, height: height) do if more @pdf.text_box "Continued on the next #{more}.", at: [ 0, height ], width: w, height: small + 2, size: small, @@ -212,6 +213,24 @@ class LogbookEntryPdf end end + # Signed entries: who certified it, when, and the fingerprint to check it by. + def electronic_signature_block(entry, w, height, small, more:) + sig = entry.signature + @pdf.bounding_box([ 0, height ], width: w, height: height) do + top = height + if more + @pdf.text_box "Continued on the next #{more}.", at: [ 0, top ], width: w, height: small + 2, size: small, style: :italic, overflow: :truncate + end + top -= small + 3 + @pdf.text_box clean("#{EntrySignature::LABEL} #{sig.signer_name}, #{sig.certificate_label} #{sig.certificate_number}" \ + "#{' (SUPERSEDED BY A CORRECTION)' if entry.superseded?}"), + at: [ 0, top ], width: w, height: small + 2, size: small, style: :bold, overflow: :shrink_to_fit, min_font_size: 5 + top -= small + 3 + @pdf.text_box clean("Signed electronically #{sig.signed_at.utc.strftime('%Y-%m-%d %H:%M UTC')} · fingerprint #{sig.content_digest.first(16)}"), + at: [ 0, top ], width: w, height: small + 2, size: small - 1, overflow: :shrink_to_fit, min_font_size: 5 + end + end + def certificate(entry) kind = { "AP" => "A&P", "IA" => "A&P/IA", "A" => "A", "P" => "P", "REPAIR_STATION" => "Repair station", "REPAIRMAN" => "Repairman", "PILOT" => "Pilot", "OTHER" => "" }[entry.signoff_certificate_type].to_s @@ -223,6 +242,7 @@ class LogbookEntryPdf # result is recorded but whose text doesn't already certify it. def body_text(entry) text = entry.text.to_s.strip + return "#{text}\n\n#{entry.signature.statement}" if entry.signature return text unless entry.entry_type == "INSPECTION" && entry.inspection_result.present? && !text.match?(/I certify/i) type = inspection_kind(entry, text) statement = diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb index e897fdb..a3d4f7e 100644 --- a/app/views/admin/users/index.html.erb +++ b/app/views/admin/users/index.html.erb @@ -7,7 +7,10 @@ <%= u.email_address %><% if u.certificates.any? %>
<%= u.certificates.map { "#{_1.short_label} #{_1.number}" }.join(", ") %>
<% end %> <%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %> <%= u.last_signed_in_at ? "#{time_ago_in_words(u.last_signed_in_at)} ago" : "never" %> - <%= link_to "Edit", edit_admin_user_path(u), class: "btn-secondary btn-sm" %> + + <% if u.disabled? %>Disabled<%= 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 %> + <%= link_to "Edit", edit_admin_user_path(u), class: "btn-secondary btn-sm" %> <% end %>

After creating an account, an aircraft owner can grant access from the aircraft's “Access & Sharing” tab.

diff --git a/app/views/entry_signatures/_form.html.erb b/app/views/entry_signatures/_form.html.erb new file mode 100644 index 0000000..ba01be4 --- /dev/null +++ b/app/views/entry_signatures/_form.html.erb @@ -0,0 +1,51 @@ +<%# Signing form: review, certificate, re-authentication, confirm. Locals: entry, url, cancel_path. %> +
+

Sign this entry

+
+

Review the entry: your signature will cover exactly what's shown here, and it can't be changed afterwards. A mistake is fixed with a correction entry.

+ <%= render "logbook_entries/content", entry: entry %> + <% if @signing_error %> + + <% end %> + <% if @certificates.empty? %> +

+ To sign, add your certificate on <%= link_to "your profile", edit_profile_path(anchor: "certificates"), class: "link" %>. +

+ <% else %> + <%= form_with url: url, method: :post, class: "space-y-4" do %> +
+ Sign with + <% @certificates.each_with_index do |c, i| %> + <% problems = entry.signing_problems(c) %> + + <% end %> +
+ <% if Sso.password_login? || !current_user.sso_uid? %> +
+ <%= label_tag :password, "Your password", class: "label" %> + <%= password_field_tag :password, nil, class: "input", autocomplete: "current-password" %> +

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? %>

+
+ <% end %> + <% if Sso.enabled? && current_user.sso_uid? %> + <% fresh = session[:reauthenticated_at] && Time.zone.at(session[:reauthenticated_at]) > EntrySigner::REAUTH_WINDOW.ago %> +

<%= fresh ? "Signed in again with #{Sso.label}: you can sign now." : "Or sign in again with #{Sso.label} first (button below the form)." %>

+ <% end %> + +
<%= submit_tag "Sign entry", class: "btn-primary" %><%= link_to "Cancel", cancel_path, class: "btn-secondary" %>
+ <% end %> + <% if Sso.enabled? && current_user.sso_uid? %> + <%= button_to "Sign in again with #{Sso.label}", "/auth/#{Sso::PROVIDER}", params: { prompt: "login" }, class: "btn-secondary btn-sm", data: { turbo: false } %> + <% end %> + <% end %> +
+
diff --git a/app/views/entry_signatures/new.html.erb b/app/views/entry_signatures/new.html.erb new file mode 100644 index 0000000..39bd6fe --- /dev/null +++ b/app/views/entry_signatures/new.html.erb @@ -0,0 +1,4 @@ +<% content_for :title, "Sign logbook entry" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "entry_signatures/form", entry: @entry, url: aircraft_logbook_entry_signature_path(@aircraft, @entry), + cancel_path: aircraft_logbook_entry_path(@aircraft, @entry) %> diff --git a/app/views/invited_signings/expired.html.erb b/app/views/invited_signings/expired.html.erb new file mode 100644 index 0000000..98ea23e --- /dev/null +++ b/app/views/invited_signings/expired.html.erb @@ -0,0 +1,5 @@ +<% content_for :title, "Invitation not found" %> +
+

This signing link has expired or was already used

+

Ask the aircraft's owner to send a new one.

+
diff --git a/app/views/invited_signings/new.html.erb b/app/views/invited_signings/new.html.erb new file mode 100644 index 0000000..19e3590 --- /dev/null +++ b/app/views/invited_signings/new.html.erb @@ -0,0 +1,12 @@ +<% content_for :title, "Sign logbook entry" %> +<% if @certificates.empty? %> +
+

Add your certificate

+ <%= form_with model: UserCertificate.new, url: certificates_path(return_to: request.path), class: "grid gap-2 sm:grid-cols-[1fr_10rem_auto]" do |f| %> + <%= f.select :kind, UserCertificate::KINDS.invert, {}, class: "input", "aria-label": "Kind of certificate" %> + <%= f.text_field :number, class: "input", placeholder: "Number", required: true, "aria-label": "Certificate number" %> + <%= f.submit "Add", class: "btn-secondary" %> + <% end %> +
+<% end %> +<%= render "entry_signatures/form", entry: @entry, url: invited_signing_path(params[:token]), cancel_path: root_path %> diff --git a/app/views/invited_signings/signed.html.erb b/app/views/invited_signings/signed.html.erb new file mode 100644 index 0000000..dba42cd --- /dev/null +++ b/app/views/invited_signings/signed.html.erb @@ -0,0 +1,6 @@ +<% content_for :title, "Logbook entry signed" %> +
+

Entry signed

+ <%= render "logbook_entries/signature", entry: @entry %> + <%= render "logbook_entries/content", entry: @entry %> +
diff --git a/app/views/invited_signings/welcome.html.erb b/app/views/invited_signings/welcome.html.erb new file mode 100644 index 0000000..c3c93fa --- /dev/null +++ b/app/views/invited_signings/welcome.html.erb @@ -0,0 +1,19 @@ +<% content_for :title, "Sign a logbook entry" %> +
+

Sign a logbook entry

+

You've been asked to sign the <%= @entry.date %> <%= LogbookEntry::LOG_TYPES[@entry.log_type].downcase %> log entry for <%= @entry.aircraft.tail_number %>. First, sign in as <%= @invitation.email %>.

+
+ <%= link_to "I have an account: sign in", new_session_path, class: "btn-primary w-full justify-center" %> +
+ <% if Sso.password_login? && !User.exists?(email_address: @invitation.email) %> + <%= form_with url: account_invited_signing_path(params[:token]), class: "card card-body space-y-3" do %> +

Or create an account

+ <% if @account_errors.present? %>
<%= @account_errors.to_sentence %>
<% end %> +
+
<%= label_tag :name, "Your name", class: "label" %><%= text_field_tag :name, params[:name], class: "input", required: true %>
+
<%= label_tag :password, "Password", class: "label" %><%= password_field_tag :password, nil, class: "input", required: true, autocomplete: "new-password" %>
+
<%= label_tag :password_confirmation, "Confirm password", class: "label" %><%= password_field_tag :password_confirmation, nil, class: "input", required: true, autocomplete: "new-password" %>
+ <%= submit_tag "Create account", class: "btn-secondary" %> + <% end %> + <% end %> +
diff --git a/app/views/invited_signings/wrong_account.html.erb b/app/views/invited_signings/wrong_account.html.erb new file mode 100644 index 0000000..2fbac27 --- /dev/null +++ b/app/views/invited_signings/wrong_account.html.erb @@ -0,0 +1,6 @@ +<% content_for :title, "Sign a logbook entry" %> +
+

Wrong account

+

This invitation is for <%= @invitation.email %>, but you're signed in as <%= current_user.email_address %>. Sign out and sign in with the invited address.

+ <%= button_to "Sign out", session_path, method: :delete, class: "btn-secondary" %> +
diff --git a/app/views/logbook_entries/_content.html.erb b/app/views/logbook_entries/_content.html.erb new file mode 100644 index 0000000..44d8c90 --- /dev/null +++ b/app/views/logbook_entries/_content.html.erb @@ -0,0 +1,19 @@ +<%# Everything a signature covers, as the signer reviews it (AC 120-78B 2.2.4). %> +
+
Aircraft
<%= entry.aircraft.tail_number %> <%= [ entry.aircraft.make, entry.aircraft.model ].compact_blank.join(" ") %><%= " · S/N #{entry.aircraft.serial_number}" if entry.aircraft.serial_number.present? %>
+
Date
<%= fmt_date(entry.date) %>
+
Logbook
<%= LogbookEntry::LOG_TYPES[entry.log_type] %> · <%= LogbookEntry::ENTRY_TYPES[entry.entry_type] %>
+
Airframe total time
<%= hours(entry.aircraft_hours_at_entry) %> (<%= entry.aircraft.time_basis %>)
+ <% if (c = entry.component) %> +
<%= c.component_type&.name %>
+
<%= c.manufacturer %> <%= c.model %><%= " · S/N #{c.serial_number}" if c.serial_number.present? %> · <%= hours(entry.component_hours_at_entry) %> total, <%= hours(entry.component_since_overhaul_at_entry) %> <%= c.since_overhaul_abbreviation %>
+ <% end %> + <% entry.parts.each do |part| %> +
<%= part.component.component_type&.name %>
+
<%= part.component.manufacturer %> <%= part.component.model %><%= " · S/N #{part.component.serial_number}" if part.component.serial_number.present? %> · <%= hours(part.hours_at_entry) %> total, <%= hours(part.since_overhaul_at_entry) %> <%= part.component.since_overhaul_abbreviation.downcase %>
+ <% end %> + <% if entry.inspection_result %>
Result
<%= entry.inspection_result_label %>
<% end %> + <% if entry.signoff_location.present? %>
Location
<%= entry.signoff_location %>
<% end %> + <% if entry.supersedes %>
Corrects
The <%= entry.supersedes.date %> entry
<% end %> +
+
<%= entry.text %>
diff --git a/app/views/logbook_entries/_form.html.erb b/app/views/logbook_entries/_form.html.erb index 277c1e7..f9292ca 100644 --- a/app/views/logbook_entries/_form.html.erb +++ b/app/views/logbook_entries/_form.html.erb @@ -1,5 +1,12 @@ <%= form_with model: [aircraft, entry], class: "card card-body space-y-4 max-w-3xl", data: { controller: "entry-template signer component-times", component_times_aircraft_hours_value: aircraft.current_hours.to_f } do |f| %> <%= f.errors_summary %> + <% if entry.supersedes %> + <%= f.hidden_field :supersedes_id %> +

+ Correcting the signed <%= link_to "#{entry.supersedes.date} entry", aircraft_logbook_entry_path(aircraft, entry.supersedes), class: "link" %>. + Change what's wrong, save, then sign it: the original's signature is then marked superseded (it's kept, not deleted). +

+ <% end %> <% templates = entry.new_record? ? LogbookTemplate.ordered.to_a : [] %> <% if templates.any? %>
diff --git a/app/views/logbook_entries/_signature.html.erb b/app/views/logbook_entries/_signature.html.erb new file mode 100644 index 0000000..0a19d36 --- /dev/null +++ b/app/views/logbook_entries/_signature.html.erb @@ -0,0 +1,14 @@ +<%# The signature block on an entry's page. %> +<% sig = entry.signature %> +<% box, title = { valid: [ "bg-emerald-50 ring-emerald-200", "text-emerald-900" ], superseded: [ "bg-amber-50 ring-amber-200", "text-amber-900" ], + altered: [ "bg-red-50 ring-red-200", "text-red-900" ] }.fetch(sig.imported? ? :valid : sig.status) %> +
+
<%= EntrySignature::LABEL %> <%= sig.signer_name %>, <%= sig.certificate_label %> <%= sig.certificate_number %>
+
Signed electronically <%= sig.signed_at.utc.strftime("%Y-%m-%d %H:%M UTC") %><%= " (#{EntrySignature::AUTH_METHODS[sig.auth_method]})" if EntrySignature::AUTH_METHODS[sig.auth_method] %>
+
“<%= sig.statement %>”
+
+ Status: <%= sig.imported? ? "Signed on #{sig.origin} (imported)" : sig.status_label %> + · Fingerprint <%= sig.content_digest.first(16) %>… + <% if entry.superseded_by %> · Corrected by <%= link_to "the #{entry.superseded_by.date} entry", aircraft_logbook_entry_path(entry.aircraft, entry.superseded_by), class: "link" %><% end %> +
+
diff --git a/app/views/logbook_entries/index.html.erb b/app/views/logbook_entries/index.html.erb index f8db638..85d706b 100644 --- a/app/views/logbook_entries/index.html.erb +++ b/app/views/logbook_entries/index.html.erb @@ -31,7 +31,8 @@ <%= e.text.truncate(220) %> <%= "📄" if e.document %> <% unless e.verified? %>; check it against the scan">Unverified<% end %> <%= e.signoff_person %><%= " ##{e.signoff_certificate_number}" if e.signoff_certificate_number %><% if e.signoff_location.present? %>
<%= e.signoff_location %><% end %> - <% if (missing = e.missing_record_items).any? %>
Incomplete<% end %> + <% if e.signature %>
<%= e.superseded? ? "Superseded" : "Signed" %> + <% elsif (missing = e.missing_record_items).any? %>
Incomplete<% end %> <% end %> diff --git a/app/views/logbook_entries/show.html.erb b/app/views/logbook_entries/show.html.erb index 0dbd2af..f332064 100644 --- a/app/views/logbook_entries/show.html.erb +++ b/app/views/logbook_entries/show.html.erb @@ -4,10 +4,22 @@

<%= LogbookEntry::LOG_TYPES[@entry.log_type] %> log — <%= fmt_date(@entry.date) %>

<%= link_to "Print for logbook", new_aircraft_logbook_print_path(@aircraft, ids: [ @entry.id ]), class: "btn-secondary btn-sm" %> - <% if owner? %><%= link_to "Edit", edit_aircraft_logbook_entry_path(@aircraft, @entry), class: "btn-secondary btn-sm" %><% end %> + <% if @entry.signed? %> + <% if owner? && !@entry.superseded? && !@entry.superseded_by %><%= link_to "Correct this entry", new_aircraft_logbook_entry_path(@aircraft, supersedes: @entry.id), class: "btn-secondary btn-sm" %><% end %> + <% else %> + <%= link_to "Sign", new_aircraft_logbook_entry_signature_path(@aircraft, @entry), class: "btn-primary btn-sm" %> + <% if owner? %> + <%= link_to "Ask someone to sign", new_aircraft_logbook_entry_signing_invitation_path(@aircraft, @entry), class: "btn-secondary btn-sm" %> + <%= link_to "Edit", edit_aircraft_logbook_entry_path(@aircraft, @entry), class: "btn-secondary btn-sm" %> + <% end %> + <% end %>
+ <% if @entry.signed? %><%= render "logbook_entries/signature", entry: @entry %> + <% elsif LogbookEntry::RECORD_TYPES.include?(@entry.entry_type) %> +

Not signed electronically.<%= " Pending correction of the #{@entry.supersedes.date} entry." if @entry.supersedes %> Sign it here, or print it and sign the paper copy.

+ <% end %> <% unless @entry.verified? %>
Transcribed by Claude<%= " (#{@entry.transcription_confidence} confidence)" if @entry.transcription_confidence %> and not yet checked. Compare it with the scan<%= @entry.document ? "" : " or the paper logbook" %> before relying on it. diff --git a/app/views/signature_mailer/signed.html.erb b/app/views/signature_mailer/signed.html.erb new file mode 100644 index 0000000..a7f06d6 --- /dev/null +++ b/app/views/signature_mailer/signed.html.erb @@ -0,0 +1,8 @@ +

You electronically signed a logbook entry.

+

Aircraft: <%= @entry.aircraft.tail_number %>
+Entry: <%= @entry.date %>, <%= LogbookEntry::LOG_TYPES[@entry.log_type] %> log
+Certified by: <%= @signature.signer_name %>, <%= @signature.certificate_label %> <%= @signature.certificate_number %>
+Signed: <%= @signature.signed_at.utc.strftime("%Y-%m-%d %H:%M:%S UTC") %>

+

Statement: <%= @signature.statement %>

+

Fingerprint: <%= @signature.content_digest %>

+

If you didn't sign this, tell the aircraft's owner right away.

diff --git a/app/views/signature_mailer/signed.text.erb b/app/views/signature_mailer/signed.text.erb new file mode 100644 index 0000000..b7ffd83 --- /dev/null +++ b/app/views/signature_mailer/signed.text.erb @@ -0,0 +1,10 @@ +You electronically signed a logbook entry. + +Aircraft: <%= @entry.aircraft.tail_number %> +Entry: <%= @entry.date %>, <%= LogbookEntry::LOG_TYPES[@entry.log_type] %> log +Certified by: <%= @signature.signer_name %>, <%= @signature.certificate_label %> <%= @signature.certificate_number %> +Signed: <%= @signature.signed_at.utc.strftime("%Y-%m-%d %H:%M:%S UTC") %> +Statement: <%= @signature.statement %> +Fingerprint: <%= @signature.content_digest %> + +If you didn't sign this, tell the aircraft's owner right away. diff --git a/app/views/signing_invitation_mailer/invite.html.erb b/app/views/signing_invitation_mailer/invite.html.erb new file mode 100644 index 0000000..a5eb631 --- /dev/null +++ b/app/views/signing_invitation_mailer/invite.html.erb @@ -0,0 +1,4 @@ +

<%= @invitation.invited_by&.display_name || "The owner" %> asks you to sign a logbook entry for <%= @entry.aircraft.tail_number %> (<%= @entry.date %>, <%= LogbookEntry::LOG_TYPES[@entry.log_type] %> log).

+<% if @invitation.message.present? %>

“<%= @invitation.message %>”

<% end %> +

<%= link_to "Review and sign the entry", @url %> (the link works once, until <%= @invitation.expires_at.to_date %>).

+

You'll sign in or create an account for <%= @invitation.email %>, add your certificate, and sign with your password.

diff --git a/app/views/signing_invitation_mailer/invite.text.erb b/app/views/signing_invitation_mailer/invite.text.erb new file mode 100644 index 0000000..92c48da --- /dev/null +++ b/app/views/signing_invitation_mailer/invite.text.erb @@ -0,0 +1,10 @@ +<%= @invitation.invited_by&.display_name || "The owner" %> asks you to sign a logbook entry for <%= @entry.aircraft.tail_number %> (<%= @entry.date %>, <%= LogbookEntry::LOG_TYPES[@entry.log_type] %> log). +<% if @invitation.message.present? %> + +"<%= @invitation.message %>" +<% end %> + +Review and sign it here (the link works once, until <%= @invitation.expires_at.to_date %>): +<%= @url %> + +You'll sign in or create an account for <%= @invitation.email %>, add your certificate, and sign with your password. diff --git a/app/views/signing_invitations/new.html.erb b/app/views/signing_invitations/new.html.erb new file mode 100644 index 0000000..4c2cd43 --- /dev/null +++ b/app/views/signing_invitations/new.html.erb @@ -0,0 +1,11 @@ +<% content_for :title, "Ask someone to sign" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= form_with model: @invitation, url: aircraft_logbook_entry_signing_invitations_path(@aircraft, @entry), class: "card card-body max-w-2xl space-y-4" do |f| %> +

Ask someone to sign

+

For a mechanic who did the work: they get a one-time link by email, sign in or create their own account, add their certificate, and sign this entry with their own password. They see only this entry.

+ <%= f.errors_summary %> +
<%= @entry.date %> · <%= LogbookEntry::LOG_TYPES[@entry.log_type] %> log · <%= @entry.text.truncate(160) %>
+ <%= f.field :email, as: :email, label: "Their email", required: true %> + <%= f.field :message, as: :textarea, rows: 2, label: "Message (optional)" %> +
<%= f.submit "Send invitation" %><%= link_to "Cancel", aircraft_logbook_entry_path(@aircraft, @entry), class: "btn-secondary" %>
+<% end %> diff --git a/config/initializers/omniauth.rb b/config/initializers/omniauth.rb index 66b8a5e..5a760fe 100644 --- a/config/initializers/omniauth.rb +++ b/config/initializers/omniauth.rb @@ -11,6 +11,8 @@ Rails.application.config.middleware.use OmniAuth::Builder do scope: %i[openid email profile], response_type: :code, pkce: true, + # "prompt=login" makes the provider ask again (signing an entry). + allow_authorize_params: %i[prompt], client_options: { identifier: ENV["OIDC_CLIENT_ID"], secret: ENV["OIDC_CLIENT_SECRET"], diff --git a/config/routes.rb b/config/routes.rb index 4480811..6d1440d 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -64,6 +64,8 @@ Rails.application.routes.draw do resource :logbook_print, path: "logbook/print", only: %i[new show] resources :logbook_entries do member { patch :verify } + resource :signature, controller: "entry_signatures", only: %i[new create] + resources :signing_invitations, only: %i[new create] end resources :documents do collection do @@ -106,10 +108,21 @@ Rails.application.routes.draw do get "airports/search", to: "airports#search", as: :airport_search # Public read-only share links (no login). + # Invited signers (outside mechanics) sign one entry. + get "sign/:token", to: "invited_signings#show", as: :invited_signing + post "sign/:token", to: "invited_signings#create" + post "sign/:token/account", to: "invited_signings#account", as: :account_invited_signing + get "shared/:token", to: "shared#show", as: :shared get "shared/:token/report", to: "shared#report", as: :shared_report namespace :admin do + resources :users, only: [] do + member do + patch :disable + patch :enable + end + end get "about", to: "about#show" resource :settings, only: %i[edit update] resources :logbook_templates, except: :show do diff --git a/db/migrate/20261108010000_create_entry_signatures.rb b/db/migrate/20261108010000_create_entry_signatures.rb new file mode 100644 index 0000000..bc3056c --- /dev/null +++ b/db/migrate/20261108010000_create_entry_signatures.rb @@ -0,0 +1,44 @@ +# Electronic signatures on logbook entries (AC 120-78B chapter 2): who signed, +# with which certificate, what they certified, when, how they authenticated, +# and a fingerprint of exactly what was signed. Corrections supersede an entry +# (2.2.8); disabled users can no longer sign (2.2.6.4). +class CreateEntrySignatures < ActiveRecord::Migration[8.1] + def change + create_table :entry_signatures do |t| + t.references :logbook_entry, null: false, foreign_key: true + t.references :user, foreign_key: { on_delete: :nullify } + t.string :signer_name, null: false + t.string :signer_email + t.string :certificate_kind, null: false + t.string :certificate_number, null: false + t.text :statement, null: false + t.datetime :signed_at, null: false + t.string :content_digest, null: false + t.text :content_snapshot, null: false + t.string :seal + t.string :auth_method, null: false + t.string :ip_address + t.string :user_agent + t.string :origin # set when imported from another system + t.timestamps + end + add_index :entry_signatures, :logbook_entry_id, unique: true, name: "index_entry_signatures_one_per_entry" + + add_reference :logbook_entries, :supersedes, foreign_key: { to_table: :logbook_entries, on_delete: :nullify } + add_column :logbook_entries, :superseded_at, :datetime + add_column :users, :disabled_at, :datetime + + create_table :signing_invitations do |t| + t.references :logbook_entry, null: false, foreign_key: { on_delete: :cascade } + t.references :invited_by, foreign_key: { to_table: :users, on_delete: :nullify } + t.references :user, foreign_key: { on_delete: :nullify } + t.string :email, null: false + t.string :token_digest, null: false + t.text :message + t.datetime :expires_at, null: false + t.datetime :used_at + t.timestamps + end + add_index :signing_invitations, :token_digest, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 560135e..16af44e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -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_000000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_08_010000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -375,6 +375,29 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_000000) do t.index ["document_collection_id"], name: "index_documents_on_document_collection_id" end + create_table "entry_signatures", force: :cascade do |t| + t.integer "logbook_entry_id", null: false + t.integer "user_id" + t.string "signer_name", null: false + t.string "signer_email" + t.string "certificate_kind", null: false + t.string "certificate_number", null: false + t.text "statement", null: false + t.datetime "signed_at", null: false + t.string "content_digest", null: false + t.text "content_snapshot", null: false + t.string "seal" + t.string "auth_method", null: false + t.string "ip_address" + t.string "user_agent" + t.string "origin" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["logbook_entry_id"], name: "index_entry_signatures_on_logbook_entry_id" + t.index ["logbook_entry_id"], name: "index_entry_signatures_one_per_entry", unique: true + t.index ["user_id"], name: "index_entry_signatures_on_user_id" + end + create_table "flight_logs", force: :cascade do |t| t.integer "aircraft_id", null: false t.integer "user_id" @@ -453,9 +476,12 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_000000) do t.integer "component_id" t.decimal "component_hours_at_entry", precision: 8, scale: 1 t.decimal "component_since_overhaul_at_entry", precision: 8, scale: 1 + t.integer "supersedes_id" + t.datetime "superseded_at" t.index ["aircraft_id"], name: "index_logbook_entries_on_aircraft_id" t.index ["component_id"], name: "index_logbook_entries_on_component_id" t.index ["document_id"], name: "index_logbook_entries_on_document_id" + t.index ["supersedes_id"], name: "index_logbook_entries_on_supersedes_id" end create_table "logbook_entry_parts", force: :cascade do |t| @@ -589,6 +615,23 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_000000) do t.index ["token"], name: "index_share_tokens_on_token", unique: true end + create_table "signing_invitations", force: :cascade do |t| + t.integer "logbook_entry_id", null: false + t.integer "invited_by_id" + t.integer "user_id" + t.string "email", null: false + t.string "token_digest", null: false + t.text "message" + t.datetime "expires_at", null: false + t.datetime "used_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["invited_by_id"], name: "index_signing_invitations_on_invited_by_id" + t.index ["logbook_entry_id"], name: "index_signing_invitations_on_logbook_entry_id" + t.index ["token_digest"], name: "index_signing_invitations_on_token_digest", unique: true + t.index ["user_id"], name: "index_signing_invitations_on_user_id" + end + create_table "squawks", force: :cascade do |t| t.integer "aircraft_id", null: false t.integer "component_id" @@ -632,6 +675,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_000000) do t.string "sso_uid" t.datetime "last_signed_in_at" t.boolean "reminder_emails", default: true, null: false + t.datetime "disabled_at" 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 @@ -684,6 +728,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_000000) do add_foreign_key "document_collections", "aircraft" add_foreign_key "documents", "aircraft" add_foreign_key "documents", "document_collections" + add_foreign_key "entry_signatures", "logbook_entries" + add_foreign_key "entry_signatures", "users", on_delete: :nullify add_foreign_key "flight_logs", "aircraft" add_foreign_key "flight_logs", "users", on_delete: :nullify add_foreign_key "inspection_records", "aircraft" @@ -694,6 +740,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_000000) do add_foreign_key "logbook_entries", "aircraft" add_foreign_key "logbook_entries", "components", on_delete: :nullify add_foreign_key "logbook_entries", "documents", on_delete: :nullify + add_foreign_key "logbook_entries", "logbook_entries", column: "supersedes_id", on_delete: :nullify add_foreign_key "logbook_entry_parts", "components", on_delete: :cascade add_foreign_key "logbook_entry_parts", "logbook_entries", on_delete: :cascade add_foreign_key "logbook_imports", "aircraft" @@ -710,6 +757,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_000000) do add_foreign_key "sessions", "users" add_foreign_key "share_tokens", "aircraft" add_foreign_key "share_tokens", "users", column: "created_by_id", on_delete: :nullify + add_foreign_key "signing_invitations", "logbook_entries", on_delete: :cascade + add_foreign_key "signing_invitations", "users", column: "invited_by_id", on_delete: :nullify + add_foreign_key "signing_invitations", "users", on_delete: :nullify add_foreign_key "squawks", "aircraft" add_foreign_key "squawks", "components", on_delete: :nullify add_foreign_key "squawks", "logbook_entries", on_delete: :nullify diff --git a/test/integration/electronic_signatures_test.rb b/test/integration/electronic_signatures_test.rb new file mode 100644 index 0000000..6125886 --- /dev/null +++ b/test/integration/electronic_signatures_test.rb @@ -0,0 +1,217 @@ +require "test_helper" +require "pdf-reader" + +# Electronic signatures on logbook entries, per AC 120-78B chapter 2. +class ElectronicSignaturesTest < ActionDispatch::IntegrationTest + include ActionMailer::TestHelper + + setup do + @owner = create_user("owner@example.com").tap { _1.update!(name: "Owen Owner") } + @mech = create_user("mech@example.com").tap { _1.update!(name: "Sam Mechanic") } + @a = create_aircraft(owner: @owner, pilot: @mech, tail_number: "N12345") + @ap = @mech.certificates.create!(kind: "AP", number: "7654321") + @entry = @a.logbook_entries.create!(date: Date.new(2026, 10, 1), log_type: "AC", entry_type: "MAINTENANCE", aircraft_hours_at_entry: 1000, + text: "Replaced left landing light lamp P/N 4509.", signoff_location: "KOQU") + 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) + end + + test "signing: review, certificate, password, confirmation; then the record shows who certified what and when" do + sign_in @mech + get aircraft_logbook_entry_path(@a, @entry) + assert_select "a[href='#{new_aircraft_logbook_entry_signature_path(@a, @entry)}']", text: "Sign" + get new_aircraft_logbook_entry_signature_path(@a, @entry) + assert_includes response.body, "Replaced left landing light lamp P/N 4509." + assert_includes response.body, "Certified by: “I certify that the work described in this entry was performed in accordance with 14 CFR Part 43" + + sign(confirm: "0") + assert_response :unprocessable_entity + assert_includes response.body, "Tick the box to confirm" + sign(password: "wrong") + assert_response :unprocessable_entity + assert_includes response.body, "Re-enter your password" + refute @entry.reload.signed? + + assert_emails 1 do + sign + end + assert_redirected_to aircraft_logbook_entry_path(@a, @entry) + sig = @entry.reload.signature + assert_equal [ "Sam Mechanic", "AP", "7654321", "password", @mech ], [ sig.signer_name, sig.certificate_kind, sig.certificate_number, sig.auth_method, sig.user ] + assert_equal [ "Sam Mechanic", "AP", "7654321" ], [ @entry.signoff_person, @entry.signoff_certificate_type, @entry.signoff_certificate_number ] + assert_equal [ @entry.content_digest, :valid ], [ sig.content_digest, sig.status ] + assert_equal "Replaced left landing light lamp P/N 4509.", JSON.parse(sig.content_snapshot)["text"] + assert_equal "You signed a logbook entry for N12345", ActionMailer::Base.deliveries.last.subject + assert_equal "Logbook entry signed electronically (2026-10-01)", @a.events.last.event_name + + get aircraft_logbook_entry_path(@a, @entry) + assert_includes response.body, "Certified by Sam Mechanic, A&P 7654321" + assert_includes response.body, "Status: Valid" + sign + assert_response :unprocessable_entity # once only + assert_includes response.body, "already signed" + end + + test "signed entries are locked; tampering shows; edits go in a correction that supersedes the original" do + sign_in @mech + engine = create_component(@a, component_type: component_type("Engine")) + filter = create_component(@a, component_type: component_type("Filter element"), parent_component: engine) + @entry.update!(component: engine, component_hours_at_entry: 500) + @entry.parts.create!(component: filter, hours_at_entry: 10) + sign + sign_in @owner + get edit_aircraft_logbook_entry_path(@a, @entry) + assert_redirected_to aircraft_logbook_entry_path(@a, @entry) + patch aircraft_logbook_entry_path(@a, @entry), params: { logbook_entry: { text: "Changed" } } + delete aircraft_logbook_entry_path(@a, @entry) + assert_equal "Replaced left landing light lamp P/N 4509.", @entry.reload.text + refute @entry.update(text: "Changed in the console") + refute @entry.reload.destroy + refute @entry.parts.first.update(hours_at_entry: 99) + assert @entry.update(verified: false, page_number: 3) # not part of what was signed + assert_raises(ActiveRecord::RecordNotSaved) { @entry.signature.update!(statement: "Different") } + + LogbookEntry.where(id: @entry.id).update_all(text: "Edited behind the app's back") + assert_equal :altered, @entry.reload.signature.status + LogbookEntry.where(id: @entry.id).update_all(text: "Replaced left landing light lamp P/N 4509.") + EntrySignature.where(id: @entry.signature.id).update_all(certificate_number: "0000000") + assert_equal :altered, @entry.reload.signature.status # the seal covers the signature too + EntrySignature.where(id: @entry.signature.id).update_all(certificate_number: "7654321") + assert_equal :valid, @entry.reload.signature.status + + get aircraft_logbook_entry_path(@a, @entry) + assert_select "a[href='#{new_aircraft_logbook_entry_path(@a, supersedes: @entry.id)}']", text: "Correct this entry" + get new_aircraft_logbook_entry_path(@a, supersedes: @entry.id) + assert_select "input[name='logbook_entry[supersedes_id]'][value='#{@entry.id}']" + assert_select "textarea[name='logbook_entry[text]']", text: "Replaced left landing light lamp P/N 4509." + post aircraft_logbook_entries_path(@a), params: { logbook_entry: { + supersedes_id: @entry.id, date: "2026-10-01", log_type: "AC", entry_type: "MAINTENANCE", aircraft_hours_at_entry: 1000, + text: "Replaced left landing light lamp P/N 4509-24." } } + correction = @a.logbook_entries.find_by!(supersedes: @entry) + refute @entry.reload.superseded? # until the correction is signed + + sign_in @mech + sign(correction) + assert @entry.reload.superseded? + assert_equal [ :superseded, :valid ], [ @entry.signature.status, correction.reload.signature.status ] + assert_equal @entry.signature.content_digest, JSON.parse(correction.signature.content_snapshot).dig("supersedes", "fingerprint") + get new_aircraft_logbook_entry_path(@a, supersedes: @entry.id) + assert_select "input[name='logbook_entry[supersedes_id]']", 0 # can't be corrected twice + end + + test "who and what can sign" do + pilot_cert = @owner.certificates.create!(kind: "PILOT", number: "1111111") + expired = @mech.certificates.create!(kind: "IA", number: "7654321", expires_on: 1.day.ago.to_date) + inspection = @a.logbook_entries.create!(date: Date.current, entry_type: "INSPECTION", text: "Annual per App. D", aircraft_hours_at_entry: 1000) + assert_includes inspection.signing_problems(@ap), "an inspection entry needs its result (airworthy, or discrepancy list)" + inspection.update!(inspection_result: "approved") + assert_empty inspection.signing_problems(@ap) + assert_includes inspection.signing_problems(pilot_cert), "a pilot certificate can sign preventive maintenance only" + assert_includes inspection.signing_problems(expired), "that certificate has expired" + assert_match "inspected in accordance with an annual inspection and was determined to be in airworthy condition", inspection.certification_statement("IA") + 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" } + assert_includes response.body, "That certificate isn'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" } + assert_equal "This account is disabled.", flash[:alert] + end + + test "single sign-on users sign after signing in again" do + saved = %w[OIDC_ISSUER OIDC_CLIENT_ID].to_h { [ _1, ENV[_1] ] } + ENV.update("OIDC_ISSUER" => "https://auth.example.com/", "OIDC_CLIENT_ID" => "sam") + OmniAuth.config.test_mode = true + OmniAuth.config.mock_auth[:oidc] = OmniAuth::AuthHash.new(provider: "oidc", uid: "sub-mech", info: { email: "mech@example.com" }) + @mech.update!(sso_uid: "sub-mech") + sign_in @mech + get new_aircraft_logbook_entry_signature_path(@a, @entry) + assert_select "form[action='/auth/oidc'] input[name=prompt][value=login]" + post aircraft_logbook_entry_signature_path(@a, @entry), params: { certificate_id: @ap.id, confirm: "1" } + assert_response :unprocessable_entity # not signed in again yet + + post "/auth/oidc", params: { prompt: "login" } + follow_redirect! + assert_redirected_to new_aircraft_logbook_entry_signature_path(@a, @entry) + post aircraft_logbook_entry_signature_path(@a, @entry), params: { certificate_id: @ap.id, confirm: "1" } + assert_equal "sso", @entry.reload.signature.auth_method + ensure + saved.each { ENV[_1] = _2 } + OmniAuth.config.mock_auth[:oidc] = nil + OmniAuth.config.test_mode = false + end + + test "an owner invites an outside mechanic, who signs that one entry with their own account" do + sign_in @mech + get new_aircraft_logbook_entry_signing_invitation_path(@a, @entry) + assert_redirected_to aircraft_path(@a) # owners only + + sign_in @owner + assert_emails 1 do + perform_enqueued_jobs do + post aircraft_logbook_entry_signing_invitations_path(@a, @entry), params: { signing_invitation: { email: "Outside@Example.com", message: "Thanks!" } } + end + end + mail = ActionMailer::Base.deliveries.last + assert_equal [ "outside@example.com" ], mail.to + path = mail.text_part.body.to_s[%r{http://example\.com(/sign/[\w-]+)}, 1] + delete session_path + + get path + assert_includes response.body, "sign in as outside@example.com" + post "#{path}/account", params: { name: "Olive Outside", password: "longpassword1", password_confirmation: "longpassword1" } + assert_redirected_to path + follow_redirect! + assert_select "form[action='#{certificates_path(return_to: path)}']" # add a certificate first + post certificates_path(return_to: path), params: { user_certificate: { kind: "IA", number: "2222222" } } + assert_redirected_to path + outside = User.find_by!(email_address: "outside@example.com") + get aircraft_path(@a) + assert_response :not_found # no access to the aircraft itself + + post path, params: { certificate_id: outside.certificates.sole.id, password: "longpassword1", confirm: "1" } + assert_redirected_to path + sig = @entry.reload.signature + assert_equal [ "Olive Outside", "IA", "2222222", outside ], [ sig.signer_name, sig.certificate_kind, sig.certificate_number, sig.user ] + follow_redirect! + assert_includes response.body, "Entry signed" + + sign_in @owner # someone else with the link: it's spent + get path + assert_response :not_found + end + + test "printouts, archives and accounts" do + sign_in @mech + sign + get aircraft_logbook_print_path(@a, format: :pdf), params: { ids: [ @entry.id ], layout: "letter" } + text = PDF::Reader.new(StringIO.new(response.body)).pages.map(&:text).join(" ").gsub(/\s+/, " ") + assert_includes text, "Certified by Sam Mechanic, A&P 7654321" + assert_includes text, "fingerprint #{@entry.signature.content_digest.first(16)}" + assert_includes text, "I certify that the work described in this entry was performed in accordance with 14 CFR Part 43" + + path = File.join(Dir.mktmpdir, "a.sam.zip") + AircraftArchive::Exporter.new(@a, source: "sam.example.com").write_to(path) + copy = AircraftArchive::Importer.new(path, owner: @owner, tail_number: "N54321").run[:aircraft] + imported = copy.logbook_entries.sole.signature + assert_equal [ "Sam Mechanic", "sam.example.com", true ], [ imported.signer_name, imported.origin, imported.imported? ] + assert copy.logbook_entries.sole.signed? + + admin = create_user("admin@example.com", admin: true) + sign_in admin + delete admin_user_path(@mech) + assert_match "disable the account instead", flash[:alert] + patch disable_admin_user_path(@mech) + assert @mech.reload.disabled? + assert_equal :valid, @entry.reload.signature.status # their signatures stay + patch enable_admin_user_path(@mech) + refute @mech.reload.disabled? + end +end