Admin setting for the maximum upload size

- Admin -> Settings: maximum upload size per file (1-1024 MB, default 50),
  stored in a new settings table and read on each use, so a change applies
  to every process at once
- Enforced by attachment validation and the direct-upload endpoint; upload
  forms, bulk upload and Admin -> About show the current limit
- .sam.zip import accepts files up to 1 GB to match

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-07 09:45:12 -05:00
1 parent 4f548f3874
commit ef7cd2efba
16 files changed
+186 -13

No files matched your search

@@ -0,0 +1,20 @@
class Admin::SettingsController < ApplicationController
before_action :require_admin!
def edit
@values = Setting::INTEGERS.keys.index_with { Setting.integer(_1) }
end
def update
submitted = params.fetch(:settings, {}).permit(*Setting::INTEGERS.keys).to_h
records = Setting.update_integers(submitted)
@errors = records.flat_map { _1.errors.full_messages }
if @errors.empty?
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
redirect_to edit_admin_settings_path, notice: "Settings saved."
else
@values = Setting::INTEGERS.keys.index_with { Setting.integer(_1) }.merge(submitted)
render :edit, status: :unprocessable_entity
end
end
end
+2 -2
View File
@@ -17,8 +17,8 @@ class DirectUploadsController < ActiveStorage::DirectUploadsController
error = error =
if !UploadValidation::ALLOWED_CONTENT_TYPES.include?(blob_args[:content_type]) if !UploadValidation::ALLOWED_CONTENT_TYPES.include?(blob_args[:content_type])
"#{blob_args[:filename]} isn't an allowed file type" "#{blob_args[:filename]} isn't an allowed file type"
elsif blob_args[:byte_size].to_i > UploadValidation::MAX_SIZE elsif blob_args[:byte_size].to_i > UploadValidation.max_size
"#{blob_args[:filename]} is over #{UploadValidation::MAX_SIZE / 1.megabyte} MB" "#{blob_args[:filename]} is over the #{UploadValidation.max_size / 1.megabyte} MB upload limit"
end end
render json: { error: error }, status: :unprocessable_entity if error render json: { error: error }, status: :unprocessable_entity if error
end end
@@ -29,7 +29,7 @@ export default class extends Controller {
add(event) { add(event) {
for (const file of event.target.files) { for (const file of event.target.files) {
const item = { file, path: file.webkitRelativePath || file.name, state: "pending", progress: 0 } const item = { file, path: file.webkitRelativePath || file.name, state: "pending", progress: 0 }
if (file.size > this.maxBytesValue) Object.assign(item, { state: "error", error: `over ${Math.round(this.maxBytesValue / 1048576)} MB` }) if (file.size > this.maxBytesValue) Object.assign(item, { state: "error", error: `over the ${Math.round(this.maxBytesValue / 1048576)} MB limit` })
this.items.push(item) this.items.push(item)
} }
event.target.value = "" event.target.value = ""
+5 -2
View File
@@ -7,7 +7,9 @@ module UploadValidation
application/pdf text/plain application/gpx+xml application/xml text/xml application/pdf text/plain application/gpx+xml application/xml text/xml
text/csv application/vnd.google-earth.kml+xml application/octet-stream text/csv application/vnd.google-earth.kml+xml application/octet-stream
].freeze ].freeze
MAX_SIZE = 50.megabytes
# Set by admins (Admin → Settings), default 50 MB.
def self.max_size = Setting.max_upload_bytes
class_methods do class_methods do
def validates_uploads(*names) def validates_uploads(*names)
@@ -18,7 +20,8 @@ module UploadValidation
unless ALLOWED_CONTENT_TYPES.include?(att.blob.content_type) unless ALLOWED_CONTENT_TYPES.include?(att.blob.content_type)
errors.add(name, "#{att.filename} is not an allowed file type") errors.add(name, "#{att.filename} is not an allowed file type")
end end
errors.add(name, "#{att.filename} is too large") if att.blob.byte_size > MAX_SIZE limit = UploadValidation.max_size
errors.add(name, "#{att.filename} is over the #{limit / 1.megabyte} MB upload limit") if att.blob.byte_size > limit
end end
end end
end end
+43
View File
@@ -0,0 +1,43 @@
# App-wide settings an admin can change (Admin → Settings), stored as
# key/value rows. Read straight from the database each time, so a change
# applies to every server process at once.
#
# Setting.max_upload_mb # => 50
# Setting.max_upload_bytes # => 52428800
class Setting < ApplicationRecord
INTEGERS = {
"max_upload_mb" => { default: 50, in: 1..1024, label: "Maximum upload size (MB)" }
}.freeze
validates :key, presence: true, uniqueness: true, inclusion: { in: INTEGERS.keys }
validate :value_in_range
class << self
def max_upload_mb = integer("max_upload_mb")
def max_upload_bytes = max_upload_mb.megabytes
def integer(key)
definition = INTEGERS.fetch(key)
value = find_by(key: key)&.value
value.present? ? value.to_i.clamp(definition[:in]) : definition[:default]
end
# Saves several settings; returns the records (check #errors) or [].
def update_integers(values)
records = values.to_h.slice(*INTEGERS.keys).map do |key, value|
find_or_initialize_by(key: key).tap { _1.value = value.to_s.strip }
end
transaction { records.each { _1.save || raise(ActiveRecord::Rollback) } }
records
end
end
private
def value_in_range
definition = INTEGERS[key] or return
unless value.to_s.match?(/\A\d+\z/) && definition[:in].cover?(value.to_i)
errors.add(:base, "#{definition[:label]} must be a whole number from #{definition[:in].min} to #{definition[:in].max}")
end
end
end
+1
View File
@@ -48,6 +48,7 @@ class SystemInfo
"Single sign-on" => Sso.enabled? ? "#{Sso.label}#{', password sign-in off' unless Sso.password_login?}" : "not configured", "Single sign-on" => Sso.enabled? ? "#{Sso.label}#{', password sign-in off' unless Sso.password_login?}" : "not configured",
"AI logbook transcription" => ENV["ANTHROPIC_API_KEY"].present? ? "on (#{LogbookTranscriber::MODEL})" : "no API key", "AI logbook transcription" => ENV["ANTHROPIC_API_KEY"].present? ? "on (#{LogbookTranscriber::MODEL})" : "no API key",
"Email" => MailSettings.configured? ? ActionMailer::Base.delivery_method.to_s.upcase : "not configured", "Email" => MailSettings.configured? ? ActionMailer::Base.delivery_method.to_s.upcase : "not configured",
"Upload limit" => "#{Setting.max_upload_mb} MB per file",
"HTTPS enforced" => Rails.application.config.force_ssl ? "yes" : "no", "HTTPS enforced" => Rails.application.config.force_ssl ? "yes" : "no",
"File storage" => ActiveStorage::Blob.service.class.name.demodulize.delete_suffix("Service") "File storage" => ActiveStorage::Blob.service.class.name.demodulize.delete_suffix("Service")
} }
+1 -1
View File
@@ -21,7 +21,7 @@ module AircraftArchive
OPTIONAL_KEYS = %w[features].freeze # and flight_logs before schema v2 OPTIONAL_KEYS = %w[features].freeze # and flight_logs before schema v2
MANIFEST_MAX_BYTES = 50.megabytes MANIFEST_MAX_BYTES = 50.megabytes
FILE_MAX_BYTES = 512.megabytes FILE_MAX_BYTES = 1.gigabyte # the most Admin → Settings allows for uploads
ARCHIVE_MAX_BYTES = 10.gigabytes # uncompressed ARCHIVE_MAX_BYTES = 10.gigabytes # uncompressed
MAX_RATIO = 100 # compression ratio above this looks like a zip bomb MAX_RATIO = 100 # compression ratio above this looks like a zip bomb
+26
View File
@@ -0,0 +1,26 @@
<% content_for :title, "Settings" %>
<h1 class="mb-4 text-2xl font-bold">Settings</h1>
<%= form_with url: admin_settings_path, method: :patch, class: "card card-body max-w-xl space-y-4" do |f| %>
<% if @errors.present? %>
<div class="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200" role="alert">
<ul class="list-disc pl-5"><% @errors.each do |e| %><li><%= e %></li><% end %></ul>
</div>
<% end %>
<h2 class="card-title">Uploads</h2>
<% upload = Setting::INTEGERS["max_upload_mb"] %>
<div>
<%= label_tag "settings[max_upload_mb]", upload[:label], class: "label" %>
<%= number_field_tag "settings[max_upload_mb]", @values["max_upload_mb"], id: "settings_max_upload_mb",
min: upload[:in].min, max: upload[:in].max, step: 1, required: true, class: "input w-32" %>
<p class="hint">
The largest single file anyone can upload: documents, squawk photos and bulk uploads. Default <%= upload[:default] %> MB, up to <%= upload[:in].max %> MB.
</p>
<p class="hint">
A proxy in front of the app can have its own, smaller limit. Cloudflare's proxy stops at 100 MB on its free plan; nginx needs <code>client_max_body_size</code>.
Logbook transcription with Claude reads PDFs up to <%= LogbookTranscriber::MAX_PDF_BYTES / 1.megabyte %> MB and images up to <%= LogbookTranscriber::MAX_IMAGE_BYTES / 1.megabyte %> MB, whatever this is set to.
</p>
</div>
<div class="flex gap-2"><%= f.submit "Save Settings", class: "btn-primary" %><%= link_to "Cancel", admin_about_path, class: "btn-secondary" %></div>
<% end %>
+1 -1
View File
@@ -10,7 +10,7 @@
</div> </div>
<%= f.field :description, as: :textarea, rows: 2 %> <%= f.field :description, as: :textarea, rows: 2 %>
<%= f.field :pages, as: :file, multiple: true, label: document.persisted? ? "Add files" : "Files", <%= f.field :pages, as: :file, multiple: true, label: document.persisted? ? "Add files" : "Files",
hint: "Images, PDFs or text. Each file is a page in the viewer, in upload order." %> hint: "Images, PDFs or text, up to #{Setting.max_upload_mb} MB each. Each file is a page in the viewer, in upload order." %>
<% if document.persisted? && document.pages.any? %> <% if document.persisted? && document.pages.any? %>
<div> <div>
<p class="label">Remove existing files</p> <p class="label">Remove existing files</p>
+2 -2
View File
@@ -3,7 +3,7 @@
<% file_classes = "block w-full text-sm text-slate-600 file:mr-3 file:rounded-md file:border-0 file:bg-slate-100 file:px-3 file:py-1.5 file:text-sm file:font-medium hover:file:bg-slate-200" %> <% file_classes = "block w-full text-sm text-slate-600 file:mr-3 file:rounded-md file:border-0 file:bg-slate-100 file:px-3 file:py-1.5 file:text-sm file:font-medium hover:file:bg-slate-200" %>
<%= form_with url: bulk_aircraft_documents_path(@aircraft), multipart: true, class: "card card-body max-w-3xl space-y-4", <%= form_with url: bulk_aircraft_documents_path(@aircraft), multipart: true, class: "card card-body max-w-3xl space-y-4",
data: { controller: "bulk-upload", bulk_upload_url_value: rails_direct_uploads_path, data: { controller: "bulk-upload", bulk_upload_url_value: rails_direct_uploads_path,
bulk_upload_max_bytes_value: UploadValidation::MAX_SIZE, action: "submit->bulk-upload#submit" } do %> bulk_upload_max_bytes_value: UploadValidation.max_size, action: "submit->bulk-upload#submit" } do %>
<div> <div>
<h2 class="card-title">Bulk upload</h2> <h2 class="card-title">Bulk upload</h2>
<p class="text-sm text-slate-500">Each file becomes its own document, named after the file. Give files the same name to combine them, in order, as the pages of one document.</p> <p class="text-sm text-slate-500">Each file becomes its own document, named after the file. Give files the same name to combine them, in order, as the pages of one document.</p>
@@ -44,7 +44,7 @@
data-bulk-upload-target="folder" data-action="change->bulk-upload#add"> data-bulk-upload-target="folder" data-action="change->bulk-upload#add">
</div> </div>
</div> </div>
<p class="hint !mt-1">Images, PDFs or text, up to <%= UploadValidation::MAX_SIZE / 1.megabyte %> MB each and <%= DocumentsController::MAX_BULK_FILES %> at a time.</p> <p class="hint !mt-1">Images, PDFs or text, up to <%= Setting.max_upload_mb %> MB each and <%= DocumentsController::MAX_BULK_FILES %> at a time.</p>
<div data-bulk-upload-target="panel" hidden class="space-y-2"> <div data-bulk-upload-target="panel" hidden class="space-y-2">
<div class="flex flex-wrap items-center justify-between gap-2"> <div class="flex flex-wrap items-center justify-between gap-2">
+2 -2
View File
@@ -37,7 +37,7 @@
<%= link_to "Profile", edit_profile_path, class: "block px-4 py-2.5 hover:bg-slate-100" %> <%= link_to "Profile", edit_profile_path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
<% if current_user.admin? %> <% if current_user.admin? %>
<p class="border-t border-slate-100 px-4 pt-2 pb-1 text-xs font-semibold text-slate-500">Admin</p> <p class="border-t border-slate-100 px-4 pt-2 pb-1 text-xs font-semibold text-slate-500">Admin</p>
<% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "About", admin_about_path ] ].each do |label, path| %> <% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Settings", edit_admin_settings_path ], [ "About", admin_about_path ] ].each do |label, path| %>
<%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %> <%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
<% end %> <% end %>
<% end %> <% end %>
@@ -53,7 +53,7 @@
Admin <span aria-hidden="true" class="text-xs">▾</span> Admin <span aria-hidden="true" class="text-xs">▾</span>
</summary> </summary>
<div class="absolute right-0 z-30 mt-2 w-48 rounded-md bg-surface py-1 text-slate-700 shadow-lg ring-1 ring-slate-200"> <div class="absolute right-0 z-30 mt-2 w-48 rounded-md bg-surface py-1 text-slate-700 shadow-lg ring-1 ring-slate-200">
<% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "About", admin_about_path ] ].each do |label, path| %> <% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Settings", edit_admin_settings_path ], [ "About", admin_about_path ] ].each do |label, path| %>
<%= link_to label, path, class: [ "block px-4 py-2 text-sm hover:bg-slate-100", ("font-semibold text-sky-700" if current_page?(path)) ] %> <%= link_to label, path, class: [ "block px-4 py-2 text-sm hover:bg-slate-100", ("font-semibold text-sky-700" if current_page?(path)) ] %>
<% end %> <% end %>
</div> </div>
+1 -1
View File
@@ -4,7 +4,7 @@
<%= f.field :issue_reported, as: :textarea, label: "Issue", required: true, autofocus: true %> <%= f.field :issue_reported, as: :textarea, label: "Issue", required: true, autofocus: true %>
<%= f.field :component_id, as: :select, label: "Component (optional)", collection: component_options(aircraft) %> <%= f.field :component_id, as: :select, label: "Component (optional)", collection: component_options(aircraft) %>
<%= f.field :attachments, as: :file, multiple: true, label: squawk.attachments.attached? ? "Add photos / files" : "Photos / files", <%= f.field :attachments, as: :file, multiple: true, label: squawk.attachments.attached? ? "Add photos / files" : "Photos / files",
hint: "Select several at once. Images, PDFs or text, up to 50 MB each." %> hint: "Select several at once. Images, PDFs or text, up to #{Setting.max_upload_mb} MB each." %>
<% if squawk.persisted? && squawk.attachments.attached? %> <% if squawk.persisted? && squawk.attachments.attached? %>
<div> <div>
<p class="label">Remove attached files</p> <p class="label">Remove attached files</p>
+1
View File
@@ -88,6 +88,7 @@ Rails.application.routes.draw do
namespace :admin do namespace :admin do
get "about", to: "about#show" get "about", to: "about#show"
resource :settings, only: %i[edit update]
post "about/test_email", to: "about#test_email", as: :test_email post "about/test_email", to: "about#test_email", as: :test_email
resources :users, except: :show resources :users, except: :show
resources :component_types, except: :show resources :component_types, except: :show
@@ -0,0 +1,10 @@
class CreateSettings < ActiveRecord::Migration[8.1]
def change
create_table :settings do |t|
t.string :key, null: false
t.text :value
t.timestamps
end
add_index :settings, :key, unique: true
end
end
Generated
+9 -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_07_170000) do ActiveRecord::Schema[8.1].define(version: 2026_11_07_180000) 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
@@ -498,6 +498,14 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_170000) do
t.index ["user_id"], name: "index_sessions_on_user_id" t.index ["user_id"], name: "index_sessions_on_user_id"
end end
create_table "settings", force: :cascade do |t|
t.string "key", null: false
t.text "value"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["key"], name: "index_settings_on_key", unique: true
end
create_table "share_tokens", force: :cascade do |t| create_table "share_tokens", force: :cascade do |t|
t.integer "aircraft_id", null: false t.integer "aircraft_id", null: false
t.integer "created_by_id" t.integer "created_by_id"
+61
View File
@@ -0,0 +1,61 @@
require "test_helper"
class AdminSettingsTest < ActionDispatch::IntegrationTest
setup do
@admin = create_user("admin@example.com", admin: true)
@owner = create_user("owner@example.com")
@a = create_aircraft(owner: @owner)
end
def pdf(bytes) = { io: StringIO.new("%PDF".ljust(bytes, "x")), filename: "big.pdf", content_type: "application/pdf" }
test "only admins change settings; bad values are refused" do
sign_in @owner
get edit_admin_settings_path
assert_redirected_to root_path
patch admin_settings_path, params: { settings: { max_upload_mb: 500 } }
assert_equal 50, Setting.max_upload_mb
sign_in @admin
get root_path
assert_select "a[href='#{edit_admin_settings_path}']", text: "Settings"
get edit_admin_settings_path
assert_select "input[name='settings[max_upload_mb]'][value='50'][max='1024']"
[ "0", "2000", "abc", "" ].each do |bad|
patch admin_settings_path, params: { settings: { max_upload_mb: bad } }
assert_response :unprocessable_entity
assert_includes response.body, "must be a whole number from 1 to 1024"
end
assert_equal 50, Setting.max_upload_mb
patch admin_settings_path, params: { settings: { max_upload_mb: "200" } }
assert_redirected_to edit_admin_settings_path
assert_equal [ 200, 200.megabytes ], [ Setting.max_upload_mb, Setting.max_upload_bytes ]
get admin_about_path
assert_includes response.body, "200 MB per file"
end
test "the limit applies to saved files, direct uploads and the upload pages" do
Setting.update_integers("max_upload_mb" => "1")
doc = @a.documents.new(name: "Scan", doc_type: "OTHER", pages: [ pdf(1.megabyte + 1) ])
refute doc.valid?
assert_includes doc.errors.full_messages.to_sentence, "big.pdf is over the 1 MB upload limit"
assert @a.documents.new(name: "Scan", doc_type: "OTHER", pages: [ pdf(1.megabyte) ]).valid?
sign_in @owner
post "/rails/active_storage/direct_uploads", as: :json, params: { blob: {
filename: "big.pdf", byte_size: 2.megabytes, checksum: "Q2hlY2tzdW0=", content_type: "application/pdf" } }
assert_response :unprocessable_entity
assert_equal "big.pdf is over the 1 MB upload limit", response.parsed_body["error"]
get new_bulk_aircraft_documents_path(@a)
assert_select "form[data-bulk-upload-max-bytes-value='#{1.megabyte}']"
assert_includes response.body, "up to 1 MB each"
get new_aircraft_squawk_path(@a)
assert_includes response.body, "up to 1 MB each"
Setting.update_integers("max_upload_mb" => "100") # raising it lets a 60 MB-class file through
assert @a.documents.new(name: "Scan", doc_type: "OTHER", pages: [ pdf(60.megabytes) ]).valid?
end
end