Comparison

plugins/mod_http.lua @ 10840:a83bfb266b15

mod_http: Add documentation to the non-obvious logic of get_ip_from_request Because docs are good.
author Jonas Schäfer <jonas@wielicki.name>
date Thu, 14 May 2020 14:59:59 +0200
parent 10465:09697a673015
child 10841:22f783d80eec
comparison
equal deleted inserted replaced
10839:018acdaf374f 10840:a83bfb266b15
206 206
207 local function get_ip_from_request(request) 207 local function get_ip_from_request(request)
208 local ip = request.conn:ip(); 208 local ip = request.conn:ip();
209 local forwarded_for = request.headers.x_forwarded_for; 209 local forwarded_for = request.headers.x_forwarded_for;
210 if forwarded_for then 210 if forwarded_for then
211 -- This logic looks weird at first, but it makes sense.
212 -- The for loop will take the last non-trusted-proxy IP from `forwarded_for`.
213 -- We append the original request IP to the header. Then, since the last IP wins, there are two cases:
214 -- 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.
215 -- 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.
216 -- 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.
217 -- 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.
211 forwarded_for = forwarded_for..", "..ip; 218 forwarded_for = forwarded_for..", "..ip;
212 for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do 219 for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do
213 if not trusted_proxies[forwarded_ip] then 220 if not trusted_proxies[forwarded_ip] then
214 ip = forwarded_ip; 221 ip = forwarded_ip;
215 end 222 end