Skip to content

Commit fb44ceb

Browse files
author
AgentC Consulting
committed
Merge pull request #1415 from crimson-knight/feature/trusted-proxy-https
Decide HTTPS and client IP through trusted proxies (server.trusted_proxies)
2 parents 0a767b6 + e1d3984 commit fb44ceb

25 files changed

Lines changed: 2337 additions & 26 deletions

‎docs/guides/configuration.md‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,148 @@ server:
5555
ssl:
5656
key_file: "config/ssl/key.pem" # SSL private key path
5757
cert_file: "config/ssl/cert.pem" # SSL certificate path
58+
trusted_proxies: # Proxies allowed to report the client's scheme
59+
- "127.0.0.0/8" # and address (default: loopback only)
60+
- "::1"
61+
trusted_proxy_headers: "x-forwarded" # Headers those proxies write: "x-forwarded" or "forwarded"
62+
unix_socket: null # Listen on this UNIX socket path instead of host/port
5863
```
5964

65+
#### Running behind a TLS-terminating proxy
66+
67+
When Caddy, nginx, a cloud load balancer, or a CDN terminates TLS and
68+
forwards plain HTTP to Amber, the connection Amber sees is HTTP. Amber
69+
decides whether a request is HTTPS with one method, `request.https?` (and
70+
`request.scheme`), and everything that depends on the answer uses it,
71+
including whether the cookie jar emits `Secure` cookies such as the session
72+
and CSRF cookies.
73+
74+
`request.https?` is `true` when Amber terminates TLS itself (`server.ssl`),
75+
or when the request's immediate peer matches an entry in
76+
`server.trusted_proxies` and that proxy reported `https`.
77+
78+
Amber reads only the header family your proxies write, named by
79+
`server.trusted_proxy_headers`:
80+
81+
| `trusted_proxy_headers` | Scheme from | Client address from | Proxies |
82+
|-------------------------|-------------|---------------------|---------|
83+
| `"x-forwarded"` (default) | the last `X-Forwarded-Proto` value | `X-Forwarded-For` | Caddy, nginx, HAProxy, cloud load balancers, Cloudflare |
84+
| `"forwarded"` | the `proto=` of the last `Forwarded` element (RFC 7239) | `Forwarded: for=` | proxies configured to write RFC 7239 `Forwarded` |
85+
86+
A proxy rewrites only the family it manages and passes the other one
87+
through from the client unchanged, so believing both would let a client
88+
choose its own scheme and address. Each proxy appends its value to the end
89+
of its header, so Amber reads the last one, which is the value the trusted
90+
hop wrote. A missing header, or a value other than `http` or `https`, keeps
91+
the connection's own scheme. Amber reads no other header for the scheme,
92+
including the CGI-style `HTTPS: on`. Requests from any other peer keep their
93+
real scheme, whatever headers they carry.
94+
95+
Entries are IP addresses or CIDR blocks of your proxies. Pick the list for
96+
your deployment:
97+
98+
| Deployment | `trusted_proxies` |
99+
|------------|-------------------|
100+
| Caddy or nginx on the same host, forwarding to `127.0.0.1` | default (loopback) |
101+
| Proxy in another container or host on a private network | that network, e.g. `"10.0.0.0/8"` |
102+
| Platform router that is the only route to the app (e.g. DigitalOcean App Platform) | the private network the router connects from; log `request.remote_address` once to see it |
103+
| Cloudflare in front of Caddy on the host | default; configure Caddy as shown below |
104+
105+
The loopback default trusts every process on the host, not only the proxy:
106+
any local program that connects to Amber's port directly can set its own
107+
scheme and client address. That is sound on a host or container that runs
108+
only your application and its proxy. On a host shared with other users or
109+
untrusted programs, set `server.unix_socket` instead, so only the proxy's
110+
user or group can connect, or set `trusted_proxies` to `[]` and send the
111+
proxy's traffic over an address only it can reach.
112+
113+
List only addresses your proxies use. An entry that covers every address
114+
(`"0.0.0.0/0"`, `"::/0"`) is rejected: every client would become a trusted
115+
proxy. A block that clients share with your proxies has the same effect for
116+
those clients, so keep it as narrow as the proxies' own addresses.
117+
118+
The same rule decides the client's IP address, `request.client_ip` (which
119+
the `Amber::Pipe::ClientIp` pipe stores in `context.client_ip`). From an
120+
untrusted peer it is the peer's own address, and forwarding headers are
121+
ignored. From a trusted proxy Amber reads the hops in the configured header
122+
(`X-Forwarded-For`, or `Forwarded: for=`) from the right, skips every hop
123+
that is itself a trusted proxy, and returns the first one that is not; a
124+
spoofed leftmost entry is never reached. A hop that is not exactly an IP
125+
address, with an optional port, ends the walk, and the nearest verified
126+
address is used. When every hop is a trusted proxy, the farthest one is the
127+
client. An empty hop also ends the walk.
128+
129+
When a CDN such as Cloudflare sits in front of Caddy, Caddy is Amber's only
130+
peer, so the CDN's own headers reach Amber only as Caddy passes them on.
131+
Let Caddy decide who the client is, and keep Amber's loopback default:
132+
133+
```caddyfile
134+
{
135+
servers {
136+
trusted_proxies static <Cloudflare's published IP ranges>
137+
client_ip_headers Cf-Connecting-Ip
138+
}
139+
}
140+
141+
example.com {
142+
reverse_proxy 127.0.0.1:3000 {
143+
header_up X-Forwarded-For {client_ip}
144+
}
145+
}
146+
```
147+
148+
With Cloudflare's ranges trusted, Caddy resolves `{client_ip}` to the
149+
visitor and keeps the `X-Forwarded-Proto` Cloudflare sent; a client that
150+
reaches Caddy directly gets its own address and scheme. Use Cloudflare's Full
151+
(strict) TLS mode so the hop from Cloudflare to Caddy is HTTPS too.
152+
153+
`ClientIp.new(["X-Real-IP"])` reads a named header instead, under the same
154+
rule. Name a header only when your proxy sets it on every request, which
155+
overwrites any value a client sent (for Caddy, `header_up X-Real-IP
156+
{client_ip}`); a proxy passes other headers through from the client
157+
unchanged.
158+
159+
To put the proxy on a UNIX socket instead of loopback TCP, set
160+
`server.unix_socket` (for Caddy, `reverse_proxy unix//run/app.sock`). While
161+
it is set, every UNIX socket peer counts as a trusted proxy: the connection
162+
is local by construction and the socket file's permissions decide who may
163+
open it. Amber creates the socket with mode `0660`, so only its own user and
164+
group can connect: run the proxy as the application's user, or add the
165+
proxy's user to the application's group (for nginx on Debian, `www-data`).
166+
Put the socket in a directory the application owns, such as `/run/app/`,
167+
rather than a shared one like `/tmp`. The `<socket>.lock` file beside it is
168+
created at mode `0600`; a lock file another user owns or other users may
169+
open, or a lock another process holds for more than 10 seconds, fails the start with
170+
`Socket::BindError`. UNIX sockets are not supported on Windows, and these
171+
three `server` settings need the V2 settings format: a flat V1 file that
172+
sets one, directly or through an `AMBER_SERVER_*` variable, fails the boot. A
173+
socket file left behind by a stopped
174+
server is replaced at boot;
175+
a socket another running server still accepts connections on is not, and the
176+
start fails with `Socket::BindError`. It cannot be combined with
177+
`server.ssl` or a `process_count` above 1; the server checks this before it
178+
forks or binds.
179+
180+
Set the list in YAML, in `config/settings.cr`
181+
(`settings.server.trusted_proxies = ["127.0.0.1", "10.0.0.0/8"]`), or with
182+
the comma-separated `AMBER_SERVER_TRUSTED_PROXIES` environment variable. An
183+
empty value trusts no proxy. The list is replaced, not edited in place:
184+
`trusted_proxies` returns a copy, so assign a new array to change it. Each
185+
entry is checked when the settings load or the list is assigned.
186+
60187
Validation rules:
61188
- `port` must be between 1 and 65535
62189
- `process_count` must be at least 1
63190
- `secret_key_base` must be set in production
64191
- `secret_key_base` should be at least 32 characters when set
65192
- SSL files must exist when SSL is enabled
193+
- every `trusted_proxies` entry must be an IP address or CIDR block that does
194+
not cover every address, checked when the settings load or the list is
195+
assigned
196+
- `trusted_proxy_headers` must be `"x-forwarded"` or `"forwarded"`, checked
197+
the same way
198+
- `unix_socket` cannot be combined with `ssl` or a `process_count` above 1,
199+
checked by `validate!` and again when the server starts
66200

