|
| 1 | +import hashlib |
| 2 | +import logging |
| 3 | +from datetime import datetime, timedelta |
| 4 | + |
| 5 | +from redis import Redis |
| 6 | +from redis.exceptions import RedisError |
| 7 | + |
| 8 | +from waterbutler.server import settings |
| 9 | +from waterbutler.core.exceptions import WaterButlerRedisError |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class RateLimitingMixin: |
| 15 | + """ Rate-limiting WB API with Redis using the "Fixed Window" algorithm. |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self): |
| 19 | + |
| 20 | + self.WINDOW_SIZE = settings.RATE_LIMITING_FIXED_WINDOW_SIZE |
| 21 | + self.WINDOW_LIMIT = settings.RATE_LIMITING_FIXED_WINDOW_LIMIT |
| 22 | + self.redis_conn = Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, |
| 23 | + password=settings.REDIS_PASSWORD) |
| 24 | + |
| 25 | + def rate_limit(self): |
| 26 | + """ Check with the WB Redis server on whether to rate-limit a request. Returns a tuple. |
| 27 | + First value is `True` if the limit is reached, `False` otherwise. Second value is the |
| 28 | + rate-limiting metadata (nbr of requests remaining, time to reset, etc.) if the request was |
| 29 | + rate-limited. |
| 30 | + """ |
| 31 | + |
| 32 | + limit_check, redis_key = self.get_auth_naive() |
| 33 | + logger.debug('>>> RATE LIMITING >>> check={} key={}'.format(limit_check, redis_key)) |
| 34 | + if not limit_check: |
| 35 | + return False, None |
| 36 | + |
| 37 | + try: |
| 38 | + counter = self.redis_conn.incr(redis_key) |
| 39 | + except RedisError: |
| 40 | + raise WaterButlerRedisError('INCR {}'.format(redis_key)) |
| 41 | + |
| 42 | + if counter > self.WINDOW_LIMIT: |
| 43 | + # The key exists and the limit has been reached. |
| 44 | + try: |
| 45 | + retry_after = self.redis_conn.ttl(redis_key) |
| 46 | + except RedisError: |
| 47 | + raise WaterButlerRedisError('TTL {}'.format(redis_key)) |
| 48 | + logger.debug('>>> RATE LIMITING >>> FAIL >>> key={} ' |
| 49 | + 'counter={} url={}'.format(redis_key, counter, self.request.full_url())) |
| 50 | + data = { |
| 51 | + 'retry_after': int(retry_after), |
| 52 | + 'remaining': 0, |
| 53 | + 'reset': str(datetime.now() + timedelta(seconds=int(retry_after))), |
| 54 | + } |
| 55 | + return True, data |
| 56 | + elif counter == 1: |
| 57 | + # The key does not exist and `.incr()` returns 1 by default. |
| 58 | + try: |
| 59 | + self.redis_conn.expire(redis_key, self.WINDOW_SIZE) |
| 60 | + except RedisError: |
| 61 | + raise WaterButlerRedisError('EXPIRE {} {}'.format(redis_key, self.WINDOW_SIZE)) |
| 62 | + logger.debug('>>> RATE LIMITING >>> NEW >>> key={} ' |
| 63 | + 'counter={} url={}'.format(redis_key, counter, self.request.full_url())) |
| 64 | + else: |
| 65 | + # The key exists and the limit has not been reached. |
| 66 | + logger.debug('>>> RATE LIMITING >>> PASS >>> key={} ' |
| 67 | + 'counter={} url={}'.format(redis_key, counter, self.request.full_url())) |
| 68 | + |
| 69 | + return False, None |
| 70 | + |
| 71 | + def get_auth_naive(self): |
| 72 | + """ Get the obfuscated authentication / authorization credentials from the request. Return |
| 73 | + a tuple ``(limit_check, auth_key)`` that tells the rate-limiter 1) whether to rate-limit, |
| 74 | + and 2) if so, limit by what key. |
| 75 | +
|
| 76 | + Refer to ``tornado.httputil.HTTPServerRequest`` for more info on tornado's request object: |
| 77 | + https://www.tornadoweb.org/en/stable/httputil.html#tornado.httputil.HTTPServerRequest |
| 78 | +
|
| 79 | + This is a NAIVE implementation in which WaterButler rate-limiter only checks the existence |
| 80 | + of auth creds in the requests without further verifying them with the OSF. Invalid creds |
| 81 | + will fail the next OSF auth part anyway even if it passes the rate-limiter. |
| 82 | +
|
| 83 | + There are four types of auth: 1) OAuth access token, 2) basic auth w/ base64-encoded |
| 84 | + username/password, 3) OSF cookie, and 4) no auth. The naive implementation checks each |
| 85 | + method in this order. Only cookie-based auth is permitted to bypass the rate-limiter. |
| 86 | + This order does not care about the validity of the auth mechanism. An invalid Basic auth |
| 87 | + header + an OSF cookie will be rate-limited according to the Basic auth header. |
| 88 | +
|
| 89 | + TODO: check with OSF API auth to see how it deals with multiple auth options. |
| 90 | + """ |
| 91 | + |
| 92 | + auth_hdrs = self.request.headers.get('Authorization', None) |
| 93 | + |
| 94 | + # CASE 1: Requests with a bearer token (PAT or OAuth) |
| 95 | + if auth_hdrs and auth_hdrs.startswith('Bearer '): # Bearer token |
| 96 | + bearer_token = auth_hdrs.split(' ')[1] if auth_hdrs.startswith('Bearer ') else None |
| 97 | + logger.debug('>>> RATE LIMITING >>> AUTH:TOKEN >>> {}'.format(bearer_token)) |
| 98 | + return True, 'TOKEN__{}'.format(self._obfuscate_creds(bearer_token)) |
| 99 | + |
| 100 | + # CASE 2: Requests with basic auth using username and password |
| 101 | + if auth_hdrs and auth_hdrs.startswith('Basic '): # Basic auth |
| 102 | + basic_creds = auth_hdrs.split(' ')[1] if auth_hdrs.startswith('Basic ') else None |
| 103 | + logger.debug('>>> RATE LIMITING >>> AUTH:BASIC >>> {}'.format(basic_creds)) |
| 104 | + return True, 'BASIC__{}'.format(self._obfuscate_creds(basic_creds)) |
| 105 | + |
| 106 | + # CASE 3: Requests with OSF cookies |
| 107 | + # SECURITY WARNING: Must check cookie last since it can only be allowed when used alone! |
| 108 | + cookies = self.request.cookies or None |
| 109 | + if cookies and cookies.get('osf'): |
| 110 | + osf_cookie = cookies.get('osf').value |
| 111 | + logger.debug('>>> RATE LIMITING >>> AUTH:COOKIE >>> {}'.format(osf_cookie)) |
| 112 | + return False, 'COOKIE_{}'.format(self._obfuscate_creds(osf_cookie)) |
| 113 | + |
| 114 | + # TODO: Work with DevOps to make sure that the `remote_ip` is the real IP instead of our |
| 115 | + # load balancers. In addition, check relevatn HTTP headers as well. |
| 116 | + # CASE 4: Requests without any expected auth (case 1, 2 or 3 above). |
| 117 | + remote_ip = self.request.remote_ip or 'NOI.PNO.IPN.OIP' |
| 118 | + logger.debug('>>> RATE LIMITING >>> AUTH:NONE >>> {}'.format(remote_ip)) |
| 119 | + return True, 'NOAUTH_{}'.format(self._obfuscate_creds(remote_ip)) |
| 120 | + |
| 121 | + @staticmethod |
| 122 | + def _obfuscate_creds(creds): |
| 123 | + """Obfuscate authentication/authorization credentials: cookie, access token and password. |
| 124 | +
|
| 125 | + It is not recommended to store the plain OSF cookie or the OAuth bearer token as key and it |
| 126 | + is evil to store the base64-encoded username and password as key since it is reversible. |
| 127 | + """ |
| 128 | + |
| 129 | + return hashlib.sha256(creds.encode('utf-8')).hexdigest().upper() |
0 commit comments