mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 23:50:36 -05:00
Harden installs reachable from the internet without a proxy
- Refuse to start with a placeholder or short SECRET_KEY_BASE (under 32 characters); warn and fail sam:doctor under 64. .env.example no longer ships a placeholder. - First-run setup needs a one-time code printed only in the server log, so only whoever runs the server can create the admin account. - AirTrail: the server resolves the address and connects to exactly that; never the server itself or link-local addresses (cloud metadata); private-network addresses only for admins or hosts in AIRTRAIL_ALLOWED_HOSTS. - Host authorization when APP_HOST is set: APP_HOST, the APP_URL host, ALLOWED_HOSTS, localhost and IP addresses; /up exempt. A blocked name gets a short explanation instead of a blank 403. - docker-compose.direct.yml: HTTPS without a proxy via Thruster's built-in Let's Encrypt (TLS_DOMAIN). - Notes' Markdown no longer allows the unused class attribute. - README, .env.example and the user guide updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
faae719b12
commit
5876c07a1a
20 files changed
+319
-29
No files matched your search
@@ -1,16 +1,24 @@
|
||||
class SetupController < ApplicationController
|
||||
allow_unauthenticated_access
|
||||
before_action { redirect_to root_path if User.exists? }
|
||||
rate_limit to: 10, within: 15.minutes, only: :create, with: -> { redirect_to new_setup_path, alert: t("flash.setup.try_again_later") }
|
||||
layout "public"
|
||||
|
||||
def new
|
||||
@user = User.new
|
||||
SetupCode.announce
|
||||
end
|
||||
|
||||
def create
|
||||
@user = User.new(params.require(:user).permit(:name, :email_address, :password, :password_confirmation))
|
||||
@user.admin = true
|
||||
unless SetupCode.matches?(params[:setup_code])
|
||||
@user.errors.add(:base, t("flash.setup.wrong_code"))
|
||||
SetupCode.announce
|
||||
return render(:new, status: :unprocessable_entity)
|
||||
end
|
||||
if @user.save
|
||||
SetupCode.clear
|
||||
start_new_session_for @user
|
||||
redirect_to root_path, notice: t("flash.setup.welcome_you_re_the")
|
||||
else
|
||||
|
||||
@@ -9,7 +9,7 @@ module MarkdownHelper
|
||||
extension: { strikethrough: true, tagfilter: true, table: true, autolink: true, tasklist: true, header_ids: nil, footnotes: false }
|
||||
}.freeze
|
||||
TAGS = %w[p br strong em del a ul ol li blockquote code pre h1 h2 h3 h4 h5 h6 hr table thead tbody tr th td input span].freeze
|
||||
ATTRIBUTES = %w[href title type checked disabled align class].freeze
|
||||
ATTRIBUTES = %w[href title type checked disabled align].freeze
|
||||
|
||||
def markdown(text)
|
||||
return "".html_safe if text.blank?
|
||||
|
||||
@@ -20,7 +20,7 @@ class AirTrailConnection < ApplicationRecord
|
||||
|
||||
scope :active, -> { where(enabled: true) }
|
||||
|
||||
def client = AirTrailClient.new(base_url: base_url, api_key: api_key)
|
||||
def client = AirTrailClient.new(base_url: base_url, api_key: api_key, allow_private: user&.admin?)
|
||||
|
||||
def ok? = status == "ok"
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# The application secret key signs the sign-in cookie and protects stored
|
||||
# secrets (two-factor keys, API keys), so anyone who can guess it can sign in
|
||||
# as anyone. A placeholder or short key stops the app from starting; one
|
||||
# shorter than what `bin/rails secret` makes is reported by sam:doctor.
|
||||
module SecretKeyCheck
|
||||
MIN = 32 # below this, refuse to start
|
||||
RECOMMENDED = 64 # below this, warn
|
||||
PLACEHOLDERS = %w[change-me changeme change_me secret password your-secret-key replace-me example].freeze
|
||||
|
||||
module_function
|
||||
|
||||
# :ok, :weak or :unsafe
|
||||
def strength(key = ENV["SECRET_KEY_BASE"].to_s)
|
||||
return :unsafe if PLACEHOLDERS.include?(key.strip.downcase) || key.length < MIN || key.chars.uniq.size < 10
|
||||
key.length < RECOMMENDED ? :weak : :ok
|
||||
end
|
||||
|
||||
def verify!(key = ENV["SECRET_KEY_BASE"].to_s)
|
||||
case strength(key)
|
||||
when :unsafe
|
||||
abort "SECRET_KEY_BASE is a placeholder or too short (#{key.length} characters). " \
|
||||
"Set it to the output of `bin/rails secret` (128 random characters) and start again."
|
||||
when :weak
|
||||
Rails.logger.warn("[security] SECRET_KEY_BASE is only #{key.length} characters; `bin/rails secret` makes 128.")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
# Until the first account exists, whoever reaches the server could create the
|
||||
# admin account. The setup page asks for this one-time code, which is only in
|
||||
# the server's log, so only whoever runs the server can finish setup.
|
||||
module SetupCode
|
||||
ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789".chars.freeze # no look-alikes (0/O, 1/I/L)
|
||||
|
||||
module_function
|
||||
|
||||
# (Each parallel test process has its own.)
|
||||
def file = Rails.env.test? ? Rails.root.join("tmp", "setup_code-#{Process.pid}") : Rails.root.join("storage", "setup_code")
|
||||
|
||||
# The code, made the first time it's needed and kept until setup is done.
|
||||
def current
|
||||
return file.read.strip if file.exist?
|
||||
code = Array.new(8) { ALPHABET[SecureRandom.random_number(ALPHABET.size)] }.join.insert(4, "-")
|
||||
file.dirname.mkpath
|
||||
File.write(file, code, perm: 0o600)
|
||||
code
|
||||
end
|
||||
|
||||
def announce
|
||||
Rails.logger.warn("Setup code: #{current} (enter it on the setup page to create the admin account)")
|
||||
end
|
||||
|
||||
def matches?(given)
|
||||
normalize = ->(s) { s.to_s.upcase.gsub(/[^A-Z0-9]/, "") }
|
||||
ActiveSupport::SecurityUtils.secure_compare(normalize.(given), normalize.(current))
|
||||
end
|
||||
|
||||
def clear
|
||||
file.delete if file.exist?
|
||||
end
|
||||
end
|
||||
@@ -16,12 +16,25 @@ class AirTrailClient
|
||||
class NotFound < Error; end
|
||||
class ValidationError < Error; end # 400/422
|
||||
|
||||
def initialize(base_url:, api_key:, timeout: 20)
|
||||
# An address the server won't send to (see #address). Like a bad key, the
|
||||
# user has to fix the connection, so it's recorded there and not retried.
|
||||
class BlockedAddress < AuthError; end
|
||||
|
||||
# allow_private: may reach addresses on the private network (admins; and
|
||||
# hosts listed in AIRTRAIL_ALLOWED_HOSTS for everyone). The server itself
|
||||
# and link-local addresses (cloud metadata) are never reached.
|
||||
def initialize(base_url:, api_key:, timeout: 20, allow_private: false)
|
||||
@base = URI.parse(base_url.to_s.chomp("/"))
|
||||
@api_key = api_key
|
||||
@timeout = timeout
|
||||
@allow_private = allow_private || self.class.allowed_hosts.include?(@base.host.to_s.downcase)
|
||||
end
|
||||
|
||||
# Host name → IP addresses (replaceable in tests, which have no DNS).
|
||||
class_attribute :resolver, default: ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address) }
|
||||
|
||||
def self.allowed_hosts = ENV.fetch("AIRTRAIL_ALLOWED_HOSTS", "").split(",").map { _1.strip.downcase }.compact_blank
|
||||
|
||||
def me = request(:get, "/api/v1/me").fetch("data")
|
||||
|
||||
def search_airports(query) = request(:get, "/api/v1/airports", query: { query: query }).fetch("data")
|
||||
@@ -63,13 +76,33 @@ class AirTrailClient
|
||||
req.body = JSON.generate(body)
|
||||
end
|
||||
|
||||
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
|
||||
open_timeout: @timeout, read_timeout: @timeout) { _1.request(req) }
|
||||
handle(response)
|
||||
http = Net::HTTP.new(uri.host, uri.port)
|
||||
http.ipaddr = address(uri.host) # connect to the address that was checked (the name can't be re-pointed in between)
|
||||
http.use_ssl = uri.scheme == "https"
|
||||
http.open_timeout = http.read_timeout = @timeout
|
||||
handle(http.start { _1.request(req) })
|
||||
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
|
||||
raise NetworkError, I18n.t("services.air_trail.can_t_reach_airtrail_at", host: @base.host, message: e.message)
|
||||
end
|
||||
|
||||
# The address to connect to: the host's first, once all of its addresses are
|
||||
# ones this connection may reach.
|
||||
def address(host)
|
||||
ips = resolver.call(host).map { IPAddr.new(_1.sub(/%.*/, "")) }.uniq
|
||||
raise SocketError, "no address" if ips.empty?
|
||||
ips.each do |ip|
|
||||
ip = ip.native # ::ffff:10.0.0.1 → 10.0.0.1
|
||||
reason = if ip.loopback? || ip.link_local? || UNREACHABLE.any? { _1.include?(ip) } then :never
|
||||
elsif (ip.private? || CGNAT.include?(ip)) && !@allow_private then :private
|
||||
end
|
||||
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{reason}", host: host) if reason
|
||||
end
|
||||
ips.first.to_s
|
||||
end
|
||||
|
||||
UNREACHABLE = [ IPAddr.new("0.0.0.0/8"), IPAddr.new("::/128"), IPAddr.new("224.0.0.0/4"), IPAddr.new("ff00::/8") ].freeze
|
||||
CGNAT = IPAddr.new("100.64.0.0/10") # shared address space, e.g. Tailscale
|
||||
|
||||
def handle(response)
|
||||
status = response.code.to_i
|
||||
json = begin
|
||||
|
||||
@@ -28,7 +28,12 @@ class SystemDoctor
|
||||
|
||||
def secret_key
|
||||
return ok("Secret key", "development/test key") unless production?
|
||||
ENV["SECRET_KEY_BASE"].present? || ENV["RAILS_MASTER_KEY"].present? ? ok("Secret key", "set (keep a copy off the server)") : warning("Secret key", "SECRET_KEY_BASE isn't set in the environment")
|
||||
return warning("Secret key", "SECRET_KEY_BASE isn't set in the environment") if ENV["SECRET_KEY_BASE"].blank? && ENV["RAILS_MASTER_KEY"].blank?
|
||||
return ok("Secret key", "set (keep a copy off the server)") if ENV["SECRET_KEY_BASE"].blank?
|
||||
case SecretKeyCheck.strength
|
||||
when :ok then ok("Secret key", "set (keep a copy off the server)")
|
||||
else failed("Secret key", "only #{ENV['SECRET_KEY_BASE'].length} characters: replace it with the output of bin/rails secret")
|
||||
end
|
||||
end
|
||||
|
||||
def host
|
||||
|
||||
@@ -3,6 +3,12 @@
|
||||
<p class="mb-4 text-sm text-slate-600"><%= t(".create_the_administrator_account_to") %></p>
|
||||
<%= form_with model: @user, url: setup_path, class: "card card-body space-y-4" do |f| %>
|
||||
<%= f.errors_summary %>
|
||||
<div>
|
||||
<%= label_tag :setup_code, t(".setup_code"), class: "label" %>
|
||||
<%= text_field_tag :setup_code, params[:setup_code], required: true, autocomplete: "off", autocapitalize: "characters", spellcheck: false,
|
||||
class: "input font-mono tracking-widest", placeholder: "XXXX-XXXX" %>
|
||||
<p class="hint"><%= t(".setup_code_hint_html") %></p>
|
||||
</div>
|
||||
<%= f.field :name %>
|
||||
<%= f.field :email_address, as: :email, label: t(".email"), required: true %>
|
||||
<%= f.field :password, as: :password, required: true, hint: t(".at_least_characters_not_one", min: User::PASSWORD_MIN) %>
|
||||
|
||||
Reference in new issue
Block a user