# HG changeset patch # User Jonas Schäfer # Date 1589461199 -7200 # Node ID a83bfb266b1520e7b7a9b89aba8d6450e0c9cc35 # Parent 018acdaf374fcd167a6a89ecaccaa362ed9f1633 mod_http: Add documentation to the non-obvious logic of get_ip_from_request Because docs are good. diff -r 018acdaf374f -r a83bfb266b15 plugins/mod_http.lua --- a/plugins/mod_http.lua Mon May 11 23:22:25 2020 +0200 +++ b/plugins/mod_http.lua Thu May 14 14:59:59 2020 +0200 @@ -208,6 +208,13 @@ local ip = request.conn:ip(); local forwarded_for = request.headers.x_forwarded_for; if forwarded_for then + -- This logic looks weird at first, but it makes sense. + -- The for loop will take the last non-trusted-proxy IP from `forwarded_for`. + -- We append the original request IP to the header. Then, since the last IP wins, there are two cases: + -- Case a) The original request IP is *not* in trusted proxies, in which case the X-Forwarded-For header will, effectively, be ineffective; the original request IP will win because it overrides any other IP in the header. + -- Case b) The original request IP is in trusted proxies. In that case, the if branch in the for loop will skip the last IP, causing it to be ignored. The second-to-last IP will be taken instead. + -- Case c) If the second-to-last IP is also a trusted proxy, it will also be ignored, iteratively, up to the last IP which isn’t in trusted proxies. + -- Case d) If all IPs are in trusted proxies, something went obviously wrong and the logic never overwrites `ip`, leaving it at the original request IP. forwarded_for = forwarded_for..", "..ip; for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do if not trusted_proxies[forwarded_ip] then