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 @@
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. %> +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 %> ++ 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 %> + + <% if Sso.password_login? || !current_user.sso_uid? %> +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? %>
+<%= fresh ? "Signed in again with #{Sso.label}: you can sign now." : "Or sign in again with #{Sso.label} first (button below the form)." %>
+ <% end %> + +Ask the aircraft's owner to send a new one.
+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 %>.
+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" %> ++ 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? %>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? %>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| %> +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 %> +