67201
### SessionConfig
68202

@@ -170,6 +304,9 @@ The naming convention is `AMBER_{SECTION}_{KEY}`:
170304
| `AMBER_SERVER_SECRET_KEY_BASE` | `server.secret_key_base` |
171305
| `AMBER_SERVER_SSL_KEY_FILE` | `server.ssl.key_file` |
172306
| `AMBER_SERVER_SSL_CERT_FILE` | `server.ssl.cert_file` |
307+
| `AMBER_SERVER_TRUSTED_PROXIES` | `server.trusted_proxies` (comma-separated) |
308+
| `AMBER_SERVER_TRUSTED_PROXY_HEADERS` | `server.trusted_proxy_headers` |
309+
| `AMBER_SERVER_UNIX_SOCKET` | `server.unix_socket` |
173310
| `AMBER_DATABASE_URL` or `DATABASE_URL` | `database.url` |
174311
| `AMBER_SESSION_KEY` | `session.key` |
175312
| `AMBER_SESSION_STORE` | `session.store` |

‎docs/migration-guide.md‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ This guide covers every breaking change between Amber V1 (1.4.x) and Amber V2, w
1515
| Import paths changed | Require statements | Low |
1616
| Configuration restructured | YAML config files | Medium |
1717
| Session security updated | Session configuration | Low |
18+
| HTTPS decided by trusted proxies | Apps behind a TLS-terminating proxy | Low |
1819

