Records integrity: history, nightly backup and check, records package

AC 120-78B chapter 3:
- Every change to logbook entries, sub-components, signatures, inspection
  records, AD compliance, major records, W&B, components, squawks and
  documents is kept as a RecordVersion (who, IP, when, field changes),
  hash-chained per aircraft; versions can't be edited or deleted. Shown on
  each logbook entry and in Activity -> Record history
- Nightly job: SQLite online-backup copy to storage/backups, verified
  (integrity_check + record counts), pruned to the configured number; then
  an integrity check of the history chains and every signature's seal and
  fingerprint. Results on Admin -> About ("Back up and check now"); admins
  are emailed on failure
- Software versions recorded (first/last seen) on Admin -> About
- Records package (Access & Sharing): logbook entries PDF with signatures,
  signatures.csv, record-history.csv, self-contained status report HTML,
  the .sam.zip, and a README, for the FAA/NTSB or a buyer
- Legacy (paper) records: documents can be marked as legacy records;
  aircraft have an "electronic records since" date (status report, package)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-07 13:21:26 -05:00
1 parent d719f663bc
commit 68a1719db2
53 files changed
+750 -12

No files matched your search

+3
View File
@@ -85,6 +85,8 @@ for db in storage/production*.sqlite3; do sqlite3 "$db" ".backup 'backup/$(basen
rsync -aH --exclude '*.sqlite3*' storage/ backup/ # uploaded files (-H keeps the hard links that store duplicates once) rsync -aH --exclude '*.sqlite3*' storage/ backup/ # uploaded files (-H keeps the hard links that store duplicates once)
``` ```
The app also makes a verified copy of the main database every night in `storage/backups` (Admin → About shows the last one), so a backup of the storage volume always contains a consistent database snapshot.
Alternatively, stop the container and copy the volume. Alternatively, stop the container and copy the volume.
To back up or move a single aircraft with all its files, use **Access & Sharing → Download .sam.zip** (or `bin/rails "sam:export[N12345]"`). Import it from **Fleet → Import** (or `bin/rails "sam:import[file.sam.zip,owner@example.com]"`). The archive format is the original Simple Aircraft Manager's, so archives move between the two apps. To back up or move a single aircraft with all its files, use **Access & Sharing → Download .sam.zip** (or `bin/rails "sam:export[N12345]"`). Import it from **Fleet → Import** (or `bin/rails "sam:import[file.sam.zip,owner@example.com]"`). The archive format is the original Simple Aircraft Manager's, so archives move between the two apps.
@@ -107,6 +109,7 @@ To back up or move a single aircraft with all its files, use **Access & Sharing
| 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. | | 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…). | | 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. | | 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. |
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer. Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
| Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. | | 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. | | 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. | | 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. |
+12 -1
View File
@@ -1,11 +1,22 @@
class Admin::AboutController < ApplicationController class Admin::AboutController < ApplicationController
before_action :require_admin! before_action :require_admin!
rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder], with: -> { redirect_to admin_about_path, alert: "Try again in a minute." } rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder check_records], with: -> { redirect_to admin_about_path, alert: "Try again in a minute." }
def show def show
@info = SystemInfo.new @info = SystemInfo.new
end end
# Back up and verify the records now (normally nightly).
def check_records
backup = DatabaseBackup.run!
check = RecordsIntegrity.check!
if backup.ok && check.ok
redirect_to admin_about_path(anchor: "records"), notice: "Backed up and checked: no problems found."
else
redirect_to admin_about_path(anchor: "records"), alert: "The records check found problems; see Records below."
end
end
# This week's reminder for the current admin, now. # This week's reminder for the current admin, now.
def test_reminder def test_reminder
return redirect_to(admin_about_path, alert: "Email isn't set up yet.") unless MailSettings.configured? return redirect_to(admin_about_path, alert: "Email isn't set up yet.") unless MailSettings.configured?
+3 -3
View File
@@ -2,18 +2,18 @@ class Admin::SettingsController < ApplicationController
before_action :require_admin! before_action :require_admin!
def edit def edit
@values = { "max_upload_mb" => Setting.max_upload_mb } @values = { "max_upload_mb" => Setting.max_upload_mb, "backups_kept" => Setting.integer("backups_kept") }
end end
def update def update
submitted = params.fetch(:settings, {}).permit(:max_upload_mb).to_h submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept).to_h
records = Setting.update_integers(submitted) records = Setting.update_integers(submitted)
@errors = records.flat_map { _1.errors.full_messages } @errors = records.flat_map { _1.errors.full_messages }
if @errors.empty? if @errors.empty?
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}") Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
redirect_to edit_admin_settings_path, notice: "Settings saved." redirect_to edit_admin_settings_path, notice: "Settings saved."
else else
@values = { "max_upload_mb" => Setting.max_upload_mb }.merge(submitted) @values = { "max_upload_mb" => Setting.max_upload_mb, "backups_kept" => Setting.integer("backups_kept") }.merge(submitted)
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
end end
+1 -1
View File
@@ -68,7 +68,7 @@ class AircraftController < ApplicationController
params.require(:aircraft).permit( params.require(:aircraft).permit(
:tail_number, :make, :model, :serial_number, :description, :purchased, :status, :tail_number, :make, :model, :serial_number, :description, :purchased, :status,
:tach_time, :tach_time_offset, :hobbs_time, :hobbs_time_offset, :tach_time, :tach_time_offset, :hobbs_time, :hobbs_time_offset,
:airworthiness_enforcement, :picture, :icao_type, :time_basis :airworthiness_enforcement, :picture, :icao_type, :time_basis, :electronic_records_since
) )
end end
end end
@@ -4,6 +4,7 @@ class ApplicationController < ActionController::Base
allow_browser versions: :modern allow_browser versions: :modern
prepend_before_action :redirect_to_setup prepend_before_action :redirect_to_setup
before_action { Current.ip_address = request.remote_ip } # for record history
helper_method :current_user helper_method :current_user
rescue_from ActiveRecord::RecordNotFound do rescue_from ActiveRecord::RecordNotFound do
+1 -1
View File
@@ -126,7 +126,7 @@ class DocumentsController < ApplicationController
def set_document = @document = @aircraft.documents.find(params[:id]) def set_document = @document = @aircraft.documents.find(params[:id])
def document_params def document_params
p = params.require(:document).permit(:name, :description, :doc_type, :visibility, :document_collection_id, :expires_on, pages: []) p = params.require(:document).permit(:name, :description, :doc_type, :visibility, :document_collection_id, :expires_on, :legacy_record, pages: [])
p[:pages]&.compact_blank! p[:pages]&.compact_blank!
p.delete(:pages) if p[:pages].blank? p.delete(:pages) if p[:pages].blank?
p[:document_collection_id] = scoped_id(@aircraft.document_collections, p[:document_collection_id]) p[:document_collection_id] = scoped_id(@aircraft.document_collections, p[:document_collection_id])
@@ -0,0 +1,12 @@
# Every change to the aircraft's maintenance records (AC 120-78B 3.2.2).
class RecordVersionsController < ApplicationController
include AircraftScoped
def index
@type = params[:type].presence_in(RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type))
scope = RecordVersion.where(aircraft_id: @aircraft.id).order(id: :desc).includes(:user)
scope = scope.where(item_type: @type) if @type
@versions = scope.limit(500)
@types = RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type).sort
end
end
@@ -0,0 +1,16 @@
# Download every record of an aircraft in one ZIP (owners).
class RecordsPackagesController < ApplicationController
include AircraftScoped
before_action :require_owner!
def show
package = RecordsPackage.new(@aircraft, source: request.host)
dir = Rails.root.join("tmp", "packages")
FileUtils.mkdir_p(dir)
Dir[dir.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago }
path = dir.join("#{SecureRandom.hex(12)}.zip").to_s
package.write_to(path)
log_event("aircraft", "Records package downloaded")
send_file path, filename: package.filename, type: "application/zip", disposition: "attachment"
end
end
+1 -1
View File
@@ -15,7 +15,7 @@ module AircraftHelper
[ "Major Records", aircraft_major_records_path(aircraft), %w[major_records] ], [ "Major Records", aircraft_major_records_path(aircraft), %w[major_records] ],
[ "W&B", aircraft_weight_balance_records_path(aircraft), %w[weight_balance_records loading_setups] ], [ "W&B", aircraft_weight_balance_records_path(aircraft), %w[weight_balance_records loading_setups] ],
[ "Notes", aircraft_notes_path(aircraft), %w[notes] ], [ "Notes", aircraft_notes_path(aircraft), %w[notes] ],
[ "Activity", aircraft_events_path(aircraft), %w[events] ], [ "Activity", aircraft_events_path(aircraft), %w[events record_versions] ],
([ "Access & Sharing", aircraft_aircraft_roles_path(aircraft), %w[aircraft_roles share_tokens] ] if owner?) ([ "Access & Sharing", aircraft_aircraft_roles_path(aircraft), %w[aircraft_roles share_tokens] ] if owner?)
].compact ].compact
end end
+13
View File
@@ -0,0 +1,13 @@
# Nightly: back up the database, then verify the records. Admins are emailed
# if either fails.
class RecordsIntegrityJob < ApplicationJob
queue_as :default
def perform
backup = DatabaseBackup.run!
check = RecordsIntegrity.check!
return if backup.ok && check.ok
return unless MailSettings.configured?
User.active.where(admin: true).find_each { AdminMailer.records_alert(_1, backup, check).deliver_now }
end
end
+6
View File
@@ -1,4 +1,10 @@
class AdminMailer < ApplicationMailer class AdminMailer < ApplicationMailer
def records_alert(user, backup, check)
@backup = backup
@check = check
mail subject: "Records check needs attention", to: user.email_address
end
def test_email(user) def test_email(user)
@user = user @user = user
mail subject: "Test email from Simple Aircraft Manager", to: user.email_address mail subject: "Test email from Simple Aircraft Manager", to: user.email_address
+1
View File
@@ -1,4 +1,5 @@
class AdCompliance < ApplicationRecord class AdCompliance < ApplicationRecord
include Versioned
# Method of compliance, recorded per 91.417(a)(2)(v). # Method of compliance, recorded per 91.417(a)(2)(v).
METHODS = { METHODS = {
"inspection" => "Inspection", "inspection" => "Inspection",
+18
View File
@@ -0,0 +1,18 @@
# Which software versions have run, and when (AC 120-78B 3.2.6): recorded
# when the app starts and by the nightly check.
class AppRevision < ApplicationRecord
scope :latest_first, -> { order(first_seen_at: :desc) }
def self.touch_current!
revision = SystemInfo.new.revision
return if revision.blank? || revision == "unknown"
now = Time.current
record = find_or_initialize_by(revision: revision)
record.first_seen_at ||= now
record.built_at ||= SystemInfo.new.built_at
record.last_seen_at = now
record.save!
rescue ActiveRecord::ActiveRecordError => e
Rails.logger.warn("[app revisions] #{e.class}: #{e.message}")
end
end
+5
View File
@@ -0,0 +1,5 @@
class BackupRun < ApplicationRecord
scope :latest_first, -> { order(created_at: :desc) }
def self.latest = latest_first.first
def self.last_good = where(ok: true).latest_first.first
end
+1
View File
@@ -1,4 +1,5 @@
class Component < ApplicationRecord class Component < ApplicationRecord
include Versioned
STATUSES = { "SPARE" => "Spare Part", "IN-USE" => "In Service", "DISPOSED" => "Disposed" }.freeze STATUSES = { "SPARE" => "Spare Part", "IN-USE" => "In Service", "DISPOSED" => "Disposed" }.freeze
# What "since overhaul" counts from, and how logbooks abbreviate it. # What "since overhaul" counts from, and how logbooks abbreviate it.
OVERHAUL_KINDS = { "major" => "Major overhaul", "factory_overhaul" => "Factory overhaul", "factory_new" => "Factory new or rebuilt (zero time)" }.freeze OVERHAUL_KINDS = { "major" => "Major overhaul", "factory_overhaul" => "Factory overhaul", "factory_new" => "Factory new or rebuilt (zero time)" }.freeze
+26
View File
@@ -0,0 +1,26 @@
# Keeps every change to the record as a RecordVersion (AC 120-78B 3.2.2):
# full values on create and destroy, [before, after] for each changed field.
module Versioned
extend ActiveSupport::Concern
IGNORED = %w[created_at updated_at].freeze
included do
has_many :versions, -> { chronological }, as: :item, class_name: "RecordVersion", inverse_of: false
after_create { record_version!("create", attributes.except(*IGNORED)) }
after_update { (c = saved_changes.except(*IGNORED)).any? && record_version!("update", c) }
after_destroy { record_version!("destroy", attributes.except(*IGNORED)) }
end
private
def record_version!(event, changes)
RecordVersion.append!(item: self, aircraft_id: versioned_aircraft_id, event: event, changes: changes.as_json)
end
def versioned_aircraft_id
return aircraft_id if has_attribute?(:aircraft_id) && aircraft_id
return component&.aircraft_id if respond_to?(:component)
logbook_entry&.aircraft_id if respond_to?(:logbook_entry)
end
end
+1 -1
View File
@@ -1,4 +1,4 @@
class Current < ActiveSupport::CurrentAttributes class Current < ActiveSupport::CurrentAttributes
attribute :session attribute :session, :ip_address
delegate :user, to: :session, allow_nil: true delegate :user, to: :session, allow_nil: true
end end
+1
View File
@@ -1,4 +1,5 @@
class Document < ApplicationRecord class Document < ApplicationRecord
include Versioned
include UploadValidation include UploadValidation
TYPES = { TYPES = {
+1
View File
@@ -6,6 +6,7 @@
# so any later change shows; seal is an HMAC over the signature itself, keyed # 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. # by this server, so the signature record can't be altered unnoticed either.
class EntrySignature < ApplicationRecord class EntrySignature < ApplicationRecord
include Versioned
AUTH_METHODS = { "password" => "password re-entered", "sso" => "single sign-on, signed in again" }.freeze AUTH_METHODS = { "password" => "password re-entered", "sso" => "single sign-on, signed in again" }.freeze
# "Certified by" conveys the intent to sign (2.2.2). # "Certified by" conveys the intent to sign (2.2.2).
LABEL = "Certified by".freeze LABEL = "Certified by".freeze
+1
View File
@@ -1,4 +1,5 @@
class InspectionRecord < ApplicationRecord class InspectionRecord < ApplicationRecord
include Versioned
belongs_to :inspection_type belongs_to :inspection_type
belongs_to :aircraft, optional: true belongs_to :aircraft, optional: true
belongs_to :component, optional: true belongs_to :component, optional: true
+4
View File
@@ -0,0 +1,4 @@
class IntegrityCheck < ApplicationRecord
scope :latest_first, -> { order(created_at: :desc) }
def self.latest = latest_first.first
end
+1
View File
@@ -1,4 +1,5 @@
class LogbookEntry < ApplicationRecord class LogbookEntry < ApplicationRecord
include Versioned
LOG_TYPES = { "AC" => "Aircraft", "ENG" => "Engine", "PROP" => "Propeller", "OTHER" => "Other" }.freeze LOG_TYPES = { "AC" => "Aircraft", "ENG" => "Engine", "PROP" => "Propeller", "OTHER" => "Other" }.freeze
ENTRY_TYPES = { ENTRY_TYPES = {
"MAINTENANCE" => "Maintenance", "INSPECTION" => "Inspection", "FLIGHT" => "Flight", "MAINTENANCE" => "Maintenance", "INSPECTION" => "Inspection", "FLIGHT" => "Flight",
+1
View File
@@ -1,6 +1,7 @@
# A sub-component a logbook entry also covers (the oil filter on the engine…) # A sub-component a logbook entry also covers (the oil filter on the engine…)
# and its times at the entry. # and its times at the entry.
class LogbookEntryPart < ApplicationRecord class LogbookEntryPart < ApplicationRecord
include Versioned
belongs_to :logbook_entry belongs_to :logbook_entry
belongs_to :component belongs_to :component
+1
View File
@@ -1,4 +1,5 @@
class MajorRecord < ApplicationRecord class MajorRecord < ApplicationRecord
include Versioned
RECORD_TYPES = { "repair" => "Major Repair", "alteration" => "Major Alteration" }.freeze RECORD_TYPES = { "repair" => "Major Repair", "alteration" => "Major Alteration" }.freeze
belongs_to :aircraft belongs_to :aircraft
+30
View File
@@ -0,0 +1,30 @@
# One change to a maintenance record (create, update, destroy), kept for
# good (AC 120-78B 3.2.2). Each aircraft's versions form a hash chain:
# chain_hash = SHA-256(prev_hash + payload), so deleting, reordering or
# editing a version breaks the chain and the nightly check reports it.
class RecordVersion < ApplicationRecord
belongs_to :user, optional: true
scope :chronological, -> { order(:id) }
before_update { throw :abort }
before_destroy { throw :abort }
def self.digest(prev_hash, payload) = OpenSSL::Digest::SHA256.hexdigest("#{prev_hash}\n#{payload}")
def self.append!(item:, aircraft_id:, event:, changes:)
now = Time.current
payload = { "item_type" => item.class.name, "item_id" => item.id, "event" => event, "changes" => changes,
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }.to_json
prev = where(aircraft_id: aircraft_id).order(:id).last&.chain_hash
create!(aircraft_id: aircraft_id, item_type: item.class.name, item_id: item.id, event: event, user_id: Current.user&.id,
ip_address: Current.ip_address, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
end
def changes_hash = JSON.parse(payload)["changes"]
# Field names changed by this version (for display).
def changed_fields
event == "update" ? changes_hash.keys : []
end
end
+1
View File
@@ -7,6 +7,7 @@
class Setting < ApplicationRecord class Setting < ApplicationRecord
INTEGERS = { INTEGERS = {
"max_upload_mb" => { default: 50, in: 1..1024, label: "Maximum upload size (MB)" }, "max_upload_mb" => { default: 50, in: 1..1024, label: "Maximum upload size (MB)" },
"backups_kept" => { default: 14, in: 1..365, label: "Database backups kept" },
"logbook_templates_seeded" => { default: 0, in: 0..1, label: "Built-in logbook templates added" } # internal flag "logbook_templates_seeded" => { default: 0, in: 0..1, label: "Built-in logbook templates added" } # internal flag
}.freeze }.freeze
+1
View File
@@ -1,4 +1,5 @@
class Squawk < ApplicationRecord class Squawk < ApplicationRecord
include Versioned
include UploadValidation include UploadValidation
PRIORITIES = { 0 => "Ground Aircraft", 1 => "Fix Soon", 2 => "Fix at Next Inspection", 3 => "Fix Eventually" }.freeze PRIORITIES = { 0 => "Ground Aircraft", 1 => "Fix Soon", 2 => "Fix at Next Inspection", 3 => "Fix Eventually" }.freeze
+1
View File
@@ -2,6 +2,7 @@
# date, usually after weighing or an equipment change (each alteration that # date, usually after weighing or an equipment change (each alteration that
# changes them needs a new one; its 337 can be linked). # changes them needs a new one; its 337 can be linked).
class WeightBalanceRecord < ApplicationRecord class WeightBalanceRecord < ApplicationRecord
include Versioned
belongs_to :aircraft belongs_to :aircraft
belongs_to :major_record, optional: true belongs_to :major_record, optional: true
belongs_to :document, optional: true belongs_to :document, optional: true
+2 -2
View File
@@ -50,7 +50,7 @@ module AircraftArchive
end, end,
documents: a.documents.map do |d| documents: a.documents.map do |d|
{ id: id(d), aircraft_id: id(a), collection_id: id(d.document_collection_id), doc_type: d.doc_type, name: d.name, { id: id(d), aircraft_id: id(a), collection_id: id(d.document_collection_id), doc_type: d.doc_type, name: d.name,
description: d.description, visibility: d.visibility, expires_on: d.expires_on&.iso8601, components: [] } description: d.description, visibility: d.visibility, expires_on: d.expires_on&.iso8601, legacy_record: d.legacy_record, components: [] }
end, end,
document_images: a.documents.includes(pages_attachments: :blob).flat_map do |d| 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") } } d.pages.map { |page| { id: id(page), document_id: id(d), notes: "", image: file(page, "health/documents") } }
@@ -125,7 +125,7 @@ module AircraftArchive
def aircraft_hash(a) def aircraft_hash(a)
{ id: id(a), tail_number: a.tail_number, make: a.make, model: a.model, serial_number: a.serial_number, { id: id(a), tail_number: a.tail_number, make: a.make, model: a.model, serial_number: a.serial_number,
description: a.description, purchased: a.purchased&.iso8601, status: a.status, time_basis: a.time_basis, description: a.description, purchased: a.purchased&.iso8601, status: a.status, time_basis: a.time_basis, electronic_records_since: a.electronic_records_since&.iso8601,
loading_stations: a.loading_stations, cg_envelope: a.cg_envelope, ad_watch_terms: a.ad_watch_terms, tach_time: dec(a.tach_time), loading_stations: a.loading_stations, cg_envelope: a.cg_envelope, ad_watch_terms: a.ad_watch_terms, tach_time: dec(a.tach_time),
tach_time_offset: dec(a.tach_time_offset), hobbs_time: dec(a.hobbs_time), hobbs_time_offset: dec(a.hobbs_time_offset), tach_time_offset: dec(a.tach_time_offset), hobbs_time: dec(a.hobbs_time), hobbs_time_offset: dec(a.hobbs_time_offset),
picture: file(a.picture, "aircraft_pictures"), icao_type: a.icao_type } picture: file(a.picture, "aircraft_pictures"), icao_type: a.icao_type }
+2 -1
View File
@@ -143,6 +143,7 @@ module AircraftArchive
make: a["make"].to_s, model: a["model"].to_s, serial_number: a["serial_number"].to_s, description: a["description"].to_s, make: a["make"].to_s, model: a["model"].to_s, serial_number: a["serial_number"].to_s, description: a["description"].to_s,
purchased: date(a["purchased"]), status: Aircraft::STATUSES.key?(a["status"]) ? a["status"] : "AVAILABLE", purchased: date(a["purchased"]), status: Aircraft::STATUSES.key?(a["status"]) ? a["status"] : "AVAILABLE",
time_basis: Aircraft::TIME_BASES.key?(a["time_basis"]) ? a["time_basis"] : "tach", time_basis: Aircraft::TIME_BASES.key?(a["time_basis"]) ? a["time_basis"] : "tach",
electronic_records_since: date(a["electronic_records_since"]),
loading_stations: a["loading_stations"].is_a?(Hash) ? a["loading_stations"] : nil, loading_stations: a["loading_stations"].is_a?(Hash) ? a["loading_stations"] : nil,
cg_envelope: a["cg_envelope"].is_a?(Array) ? a["cg_envelope"] : nil, ad_watch_terms: a["ad_watch_terms"].to_s.first(500).presence, cg_envelope: a["cg_envelope"].is_a?(Array) ? a["cg_envelope"] : nil, ad_watch_terms: a["ad_watch_terms"].to_s.first(500).presence,
tach_time: num(a["tach_time"] || a["flight_time"]) || 0, tach_time_offset: num(a["tach_time_offset"]) || 0, tach_time: num(a["tach_time"] || a["flight_time"]) || 0, tach_time_offset: num(a["tach_time_offset"]) || 0,
@@ -207,7 +208,7 @@ module AircraftArchive
d = @aircraft.documents.new(name: data["name"].to_s.presence || "Untitled", description: data["description"].to_s, d = @aircraft.documents.new(name: data["name"].to_s.presence || "Untitled", description: data["description"].to_s,
doc_type: data["doc_type"].presence, visibility: visibility(data["visibility"]), doc_type: data["doc_type"].presence, visibility: visibility(data["visibility"]),
document_collection_id: @map[:collection][data["collection_id"].to_s], document_collection_id: @map[:collection][data["collection_id"].to_s],
expires_on: date(data["expires_on"])) expires_on: date(data["expires_on"]), legacy_record: data["legacy_record"] == true)
d.doc_type = "OTHER" unless Document::TYPES.key?(d.doc_type) d.doc_type = "OTHER" unless Document::TYPES.key?(d.doc_type)
d.save!(validate: false) d.save!(validate: false)
@map[:document][data["id"].to_s] = d.id @map[:document][data["id"].to_s] = d.id
+57
View File
@@ -0,0 +1,57 @@
# Built-in backup of the main database (AC 120-78B 3.2.7): a consistent
# snapshot (SQLite's online backup API, safe while the app runs) in storage/backups,
# checked by opening it and running SQLite's integrity check, and the newest
# few kept. Uploaded files aren't copied (they're already in storage/ and,
# being deduplicated, cheap to back up with the rest of the volume).
class DatabaseBackup
DIR = Rails.root.join("storage", "backups")
def self.run! = new.run!
def run!
FileUtils.mkdir_p(DIR)
path = DIR.join("sam-#{Time.current.utc.strftime('%Y%m%d-%H%M%S')}.sqlite3")
copy(path)
message = verify(path)
bytes = File.size(path)
prune(keep_path: path)
BackupRun.create!(ok: true, path: path.to_s, bytes: bytes, message: message)
rescue StandardError => e
Rails.logger.error("[backup] #{e.class}: #{e.message}")
BackupRun.create!(ok: false, path: path&.to_s, message: "#{e.class.name.demodulize}: #{e.message}".truncate(500))
end
private
def copy(path)
source = ActiveRecord::Base.connection.raw_connection
dest = SQLite3::Database.new(path.to_s)
backup = SQLite3::Backup.new(dest, "main", source, "main")
result = backup.step(-1)
backup.finish
raise "the database was busy (SQLite code #{result}); try again" unless result == SQLite3::Constants::ErrorCode::DONE
ensure
dest&.close
end
# Opens the copy and checks it: SQLite's integrity check, and the same
# number of logbook entries and signatures as the live database.
def verify(path)
db = SQLite3::Database.new(path.to_s, readonly: true)
result = db.get_first_value("PRAGMA integrity_check")
raise "integrity check failed: #{result}" unless result == "ok"
counts = %w[logbook_entries entry_signatures].map { |t| [ t, db.get_first_value("SELECT COUNT(*) FROM #{t}") ] }.to_h
live = { "logbook_entries" => LogbookEntry.count, "entry_signatures" => EntrySignature.count }
raise "record counts differ (#{counts} vs #{live})" unless counts == live
"Verified: SQLite integrity check ok; #{counts['logbook_entries']} logbook entries, #{counts['entry_signatures']} signatures"
ensure
db&.close
end
# Keeps the newest few (by file time), always including the one just made.
def prune(keep_path:)
keep = Setting.integer("backups_kept")
older = Dir[DIR.join("sam-*.sqlite3")].reject { _1 == keep_path.to_s }.sort_by { File.mtime(_1) }.reverse
older.drop(keep - 1).each { File.delete(_1) }
end
end
+31
View File
@@ -0,0 +1,31 @@
# Verifies the records (AC 120-78B 3.2.2 / 3.2.4 / 3.2.8.5.3): each
# aircraft's history chain is unbroken, and every signature's seal and
# fingerprint still match. The result is kept as an IntegrityCheck.
class RecordsIntegrity
def self.check! = new.check!
def check!
problems = []
versions = 0
RecordVersion.distinct.pluck(:aircraft_id).each do |aircraft_id|
prev = nil
RecordVersion.where(aircraft_id: aircraft_id).chronological.find_each do |v|
versions += 1
tail = Aircraft.find_by(id: aircraft_id)&.tail_number || "aircraft #{aircraft_id.inspect}"
problems << "#{tail}: history entry #{v.id} doesn't follow the one before it (missing or reordered history)" if v.prev_hash != prev
problems << "#{tail}: history entry #{v.id} was altered" if v.chain_hash != RecordVersion.digest(v.prev_hash, v.payload)
prev = v.chain_hash
end
end
signatures = 0
EntrySignature.includes(logbook_entry: [ :aircraft, :parts ]).find_each do |sig|
signatures += 1
next if sig.imported? || sig.status != :altered
entry = sig.logbook_entry
problems << "#{entry.aircraft.tail_number}: the #{entry.date} logbook entry (signed by #{sig.signer_name}) " \
"#{sig.seal_valid? ? 'changed after it was signed' : 'has an altered signature'}"
end
AppRevision.touch_current!
IntegrityCheck.create!(ok: problems.empty?, versions_checked: versions, signatures_checked: signatures, problems: problems.first(200))
end
end
+100
View File
@@ -0,0 +1,100 @@
require "csv"
# Everything about an aircraft's records in one ZIP, for the FAA or NTSB on
# request (91.417(c), AC 120-78B 3.2.8.6) or a buyer at sale (91.419,
# 3.2.8.12): the logbook entries as a PDF with their electronic signatures,
# a signature register, the full change history, the status report, and the
# data archive (.sam.zip) to load into another system.
class RecordsPackage
def initialize(aircraft, source:)
@aircraft = aircraft
@source = source
@generated_at = Time.current
end
def filename = "#{@aircraft.tail_number.downcase}-records-#{@generated_at.to_date.iso8601}.zip"
def write_to(path)
entries = @aircraft.logbook_entries.includes(:component, :parts, :signature, inspection_records: :inspection_type).order(:date, :id).to_a
Zip::OutputStream.open(path) do |zip|
add(zip, "README.txt", readme(entries))
add(zip, "logbook-entries.pdf", LogbookEntryPdf.new(@aircraft, entries, layout: "letter").render) if entries.any?
add(zip, "signatures.csv", signatures_csv(entries))
add(zip, "record-history.csv", history_csv)
add(zip, "status-report.html", status_report_html)
archive = Tempfile.new([ "archive", ".sam.zip" ])
AircraftArchive::Exporter.new(@aircraft, source: @source).write_to(archive.path)
zip.put_next_entry("#{@aircraft.tail_number.downcase}.sam.zip")
File.open(archive.path, "rb") { IO.copy_stream(_1, zip) }
ensure
archive&.close!
end
path
end
private
def add(zip, name, content)
zip.put_next_entry(name)
zip.write(content)
end
def readme(entries)
signed = entries.count(&:signed?)
check = IntegrityCheck.latest
<<~TXT
Maintenance records for #{@aircraft.tail_number} (#{[ @aircraft.make, @aircraft.model ].compact_blank.join(' ')}, S/N #{@aircraft.serial_number.presence || 'not recorded'})
Prepared #{@generated_at.utc.strftime('%Y-%m-%d %H:%M UTC')} by Simple Aircraft Manager (#{@source}), software version #{SystemInfo.new.revision}.
Electronic records since: #{@aircraft.electronic_records_since&.iso8601 || 'not stated'}. Earlier records are the paper logbooks#{' (scans marked "legacy record" are in the archive)' if @aircraft.documents.where(legacy_record: true).exists?}.
Contents
- logbook-entries.pdf All #{entries.size} logbook entries, oldest first. #{signed} are signed electronically: each shows
"Certified by" the signer and certificate, the time (UTC) and the first 16 characters of its fingerprint.
- signatures.csv Every electronic signature: signer, certificate, statement, time, status and full fingerprint.
- record-history.csv Every change to the maintenance records (created, changed, deleted), with who and when.
- status-report.html Maintenance status per 14 CFR 91.417(a)(2): times, life-limited parts, inspections, ADs, alterations.
- #{@aircraft.tail_number.downcase}.sam.zip All records and files as data, to load into another system.
Signatures
Each electronic signature records who signed, with which certificate, what they certified, when, and a SHA-256
fingerprint of the entry's content at signing. A signed entry can't be edited; corrections are new signed entries
that supersede the original (both are included). Status "Valid" means the entry and signature are unchanged since
signing; "Superseded" means a later signed correction replaces it.
Last records integrity check: #{check ? "#{check.created_at.utc.strftime('%Y-%m-%d %H:%M UTC')}, #{check.ok ? 'no problems found' : "#{check.problems.size} problem(s) found"}" : 'not run yet'}.
TXT
end
def signatures_csv(entries)
CSV.generate do |csv|
csv << %w[entry_date log entry_type signer certificate_kind certificate_number signed_at_utc status fingerprint statement corrects_entry_dated]
entries.select(&:signed?).each do |e|
s = e.signature
csv << [ e.date, LogbookEntry::LOG_TYPES[e.log_type], LogbookEntry::ENTRY_TYPES[e.entry_type], s.signer_name, s.certificate_label,
s.certificate_number, s.signed_at.utc.iso8601, s.imported? ? "imported from #{s.origin}" : s.status_label,
s.content_digest, s.statement, e.supersedes&.date ]
end
end
end
def history_csv
users = User.pluck(:id, :email_address).to_h
CSV.generate do |csv|
csv << %w[id at_utc record record_id event by changed_fields chain_hash]
RecordVersion.where(aircraft_id: @aircraft.id).chronological.find_each do |v|
csv << [ v.id, v.created_at.utc.iso8601, v.item_type.underscore.humanize, v.item_id, v.event, users[v.user_id] || "system",
v.event == "update" ? v.changed_fields.join(" ") : "", v.chain_hash ]
end
end
end
# The status report as one self-contained HTML file (styles inlined).
def status_report_html
html = ApplicationController.render("maintenance_reports/show", layout: "report",
assigns: { report: MaintenanceReport.new(@aircraft) })
css = %w[tailwind.css application.css].filter_map { Rails.application.assets.load_path.find(_1)&.content }.join("\n")
html.gsub(%r{<link rel="stylesheet"[^>]*>\s*}, "").sub("</head>", "<style>#{css}</style></head>")
.gsub(%r{<script\b[^>]*>.*?</script>}m, "").gsub(%r{<link rel="modulepreload"[^>]*>\s*}, "")
end
end
+32
View File
@@ -78,6 +78,38 @@
</div> </div>
</div> </div>
<section class="card mt-5" id="records">
<div class="card-header">
<div>
<h2 class="card-title">Records integrity</h2>
<p class="text-xs text-slate-500">Nightly: a verified database backup, then a check of the record history chains and every electronic signature (AC 120-78B 3.2).</p>
</div>
<%= button_to "Back up and check now", admin_check_records_path, class: "btn-secondary btn-sm", data: { turbo_submits_with: "Checking…" } %>
</div>
<% check = IntegrityCheck.latest %>
<% backup = BackupRun.latest %>
<%= render "pairs", pairs: [
[ "Last check", check ? "#{l(check.created_at, format: :short)} · #{check.ok ? 'no problems' : pluralize(check.problems.size, 'problem')}" : "not run yet" ],
[ "Checked", check ? "#{number_with_delimiter(check.versions_checked)} history entries, #{number_with_delimiter(check.signatures_checked)} signatures" : nil ],
[ "Last backup", backup ? "#{l(backup.created_at, format: :short)} · #{backup.ok ? number_to_human_size(backup.bytes) : 'FAILED'}" : "not run yet" ],
[ "Backup check", backup&.message ],
[ "Backups kept", "#{Setting.integer('backups_kept')} (in storage/backups)" ]
] %>
<% if check && !check.ok %>
<ul class="list-disc space-y-1 px-8 pb-3 text-sm text-red-700"><% check.problems.each do |p| %><li><%= p %></li><% end %></ul>
<% end %>
</section>
<section class="card mt-5">
<div class="card-header"><h2 class="card-title">Software versions</h2></div>
<% revisions = AppRevision.latest_first.limit(20) %>
<% if revisions.any? %>
<%= render "pairs", pairs: revisions.map { |r| [ r.revision, "#{l(r.first_seen_at, format: :short)} – #{l(r.last_seen_at, format: :short)}" ] } %>
<% else %>
<%= empty_state "No versions recorded yet." %>
<% end %>
</section>
<details class="card mt-5"> <details class="card mt-5">
<summary class="card-header cursor-pointer"><span class="card-title">All gems (<%= info.all_gems.size %>)</span></summary> <summary class="card-header cursor-pointer"><span class="card-title">All gems (<%= info.all_gems.size %>)</span></summary>
<div class="grid gap-x-6 px-4 py-3 font-mono text-xs sm:grid-cols-2 lg:grid-cols-3"> <div class="grid gap-x-6 px-4 py-3 font-mono text-xs sm:grid-cols-2 lg:grid-cols-3">
+9
View File
@@ -22,5 +22,14 @@
</p> </p>
</div> </div>
<h2 class="card-title pt-2">Backups</h2>
<% kept = Setting::INTEGERS["backups_kept"] %>
<div>
<%= label_tag "settings[backups_kept]", kept[:label], class: "label" %>
<%= number_field_tag "settings[backups_kept]", @values["backups_kept"], id: "settings_backups_kept", min: kept[:in].min, max: kept[:in].max,
step: 1, required: true, class: "input w-32" %>
<p class="hint">A verified copy of the database is made nightly in storage/backups; this many of the newest are kept. Back up the whole storage volume off the server too.</p>
</div>
<div class="flex gap-2"><%= f.submit "Save Settings", class: "btn-primary" %><%= link_to "Cancel", admin_about_path, class: "btn-secondary" %></div> <div class="flex gap-2"><%= f.submit "Save Settings", class: "btn-primary" %><%= link_to "Cancel", admin_about_path, class: "btn-secondary" %></div>
<% end %> <% end %>
@@ -0,0 +1,5 @@
<p>Last night's records check found a problem.</p>
<p>Backup: <strong><%= @backup.ok ? "OK" : "FAILED: #{@backup.message}" %></strong><br>
Integrity check: <strong><%= @check.ok ? "OK" : "#{@check.problems.size} problem(s)" %></strong></p>
<ul><% Array(@check.problems).first(20).each do |p| %><li><%= p %></li><% end %></ul>
<p>See Admin → About for details.</p>
@@ -0,0 +1,9 @@
Last night's records check found a problem.
Backup: <%= @backup.ok ? "OK" : "FAILED: #{@backup.message}" %>
Integrity check: <%= @check.ok ? "OK" : "#{@check.problems.size} problem(s)" %>
<% Array(@check.problems).first(20).each do |p| %>
- <%= p %>
<% end %>
See Admin → About for details.
+2
View File
@@ -25,6 +25,8 @@
<p class="hint">To change hours use “Update Hours” on the overview, so component times stay in sync.</p> <p class="hint">To change hours use “Update Hours” on the overview, so component times stay in sync.</p>
<% end %> <% end %>
<%= f.field :picture, as: :file, accept: "image/*" %> <%= f.field :picture, as: :file, accept: "image/*" %>
<%= f.field :electronic_records_since, as: :date, label: "Electronic records since", wrapper: { class: "max-w-xs" },
hint: "The date this app became the maintenance record. Earlier records stay in the paper logbooks (mark their scans as legacy records)." %>
<%= f.field :airworthiness_enforcement, as: :checkbox, label: "Enforce airworthiness", <%= f.field :airworthiness_enforcement, as: :checkbox, label: "Enforce airworthiness",
hint: "Block flight logs and hours updates while the aircraft shows Grounded." %> hint: "Block flight logs and hours updates while the aircraft shows Grounded." %>
<div class="flex gap-2"> <div class="flex gap-2">
+7
View File
@@ -67,5 +67,12 @@
</div> </div>
<%= link_to "Download .sam.zip", aircraft_export_path(@aircraft), class: "btn-secondary", data: { turbo: false } %> <%= link_to "Download .sam.zip", aircraft_export_path(@aircraft), class: "btn-secondary", data: { turbo: false } %>
</div> </div>
<div class="card-header border-t border-slate-100">
<div>
<h2 class="card-title">Records package</h2>
<p class="hint">For an FAA or NTSB request, or a buyer: every logbook entry as a PDF with its electronic signature, a signature register, the full change history, the status report, and the .sam.zip, in one ZIP with a README.</p>
</div>
<%= link_to "Download records package", aircraft_records_package_path(@aircraft), class: "btn-secondary", data: { turbo: false } %>
</div>
</section> </section>
</div> </div>
+1
View File
@@ -2,6 +2,7 @@
<div> <div>
<%= link_to doc.name, aircraft_document_path(aircraft, doc), class: "link font-medium" %> <%= link_to doc.name, aircraft_document_path(aircraft, doc), class: "link font-medium" %>
<span class="ml-2 text-xs text-slate-500"><%= doc.type_label %> · <%= pluralize(doc.pages.size, "file") %></span> <span class="ml-2 text-xs text-slate-500"><%= doc.type_label %> · <%= pluralize(doc.pages.size, "file") %></span>
<% if doc.legacy_record? %><span class="ml-1 badge-gray" title="Scan of the paper (legacy) records">Legacy record</span><% end %>
<% if doc.expires_on %><span class="ml-1 <%= doc.expired? ? 'badge-red' : (Date.current + doc.expiry_warning_days >= doc.expires_on ? 'badge-orange' : 'badge-gray') %>"><%= doc.expired? ? "Expired" : "Expires" %> <%= doc.expires_on %></span><% end %> <% if doc.expires_on %><span class="ml-1 <%= doc.expired? ? 'badge-red' : (Date.current + doc.expiry_warning_days >= doc.expires_on ? 'badge-orange' : 'badge-gray') %>"><%= doc.expired? ? "Expired" : "Expires" %> <%= doc.expires_on %></span><% end %>
<% if doc.description.present? %><div class="text-xs text-slate-500"><%= doc.description.truncate(120) %></div><% end %> <% if doc.description.present? %><div class="text-xs text-slate-500"><%= doc.description.truncate(120) %></div><% end %>
</div> </div>
+2
View File
@@ -8,6 +8,8 @@
<%= f.field :visibility, as: :select, label: "Share-link visibility", <%= f.field :visibility, as: :select, label: "Share-link visibility",
collection: [["Inherit from collection", nil]] + DocumentCollection::VISIBILITIES.invert.to_a %> collection: [["Inherit from collection", nil]] + DocumentCollection::VISIBILITIES.invert.to_a %>
</div> </div>
<%= f.field :legacy_record, as: :checkbox, label: "Legacy record (a scan of the paper logbooks or records)",
hint: "Records from before the electronic records began. Keep the paper originals." %>
<%= f.field :expires_on, as: :date, label: "Expires on", wrapper: { class: "max-w-xs" }, <%= f.field :expires_on, as: :date, label: "Expires on", wrapper: { class: "max-w-xs" },
hint: "Optional. Registration (good for 7 years, 14 CFR 47.40), insurance, radio license… You'll be reminded before it expires; an expired registration shows the aircraft grounded." %> hint: "Optional. Registration (good for 7 years, 14 CFR 47.40), insurance, radio license… You'll be reminded before it expires; an expired registration shows the aircraft grounded." %>
<%= f.field :description, as: :textarea, rows: 2 %> <%= f.field :description, as: :textarea, rows: 2 %>
+3
View File
@@ -3,9 +3,12 @@
<section class="card"> <section class="card">
<div class="card-header"> <div class="card-header">
<h2 class="card-title">Activity Log</h2> <h2 class="card-title">Activity Log</h2>
<div class="flex flex-wrap items-center gap-2">
<%= link_to "Record history", aircraft_record_versions_path(@aircraft), class: "btn-secondary btn-sm", title: "Every change to the maintenance records, field by field" %>
<%= form_with url: aircraft_events_path(@aircraft), method: :get, class: "flex gap-2" do |f| %> <%= form_with url: aircraft_events_path(@aircraft), method: :get, class: "flex gap-2" do |f| %>
<%= f.select :category, AircraftEvent::CATEGORIES.invert, { include_blank: "All categories", selected: @category }, class: "input", data: { submit_on_change: true } %> <%= f.select :category, AircraftEvent::CATEGORIES.invert, { include_blank: "All categories", selected: @category }, class: "input", data: { submit_on_change: true } %>
<% end %> <% end %>
</div> </div>
</div>
<%= render "events/list", events: @events, full: true %> <%= render "events/list", events: @events, full: true %>
</section> </section>
+8
View File
@@ -58,3 +58,11 @@
<% end %> <% end %>
</div> </div>
</section> </section>
<% history = (@entry.versions.to_a + @entry.parts.flat_map { _1.versions.to_a } + (@entry.signature ? @entry.signature.versions.to_a : [])).sort_by(&:id).reverse %>
<% if history.any? %>
<details class="card mt-5 max-w-4xl">
<summary class="card-header cursor-pointer"><span class="card-title">Change history (<%= history.size %>)</span></summary>
<%= render "record_versions/list", versions: history %>
</details>
<% end %>
@@ -22,6 +22,7 @@
<dt class="text-slate-500">Airframe time in service</dt><dd class="font-semibold"><%= hours(@report.time_in_service) %> hrs (<%= clock %>)</dd> <dt class="text-slate-500">Airframe time in service</dt><dd class="font-semibold"><%= hours(@report.time_in_service) %> hrs (<%= clock %>)</dd>
<dt class="text-slate-500">Tach / Hobbs</dt><dd><%= hours(a.tach_time) %> / <%= hours(a.hobbs_time) %></dd> <dt class="text-slate-500">Tach / Hobbs</dt><dd><%= hours(a.tach_time) %> / <%= hours(a.hobbs_time) %></dd>
<dt class="text-slate-500">Status</dt><dd><%= airworthiness_badge(@report.airworthiness) %></dd> <dt class="text-slate-500">Status</dt><dd><%= airworthiness_badge(@report.airworthiness) %></dd>
<dt class="text-slate-500">Electronic records since</dt><dd><%= a.electronic_records_since || "—" %></dd>
</dl> </dl>
</header> </header>
+19
View File
@@ -0,0 +1,19 @@
<%# Locals: versions. %>
<ul class="divide-y divide-slate-100 text-sm">
<% versions.each do |v| %>
<li class="px-4 py-2">
<div class="flex flex-wrap items-baseline justify-between gap-2">
<span><span class="font-medium"><%= v.item_type.underscore.humanize %> #<%= v.item_id %></span>
<span class="<%= { 'create' => 'badge-green', 'update' => 'badge-blue', 'destroy' => 'badge-red' }[v.event] %> ml-1"><%= { "create" => "created", "update" => "changed", "destroy" => "deleted" }[v.event] %></span></span>
<span class="text-xs text-slate-500"><%= v.created_at.utc.strftime("%Y-%m-%d %H:%M:%S UTC") %> · <%= v.user&.display_name || "system" %><%= " · #{v.ip_address}" if v.ip_address %></span>
</div>
<% if v.event == "update" %>
<dl class="mt-1 grid gap-x-3 text-xs text-slate-600 sm:grid-cols-[10rem_1fr]">
<% v.changes_hash.each do |field, (before, after)| %>
<dt class="text-slate-500"><%= field.humanize %></dt><dd class="break-words"><span class="line-through decoration-slate-400"><%= before.to_s.truncate(120).presence || "—" %></span> → <%= after.to_s.truncate(120).presence || "—" %></dd>
<% end %>
</dl>
<% end %>
</li>
<% end %>
</ul>
+14
View File
@@ -0,0 +1,14 @@
<% content_for :title, "#{@aircraft.tail_number} Record history" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<section class="card">
<div class="card-header">
<div>
<h2 class="card-title">Record history</h2>
<p class="text-xs text-slate-500">Every change to the maintenance records, kept for good and chained so that removing or altering history shows in the nightly check.</p>
</div>
<%= form_with url: aircraft_record_versions_path(@aircraft), method: :get, class: "flex gap-2" do %>
<%= select_tag :type, options_for_select([ [ "All records", "" ] ] + @types.map { [ _1.underscore.humanize, _1 ] }, @type), class: "input w-48", data: { submit_on_change: true } %>
<% end %>
</div>
<% if @versions.any? %><%= render "record_versions/list", versions: @versions %><% else %><%= empty_state "No changes recorded yet." %><% end %>
</section>
+7
View File
@@ -0,0 +1,7 @@
# Record the running software version (Admin → About) once the app is up.
Rails.application.config.after_initialize do
next unless defined?(Rails::Server) || ENV["SOLID_QUEUE_IN_PUMA"]
AppRevision.touch_current! if ActiveRecord::Base.connection.data_source_exists?("app_revisions")
rescue StandardError => e
Rails.logger.warn("[app revisions] #{e.class}: #{e.message}")
end
+3
View File
@@ -25,3 +25,6 @@ production:
ad_watch: ad_watch:
class: AdWatchJob class: AdWatchJob
schedule: every sunday at 10am schedule: every sunday at 10am
records_integrity:
class: RecordsIntegrityJob
schedule: every day at 3:30am
+3
View File
@@ -102,6 +102,8 @@ Rails.application.routes.draw do
resources :share_tokens, only: %i[create destroy] resources :share_tokens, only: %i[create destroy]
resource :export, controller: "aircraft_exports", only: :show resource :export, controller: "aircraft_exports", only: :show
resource :report, controller: "maintenance_reports", only: :show resource :report, controller: "maintenance_reports", only: :show
resource :records_package, path: "records", only: :show
resources :record_versions, path: "history", only: :index
resources :events, only: :index resources :events, only: :index
end end
@@ -130,6 +132,7 @@ Rails.application.routes.draw do
end end
post "about/test_email", to: "about#test_email", as: :test_email post "about/test_email", to: "about#test_email", as: :test_email
post "about/test_reminder", to: "about#test_reminder", as: :test_reminder post "about/test_reminder", to: "about#test_reminder", as: :test_reminder
post "about/check_records", to: "about#check_records", as: :check_records
resources :users, except: :show resources :users, except: :show
resources :component_types, except: :show resources :component_types, except: :show
resources :airports, except: :show do resources :airports, except: :show do
@@ -0,0 +1,52 @@
# Electronic recordkeeping (AC 120-78B chapter 3):
# - record_versions: every change to a maintenance record, chained by hash per
# aircraft so removing or altering history shows (3.2.2, 3.2.4)
# - integrity_checks: results of verifying those chains and the signatures
# - backup_runs: the built-in database backups and their verification (3.2.7)
# - app_revisions: which software versions ran when (3.2.6)
# - legacy (paper) records: documents marked as such and the date the
# electronic records start (3.2.8.10)
class AddRecordsIntegrity < ActiveRecord::Migration[8.1]
def change
create_table :record_versions do |t|
t.integer :aircraft_id, index: true
t.string :item_type, null: false
t.integer :item_id, null: false
t.string :event, null: false
t.integer :user_id
t.string :ip_address
t.text :payload, null: false
t.string :prev_hash
t.string :chain_hash, null: false
t.datetime :created_at, null: false
end
add_index :record_versions, %i[item_type item_id]
create_table :integrity_checks do |t|
t.boolean :ok, null: false
t.integer :versions_checked, null: false, default: 0
t.integer :signatures_checked, null: false, default: 0
t.json :problems
t.timestamps
end
create_table :backup_runs do |t|
t.boolean :ok, null: false
t.string :path
t.bigint :bytes
t.text :message
t.timestamps
end
create_table :app_revisions do |t|
t.string :revision, null: false
t.datetime :built_at
t.datetime :first_seen_at, null: false
t.datetime :last_seen_at, null: false
end
add_index :app_revisions, :revision, unique: true
add_column :documents, :legacy_record, :boolean, null: false, default: false
add_column :aircraft, :electronic_records_since, :date
end
end
Generated
+44 -1
View File
@@ -10,7 +10,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2026_11_08_010000) do ActiveRecord::Schema[8.1].define(version: 2026_11_08_020000) do
create_table "active_storage_attachments", force: :cascade do |t| create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false t.string "name", null: false
t.string "record_type", null: false t.string "record_type", null: false
@@ -147,6 +147,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_010000) do
t.json "cg_envelope" t.json "cg_envelope"
t.string "ad_watch_terms" t.string "ad_watch_terms"
t.datetime "ad_watch_checked_at" t.datetime "ad_watch_checked_at"
t.date "electronic_records_since"
end end
create_table "aircraft_airworthiness_directives", id: false, force: :cascade do |t| create_table "aircraft_airworthiness_directives", id: false, force: :cascade do |t|
@@ -285,6 +286,23 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_010000) do
t.index ["component_id", "airworthiness_directive_id"], name: "idx_component_ads", unique: true t.index ["component_id", "airworthiness_directive_id"], name: "idx_component_ads", unique: true
end end
create_table "app_revisions", force: :cascade do |t|
t.string "revision", null: false
t.datetime "built_at"
t.datetime "first_seen_at", null: false
t.datetime "last_seen_at", null: false
t.index ["revision"], name: "index_app_revisions_on_revision", unique: true
end
create_table "backup_runs", force: :cascade do |t|
t.boolean "ok", null: false
t.string "path"
t.bigint "bytes"
t.text "message"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "component_types", force: :cascade do |t| create_table "component_types", force: :cascade do |t|
t.string "name", null: false t.string "name", null: false
t.boolean "consumable", default: false, null: false t.boolean "consumable", default: false, null: false
@@ -371,6 +389,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_010000) do
t.datetime "created_at", null: false t.datetime "created_at", null: false
t.datetime "updated_at", null: false t.datetime "updated_at", null: false
t.date "expires_on" t.date "expires_on"
t.boolean "legacy_record", default: false, null: false
t.index ["aircraft_id"], name: "index_documents_on_aircraft_id" t.index ["aircraft_id"], name: "index_documents_on_aircraft_id"
t.index ["document_collection_id"], name: "index_documents_on_document_collection_id" t.index ["document_collection_id"], name: "index_documents_on_document_collection_id"
end end
@@ -455,6 +474,15 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_010000) do
t.index ["satisfies_id"], name: "index_inspection_types_on_satisfies_id" t.index ["satisfies_id"], name: "index_inspection_types_on_satisfies_id"
end end
create_table "integrity_checks", force: :cascade do |t|
t.boolean "ok", null: false
t.integer "versions_checked", default: 0, null: false
t.integer "signatures_checked", default: 0, null: false
t.json "problems"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "logbook_entries", force: :cascade do |t| create_table "logbook_entries", force: :cascade do |t|
t.integer "aircraft_id", null: false t.integer "aircraft_id", null: false
t.integer "document_id" t.integer "document_id"
@@ -584,6 +612,21 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_010000) do
t.index ["component_id"], name: "index_oil_analyses_on_component_id" t.index ["component_id"], name: "index_oil_analyses_on_component_id"
end end
create_table "record_versions", force: :cascade do |t|
t.integer "aircraft_id"
t.string "item_type", null: false
t.integer "item_id", null: false
t.string "event", null: false
t.integer "user_id"
t.string "ip_address"
t.text "payload", null: false
t.string "prev_hash"
t.string "chain_hash", null: false
t.datetime "created_at", null: false
t.index ["aircraft_id"], name: "index_record_versions_on_aircraft_id"
t.index ["item_type", "item_id"], name: "index_record_versions_on_item_type_and_item_id"
end
create_table "sessions", force: :cascade do |t| create_table "sessions", force: :cascade do |t|
t.integer "user_id", null: false t.integer "user_id", null: false
t.string "ip_address" t.string "ip_address"
+59
View File
@@ -0,0 +1,59 @@
require "test_helper"
# Backups copy the live database with SQLite's online backup API, which can't
# run inside the transaction each test normally runs in: these tests commit
# for real and clean up after themselves.
class DatabaseBackupTest < ActionDispatch::IntegrationTest
include ActionMailer::TestHelper
self.use_transactional_tests = false
setup do
@owner = create_user("owner@example.com")
@a = create_aircraft(owner: @owner, tail_number: "N12345")
@mech = create_user("mech@example.com").tap { _1.update!(name: "Sam Mechanic") }
@ap = @mech.certificates.create!(kind: "AP", number: "7654321")
end
teardown do
FileUtils.rm_rf(DatabaseBackup::DIR)
[ EntrySignature, LogbookEntry ].each { _1.delete_all }
[ RecordVersion, IntegrityCheck, BackupRun, AircraftEvent, AircraftRole, UserCertificate, Aircraft, Session, Setting, User ].each(&:delete_all)
end
def entry(**attrs)
@a.logbook_entries.create!({ date: Date.new(2026, 10, 1), entry_type: "MAINTENANCE", text: "Changed oil", aircraft_hours_at_entry: 1000 }.merge(attrs))
end
test "the nightly job backs up and verifies the database, prunes old copies, and emails admins on trouble" do
admin = create_user("admin@example.com", admin: true)
entry
Setting.update_integers("backups_kept" => "2")
dir = DatabaseBackup::DIR
FileUtils.rm_rf(dir)
3.times { |i| travel(i.minutes) { DatabaseBackup.run! } }
run = BackupRun.latest
assert run.ok, run.message
assert_match "Verified: SQLite integrity check ok; 1 logbook entries", run.message
assert_equal 2, Dir[dir.join("sam-*.sqlite3")].size
db = SQLite3::Database.new(run.path, readonly: true)
assert_equal 1, db.get_first_value("SELECT COUNT(*) FROM logbook_entries")
db.close
assert_no_emails { RecordsIntegrityJob.perform_now }
assert [ BackupRun.latest.ok, IntegrityCheck.latest.ok ].all?, [ BackupRun.latest.message, IntegrityCheck.latest.problems ].inspect
LogbookEntry.update_all(text: "x") # no signatures, so this alone isn't a problem
EntrySigner.new(entry(date: Date.new(2026, 10, 2)), user: @mech, certificate: @ap, auth_method: "password").sign!
LogbookEntry.where(date: Date.new(2026, 10, 2)).update_all(text: "tampered")
assert_emails 1 do
RecordsIntegrityJob.perform_now
end
assert_equal [ admin.email_address ], ActionMailer::Base.deliveries.last.to
sign_in admin
get admin_about_path
assert_includes response.body, "Records integrity"
assert_includes response.body, "changed after it was signed"
post admin_check_records_path
assert_redirected_to admin_about_path(anchor: "records")
end
end
+114
View File
@@ -0,0 +1,114 @@
require "test_helper"
# Electronic recordkeeping (AC 120-78B chapter 3): history, integrity,
# backups, software versions, the records package, legacy records.
class RecordsIntegrityTest < ActionDispatch::IntegrationTest
include ActionMailer::TestHelper
setup do
@owner = create_user("owner@example.com")
@a = create_aircraft(owner: @owner, tail_number: "N12345")
@mech = create_user("mech@example.com").tap { _1.update!(name: "Sam Mechanic") }
@ap = @mech.certificates.create!(kind: "AP", number: "7654321")
end
def entry(**attrs)
@a.logbook_entries.create!({ date: Date.new(2026, 10, 1), entry_type: "MAINTENANCE", text: "Changed oil", aircraft_hours_at_entry: 1000 }.merge(attrs))
end
test "every change to a record is kept, with who and what changed, and shown" do
sign_in @owner
post aircraft_logbook_entries_path(@a), params: { logbook_entry: { date: "2026-10-01", log_type: "AC", entry_type: "MAINTENANCE", text: "Changed oil" } }
e = @a.logbook_entries.sole
patch aircraft_logbook_entry_path(@a, e), params: { logbook_entry: { text: "Changed oil and filter" } }
versions = e.versions.to_a
assert_equal %w[create update], versions.map(&:event)
assert_equal [ "Changed oil", "Changed oil and filter" ], versions.last.changes_hash["text"]
assert_equal [ @owner, @owner ], versions.map(&:user)
assert versions.all? { _1.ip_address.present? }
get aircraft_logbook_entry_path(@a, e)
assert_includes response.body, "Change history (2)"
delete aircraft_logbook_entry_path(@a, e)
assert_equal "destroy", RecordVersion.where(item_type: "LogbookEntry", item_id: e.id).last.event # history outlives the record
get aircraft_record_versions_path(@a)
assert_select "li", minimum: 3
assert_includes response.body, "deleted"
assert_raises(ActiveRecord::RecordNotSaved) { RecordVersion.last.update!(event: "x") }
end
test "the integrity check finds broken history chains and altered signed entries" do
e = entry
EntrySigner.new(e, user: @mech, certificate: @ap, auth_method: "password").sign!
other = create_aircraft(owner: @owner)
other.squawks.create!(priority: 2, issue_reported: "Chip in paint")
check = RecordsIntegrity.check!
assert check.ok, check.problems.inspect
assert check.versions_checked >= 4
assert_equal 1, check.signatures_checked
LogbookEntry.where(id: e.id).update_all(text: "Changed oil (edited in the database)")
victim = RecordVersion.where(aircraft_id: other.id).first
RecordVersion.where(id: victim.id).delete_all
check = RecordsIntegrity.check!
refute check.ok
assert(check.problems.any? { _1.include?("the 2026-10-01 logbook entry (signed by Sam Mechanic) changed after it was signed") })
assert(check.problems.any? { _1.include?("doesn't follow the one before it") || _1.include?("missing") } || RecordVersion.where(aircraft_id: other.id).count.zero?)
RecordVersion.where(aircraft_id: @a.id).last.then { RecordVersion.where(id: _1.id).update_all(payload: _1.payload.sub("Changed oil", "Changed gas")) }
assert(RecordsIntegrity.check!.problems.any? { _1.include?("was altered") })
end
test "software versions are recorded" do
with_revision("abc1234") { AppRevision.touch_current! }
with_revision("def5678") { AppRevision.touch_current! }
with_revision("def5678") { AppRevision.touch_current! }
assert_equal %w[def5678 abc1234], AppRevision.latest_first.pluck(:revision) & %w[def5678 abc1234]
assert_equal 1, AppRevision.where(revision: "def5678").count
end
test "the records package has everything for the FAA or a buyer" do
@a.update!(electronic_records_since: Date.new(2026, 1, 1))
@a.documents.create!(name: "Logbook scans 1975-2025", doc_type: "LOG", legacy_record: true)
signed = entry
EntrySigner.new(signed, user: @mech, certificate: @ap, auth_method: "password").sign!
entry(date: Date.new(2026, 10, 5), text: "Unsigned entry")
sign_in @owner
get aircraft_records_package_path(@a)
assert_response :success
assert_match(/filename="n12345-records-\d{4}-\d\d-\d\d\.zip"/, response.headers["Content-Disposition"])
path = File.join(Dir.mktmpdir, "pkg.zip")
File.binwrite(path, response.body)
Zip::File.open(path) do |zip|
def zip.text(name) = read(name).force_encoding("UTF-8")
assert_equal %w[README.txt logbook-entries.pdf n12345.sam.zip record-history.csv signatures.csv status-report.html], zip.entries.map(&:name).sort
readme = zip.text("README.txt")
assert_includes readme, "All 2 logbook entries, oldest first. 1 are signed electronically"
assert_includes readme, "Electronic records since: 2026-01-01"
assert_includes readme, "scans marked \"legacy record\""
sigs = CSV.parse(zip.text("signatures.csv"), headers: true)
assert_equal [ "Sam Mechanic", "7654321", "Valid", signed.reload.signature.content_digest ], sigs.first.fields.values_at(3, 5, 7, 8)
assert_operator CSV.parse(zip.text("record-history.csv"), headers: true).size, :>=, 3
html = zip.text("status-report.html")
assert_includes html, "Maintenance status · 14 CFR 91.417(a)(2)"
refute_includes html, "<script"
assert_includes html, "<style>"
end
assert @a.events.exists?(event_name: "Records package downloaded")
pilot = create_user
@a.roles.create!(user: pilot, role: "pilot")
sign_in pilot
get aircraft_records_package_path(@a)
assert_redirected_to aircraft_path(@a) # owners only
end
private
def with_revision(sha)
saved = ENV["APP_REVISION"]
ENV["APP_REVISION"] = sha
yield
ensure
ENV["APP_REVISION"] = saved
end
end