The personal finance app for everyone (by everyone)
Ruby
security: CORS allow-list instead of a wildcard, DNS rebinding protection behind ALLOWED_HOSTS (#1944)
David Gil9089ccb84d48
diff --git a/charts/sure/README.md b/charts/sure/README.mdindex df221dd4e0..6986b299ea 100644--- a/charts/sure/README.md+++ b/charts/sure/README.md@@ -534,6 +534,8 @@ ingress:secretName: finance-tls```+To refuse requests for any other `Host`, set `ALLOWED_HOSTS` under `rails.extraEnv` to every ingress host. The probes call `/up`, which the check skips. With Pipelock enabled, MCP requests reach the app under the chart's service name, the release fullname (`sure` for a release named `sure`) or the host in `pipelock.mcpProxy.upstream`, so list that name too or every MCP call through Pipelock gets a 403. `ALLOWED_ORIGINS` and the rest are described in [Restricting who can reach your instance](../../docs/hosting/docker.md#restricting-who-can-reach-your-instance).+## Boot-required secretsThe Rails initializer for Active Record Encryption loads on boot. To prevent boot crashes, ensure the following environment variables are present for ALL workloads (web, worker, migrate job/initContainer, CronJobs, and the SimpleFin backfill job):diff --git a/config/environments/production.rb b/config/environments/production.rbindex fc7120a0a9..9aa57f62db 100644--- a/config/environments/production.rb+++ b/config/environments/production.rb@@ -101,13 +101,33 @@ Rails.application.configure do# Do not dump schema after migrations.config.active_record.dump_schema_after_migration = false- # 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" } }+ # DNS rebinding protection. Set ALLOWED_HOSTS to turn it on; APP_DOMAIN then+ # joins the list. APP_DOMAIN alone does not turn it on, since operators set it+ # for mail. Left off, the app answers to any Host, which is how it behaved+ # before, so an upgrade cannot lock an operator out of an instance they reach+ # by LAN address, Tailscale name, tunnel or Pipelock.+ #+ # Turned on, any Host outside the list gets a 403, so every name the app is+ # reached by belongs in ALLOWED_HOSTS.+ # Required explicitly: this file is evaluated while the environment is being+ # configured, before the autoloader is set up, so a bare constant reference+ # here raises NameError and the app never boots.+ require_relative "../../lib/allowed_hosts"+ allowed_hosts = AllowedHosts.list+ rejected_hosts = AllowedHosts.rejected++ if rejected_hosts.any?+ config.after_initialize do+ Rails.logger.warn("[SECURITY] Ignoring host entries that are not a single host: #{rejected_hosts.join(', ')}. Wildcards are not accepted; list each host.")+ end+ end++ if allowed_hosts.any?+ config.hosts = allowed_hosts+ config.host_authorization = AllowedHosts.host_authorization+ else+ AllowedHosts.warn_unprotected_on_server_boot(self)+ end# set REDIS_URL for Sidekiq to use Redisconfig.active_job.queue_adapter = :sidekiqdiff --git a/config/initializers/cors.rb b/config/initializers/cors.rbindex 8ffb294d49..0150f51fd3 100644--- a/config/initializers/cors.rb+++ b/config/initializers/cors.rb@@ -5,12 +5,15 @@# This enables Cross-Origin Resource Sharing for the /api, /oauth, and /sessions endpoints,# allowing the Flutter mobile client and other authorized clients to communicate# with the Rails backend.+#+# The allowed origins come from ALLOWED_ORIGINS or APP_DOMAIN; see CorsOrigins.+# Native mobile clients send no Origin header and are unaffected by any of this.Rails.application.config.middleware.insert_before 0, Rack::Cors doallow do- # Allow requests from any origin for API endpoints- # Mobile apps and development environments need flexible CORS- origins "*"+ # Consulted per request rather than expanded once at boot, so the allow-list+ # follows the environment instead of the moment the process started.+ origins { |source, _env| CorsOrigins.allowed?(source) }# API endpoints for mobile client and third-party integrationsresource "/api/*",diff --git a/docs/hosting/docker.md b/docs/hosting/docker.mdindex 663c78ca5f..4bc4f78192 100644--- a/docs/hosting/docker.md+++ b/docs/hosting/docker.md@@ -98,6 +98,43 @@ POSTGRES_PASSWORD="replacemewithyourdesireddatabasepassword"To encrypt sensitive data such as bank credentials with your own keys, set them now, before the first start; see [Encrypting sensitive data](#encrypting-sensitive-data).+#### Restricting who can reach your instance++These optional variables tighten things once your instance is reachable from+the internet. All are unset by default, and leaving them unset keeps the app+answering to any `Host`. Cross-origin browser requests are refused unless an+origin is listed.++| Variable | Purpose |+|---|---|+| `ALLOWED_ORIGINS` | Comma-separated list of browser origins allowed to call the app cross-origin, including the scheme, for example `https://app.example.com,https://staging.example.com`. Without it the app answers cross-origin requests the way any site does by default: it does not. Native mobile clients are unaffected, since they send no `Origin` header. |+| `APP_DOMAIN` | The single host your instance is served on. Used as the fallback for `ALLOWED_ORIGINS`, and added to the `Host` allow-list once `ALLOWED_HOSTS` is set. On its own it does not turn the `Host` check on. |+| `ALLOWED_HOSTS` | Comma-separated hostnames the app answers to. Setting it turns the `Host` check on, with `APP_DOMAIN` added to the list. One host per entry: a leading dot is refused rather than read as a wildcard, and IPv6 goes in brackets, `[::1]`. |++Prefer `ALLOWED_ORIGINS` when a reverse proxy terminates TLS for you. The+`APP_DOMAIN` fallback has to guess the scheme from `RAILS_FORCE_SSL` and+`RAILS_ASSUME_SSL`, so with both off, a common setting behind Traefik, NGINX or+a Cloudflare Tunnel, it builds an `http://` origin while the browser sends+`https://` and the request is refused.++Setting `ALLOWED_HOSTS` turns on DNS-rebinding protection: any request whose+`Host` header is neither in `ALLOWED_HOSTS` nor `APP_DOMAIN` is refused with a+403. List every name you reach the app by, such as a LAN address, a Tailscale+name or `localhost`, or those requests stop working. The `/up` health endpoint+is always exempt, so container probes keep passing. With+`compose.example.ai.yml`, Pipelock forwards MCP requests to the app with the+`Host` header `web:3000`, so add `web` to `ALLOWED_HOSTS` or every MCP call+through it is refused.++Without `ALLOWED_HOSTS`, the app answers to any `Host`, whether or not+`APP_DOMAIN` is set, and logs a `[SECURITY]` warning when the web server+starts.++Like the SMTP settings below, these reach the app only when `compose.yml` lists+them in the `x-rails-env` anchor, for example `ALLOWED_HOSTS: ${ALLOWED_HOSTS}`.+Setting them in `.env` alone does nothing; see **Passing the settings to the+containers** under [Sending email (SMTP)](#sending-email-smtp).+#### Using HTTPSAssuming you want to access your instance from the internet, you should have secured your URL address with an SSL certificate.@@ -138,7 +175,7 @@ Invitations are never emailed on a self-hosted instance, even with SMTP set up.| `SMTP_TLS_SKIP_VERIFY` | `true` turns off verification of the SMTP server's certificate. | Off (the certificate is verified) || `SSL_CA_FILE` | Path inside the container to a CA certificate (PEM) for verifying a server with a self-signed or internal certificate. The file must be mounted into the containers; see **Using a custom CA certificate** below. | None || `EMAIL_SENDER` | Address that emails are sent from, for example `[email protected]`. | `[email protected]` |-| `APP_DOMAIN` | Host name your instance is reached at, for example `sure.example.com`. Used to build links in emails. | None |+| `APP_DOMAIN` | Host name your instance is reached at, for example `sure.example.com`. Used to build links in emails. It does not restrict which `Host` the app answers to unless `ALLOWED_HOSTS` is also set; see [Restricting who can reach your instance](#restricting-who-can-reach-your-instance). | None |A few things to watch:diff --git a/lib/allowed_hosts.rb b/lib/allowed_hosts.rbnew file mode 100644index 0000000000..1b8ed0fe5f--- /dev/null+++ b/lib/allowed_hosts.rb@@ -0,0 +1,91 @@+# frozen_string_literal: true++# The Host header values this instance answers to, for Rails' DNS-rebinding+# protection.+#+# Only ALLOWED_HOSTS turns the check on. Once it lists a usable host,+# APP_DOMAIN joins the list, so the public name does not have to be written+# twice. APP_DOMAIN alone turns nothing on: the SMTP guide and the Helm chart+# set it for mail, and those same instances are often reached over a LAN+# address, a Tailscale name, a tunnel or Pipelock, none of which match it.+# Letting it switch the check on would turn all of those into 403s on upgrade.+#+# An empty list leaves config.hosts unset, which means Rails accepts any Host.+# That is the pre-existing behaviour, kept so an upgrade cannot lock an operator+# out of their own instance; the warning logged when the web server starts+# points at the fix.+module AllowedHosts+ module_function++ def list+ parse.fetch(:allowed)+ end++ # Entries that were thrown away, so the caller can say so at boot rather than+ # leaving an operator to work out why their host still gets a 403.+ def rejected+ parse.fetch(:rejected)+ end++ # Probes hit /up over the pod IP or localhost, neither of which matches a+ # configured host, so without this exclusion every liveness and readiness+ # check starts failing with a 403 the moment the list is set.+ def host_authorization+ { exclude: ->(request) { request.path == "/up" } }+ end++ # Registered as a server block, which Rails runs from the load_server call in+ # config.ru, so it is logged once when the web server boots. after_initialize+ # also runs for every rails runner, console, rake task and Sidekiq worker,+ # which filled self-hosters' cron output and worker logs with it.+ def warn_unprotected_on_server_boot(app)+ app.server do+ Rails.logger.warn("[SECURITY] ALLOWED_HOSTS lists no usable host, so DNS rebinding protection is off")+ end+ end++ def parse+ allowed, rejected = partition(ENV["ALLOWED_HOSTS"].to_s.split(","))+ return { allowed: [], rejected: rejected } if allowed.empty?++ app_allowed, app_rejected = partition([ ENV["APP_DOMAIN"] ])+ { allowed: (app_allowed + allowed).uniq, rejected: (app_rejected + rejected).uniq }+ end++ # Splits raw entries into usable hosts and the entries that were refused,+ # skipping blanks.+ def partition(entries)+ allowed = []+ rejected = []++ entries.map { |entry| entry.to_s.strip }.reject(&:empty?).each do |entry|+ host = normalize(entry)+ host ? allowed << host : rejected << entry+ end++ [ allowed.uniq, rejected.uniq ]+ end++ # A Host header is a bare hostname, so drop anything an operator may have+ # pasted around it. The WebAuthn initializer already does the same with+ # APP_DOMAIN, which is where most of these values come from.+ def normalize(entry)+ value = entry.to_s.strip.sub(%r{\Ahttps?://}i, "").split("/").first.to_s+ return nil if value.empty?++ # Rails reads a leading dot as "any subdomain of", so ".example.com" would+ # quietly turn an allow-list into a wildcard. Hosts are listed one by one+ # here, so this is refused rather than silently honoured.+ return nil if value.start_with?(".")++ # An IPv6 Host header is bracketed, and the brackets are part of what Rails+ # matches, so they stay. Only the port comes off.+ return value[/\A\[[^\]]+\]/]&.downcase if value.start_with?("[")++ # A bare IPv6 address has no port to strip, and needs bracketing to match+ # the Host header a browser actually sends.+ return "[#{value.downcase}]" if value.count(":") > 1++ value.split(":").first.to_s.downcase.presence+ end+enddiff --git a/lib/cors_origins.rb b/lib/cors_origins.rbnew file mode 100644index 0000000000..4f9f573ab8--- /dev/null+++ b/lib/cors_origins.rb@@ -0,0 +1,77 @@+# The browser origins allowed to make cross-origin requests to this instance.+#+# Configured with ALLOWED_ORIGINS (comma-separated, full origins including the+# scheme), falling back to APP_DOMAIN for the common single-host deploy.+#+# When neither is set the list is empty, which means no Access-Control-Allow-Origin+# header is sent and browsers apply their same-origin default. That is the safe+# outcome, and the boot warning tells the operator how to widen it.+module CorsOrigins+ module_function++ LOOPBACK_HOSTS = %w[localhost 127.0.0.1 ::1].freeze++ # The match is exact: an origin is a scheme, host and port, and prefix+ # matching is how "https://app.example.com.evil.test" gets let in.+ #+ # Development also accepts loopback origins on any port. Clients served by a+ # local dev server, such as `flutter run -d chrome`, pick a port at random,+ # and those relied on the wildcard this list replaced.+ def allowed?(origin)+ list.include?(origin) || (Rails.env.development? && loopback?(origin))+ end++ def loopback?(origin)+ uri = parse(origin)+ !uri.nil? && %w[http https].include?(uri.scheme) && LOOPBACK_HOSTS.include?(uri.hostname)+ end++ def list+ explicit_origins.presence || app_domain_origin+ end++ def explicit_origins+ ENV["ALLOWED_ORIGINS"].to_s.split(",").filter_map { |origin| normalize(origin) }+ end++ def app_domain_origin+ domain = ENV["APP_DOMAIN"].to_s.strip+ return [] if domain.empty?++ # APP_DOMAIN is documented as a bare domain, but the WebAuthn initializer+ # already copes with operators pasting a full URL, so do the same here+ # rather than building "https://https://app.example.com".+ origin = domain.match?(%r{\Ahttps?://}i) ? domain : "#{scheme}://#{domain}"+ [ normalize(origin) ].compact+ end++ # Only reached through the APP_DOMAIN fallback, and only as good as what the+ # app knows about how it is served. Behind a proxy that terminates TLS while+ # neither RAILS_FORCE_SSL nor RAILS_ASSUME_SSL is set, this says http while+ # the browser sends https, and a legitimate origin is refused. Set+ # ALLOWED_ORIGINS explicitly on those deploys.+ def scheme+ config = Rails.application.config+ ssl = config.force_ssl || (config.respond_to?(:assume_ssl) && config.assume_ssl)+ ssl ? "https" : "http"+ end++ # An Origin header carries a lowercased scheme and host, no path and no+ # trailing slash. Operators write the value by hand, often copied from a+ # browser's address bar, so normalize what they give us instead of failing+ # the comparison silently.+ def normalize(origin)+ uri = parse(origin)+ return nil if uri.nil? || uri.scheme.nil? || uri.host.nil?++ port = uri.port && uri.port != uri.default_port ? ":#{uri.port}" : ""+ "#{uri.scheme.downcase}://#{uri.host.downcase}#{port}"+ end++ def parse(origin)+ value = origin.to_s.strip+ URI.parse(value) unless value.empty?+ rescue URI::InvalidURIError+ nil+ end+enddiff --git a/mobile/README.md b/mobile/README.mdindex b5dbca345e..1d2432ddf8 100644--- a/mobile/README.md+++ b/mobile/README.md@@ -82,6 +82,11 @@ flutter run -d "iPhone 17 Pro"flutter run -d chrome```+The web build is a browser client, so the server must grant its origin through+CORS. A local `bin/dev` server accepts any `localhost` origin. Any other server+needs the dev server's origin, including its port, in `ALLOWED_ORIGINS`; pass+`--web-port` to keep that port fixed.+## Project Structure```diff --git a/test/integration/cors_test.rb b/test/integration/cors_test.rbindex e16d98d3c4..f48922f178 100644--- a/test/integration/cors_test.rb+++ b/test/integration/cors_test.rb@@ -8,65 +8,110 @@ class CorsTest < ActionDispatch::IntegrationTestassert_includes middleware_classes, Rack::Cors, "Rack::Cors should be in middleware stack"end- test "cors headers are returned for api endpoints" do- get "/api/v1/usage", headers: { "Origin" => "http://localhost:3000" }+ # Nothing configures an allow-list in the test environment, so an arbitrary+ # origin gets no Access-Control-Allow-Origin header at all and the browser+ # falls back to its same-origin default. These used to assert "*".+ test "an origin that is not on the allow-list gets no CORS grant" do+ get "/api/v1/usage", headers: { "Origin" => "http://evil.example" }- assert_equal "*", response.headers["Access-Control-Allow-Origin"]- assert response.headers["Access-Control-Expose-Headers"].present?+ assert_nil response.headers["Access-Control-Allow-Origin"]end- test "cors preflight request is handled for api endpoints" do- # Simulate a preflight OPTIONS request+ test "no request is ever answered with a wildcard origin" do+ [ "/api/v1/usage", "/sessions/new" ].each do |path|+ get path, headers: { "Origin" => "http://evil.example" }+ assert_not_equal "*", response.headers["Access-Control-Allow-Origin"], "#{path} answered with a wildcard"+ end+ end++ test "a preflight from an origin that is not allowed is not granted" dooptions "/api/v1/transactions",headers: {- "Origin" => "http://localhost:3000",+ "Origin" => "http://evil.example","Access-Control-Request-Method" => "POST","Access-Control-Request-Headers" => "Content-Type, Authorization"}- assert_response :ok- assert_equal "*", response.headers["Access-Control-Allow-Origin"]- assert response.headers["Access-Control-Allow-Methods"].present?- assert_includes response.headers["Access-Control-Allow-Methods"], "POST"+ assert_nil response.headers["Access-Control-Allow-Origin"]end- test "cors headers are returned for oauth endpoints" do+ test "oauth endpoints are not granted to an origin that is not allowed" dopost "/oauth/token",params: { grant_type: "authorization_code", code: "test" },- headers: { "Origin" => "http://localhost:3000" }+ headers: { "Origin" => "http://evil.example" }- assert_equal "*", response.headers["Access-Control-Allow-Origin"]+ assert_nil response.headers["Access-Control-Allow-Origin"]end- test "cors preflight request is handled for oauth endpoints" do+ test "an oauth preflight from an origin that is not allowed is not granted" dooptions "/oauth/token",headers: {- "Origin" => "http://localhost:3000",+ "Origin" => "http://evil.example","Access-Control-Request-Method" => "POST","Access-Control-Request-Headers" => "Content-Type"}- assert_response :ok- assert_equal "*", response.headers["Access-Control-Allow-Origin"]+ assert_nil response.headers["Access-Control-Allow-Origin"]end- test "cors headers are returned for session endpoints" do+ test "session endpoints are not granted to an origin that is not allowed" dopost "/sessions",params: { email: "[email protected]", password: "password" },- headers: { "Origin" => "http://localhost:3000" }+ headers: { "Origin" => "http://evil.example" }- assert_equal "*", response.headers["Access-Control-Allow-Origin"]+ assert_nil response.headers["Access-Control-Allow-Origin"]end- test "cors preflight request is handled for session endpoints" do+ test "a session preflight from an origin that is not allowed is not granted" dooptions "/sessions/new",headers: {- "Origin" => "http://localhost:3000",+ "Origin" => "http://evil.example","Access-Control-Request-Method" => "GET","Access-Control-Request-Headers" => "Content-Type"}+ assert_nil response.headers["Access-Control-Allow-Origin"]+ end++ test "an allow-listed origin is granted, and only that origin" do+ CorsOrigins.stubs(:list).returns([ "https://app.example.com" ])++ get "/api/v1/usage", headers: { "Origin" => "https://app.example.com" }+ assert_equal "https://app.example.com", response.headers["Access-Control-Allow-Origin"]++ get "/api/v1/usage", headers: { "Origin" => "https://other.example.com" }+ assert_nil response.headers["Access-Control-Allow-Origin"]+ end++ # A prefix match would let this through, which is why the check is equality.+ test "an origin that merely starts with an allowed one is refused" do+ CorsOrigins.stubs(:list).returns([ "https://app.example.com" ])++ get "/api/v1/usage", headers: { "Origin" => "https://app.example.com.evil.test" }++ assert_nil response.headers["Access-Control-Allow-Origin"]+ end++ test "an allow-listed origin gets a preflight grant" do+ CorsOrigins.stubs(:list).returns([ "https://app.example.com" ])++ options "/api/v1/transactions",+ headers: {+ "Origin" => "https://app.example.com",+ "Access-Control-Request-Method" => "POST",+ "Access-Control-Request-Headers" => "Content-Type, Authorization"+ }+assert_response :ok- assert_equal "*", response.headers["Access-Control-Allow-Origin"]+ assert_equal "https://app.example.com", response.headers["Access-Control-Allow-Origin"]+ assert_includes response.headers["Access-Control-Allow-Methods"], "POST"+ end++ test "a loopback origin is granted in development" do+ Rails.stubs(:env).returns(ActiveSupport::EnvironmentInquirer.new("development"))++ get "/api/v1/usage", headers: { "Origin" => "http://localhost:52731" }++ assert_equal "http://localhost:52731", response.headers["Access-Control-Allow-Origin"]endenddiff --git a/test/lib/allowed_hosts_test.rb b/test/lib/allowed_hosts_test.rbnew file mode 100644index 0000000000..dec09f167e--- /dev/null+++ b/test/lib/allowed_hosts_test.rb@@ -0,0 +1,147 @@+require "test_helper"++class AllowedHostsTest < ActiveSupport::TestCase+ test "adds APP_DOMAIN to ALLOWED_HOSTS once ALLOWED_HOSTS is set" do+ with_env_overrides(APP_DOMAIN: "app.example.com", ALLOWED_HOSTS: "10.0.0.5, box.tailnet.ts.net") do+ assert_equal [ "app.example.com", "10.0.0.5", "box.tailnet.ts.net" ], AllowedHosts.list+ end+ end++ test "drops blanks and duplicates" do+ with_env_overrides(APP_DOMAIN: "app.example.com", ALLOWED_HOSTS: " , app.example.com , ,10.0.0.5") do+ assert_equal [ "app.example.com", "10.0.0.5" ], AllowedHosts.list+ end+ end++ # Main's SMTP guide and the Helm chart set APP_DOMAIN for mail. If it turned+ # the check on, every instance also reached by LAN address, Tailscale name,+ # tunnel or Pipelock would start answering 403 after an upgrade.+ test "APP_DOMAIN alone leaves the list empty, so the check stays off" do+ with_env_overrides(APP_DOMAIN: "app.example.com", ALLOWED_HOSTS: nil) do+ assert_empty AllowedHosts.list+ end+ end++ test "ALLOWED_HOSTS with no usable host leaves the check off even with APP_DOMAIN" do+ with_env_overrides(APP_DOMAIN: "app.example.com", ALLOWED_HOSTS: " , .example.com") do+ assert_empty AllowedHosts.list+ assert_equal [ ".example.com" ], AllowedHosts.rejected+ end+ end++ # An empty list must stay empty rather than becoming [""], which Rails would+ # read as an allow-list that matches nothing and reject every request.+ test "junk alone produces an empty list" do+ with_env_overrides(APP_DOMAIN: nil, ALLOWED_HOSTS: " , , ") do+ assert_empty AllowedHosts.list+ end+ end++ test "returns nothing when neither variable is set" do+ with_env_overrides(APP_DOMAIN: nil, ALLOWED_HOSTS: nil) do+ assert_empty AllowedHosts.list+ end+ end++ # config.hosts matches against the Host header, which is a bare hostname, so+ # a pasted URL has to be reduced to one or it silently matches nothing.+ test "reduces a pasted URL to a bare hostname" do+ with_env_overrides(APP_DOMAIN: "https://App.Example.com/path", ALLOWED_HOSTS: "http://10.0.0.5:3000") do+ assert_equal [ "app.example.com", "10.0.0.5" ], AllowedHosts.list+ end+ end++ # Rails reads a leading dot as "any subdomain of", so honouring it would turn+ # the allow-list into a wildcard for every name under the domain.+ test "refuses a leading dot instead of turning the list into a wildcard" do+ with_env_overrides(APP_DOMAIN: nil, ALLOWED_HOSTS: ".example.com,app.example.com") do+ assert_equal [ "app.example.com" ], AllowedHosts.list+ assert_equal [ ".example.com" ], AllowedHosts.rejected+ end+ end++ # The brackets are part of what Rails matches against the Host header, so+ # they stay and only the port comes off. Splitting on ":" turned these into+ # "[", which switched host authorization on with a list nothing could match.+ test "keeps IPv6 addresses usable" do+ with_env_overrides(APP_DOMAIN: nil, ALLOWED_HOSTS: "[::1]:3000,[2001:DB8::1]") do+ assert_equal [ "[::1]", "[2001:db8::1]" ], AllowedHosts.list+ end+ end++ # A browser sends "[::1]:3000", so an unbracketed entry would match nothing.+ test "brackets an IPv6 address written without them" do+ with_env_overrides(APP_DOMAIN: nil, ALLOWED_HOSTS: "::1") do+ assert_equal [ "[::1]" ], AllowedHosts.list+ end+ end++ test "reports nothing as rejected when every entry is usable" do+ with_env_overrides(APP_DOMAIN: "app.example.com", ALLOWED_HOSTS: "10.0.0.5") do+ assert_empty AllowedHosts.rejected+ end+ end++ # The tests above check the list; these run it through Rails' own+ # HostAuthorization middleware, configured the way production.rb configures+ # it, so they fail if the list stops meaning what Rails reads it as.+ test "lets the listed hosts through on any port and refuses any other Host" do+ with_env_overrides(APP_DOMAIN: "app.example.com", ALLOWED_HOSTS: "10.0.0.5,[::1]:3000") do+ assert_equal 200, status_for("app.example.com")+ assert_equal 200, status_for("app.example.com:8443")+ assert_equal 200, status_for("10.0.0.5:3000")+ assert_equal 200, status_for("[::1]:3000")+ assert_equal 403, status_for("rebound.attacker.test")+ end+ end++ test "a refused leading-dot entry does not let subdomains in" do+ with_env_overrides(APP_DOMAIN: nil, ALLOWED_HOSTS: ".example.com,app.example.com") do+ assert_equal 403, status_for("evil.example.com")+ end+ end++ test "APP_DOMAIN alone lets every Host through" do+ with_env_overrides(APP_DOMAIN: "app.example.com", ALLOWED_HOSTS: nil) do+ assert_equal 200, status_for("192.168.1.10:3000")+ assert_equal 200, status_for("web:3000")+ end+ end++ # Probes reach /up over the pod IP or localhost, which no list contains.+ test "/up answers on any Host so container probes keep passing" do+ with_env_overrides(APP_DOMAIN: nil, ALLOWED_HOSTS: "app.example.com") do+ assert_equal 200, status_for("10.1.2.3:3000", path: "/up")+ assert_equal 403, status_for("10.1.2.3:3000", path: "/")+ end+ end++ # Registering happens in every process that loads production.rb: runner,+ # console, rake, the Sidekiq worker. Only the web server runs server blocks,+ # through the Rails.application.load_server call in config.ru.+ test "warns about the missing host check only when the web server boots" do+ server_blocks = Rails.application.class.server+ registered_before = server_blocks.dup+ log = StringIO.new+ Rails.stubs(:logger).returns(ActiveSupport::Logger.new(log))++ AllowedHosts.warn_unprotected_on_server_boot(Rails.application)+ assert_empty log.string++ Rails.application.load_server+ assert_equal 1, log.string.scan("[SECURITY] ALLOWED_HOSTS lists no usable host").size+ ensure+ server_blocks.replace(registered_before)+ end++ test "config.ru runs the server blocks the warning is registered as" do+ assert_match(/^Rails\.application\.load_server$/, Rails.root.join("config.ru").read)+ end++ private+ def status_for(host, path: "/")+ app = ->(_env) { [ 200, {}, [ "ok" ] ] }+ middleware = ActionDispatch::HostAuthorization.new(app, AllowedHosts.list, **AllowedHosts.host_authorization)+ middleware.call(Rack::MockRequest.env_for("http://placeholder#{path}", "HTTP_HOST" => host)).first+ end+enddiff --git a/test/lib/cors_origins_test.rb b/test/lib/cors_origins_test.rbnew file mode 100644index 0000000000..020cab5c47--- /dev/null+++ b/test/lib/cors_origins_test.rb@@ -0,0 +1,99 @@+require "test_helper"++class CorsOriginsTest < ActiveSupport::TestCase+ test "reads a comma-separated list, trimming blanks" do+ with_env_overrides(ALLOWED_ORIGINS: " https://app.example.com , ,https://staging.example.com ") do+ assert_equal [ "https://app.example.com", "https://staging.example.com" ], CorsOrigins.list+ end+ end++ test "falls back to APP_DOMAIN when no explicit list is set" do+ with_env_overrides(ALLOWED_ORIGINS: nil, APP_DOMAIN: "app.example.com") do+ Rails.application.config.stubs(:force_ssl).returns(true)+ assert_equal [ "https://app.example.com" ], CorsOrigins.list+ end+ end++ test "uses http for APP_DOMAIN when the app is not served over SSL" do+ with_env_overrides(ALLOWED_ORIGINS: nil, APP_DOMAIN: "app.example.com") do+ Rails.application.config.stubs(:force_ssl).returns(false)+ Rails.application.config.stubs(:assume_ssl).returns(false)+ assert_equal [ "http://app.example.com" ], CorsOrigins.list+ end+ end++ # A list of junk separators must not become an empty allow-list by accident,+ # nor swallow the APP_DOMAIN fallback.+ test "junk in ALLOWED_ORIGINS falls through to APP_DOMAIN" do+ with_env_overrides(ALLOWED_ORIGINS: " , , ", APP_DOMAIN: "app.example.com") do+ Rails.application.config.stubs(:force_ssl).returns(true)+ assert_equal [ "https://app.example.com" ], CorsOrigins.list+ end+ end++ test "returns nothing when neither variable is set" do+ with_env_overrides(ALLOWED_ORIGINS: nil, APP_DOMAIN: nil) do+ assert_empty CorsOrigins.list+ end+ end++ # These are all things an operator plausibly writes by hand or pastes from a+ # browser. Silently failing to match is worse than accepting them.+ test "normalizes case, trailing slashes, paths and default ports" do+ with_env_overrides(ALLOWED_ORIGINS: "HTTPS://App.Example.com/, https://a.example.com:443, https://b.example.com/path") do+ assert_equal [ "https://app.example.com", "https://a.example.com", "https://b.example.com" ], CorsOrigins.list+ end+ end++ test "keeps a port that is not the default for the scheme" do+ with_env_overrides(ALLOWED_ORIGINS: "http://app.example.com:3000") do+ assert_equal [ "http://app.example.com:3000" ], CorsOrigins.list+ end+ end++ test "drops entries that are not origins at all" do+ with_env_overrides(ALLOWED_ORIGINS: "app.example.com, https://ok.example.com, not a url") do+ assert_equal [ "https://ok.example.com" ], CorsOrigins.list+ end+ end++ test "accepts an APP_DOMAIN that already carries a scheme" do+ with_env_overrides(ALLOWED_ORIGINS: nil, APP_DOMAIN: "https://app.example.com/") do+ assert_equal [ "https://app.example.com" ], CorsOrigins.list+ end+ end++ # Equality, not a prefix: an origin is a scheme, host and port.+ test "allows only an exact match" do+ CorsOrigins.stubs(:list).returns([ "https://app.example.com" ])++ assert CorsOrigins.allowed?("https://app.example.com")+ assert_not CorsOrigins.allowed?("https://app.example.com.evil.test")+ assert_not CorsOrigins.allowed?("https://app.example.com:8443")+ assert_not CorsOrigins.allowed?("null")+ assert_not CorsOrigins.allowed?(nil)+ end++ # `flutter run -d chrome`, documented in mobile/README.md, serves the client+ # from localhost on a port it picks at random, and used to rely on the "*".+ test "allows a loopback origin on any port in development" do+ Rails.stubs(:env).returns(ActiveSupport::EnvironmentInquirer.new("development"))++ with_env_overrides(ALLOWED_ORIGINS: nil, APP_DOMAIN: nil) do+ assert CorsOrigins.allowed?("http://localhost:52731")+ assert CorsOrigins.allowed?("http://127.0.0.1:8080")+ assert CorsOrigins.allowed?("http://[::1]:8080")+ assert_not CorsOrigins.allowed?("http://evil.example")+ assert_not CorsOrigins.allowed?("http://localhost.evil.example")+ assert_not CorsOrigins.allowed?("file://localhost")+ end+ end++ test "does not allow loopback origins outside development" do+ Rails.stubs(:env).returns(ActiveSupport::EnvironmentInquirer.new("production"))++ with_env_overrides(ALLOWED_ORIGINS: nil, APP_DOMAIN: nil) do+ assert_not CorsOrigins.allowed?("http://localhost:52731")+ end+ end+end