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:
rickyandClaude Opus 5.5 committed 2026-11-14 12:42:53 -05:00
1 parent faae719b12
commit 5876c07a1a
20 files changed
+319 -29

No files matched your search

+22 -5
View File
@@ -2,10 +2,11 @@
# block is required. Every setting is explained in the README.
# --- Required ----------------------------------------------------------
# Generate with: bin/rails secret (or: openssl rand -hex 64)
# Keep a copy somewhere safe off the server: signatures and stored secrets
# depend on it, and a restore needs the same one.
SECRET_KEY_BASE=change-me
# Generate with: bin/rails secret (or: openssl rand -hex 64). Anyone who knows
# it can sign in as anyone, so the app won't start with a placeholder or a
# short one. Keep a copy somewhere safe off the server: signatures and stored
# secrets depend on it, and a restore needs the same one.
SECRET_KEY_BASE=
# The host name people use to reach the app (used in email links).
APP_HOST=aircraft.example.com
@@ -13,9 +14,20 @@ APP_HOST=aircraft.example.com
# their own zone, from Profile or their device). Default UTC.
# TZ=America/New_York
# true: the app redirects to HTTPS and sets secure cookies (use behind a TLS
# proxy such as Traefik, Caddy or Cloudflare Tunnel). false: plain HTTP on a LAN.
# proxy such as Traefik, Caddy or Cloudflare Tunnel, or with TLS_DOMAIN).
# false: plain HTTP, only on a private network: passwords travel unencrypted.
FORCE_SSL=true
# --- HTTPS without a proxy (docker-compose.direct.yml) -------------------
# The app gets a Let's Encrypt certificate for this name itself (ports 80
# and 443 must reach it).
# TLS_DOMAIN=aircraft.example.com
# --- Allowed addresses ---------------------------------------------------
# Requests are answered only for APP_HOST (and the APP_URL host), localhost
# and IP addresses. Other names that should work, comma-separated:
# ALLOWED_HOSTS=sam.lan,aircraft.home.arpa
# --- Address -----------------------------------------------------------
# Full public URL, if it isn't https://APP_HOST (used for the single sign-on
# and Google Drive redirect URIs).
@@ -37,6 +49,11 @@ FORCE_SSL=true
# OIDC_AUTO_CREATE_USERS=false # true: create an account at first sign-in
# OIDC_TRUST_EMAIL=false # true: link accounts by unverified email
# OIDC_ADMIN_GROUP= # members become admins (synced at sign-in)
# --- AirTrail ------------------------------------------------------------
# AirTrail servers on your private network that everyone may connect to
# (admins can always use private addresses), comma-separated host names:
# AIRTRAIL_ALLOWED_HOSTS=airtrail.lan
# PASSWORD_LOGIN=true # false: SSO only (invited mechanics then can't sign in)
# --- Sign-in security ----------------------------------------------------
+11 -5
View File
@@ -33,7 +33,7 @@ bin/dev # http://localhost:3000
```
With demo data, sign in as `admin@example.com` / `demo-password-123` (admin, owner of N12345) or `pilot@example.com` / `demo-password-123` (pilot).
Without demo data, the first visit asks you to create the admin account.
Without demo data, the first visit asks you to create the admin account. It needs the one-time setup code printed in the server's log (the line starting `Setup code`), so only whoever runs the server can claim it.
Run the tests: `bin/rails test`
@@ -48,11 +48,14 @@ cp .env.example .env # set SECRET_KEY_BASE (bin/rails secret), APP_HOST
docker compose up -d --build # http://<host>:3000
```
Data lives in the `sam_storage` volume. Set `FORCE_SSL=false` if you serve plain HTTP on a LAN. Set it to `true` when a TLS reverse proxy such as Caddy, Traefik, or Cloudflare Tunnel sits in front.
Data lives in the `sam_storage` volume. Set `FORCE_SSL=false` only if you serve plain HTTP on a private network: passwords and sign-in cookies then travel unencrypted. Set it to `true` when a TLS reverse proxy such as Caddy, Traefik, or Cloudflare Tunnel sits in front, or use the built-in HTTPS below.
The first visit asks for the setup code from the log: `docker compose logs web | grep "Setup code"`.
Other examples in the repository:
- [`docker-compose.image.yml`](docker-compose.image.yml): runs the published image (`barrettefab/simple-aircraft-manager-rails` on Docker Hub) without cloning the source, with a health check and update steps.
- [`docker-compose.direct.yml`](docker-compose.direct.yml): directly on the internet with HTTPS and no proxy. The image's web server gets and renews a Let's Encrypt certificate for `TLS_DOMAIN` by itself (ports 80 and 443 must reach the server).
- [`docker-compose.traefik.yml`](docker-compose.traefik.yml): behind Traefik with HTTPS, with optional Authentik forward auth (see [Running behind Authentik](docs/authentik.md)).
[`.env.example`](.env.example) lists every setting, grouped and commented. After starting or updating, `docker compose exec web bin/rails sam:doctor` checks the installation.
@@ -69,9 +72,12 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
| Variable | Purpose |
|---|---|
| `SECRET_KEY_BASE` | Required in production (`bin/rails secret`). Alternatively provide `RAILS_MASTER_KEY`. |
| `FORCE_SSL` | `true` (default) redirects to HTTPS and sets secure cookies. Use `false` for plain HTTP. |
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). |
| `SECRET_KEY_BASE` | Required in production (`bin/rails secret`). Anyone who knows it can sign in as anyone, so the app won't start with a placeholder or one under 32 characters, and `sam:doctor` flags one under 64. Alternatively provide `RAILS_MASTER_KEY`. |
| `FORCE_SSL` | `true` (default) redirects to HTTPS and sets secure cookies. Use `false` for plain HTTP, only on a private network. |
| `TLS_DOMAIN` | Optional. HTTPS without a proxy: the app gets a Let's Encrypt certificate for this name (see `docker-compose.direct.yml`). |
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). When set, the app answers only for this name, the `APP_URL` host, `ALLOWED_HOSTS`, `localhost` and IP addresses. |
| `ALLOWED_HOSTS` | Optional. Other names the app may be reached by, comma-separated (e.g. a LAN name). |
| `AIRTRAIL_ALLOWED_HOSTS` | Optional. AirTrail servers on your private network that anyone may connect to, comma-separated. Admins can always connect to private addresses; nobody can use the server itself or link-local addresses. |
| `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable email: password resets and **Email me a sign-in link**. Without them an admin resets passwords from **Users**. Check the setup with **Admin → About → Send test email**. |
| `SMTP_TLS` | `true` for servers that use TLS from the start. That's the default on port 465; other ports upgrade with STARTTLS. |
| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | Optional. The key pair that signs push notifications (generate with `bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'`). Without them the app generates a pair once and keeps it in `storage/vapid_keys.json`. Changing it turns notifications off on every device until they're turned on again. |
+8
View File
@@ -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
+1 -1
View File
@@ -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?
+1 -1
View File
@@ -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"
+27
View File
@@ -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
+33
View File
@@ -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
+37 -4
View File
@@ -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
+6 -1
View File
@@ -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
+6
View File
@@ -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) %>
+22 -8
View File
@@ -100,12 +100,26 @@ Rails.application.configure do
# Only use :id for inspections in production.
config.active_record.attributes_for_inspect = [ :id ]
# Enable DNS rebinding protection and other `Host` header attacks.
# config.hosts = [
# "example.com", # Allow requests from example.com
# /.*\.example\.com/ # Allow requests from subdomains like `www.example.com`
# ]
#
# Skip DNS rebinding protection for the default health check endpoint.
# config.host_authorization = { exclude: ->(request) { request.path == "/up" } }
# Answer only for the app's own names (stops DNS rebinding and forged Host
# headers): APP_HOST, the APP_URL host, ALLOWED_HOSTS, localhost and IP
# addresses (a rebinding attack needs a name). Off when APP_HOST isn't set.
if ENV["APP_HOST"].present?
config.hosts = [
ENV["APP_HOST"].sub(/:\d+\z/, ""),
(URI.parse(ENV["APP_URL"]).host if ENV["APP_URL"].present?),
*ENV.fetch("ALLOWED_HOSTS", "").split(",").map(&:strip),
"localhost",
IPAddr.new("0.0.0.0/0"),
IPAddr.new("::/0")
].compact_blank
config.host_authorization = {
exclude: ->(request) { request.path == "/up" },
# Say why, rather than a blank page: usually a name that's simply missing.
response_app: ->(env) {
host = ActionDispatch::Request.new(env).host.to_s.gsub(/[^a-z0-9.\-:\[\]]/i, "").first(253)
[ 403, { "content-type" => "text/plain; charset=utf-8" },
[ "This server doesn't answer for \"#{host}\". If that's a name for this app, add it to ALLOWED_HOSTS (comma-separated) and restart.\n" ] ]
}
}
end
end
+5
View File
@@ -0,0 +1,5 @@
# Refuse to run in production with a guessable secret key (see SecretKeyCheck).
# Skipped for the image build's asset step, which uses a throwaway key.
if Rails.env.production? && ENV["SECRET_KEY_BASE"].present? && ENV["SECRET_KEY_BASE_DUMMY"].blank?
Rails.application.config.after_initialize { SecretKeyCheck.verify! }
end
+6
View File
@@ -829,6 +829,8 @@ en:
unreachable: couldn't reach or verify %{provider}; see the server log
setup:
welcome_you_re_the: Welcome! You're the administrator. Add your first aircraft.
wrong_code: That setup code isn't right. It's in the server's log, on the line starting "Setup code".
try_again_later: Too many tries. Wait a few minutes and try again.
invited_signings:
try_again_later: Try again later.
sign_in_to_continue: Sign in to continue.
@@ -3109,6 +3111,8 @@ en:
new:
welcome: Welcome
create_the_administrator_account_to: Create the administrator account to get started.
setup_code: Setup code
setup_code_hint_html: 'Shown in the server''s log, so only whoever runs the server can finish setup. With Docker: <code>docker compose logs web | grep "Setup code"</code>'
email: Email
at_least_characters_not_one: At least %{min} characters; not one known from a data breach.
simple_aircraft_manager_is_provided: Simple Aircraft Manager is provided as is, without warranty, and is not approved by the FAA or any other aviation authority. It is up to you to verify that using it for your aircraft and operation is legal and suitable. The full disclaimer is under Help once you're signed in.
@@ -3671,6 +3675,8 @@ en:
signed_event: Logbook entry signed electronically (%{date})
air_trail:
can_t_reach_airtrail_at: 'Can''t reach AirTrail at %{host}: %{message}'
blocked_never: "%{host} is this server or a link-local address, which AirTrail can't be."
blocked_private: "%{host} is on the private network. Ask an administrator to connect it, or to list it in AIRTRAIL_ALLOWED_HOSTS."
airtrail_username_must_be_3: AirTrail username must be 3–20 letters, numbers, “.”, “_” or “-”
aircraft_type_must_be_an: Aircraft type must be an ICAO type designator like C150 (up to 4 letters/numbers)
no_flights_to_export: No flights to export
+33
View File
@@ -0,0 +1,33 @@
# Directly on the internet, with HTTPS and no proxy in front: the image's web
# server (Thruster) gets and renews a Let's Encrypt certificate by itself.
#
# 1. Point a DNS name (A/AAAA record) at this server, and open ports 80 and
# 443 to it (80 is needed for the certificate check and redirects).
# 2. In .env: APP_HOST and TLS_DOMAIN set to that name, FORCE_SSL=true, and
# a SECRET_KEY_BASE from `bin/rails secret`.
# 3. docker compose -f docker-compose.direct.yml up -d
# 4. Open https://<name>, and create the admin account with the setup code
# from: docker compose -f docker-compose.direct.yml logs web | grep "Setup code"
#
# The certificate is kept in the storage volume, so it isn't requested again
# on every start.
services:
web:
image: barrettefab/simple-aircraft-manager-rails:latest # or your own image, or: build: .
restart: unless-stopped
ports:
- "80:80"
- "443:443"
env_file: .env
environment:
SOLID_QUEUE_IN_PUMA: "true" # nightly backup, reminders and AD search run in the web process
FORCE_SSL: "true"
volumes:
- sam_storage:/rails/storage # databases, uploaded files, nightly backups and the certificate: back this up
healthcheck:
test: ["CMD", "curl", "-fsS", "http://localhost/up"]
interval: 30s
timeout: 5s
retries: 3
volumes:
sam_storage:
+1 -1
View File
@@ -103,7 +103,7 @@ Run on the server like the account recovery commands (`docker compose exec web`
| Command | What it does |
|---|---|
| `bin/rails sam:doctor` | Health report: secret key, address, HTTPS, email (SMTP reachable), single sign-on (issuer reachable), Google Drive, migrations, disk space, background jobs, and how recent the backup, records check, off-site copy, procedures and audit are. Exits non-zero if something fails |
| `bin/rails sam:doctor` | Health report: secret key (set and long enough), address, HTTPS, email (SMTP reachable), single sign-on (issuer reachable), Google Drive, migrations, disk space, background jobs, and how recent the backup, records check, off-site copy, procedures and audit are. Exits non-zero if something fails |
| `bin/rails records:check` | Backs up the database now and checks the record history and every signature; prints any problems and exits non-zero |
| `bin/rails backups:list` | Lists the nightly database copies |
| `bin/rails "backups:restore[file]"` | Replaces the database with a backup (newest nightly copy if no file; a Google Drive `.sqlite3.gz` works too). The app must be stopped: `docker compose stop web`, then `docker compose run --rm web bin/rails backups:restore`. The current database is moved to `storage/pre-restore-…`, never deleted. `CONFIRM=yes` skips the question |
+1 -1
View File
@@ -12,7 +12,7 @@ If you've set up an authenticator app (see [Your profile](profile.md#two-factor-
After 10 failed tries in a row (wrong passwords or codes), an account is locked for 15 minutes and its owner is emailed. Wait, or ask the administrator to unlock it.
The very first visit to a new installation asks for the administrator account instead.
The very first visit to a new installation asks for the administrator account instead. It also asks for a one-time setup code, which is printed only in the server's log (the line starting `Setup code`; with Docker, `docker compose logs web | grep "Setup code"`), so only whoever runs the server can create that account.
## Roles
+2
View File
@@ -55,3 +55,5 @@ Turn it on on each phone or computer you want them on; **Send a test** checks it
## Integrations: AirTrail
**AirTrail sync** pushes the flights you log to your AirTrail flight map, with their GPS tracks. In AirTrail, create an API key (Settings → Security) with the scopes shown, then paste your AirTrail address and key here. A full sync first links flights already in AirTrail, so nothing is duplicated. If an airport code can't be matched, enter the code AirTrail uses for it.
If your AirTrail server is on your private network (an address like 192.168.x.x or 10.x.x.x), only an administrator can connect to it, unless the administrator lists it in `AIRTRAIL_ALLOWED_HOSTS`. This stops accounts from using the app to probe the private network. The app's own server and link-local addresses can't be used at all.
@@ -0,0 +1,84 @@
require "test_helper"
# Protections for an installation reachable from the internet with nothing in
# front of it: secret key strength, the setup code, the AirTrail address check
# and the allowed host names.
class InternetExposureTest < ActionDispatch::IntegrationTest
test "a placeholder or short secret key is refused; one shorter than recommended is weak" do
assert_equal :unsafe, SecretKeyCheck.strength("change-me")
assert_equal :unsafe, SecretKeyCheck.strength("x")
assert_equal :unsafe, SecretKeyCheck.strength("a" * 80)
assert_equal :weak, SecretKeyCheck.strength(SecureRandom.hex(20))
assert_equal :ok, SecretKeyCheck.strength(SecureRandom.hex(64))
end
test "the setup code is required, shown only in the log, and used up" do
SetupCode.clear
logged = capture_log { get new_setup_path }
assert_match(/Setup code: #{Regexp.escape(SetupCode.current)}/, logged)
assert_no_match SetupCode.current, response.body
end
test "AirTrail can't be pointed at the server itself or link-local addresses, nor the private network by non-admins" do
{ "http://127.0.0.1:8080" => :never, "http://169.254.169.254" => :never, "http://[::1]" => :never,
"http://10.0.0.5" => :private, "http://192.168.1.20:3000" => :private, "http://100.100.1.1" => :private }.each do |url, reason|
error = assert_raises(AirTrailClient::BlockedAddress, url) { AirTrailClient.new(base_url: url, api_key: "k").me }
assert_match(reason == :never ? "link-local" : "private network", error.message)
end
end
test "admins and listed hosts may use private addresses, but never the server itself" do
stub_request(:get, "http://192.168.1.20:3000/api/v1/me").to_return(status: 200, body: { data: { username: "u" } }.to_json)
assert_equal "u", AirTrailClient.new(base_url: "http://192.168.1.20:3000", api_key: "k", allow_private: true).me["username"]
assert_raises(AirTrailClient::BlockedAddress) { AirTrailClient.new(base_url: "http://127.0.0.1", api_key: "k", allow_private: true).me }
with_env("AIRTRAIL_ALLOWED_HOSTS" => "airtrail.lan") do
resolving_to("192.168.1.30") do
stub_request(:get, "http://airtrail.lan/api/v1/me").to_return(status: 200, body: { data: { username: "v" } }.to_json)
assert_equal "v", AirTrailClient.new(base_url: "http://airtrail.lan", api_key: "k").me["username"]
end
end
end
test "a name that resolves to a private address is checked by its address" do
resolving_to("203.0.113.5", "10.1.2.3") do
assert_raises(AirTrailClient::BlockedAddress) { AirTrailClient.new(base_url: "https://rebind.example.com", api_key: "k").me }
end
end
test "a non-admin's connection to a private address is refused with a reason" do
pilot = create_user
sign_in pilot
post air_trail_connection_path, params: { air_trail_connection: { base_url: "http://192.168.1.20", api_key: "k" } }
follow_redirect! if response.redirect?
assert_match "private network", flash[:alert].to_s + response.body
end
private
def resolving_to(*ips)
old = AirTrailClient.resolver
AirTrailClient.resolver = ->(_) { ips }
yield
ensure
AirTrailClient.resolver = old
end
def with_env(vars)
old = vars.keys.to_h { [ _1, ENV[_1] ] }
vars.each { ENV[_1] = _2 }
yield
ensure
old.each { ENV[_1] = _2 }
end
def capture_log
io = StringIO.new
logger = ActiveSupport::Logger.new(io)
old, Rails.logger = Rails.logger, logger
yield
io.string
ensure
Rails.logger = old
end
end
+11 -2
View File
@@ -1,11 +1,20 @@
require "test_helper"
class SetupTest < ActionDispatch::IntegrationTest
test "first run creates admin, then setup is closed" do
test "first run creates admin with the code from the server log, then setup is closed" do
get root_path
assert_redirected_to new_setup_path
post setup_path, params: { user: { name: "Jane", email_address: "a@b.com", password: "test-password-123", password_confirmation: "test-password-123" } }
get new_setup_path
assert_select "input[name=setup_code]"
admin = { name: "Jane", email_address: "a@b.com", password: "test-password-123", password_confirmation: "test-password-123" }
post setup_path, params: { user: admin, setup_code: "AAAA-AAAA" }
assert_response :unprocessable_entity
assert_not User.exists?
post setup_path, params: { user: admin, setup_code: SetupCode.current.downcase.delete("-") } # forgiving about case and the dash
assert_redirected_to root_path
assert_not SetupCode.file.exist?, "the code is used up"
assert User.last.admin?
get new_setup_path
assert_redirected_to root_path
+2
View File
@@ -5,6 +5,8 @@ require "webmock/minitest"
WebMock.disable_net_connect!(allow_localhost: true)
Dir[File.expand_path("support/**/*.rb", __dir__)].each { require _1 }
PwnedPasswords.checker = ->(password) { password == "breached-password-1" } # no network in tests
# No DNS in tests: names resolve to a public address, IP addresses to themselves.
AirTrailClient.resolver = ->(host) { host.match?(/\A[\d.]+\z|:/) ? [ host.delete("[]") ] : [ "203.0.113.10" ] }
module ActiveSupport
class TestCase