mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 15:50:36 -05:00
Fix crashes found by fuzzing malformed input
- Components can't be made into a parent loop, and the parts tree walks stop safely if one exists (logbook entry and squawk resolution pages crashed). - A rejected aircraft photo no longer breaks the edit page; empty photos are refused; images that can't be read aren't resized, and a failed resize sends the original instead of an error. - Unsupported formats (/report.pdf…) answer 406; tampered upload references, out-of-range numbers and constraint violations get a form message instead of a 500; requests with null bytes are refused (400). - Blank values in required columns with defaults take the default; optional links to records that don't exist are validation errors. - Imports (oil report, logbook scans, .sam.zip) accept only uploaded files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5876c07a1a
commit
908c943e21
15 files changed
+201
-15
No files matched your search
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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").
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
+15
-4
@@ -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
|
||||
@@ -18,7 +18,7 @@
|
||||
<% aw = aircraft.airworthiness %>
|
||||
<%= link_to aircraft_path(aircraft), class: "card block overflow-hidden transition hover:shadow-md" do %>
|
||||
<div class="flex h-36 items-center justify-center bg-slate-200">
|
||||
<% if aircraft.picture.attached? %>
|
||||
<% if aircraft.picture_shown? %>
|
||||
<%= image_tag aircraft.picture_for(:card), class: "h-full w-full object-cover", loading: "lazy", alt: t(".photo_of", tail_number: aircraft.tail_number) %>
|
||||
<% else %>
|
||||
<span class="text-5xl text-slate-400" aria-hidden="true">✈</span>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<% aw = aircraft.airworthiness %>
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-3">
|
||||
<% if aircraft.picture.attached? %>
|
||||
<% if aircraft.picture_shown? %>
|
||||
<%= image_tag aircraft.picture_for(:thumb), width: 48, height: 48, class: "h-12 w-12 rounded-md object-cover", alt: "" %>
|
||||
<% end %>
|
||||
<div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<% content_for :title, @aircraft.tail_number %>
|
||||
<div class="mb-5 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-3">
|
||||
<% if @aircraft.picture.attached? %><%= image_tag @aircraft.picture_for(:thumb), width: 64, height: 64, class: "h-16 w-16 rounded-md object-cover", alt: t(".photo_of", tail_number: @aircraft.tail_number) %><% end %>
|
||||
<% if @aircraft.picture_shown? %><%= image_tag @aircraft.picture_for(:thumb), width: 64, height: 64, class: "h-16 w-16 rounded-md object-cover", alt: t(".photo_of", tail_number: @aircraft.tail_number) %><% end %>
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold"><%= @aircraft.tail_number %> <span class="text-base font-normal text-slate-500"><%= [@aircraft.make, @aircraft.model].compact_blank.join(" ") %></span></h1>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-2 text-sm">
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
(which has Download); other files open in a new tab and have a download link. %>
|
||||
<% files = squawk.attachments.to_a %>
|
||||
<% if files.any? %>
|
||||
<% photos, others = files.partition { _1.image? && _1.variable? } %>
|
||||
<%# Thumbnails for images that can be resized; others are listed as files. %>
|
||||
<% photos, others = files.partition { _1.image? && _1.blob.resizable_image? } %>
|
||||
<div class="mt-1" data-controller="gallery">
|
||||
<ul class="flex flex-wrap gap-1.5">
|
||||
<% photos.each do |file| %>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Uploads that claim to be images but can't be read as one (empty, corrupt,
|
||||
# or another kind of file with an image name).
|
||||
Rails.application.config.to_prepare do
|
||||
ActiveStorage::Blob.class_eval do
|
||||
# Worth resizing: an image kind that the upload check didn't find
|
||||
# unreadable. (Until that check has run, assume it's fine.)
|
||||
def resizable_image?
|
||||
variable? && !(metadata[:analyzed] && metadata[:width].blank?)
|
||||
end
|
||||
end
|
||||
|
||||
# If resizing fails anyway, send the original rather than an error.
|
||||
ActiveStorage::Representations::BaseController.rescue_from(Vips::Error, ActiveStorage::InvariableError) do
|
||||
redirect_to Rails.application.routes.url_helpers.rails_blob_path(@blob, disposition: params[:disposition], only_path: true)
|
||||
end
|
||||
end
|
||||
@@ -301,6 +301,7 @@ en:
|
||||
attributes:
|
||||
parent_component:
|
||||
itself: can't be itself
|
||||
own_part: can't be one of its own parts
|
||||
other_aircraft: must be on the same aircraft
|
||||
user:
|
||||
attributes:
|
||||
@@ -919,6 +920,7 @@ en:
|
||||
certificate_removed: Certificate removed.
|
||||
application:
|
||||
admins_only: Admins only.
|
||||
invalid_input: Something in that form couldn't be saved. Check what you entered and try again.
|
||||
oil_analyses:
|
||||
oil_analysis_saved: Oil analysis saved.
|
||||
choose_a_lab_report: Choose a lab report PDF.
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
require "test_helper"
|
||||
|
||||
# Requests no form sends, found by fuzzing: each used to be a server error.
|
||||
class MalformedInputTest < ActionDispatch::IntegrationTest
|
||||
setup do
|
||||
@owner = create_user("owner@example.com")
|
||||
@a = create_aircraft(owner: @owner)
|
||||
sign_in @owner
|
||||
end
|
||||
|
||||
test "a page in a format it doesn't have is 'not acceptable', not an error" do
|
||||
%w[pdf json csv zip xml].each do |ext|
|
||||
get "/aircraft/#{@a.id}/report.#{ext}"
|
||||
assert_response :not_acceptable, ext
|
||||
end
|
||||
end
|
||||
|
||||
test "parts can't be made into a loop, and an existing loop doesn't break the pages" do
|
||||
engine = @a.components.create!(component_type: ComponentType.create!(name: "Engine"), manufacturer: "L", model: "O-320", date_in_service: Date.current)
|
||||
mag = @a.components.create!(component_type: ComponentType.create!(name: "Magneto"), manufacturer: "S", model: "4370", date_in_service: Date.current, parent_component: engine)
|
||||
patch aircraft_component_path(@a, engine), params: { component: { parent_component_id: mag.id } }
|
||||
assert_response :unprocessable_entity
|
||||
assert_nil engine.reload.parent_component_id
|
||||
|
||||
engine.update_column(:parent_component_id, mag.id) # as if made before the check existed
|
||||
assert_equal [ mag.id ], engine.reload.ancestor_ids
|
||||
assert_equal [ mag.id ], engine.descendant_ids
|
||||
get new_aircraft_logbook_entry_path(@a)
|
||||
assert_response :success
|
||||
end
|
||||
|
||||
test "a link to a record that doesn't exist is a validation error" do
|
||||
part = @a.components.create!(component_type: ComponentType.create!(name: "Alternator"), manufacturer: "P", model: "ALX", date_in_service: Date.current)
|
||||
patch aircraft_component_path(@a, part), params: { component: { parent_component_id: 999_999 } }
|
||||
assert_response :unprocessable_entity
|
||||
end
|
||||
|
||||
test "a blank required checkbox or number takes its default" do
|
||||
post aircraft_notes_path(@a), params: { aircraft_note: { text: "Blank public", public: "" } }
|
||||
assert_equal false, @a.notes.last.public
|
||||
end
|
||||
|
||||
test "text where a file belongs, or a tampered upload reference, is turned away politely" do
|
||||
post import_aircraft_oil_analyses_path(@a), params: { report: "not a file" }
|
||||
assert_redirected_to new_aircraft_oil_analysis_path(@a)
|
||||
post aircraft_imports_path, params: { archive: "not a file" }
|
||||
assert_redirected_to new_aircraft_import_path
|
||||
post aircraft_logbook_imports_path(@a), params: { pages: [ "not a file" ] }
|
||||
assert_redirected_to new_aircraft_logbook_import_path(@a)
|
||||
|
||||
post aircraft_squawks_path(@a), params: { squawk: { issue_reported: "Leak", attachments: [ "eyJfcmFpbHMiOnt9fQ==--forged" ] } }
|
||||
assert_response :redirect
|
||||
assert_equal "Something in that form couldn't be saved. Check what you entered and try again.", flash[:alert]
|
||||
end
|
||||
|
||||
test "a null byte is refused up front" do
|
||||
post aircraft_notes_path(@a), params: { aircraft_note: { text: "a\u0000b" } }
|
||||
assert_response :bad_request
|
||||
assert_equal 0, @a.notes.count
|
||||
end
|
||||
|
||||
test "a number too big to store is turned away politely" do
|
||||
admin = create_user("admin@example.com", admin: true)
|
||||
sign_in admin
|
||||
template = LogbookTemplate.create!(name: "T", log_type: "AC", entry_type: "MAINTENANCE", text: "x")
|
||||
patch admin_logbook_template_path(template), params: { logbook_template: { position: "9" * 40 } }
|
||||
assert_response :redirect
|
||||
assert_match "couldn't be saved", flash[:alert]
|
||||
end
|
||||
|
||||
test "a rejected photo shows the form's error, not a server error" do
|
||||
patch aircraft_path(@a), params: { aircraft: { picture: Rack::Test::UploadedFile.new(StringIO.new("<html>not a photo</html>"), "text/html", original_filename: "photo.html") } }
|
||||
assert_response :unprocessable_entity
|
||||
patch aircraft_path(@a), params: { aircraft: { picture: Rack::Test::UploadedFile.new(StringIO.new(""), "image/jpeg", original_filename: "empty.jpg") } }
|
||||
assert_response :unprocessable_entity
|
||||
end
|
||||
|
||||
test "an image that can't be read is shown as the file, never resized" do
|
||||
@a.picture.attach(io: StringIO.new("GIF89a not really"), filename: "broken.gif", content_type: "image/gif")
|
||||
@a.picture.blob.update!(metadata: { identified: true, analyzed: true }) # analysis found no dimensions
|
||||
assert_kind_of ActiveStorage::Attached::One, @a.picture_for(:thumb)
|
||||
get aircraft_path(@a)
|
||||
assert_response :success
|
||||
assert_select "img[src*='/representations/']", 0
|
||||
end
|
||||
|
||||
test "if resizing a photo fails anyway, the original is sent instead of an error" do
|
||||
@a.picture.attach(io: StringIO.new("GIF89a not really"), filename: "broken.gif", content_type: "image/gif")
|
||||
get url_for(@a.picture.variant(:thumb))
|
||||
assert_response :redirect
|
||||
assert_match %r{/rails/active_storage/blobs/redirect/}, response.location
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user