From dee2fc1fcc76944a78d58410d083603db09c9633 Mon Sep 17 00:00:00 2001 From: David Tan Date: Thu, 19 Oct 2017 17:05:38 -0400 Subject: [PATCH] Remove HTTP prefix from Django-style headers Remove right_most_proxy because it's outside spec --- sanic/ip.py | 19 +++++++++---------- sanic/request.py | 18 ++++++------------ 2 files changed, 15 insertions(+), 22 deletions(-) diff --git a/sanic/ip.py b/sanic/ip.py index 8746c069..d0a7c9d2 100644 --- a/sanic/ip.py +++ b/sanic/ip.py @@ -1,16 +1,15 @@ import socket -# CAPS R OK BCUZ STR.CASEFOLD +# CAPS R OK BCUZ WE HAZ CIDict HEADER_PRECEDENCE_ORDER = ( - 'HTTP_X_FORWARDED_FOR', 'X_FORWARDED_FOR', - # (client, proxy1, proxy2) OR (proxy2, proxy1, client) - 'HTTP_CLIENT_IP', - 'HTTP_X_REAL_IP', - 'HTTP_X_FORWARDED', - 'HTTP_X_CLUSTER_CLIENT_IP', - 'HTTP_FORWARDED_FOR', - 'HTTP_FORWARDED', - 'HTTP_VIA', + 'X_FORWARDED_FOR', + 'CLIENT_IP', + 'X_REAL_IP', + 'X_FORWARDED', + 'X_CLUSTER_CLIENT_IP', + 'FORWARDED_FOR', + 'FORWARDED', + 'VIA', 'REMOTE_ADDR', ) diff --git a/sanic/request.py b/sanic/request.py index 54cef6aa..ab70e49b 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -167,23 +167,17 @@ class Request(dict): return self._cookies @property - def ip(self, right_most_proxy=False): - # Need attr to differentiate the right_most_proxy thing - # Or we could use a separate method for right_most_proxy - attr = f'_ip{right_most_proxy}' - if not hasattr(self, attr): - setattr(self, attr, None) + def ip(self): + if not hasattr(self, '_ip'): + self._ip = None for key in HEADER_PRECEDENCE_ORDER: value = self.headers.get(key, self.headers.get(key.replace('_', '-'), '')).strip() if value is not None and value != '': - ips = [ip.strip().lower() for ip in value.split(',')] - if right_most_proxy and len(ips) > 1: - ips = reversed(ips) - for ip_str in ips: + for ip_str in [ip.strip().lower() for ip in value.split(',')]: if ip_str and is_valid_ip(ip_str): if not ip_str.startswith(NON_PUBLIC_IP_PREFIX): - setattr(self, attr, ip_str) - return getattr(self, attr) + self._ip = ip_str + return self._ip @property def remote_addr(self):