diff --git a/app/controllers/aircraft_imports_controller.rb b/app/controllers/aircraft_imports_controller.rb index 9abf8b4..33fe850 100644 --- a/app/controllers/aircraft_imports_controller.rb +++ b/app/controllers/aircraft_imports_controller.rb @@ -8,7 +8,7 @@ class AircraftImportsController < ApplicationController def create file = params[:archive] - return redirect_to(new_aircraft_import_path, alert: t("flash.aircraft_imports.choose_a_sam_zip")) if file.blank? + return redirect_to(new_aircraft_import_path, alert: t("flash.aircraft_imports.choose_a_sam_zip")) unless file.respond_to?(:tempfile) preview = AircraftArchive::Importer.check(file.tempfile.path) tail = params[:tail_number].to_s.strip.upcase.presence || preview.tail_number.to_s.upcase diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index f840134..2040b6c 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -5,6 +5,7 @@ class ApplicationController < ActionController::Base allow_browser versions: :modern prepend_before_action :redirect_to_setup + prepend_before_action :reject_null_bytes before_action { Current.ip_address = request.remote_ip } # for record history helper_method :current_user @@ -15,8 +16,41 @@ class ApplicationController < ActionController::Base end end + # Asked for a format a page doesn't have (/aircraft/1/report.pdf): not a crash. + rescue_from ActionView::MissingTemplate do |error| + raise error if request.format.html? + head :not_acceptable + end + + # Input no form produces: a tampered upload reference, a number too big to + # store, a missing required value or a link to a record that isn't there. + # The forms validate what people can enter; this is the safety net. + rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError, + ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do |error| + Rails.logger.warn("[input] #{error.class}: #{error.message.truncate(200)}") + respond_to do |format| + format.html { redirect_back_or_to root_path, alert: t("flash.application.invalid_input") } + format.any { head :unprocessable_entity } + end + end + private + # No form sends a null byte; some libraries (password hashing, file paths) + # raise on one, so refuse the request up front. + def reject_null_bytes + head :bad_request if contains_null_byte?(request.params) + end + + def contains_null_byte?(value) + case value + when String then value.include?("\0") + when Hash then value.any? { |k, v| contains_null_byte?(k) || contains_null_byte?(v) } + when Array then value.any? { contains_null_byte?(_1) } + else false + end + end + def current_user = Current.user # First run: no users yet → create the initial admin. diff --git a/app/controllers/logbook_imports_controller.rb b/app/controllers/logbook_imports_controller.rb index 12e9adb..f3e359b 100644 --- a/app/controllers/logbook_imports_controller.rb +++ b/app/controllers/logbook_imports_controller.rb @@ -10,7 +10,7 @@ class LogbookImportsController < ApplicationController end def create - files = Array(params[:pages]).compact_blank + files = Array(params[:pages]).select { _1.respond_to?(:original_filename) } # uploaded files only return redirect_to(new_aircraft_logbook_import_path(@aircraft), alert: t("flash.logbook_imports.choose_the_scanned_pages")) if files.empty? # Page order follows the file names ("page-002" before "page-010"). diff --git a/app/controllers/oil_analyses_controller.rb b/app/controllers/oil_analyses_controller.rb index fc6c301..b6c9996 100644 --- a/app/controllers/oil_analyses_controller.rb +++ b/app/controllers/oil_analyses_controller.rb @@ -35,7 +35,7 @@ class OilAnalysesController < ApplicationController # earlier samples, so samples already on file are skipped rather than duplicated. def import file = params[:report] - return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: t("flash.oil_analyses.choose_a_lab_report")) if file.blank? + return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: t("flash.oil_analyses.choose_a_lab_report")) unless file.respond_to?(:tempfile) report = OilReportParser.from_pdf(file.tempfile) file.rewind diff --git a/app/helpers/aircraft_helper.rb b/app/helpers/aircraft_helper.rb index 225bb4a..ac68611 100644 --- a/app/helpers/aircraft_helper.rb +++ b/app/helpers/aircraft_helper.rb @@ -8,7 +8,7 @@ module AircraftHelper current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a| { tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ], flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a), - pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture.attached?) }.compact + pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture_shown?) }.compact end end # Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only] diff --git a/app/models/aircraft.rb b/app/models/aircraft.rb index 7938183..1053b55 100644 --- a/app/models/aircraft.rb +++ b/app/models/aircraft.rb @@ -82,16 +82,20 @@ class Aircraft < ApplicationRecord events.create!(category: category, event_name: event_name, user: user, notes: notes) end + # A saved photo to show (not one just rejected by validation, which has no + # address yet). + def picture_shown? = picture.attached? && picture.attachment.persisted? + # The photo at a page's size (:thumb or :card), or the original when it - # isn't a kind that can be resized. + # can't be resized (see ActiveStorage::Blob#resizable_image?). def picture_for(size) - picture.variable? ? picture.variant(size) : picture + picture.blob.resizable_image? ? picture.variant(size) : picture end private def picture_is_image - if picture.attached? && !picture.content_type.to_s.start_with?("image/") + if picture.attached? && (!picture.content_type.to_s.start_with?("image/") || picture.blob.byte_size.zero?) errors.add(:picture, :not_image) end end diff --git a/app/models/application_record.rb b/app/models/application_record.rb index b63caeb..2b692fc 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -1,3 +1,28 @@ class ApplicationRecord < ActiveRecord::Base primary_abstract_class + + before_validation :default_blank_required_columns + validate :optional_references_exist + + private + + # A blank form field arrives as nil; for a column that can't be empty and has + # a default (a checkbox, a count, a position), use the default rather than + # failing in the database. + def default_blank_required_columns + self.class.columns.each do |column| + next if column.null || column.default.nil? || !self[column.name].nil? + self[column.name] = self.class.type_for_attribute(column.name).cast(column.default) + end + end + + # An optional link (a parent part, a collection…) given an id that doesn't + # exist is a mistake in the form, not something to store. + def optional_references_exist + self.class.reflect_on_all_associations(:belongs_to).each do |assoc| + next if assoc.polymorphic? || !assoc.options[:optional] + next if self[assoc.foreign_key].blank? || !attribute_changed?(assoc.foreign_key) + errors.add(assoc.name, :invalid) unless public_send(assoc.name) + end + end end diff --git a/app/models/component.rb b/app/models/component.rb index f34cb07..35518a8 100644 --- a/app/models/component.rb +++ b/app/models/component.rb @@ -44,13 +44,23 @@ class Component < ApplicationRecord OVERHAUL_ABBREVIATIONS.fetch(overhaul_kind) { engine? || propeller? ? "TSO" : I18n.t("models.component.since_service") } end - # Its sub-components, and theirs. - def descendant_ids - child_components.flat_map { [ _1.id, *_1.descendant_ids ] } + # Its sub-components, and theirs. (Stops at a loop, should one exist.) + def descendant_ids(seen = Set[id]) + child_components.flat_map do |child| + next [] unless seen.add?(child.id) + [ child.id, *child.descendant_ids(seen) ] + end end + # Its parent, the parent's parent, and so on up. def ancestor_ids - parent_component ? [ parent_component_id, *parent_component.ancestor_ids ] : [] + ids = [] + node = self + while (parent_id = node.parent_component_id) && parent_id != id && !ids.include?(parent_id) + ids << parent_id + node = Component.find_by(id: parent_id) or break + end + ids end def engine? = component_type&.name.to_s.match?(/engine/i) def propeller? = component_type&.name.to_s.match?(/propell?er|\bprop\b/i) @@ -133,6 +143,7 @@ class Component < ApplicationRecord def parent_on_same_aircraft return unless parent_component errors.add(:parent_component, :itself) if parent_component_id == id && id + errors.add(:parent_component, :own_part) if id && parent_component.ancestor_ids.include?(id) # would make a loop errors.add(:parent_component, :other_aircraft) if parent_component.aircraft_id != aircraft_id end end diff --git a/app/views/aircraft/index.html.erb b/app/views/aircraft/index.html.erb index 8881bd7..fdb7c47 100644 --- a/app/views/aircraft/index.html.erb +++ b/app/views/aircraft/index.html.erb @@ -18,7 +18,7 @@ <% aw = aircraft.airworthiness %> <%= link_to aircraft_path(aircraft), class: "card block overflow-hidden transition hover:shadow-md" do %>