trust proxy
Reverse proxies and trust
1. The Theory: What is a Reverse Proxy?
Theory: A reverse proxy is an intermediary server that receives client requests and forwards them to the internal web server.
Security: It masks the internal IP address of the application server.
SSL Termination: It handles HTTPS encryption, allowing the Node.js application to process standard HTTP and save CPU resources.
Load Balancing: It distributes incoming traffic across multiple instances of the application.
2. The "Trust" Problem
Theory: When a request passes through a proxy, the req.ip detected by Express is the IP of the Proxy rather than the actual user.
The Consequence: Security features like rate limiting will mistakenly identify all users as a single entity (the proxy) and potentially block all traffic.
The Solution: Proxies attach an
X-Forwarded-Forheader containing the original user's IP. However, Express ignores this header by default to prevent "IP spoofing," where an attacker fakes their identity.
3. Configuring trust proxy in Express
Theory: You must explicitly tell Express to trust the proxy so it accurately reads the X-Forwarded-* headers.
const express = require('express');
const app = express();
// Enabling trust so Express reads X-Forwarded-For headers
app.set('trust proxy', 1); // '1' represents the number of trusted hops (e.g., Nginx)
app.get('/check-ip', (req, res) => {
// Shows the real user IP instead of the proxy IP
res.send(`Your IP is: ${req.ip}`);
});4. Security Risks of Misconfiguration
Theory: Setting trust proxy to true globally is a significant security risk.
IP Spoofing: If you trust any proxy, a malicious actor can send a fake
X-Forwarded-Forheader to bypass security protocols.Access Control: Attackers could gain unauthorized access by pretending to be a whitelisted internal IP.
Best Practice: Only trust the specific number of "hops" or the known static IP addresses of your load balancers.