1920
## 1. CLI Extracted from the Framework
2021

@@ -493,6 +494,68 @@ V2 updates the default session configuration for improved security:
493494

494495
Review your session configuration and update as needed.
495496

497+
## 10. HTTPS Behind a Reverse Proxy
498+
499+
Production sessions use `Secure` cookies, and Amber emits a `Secure` cookie
500+
only on a request it considers HTTPS. Earlier V2 betas considered a request
501+
HTTPS only when it carried the header `HTTPS: on`, which TLS-terminating
502+
proxies (Caddy, nginx, DigitalOcean App Platform, Cloudflare) do not send.
503+
They send `X-Forwarded-Proto: https` or `Forwarded: proto=https`. Behind such
504+
a proxy the session cookie never arrived, so login and CSRF failed.
505+
506+
Amber now answers "is this request HTTPS" in one place, `request.https?`,
507+
using the new `server.trusted_proxies` setting: a list of IP addresses and
508+
CIDR blocks, loopback only by default. When the immediate peer is in the
509+
list, Amber believes the scheme that proxy appended to `X-Forwarded-Proto`
510+
(or, with `server.trusted_proxy_headers: "forwarded"`, to RFC 7239
511+
`Forwarded`). Requests from any other peer keep their real scheme.
512+
513+
What to change:
514+
515+
1. **Proxy on the same host** (Caddy or nginx forwarding to `127.0.0.1`):
516+
nothing to configure; the default trusts loopback.
517+
2. **Proxy elsewhere** (App Platform, a load balancer, a proxy container):
518+
list its addresses.
519+
520+
```yaml
521+
# config/environments/production.yml
522+
server:
523+
trusted_proxies:
524+
- "10.0.0.0/8"
525+
```
526+
527+
or set `AMBER_SERVER_TRUSTED_PROXIES=10.0.0.0/8` in the deployment. List
528+
only the network your proxies or platform router connect from; an entry
529+
that covers every address (`"0.0.0.0/0"`, `"::/0"`) is rejected.
530+
3. **Proxy that writes RFC 7239 `Forwarded`** instead of `X-Forwarded-*`:
531+
set `server.trusted_proxy_headers: "forwarded"` (or
532+
`AMBER_SERVER_TRUSTED_PROXY_HEADERS=forwarded`). Amber reads only the
533+
family you name, because a proxy passes the other one through from the
534+
client.
535+
4. **Delete any workaround pipe** that writes `HTTPS: on` into the request
536+
(for example one that sets it unconditionally in production). Amber no
537+
longer reads `HTTPS: on` at all; it reads the proxy's own
538+
`X-Forwarded-Proto`. If your proxy sends only `HTTPS: on`, configure it
539+
to send `X-Forwarded-Proto` instead.
540+
541+
The same setting decides the client's IP address. `request.client_ip` and
542+
the `ClientIp` pipe now return the peer's own address for an untrusted peer,
543+
and for a trusted proxy the nearest untrusted hop in `X-Forwarded-For` (or
544+
`Forwarded: for=`), read from the right. Earlier versions took the leftmost
545+
`X-Forwarded-For` entry from any peer, which a client controls; if your app
546+
logged or rate-limited on that value, expect the real address now.
547+
548+
A proxy can also reach Amber over a UNIX socket: set `server.unix_socket`,
549+
and UNIX socket peers are trusted while it is set.
550+
551+
One behavior changes: `HTTPS: on` no longer marks a request as HTTPS, from
552+
any peer, because a proxy passes it through from the client unchanged.
553+
Behind Caddy, nginx or a cloud load balancer nothing else changes, since
554+
they send `X-Forwarded-Proto`.
555+
556+
See the [configuration guide](guides/configuration.md#running-behind-a-tls-terminating-proxy)
557+
for the full rules.
558+
496559
## Dependency Changes Summary
497560

498561
### Remove from shard.yml
@@ -540,5 +603,6 @@ is published.
540603
- [ ] Update session configuration to use adapter pattern
541604
- [ ] Remove any direct `require "redis"`, `require "amber_router"`, or `require "kilt"` statements
542605
- [ ] Add database drivers explicitly to shard.yml if needed
606+
- [ ] Behind a TLS-terminating proxy, set `server.trusted_proxies` to the proxy's addresses, make sure it sends `X-Forwarded-Proto`, and delete any pipe that writes `HTTPS: on`
543607
- [ ] Test all routes and templates
544608
- [ ] (Optional) Start migrating controller actions to use Schema API

‎spec/amber/amber_spec.cr‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ describe Amber do
3232
end
3333

3434
describe Amber::Server do
35+
describe "#host_url" do
36+
it "names the UNIX socket when server.unix_socket is set" do
37+
server_config = Amber.settings.server
38+
begin
39+
server_config.unix_socket = "/run/app.sock"
40+
Amber::Server.instance.host_url.should eq "unix:///run/app.sock"
41+
ensure
42+
server_config.unix_socket = nil
43+
end
44+
end
45+
end
46+
3547
describe ".configure" do
3648
it "overrides current environment settings" do
3749
Amber.env = :test

‎spec/amber/configuration/env_override_spec.cr‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,54 @@ module Amber::Configuration
186186
end
187187
end
188188

189+
it "overrides server.trusted_proxies from AMBER_SERVER_TRUSTED_PROXIES" do
190+
with_env({"AMBER_SERVER_TRUSTED_PROXIES" => "127.0.0.1, 10.0.0.0/8"}) do
191+
config = AppConfig.new
192+
EnvOverride.apply_all(config)
193+
config.server.trusted_proxies.should eq ["127.0.0.1", "10.0.0.0/8"]
194+
end
195+
end
196+
197+
it "trusts no proxy when AMBER_SERVER_TRUSTED_PROXIES is empty" do
198+
with_env({"AMBER_SERVER_TRUSTED_PROXIES" => ""}) do
199+
config = AppConfig.new
200+
EnvOverride.apply_all(config)
201+
config.server.trusted_proxies.should be_empty
202+
end
203+
end
204+
205+
it "overrides server.trusted_proxy_headers from AMBER_SERVER_TRUSTED_PROXY_HEADERS" do
206+
with_env({"AMBER_SERVER_TRUSTED_PROXY_HEADERS" => "forwarded"}) do
207+
config = AppConfig.new
208+
EnvOverride.apply_all(config)
209+
config.server.reads_forwarded_header?.should be_true
210+
end
211+
end
212+
213+
it "rejects an unknown AMBER_SERVER_TRUSTED_PROXY_HEADERS value" do
214+
with_env({"AMBER_SERVER_TRUSTED_PROXY_HEADERS" => "x-real-ip"}) do
215+
expect_raises(Amber::Exceptions::ConfigurationError, /trusted_proxy_headers/) do
216+
EnvOverride.apply_all(AppConfig.new)
217+
end
218+
end
219+
end
220+
221+
it "rejects an AMBER_SERVER_TRUSTED_PROXIES entry that trusts every address" do
222+
with_env({"AMBER_SERVER_TRUSTED_PROXIES" => "0.0.0.0/0"}) do
223+
expect_raises(Amber::Exceptions::ConfigurationError, /trusts every address/) do
224+
EnvOverride.apply_all(AppConfig.new)
225+
end
226+
end
227+
end
228+
229+
it "overrides server.unix_socket from AMBER_SERVER_UNIX_SOCKET" do
230+
with_env({"AMBER_SERVER_UNIX_SOCKET" => "/run/app.sock"}) do
231+
config = AppConfig.new
232+
EnvOverride.apply_all(config)
233+
config.server.unix_socket.should eq "/run/app.sock"
234+
end
235+
end
236+
189237
it "overrides server.port from AMBER_SERVER_PORT" do
190238
with_env({"AMBER_SERVER_PORT" => "8080"}) do
191239
config = AppConfig.new

‎spec/amber/configuration/loader_v2_spec.cr‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,17 @@ module Amber::Environment
141141
end
142142

143143
describe "V1 YAML backward compatibility" do
144+
it "rejects AMBER_SERVER_UNIX_SOCKET with a V1 file instead of serving on TCP" do
145+
ENV["AMBER_SERVER_UNIX_SOCKET"] = "/run/app/app.sock"
146+
begin
147+
expect_raises(Amber::Exceptions::ConfigurationError, /server.unix_socket needs the V2 settings format/) do
148+
Loader.new(:test, "./spec/support/config/").settings
149+
end
150+
ensure
151+
ENV.delete("AMBER_SERVER_UNIX_SOCKET")
152+
end
153+
end
154+
144155
it "still loads V1 format YAML files correctly" do
145156
loader = Loader.new(:test, "./spec/support/config/")
146157
settings = loader.settings

0 commit comments

Comments
 (0)