Locking the Admin Section Behind a VPN: How We Did It in Rails and Phoenix at Edge
At Edge Payment Technologies our staff tools lived in the same applications our merchants used. The admin section sat at dashboard.<our domain>/admin, next to the merchant dashboard, and from there staff could look up accounts, edit integrations, review merchants, open the Phoenix LiveDashboard and even sign in as a merchant to see what they saw.
That is a lot of power behind one URL. For a payment gateway serving high-risk merchants, a strong password and a second factor were not enough on their own. We wanted the admin section to be unreachable unless you were on the company VPN, and that is how it ran in production: if your request did not come from our VPN, you did not get in, whatever credentials you held.
This post covers how we did it, first in Ruby on Rails, where Edge started, and then in Phoenix, where we moved, and why I think a VPN gate is one of the cheapest, most effective security controls a small team can add.
The idea in one sentence
Every staff member connects to a VPN, all VPN traffic leaves through one fixed public IP address, and the application refuses admin requests from any other address.
There are three parts to it:
- A VPN server with a static egress IP. We used Pritunl, an open-source VPN server built on OpenVPN (it supports WireGuard too), with a web console for managing users, organisations and profiles.
- An application-level check that compares the client's IP with the VPN's IP before any admin route runs.
- Network rules that do the same thing for tools that have no application of ours in front of them.
Running Pritunl on AWS
Our Pritunl server was small and boring, which is what you want from a VPN. Everything was in Terraform:
- Its own VPC. The VPN lived in a separate, isolated VPC with a large address range, so it had room for many clients and nothing else ran beside it.
- VPC peering into production. A route in the VPN's route table sent production's private range over a peering connection, so a connected engineer could reach private resources without anything being exposed to the internet.
- An Elastic IP. This is the important bit. The EIP gave the VPN a public address that never changes, so every connected client appears to the outside world, and to our own load balancers, as that one IP.
- A tiny instance. A
t2.microwas plenty for a team our size. - Flow logs. VPC flow logs from the VPN and production networks went to CloudWatch, so we had a record of traffic if we ever needed one.
The security group on the instance opened only the VPN's UDP port to the world, plus HTTPS for the Pritunl console. Each staff member got a Pritunl profile protected by a PIN, imported into the Pritunl client on their machine.
The Rails version
Edge started life as a Rails application, and Rails has two natural places for a check like this.
The first is a route constraint. A request that fails the constraint never matches the route, so it gets a plain 404, and the admin section does not even admit to existing:
# app/constraints/vpn_constraint.rb
class VpnConstraint
VPN_RANGES = ENV.fetch("VPN_EGRESS_IPS").split(",").map { IPAddr.new(_1) }.freeze
def self.matches?(request)
return true if Rails.env.development?
ip = IPAddr.new(request.remote_ip)
VPN_RANGES.any? { |range| range.include?(ip) }
rescue IPAddr::InvalidAddressError
false
end
end
# config/routes.rb
constraints(VpnConstraint) do
namespace :admin do
resources :merchants
resources :accounts
end
end
The second is a before_action in the admin base controller, which is handy when you would rather show a friendly message than a 404:
class Admin::BaseController < ApplicationController
before_action :authenticate_admin!
before_action :require_vpn!
private
def require_vpn!
return if VpnConstraint.matches?(request)
redirect_to root_path, alert: "You must be on the company VPN to access this page."
end
end
Both depend on request.remote_ip being the client's address, not your load balancer's. Rails works that out with the ActionDispatch::RemoteIp middleware, which walks the X-Forwarded-For header and skips trusted proxies. If your load balancer's addresses are not in its default trusted list, add them with config.action_dispatch.trusted_proxies, or every request will look like it came from the load balancer.
The Phoenix version
When we moved to Phoenix the shape stayed the same, and the code became a plug in our authentication module.
First, the endpoint needs the real client IP. Behind an AWS load balancer, conn.remote_ip is the balancer's address, so we used the remote_ip library early in the endpoint:
# lib/core_web/endpoint.ex
plug RemoteIp, headers: ["x-forwarded-for"]
RemoteIp reads the forwarded header from right to left and skips private and reserved addresses, so it lands on the first public address the load balancer actually saw, not whatever a client chose to put at the front of the header.
Then the check itself, close to what we ran:
defmodule CoreWeb.AccountAuth do
# The VPN's Elastic IP (example address)
@vpn_ip {203, 0, 113, 10}
def vpn_request?(%Plug.Conn{remote_ip: remote_ip}), do: vpn_remote_ip?(remote_ip)
def vpn_remote_ip?(remote_ip) when is_tuple(remote_ip) do
case Core.env() do
"dev" -> true
_env -> remote_ip == @vpn_ip
end
end
def vpn_remote_ip?(_remote_ip), do: false
def require_authenticated_vpn_account(conn, opts),
do: do_require_authenticated_vpn_account(Core.env(), conn, opts)
defp do_require_authenticated_vpn_account("prod", conn, _opts) do
if vpn_request?(conn) do
conn
else
conn
|> put_flash(:warning, "You must use the company VPN to access this page")
|> redirect(to: ~p"/accounts/log_in")
|> halt()
end
end
defp do_require_authenticated_vpn_account(_env, conn, _opts), do: conn
end
Because conn.remote_ip is an Erlang tuple, the comparison is a plain ==. If you have more than one egress address, or a whole range, inet_cidr gives you InetCidr.contains?/2; we used it elsewhere in the app to verify that webhooks came from our partners' published IP ranges.
The router then stacks the VPN plug on top of the normal admin checks:
scope "/admin", AdminWeb, host: "dashboard." do
pipe_through [
:browser,
:require_authenticated_admin_account,
:require_authenticated_vpn_account
]
live "/", OverviewLive, :show
live "/accounts", Accounts.ListLive, :list
live "/merchants", Merchants.ListLive, :list
end
scope "/admin", host: "dashboard." do
pipe_through [
:browser,
:require_authenticated_admin_account,
:require_authenticated_vpn_account
]
live_dashboard "/phoenix", metrics: CoreWeb.Telemetry
end
The same pipeline guarded the "become this merchant" action and LiveDashboard, which are the routes you would least like a stranger to find.
A note on LiveView
A router pipeline runs on the HTTP request that first renders a LiveView. Live navigation between LiveViews in the same live_session happens over the already-open WebSocket and does not run the pipeline again. That is fine when the WebSocket was opened from behind the gate, but if you want the check to hold for every mount, repeat it in an on_mount hook. The socket does not carry remote_ip the way a conn does, so declare connect_info: [:x_headers] on the LiveView socket and resolve the address with RemoteIp.from/2:
def remote_ip_from_socket(socket) do
x_headers = Phoenix.LiveView.get_connect_info(socket, :x_headers) || []
RemoteIp.from(x_headers, headers: ["x-forwarded-for"])
end
Beyond the admin section
Once the VPN had a fixed IP, it became the key to everything internal, not just one set of routes:
- Internal tools and preview builds. Load balancers for internal services and per-pull-request preview environments carried security groups that allowed HTTP and HTTPS only from the VPN's IP. No application check needed: the traffic never reached the app.
- Partner SFTP. Our SFTP server accepted connections only from a short allowlist of partner addresses, plus the VPN so our own staff could get in to troubleshoot.
- CI. The preview-build job in GitHub Actions connected to Pritunl with a profile stored in repository secrets before deploying, so even automation came in through the same front door as people.
Why a VPN gate is worth it
Stolen credentials stop being enough
Phishing, password reuse and session theft are how most admin panels get broken into. With a VPN gate, an attacker who has an admin's email, password and even a second factor still gets a "you must use the VPN" message. They also need a valid VPN profile and its PIN, which live on a different device and in a different system.
A much smaller attack surface
The public internet cannot probe what it cannot reach. Login forms, password resets, LiveDashboard and any admin-only bug you have not found yet are all invisible to scanners and bots. With the Rails route-constraint approach the admin namespace does not even return a login page; it returns a 404.
One switch for joining and leaving
Onboarding someone means creating a Pritunl user and handing them a profile. Offboarding means disabling that user, and their access to every internal tool ends at once, even if an application account was missed. For a small team that does not have an identity platform wired into every tool, that single switch matters.
Private resources stay private
Peering the VPN's VPC with production let engineers reach private services directly, without opening ports to the internet or juggling bastion hosts.
A clear story for auditors
As a payment company we answered to sponsor banks and card-network requirements such as PCI DSS, which expect access to sensitive systems to be restricted to those who need it and remote access to be strongly authenticated. "Admin access requires an authenticated staff account, a second factor and a connection from our VPN, and here is the code and the Terraform that enforce it" is a far easier conversation than "we have strong passwords".
It is cheap
A small instance, an Elastic IP and an open-source VPN server cost very little each month. The application change is a dozen lines.
The limits to keep in mind
A VPN gate is a layer, not a replacement for the others.
- It is network identity, not personal identity. Everyone on the VPN shares one IP, so the check proves that a request came through the VPN, not who sent it. Keep proper authentication, roles and audit logs in the application.
- Get the client IP right. If your proxy configuration is wrong, either everyone looks like the load balancer (and is locked out, or worse, let in) or a client can spoof
X-Forwarded-For. Test it from inside and outside the VPN. - The VPN is now critical infrastructure. If it goes down, staff are locked out of the admin section. Keep its configuration in code so you can rebuild it quickly, and know how you would get in during an outage.
- Watch for IPv6. If your load balancer accepts IPv6 and clients reach it over IPv6 outside the tunnel, their requests will not come from your VPN's IPv4 address. Route all traffic through the tunnel, or allow the right ranges.
- Disable the check deliberately in development. Both versions above let every request through outside production. Make sure that switch is driven by the environment and cannot be flipped by configuration in production.
Newer zero-trust tools such as Cloudflare Access or Tailscale take the idea further by checking a person's identity on every request instead of trusting a network. They are worth a look. But for a small team protecting an admin section, a self-hosted VPN with a fixed IP and a few lines of Rails or Phoenix gives you most of the benefit for very little cost, and it served us well at Edge.