2017-11-16 00:50:28 +01:00
|
|
|
import cProfile
|
|
|
|
import logging
|
|
|
|
import time
|
|
|
|
import traceback
|
2020-06-11 00:54:34 +02:00
|
|
|
from typing import Any, AnyStr, Dict, Iterable, List, MutableMapping, Optional
|
2013-04-23 18:51:17 +02:00
|
|
|
|
2013-02-11 23:33:47 +01:00
|
|
|
from django.conf import settings
|
2020-04-06 23:32:50 +02:00
|
|
|
from django.core.exceptions import DisallowedHost
|
2017-11-16 00:50:28 +01:00
|
|
|
from django.db import connection
|
|
|
|
from django.http import HttpRequest, HttpResponse, StreamingHttpResponse
|
2020-02-14 20:29:05 +01:00
|
|
|
from django.middleware.common import CommonMiddleware
|
2019-02-02 23:53:55 +01:00
|
|
|
from django.shortcuts import render
|
2017-05-18 11:56:03 +02:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2017-11-16 00:50:28 +01:00
|
|
|
from django.utils.translation import ugettext as _
|
|
|
|
from django.views.csrf import csrf_failure as html_csrf_failure
|
2016-05-25 15:02:02 +02:00
|
|
|
|
2019-04-24 02:50:25 +02:00
|
|
|
from zerver.lib.cache import get_remote_cache_requests, get_remote_cache_time
|
2018-11-01 00:19:48 +01:00
|
|
|
from zerver.lib.db import reset_queries
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.debug import maybe_tracemalloc_listen
|
2017-11-16 00:50:28 +01:00
|
|
|
from zerver.lib.exceptions import ErrorCode, JsonableError, RateLimited
|
2019-04-24 02:50:25 +02:00
|
|
|
from zerver.lib.html_to_text import get_content_description
|
2020-06-26 23:06:05 +02:00
|
|
|
from zerver.lib.markdown import get_markdown_requests, get_markdown_time
|
2020-03-04 14:05:25 +01:00
|
|
|
from zerver.lib.rate_limiter import RateLimitResult
|
2017-07-21 02:19:52 +02:00
|
|
|
from zerver.lib.response import json_error, json_response_from_error
|
2017-10-19 07:21:57 +02:00
|
|
|
from zerver.lib.subdomains import get_subdomain
|
2018-03-14 23:16:27 +01:00
|
|
|
from zerver.lib.types import ViewFuncT
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.utils import statsd
|
2017-10-20 02:56:49 +02:00
|
|
|
from zerver.models import Realm, flush_per_request_caches, get_realm
|
2012-10-16 23:52:10 +02:00
|
|
|
|
2013-08-06 22:51:47 +02:00
|
|
|
logger = logging.getLogger('zulip.requests')
|
2020-05-08 16:37:58 +02:00
|
|
|
slow_query_logger = logging.getLogger('zulip.slow_queries')
|
2012-10-16 23:52:10 +02:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def record_request_stop_data(log_data: MutableMapping[str, Any]) -> None:
|
2013-11-08 21:40:44 +01:00
|
|
|
log_data['time_stopped'] = time.time()
|
2016-03-31 03:23:21 +02:00
|
|
|
log_data['remote_cache_time_stopped'] = get_remote_cache_time()
|
2016-03-31 03:24:05 +02:00
|
|
|
log_data['remote_cache_requests_stopped'] = get_remote_cache_requests()
|
2020-06-26 23:06:05 +02:00
|
|
|
log_data['markdown_time_stopped'] = get_markdown_time()
|
|
|
|
log_data['markdown_requests_stopped'] = get_markdown_requests()
|
2013-11-18 18:55:19 +01:00
|
|
|
if settings.PROFILE_ALL_REQUESTS:
|
|
|
|
log_data["prof"].disable()
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2018-10-17 00:39:10 +02:00
|
|
|
def async_request_timer_stop(request: HttpRequest) -> None:
|
2013-11-08 21:40:44 +01:00
|
|
|
record_request_stop_data(request._log_data)
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def record_request_restart_data(log_data: MutableMapping[str, Any]) -> None:
|
2013-11-18 18:55:19 +01:00
|
|
|
if settings.PROFILE_ALL_REQUESTS:
|
|
|
|
log_data["prof"].enable()
|
2013-11-08 21:40:44 +01:00
|
|
|
log_data['time_restarted'] = time.time()
|
2016-03-31 03:23:21 +02:00
|
|
|
log_data['remote_cache_time_restarted'] = get_remote_cache_time()
|
2016-03-31 03:24:05 +02:00
|
|
|
log_data['remote_cache_requests_restarted'] = get_remote_cache_requests()
|
2020-06-26 23:06:05 +02:00
|
|
|
log_data['markdown_time_restarted'] = get_markdown_time()
|
|
|
|
log_data['markdown_requests_restarted'] = get_markdown_requests()
|
2013-04-23 19:36:50 +02:00
|
|
|
|
2018-10-17 00:39:10 +02:00
|
|
|
def async_request_timer_restart(request: HttpRequest) -> None:
|
2013-12-12 18:59:02 +01:00
|
|
|
if "time_restarted" in request._log_data:
|
|
|
|
# Don't destroy data when being called from
|
|
|
|
# finish_current_handler
|
|
|
|
return
|
2013-11-08 21:40:44 +01:00
|
|
|
record_request_restart_data(request._log_data)
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def record_request_start_data(log_data: MutableMapping[str, Any]) -> None:
|
2013-11-18 18:55:19 +01:00
|
|
|
if settings.PROFILE_ALL_REQUESTS:
|
|
|
|
log_data["prof"] = cProfile.Profile()
|
|
|
|
log_data["prof"].enable()
|
|
|
|
|
2018-11-01 00:19:48 +01:00
|
|
|
reset_queries()
|
2013-11-08 21:40:44 +01:00
|
|
|
log_data['time_started'] = time.time()
|
2016-03-31 03:23:21 +02:00
|
|
|
log_data['remote_cache_time_start'] = get_remote_cache_time()
|
2016-03-31 03:24:05 +02:00
|
|
|
log_data['remote_cache_requests_start'] = get_remote_cache_requests()
|
2020-06-26 23:06:05 +02:00
|
|
|
log_data['markdown_time_start'] = get_markdown_time()
|
|
|
|
log_data['markdown_requests_start'] = get_markdown_requests()
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def timedelta_ms(timedelta: float) -> float:
|
2013-11-08 23:11:37 +01:00
|
|
|
return timedelta * 1000
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def format_timedelta(timedelta: float) -> str:
|
2013-11-08 23:11:37 +01:00
|
|
|
if (timedelta >= 1):
|
2020-06-10 06:41:04 +02:00
|
|
|
return f"{timedelta:.1f}s"
|
|
|
|
return f"{timedelta_ms(timedelta):.0f}ms"
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def is_slow_query(time_delta: float, path: str) -> bool:
|
2013-12-26 15:16:49 +01:00
|
|
|
if time_delta < 1.2:
|
2013-12-26 15:13:00 +01:00
|
|
|
return False
|
|
|
|
is_exempt = \
|
2017-10-16 22:07:19 +02:00
|
|
|
path in ["/activity", "/json/report/error",
|
2013-12-26 15:13:00 +01:00
|
|
|
"/api/v1/deployments/report_error"] \
|
|
|
|
or path.startswith("/realm_activity/") \
|
|
|
|
or path.startswith("/user_activity/")
|
|
|
|
if is_exempt:
|
2013-12-26 15:23:18 +01:00
|
|
|
return time_delta >= 5
|
2013-12-26 15:20:59 +01:00
|
|
|
if 'webathena_kerberos' in path:
|
|
|
|
return time_delta >= 10
|
2013-12-26 15:13:00 +01:00
|
|
|
return True
|
2013-12-26 15:01:46 +01:00
|
|
|
|
2019-02-28 02:46:00 +01:00
|
|
|
statsd_blacklisted_requests = [
|
|
|
|
'do_confirm', 'signup_send_confirm', 'new_realm_send_confirm,'
|
|
|
|
'eventslast_event_id', 'webreq.content', 'avatar', 'user_uploads',
|
|
|
|
'password.reset', 'static', 'json.bots', 'json.users', 'json.streams',
|
|
|
|
'accounts.unsubscribe', 'apple-touch-icon', 'emoji', 'json.bots',
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
'upload_file', 'realm_activity', 'user_activity',
|
2019-02-28 02:46:00 +01:00
|
|
|
]
|
|
|
|
|
2020-03-09 11:39:20 +01:00
|
|
|
def write_log_line(log_data: MutableMapping[str, Any], path: str, method: str, remote_ip: str,
|
|
|
|
requestor_for_logs: str, client_name: str, status_code: int=200,
|
|
|
|
error_content: Optional[AnyStr]=None,
|
2017-12-08 17:42:02 +01:00
|
|
|
error_content_iter: Optional[Iterable[AnyStr]]=None) -> None:
|
2015-08-22 23:38:01 +02:00
|
|
|
assert error_content is None or error_content_iter is None
|
2015-08-22 23:18:31 +02:00
|
|
|
if error_content is not None:
|
|
|
|
error_content_iter = (error_content,)
|
|
|
|
|
2019-02-28 02:46:00 +01:00
|
|
|
if settings.STATSD_HOST != '':
|
|
|
|
# For statsd timer name
|
|
|
|
if path == '/':
|
2020-04-09 21:51:58 +02:00
|
|
|
statsd_path = 'webreq'
|
2019-02-28 02:46:00 +01:00
|
|
|
else:
|
2020-06-10 06:41:04 +02:00
|
|
|
statsd_path = "webreq.{}".format(path[1:].replace('/', '.'))
|
2019-02-28 02:46:00 +01:00
|
|
|
# Remove non-ascii chars from path (there should be none, if there are it's
|
|
|
|
# because someone manually entered a nonexistent path), as UTF-8 chars make
|
|
|
|
# statsd sad when it sends the key name over the socket
|
|
|
|
statsd_path = statsd_path.encode('ascii', errors='ignore').decode("ascii")
|
|
|
|
# TODO: This could probably be optimized to use a regular expression rather than a loop.
|
2020-04-09 21:51:58 +02:00
|
|
|
suppress_statsd = any(blacklisted in statsd_path for blacklisted in statsd_blacklisted_requests)
|
2013-11-08 21:40:44 +01:00
|
|
|
else:
|
2019-02-28 02:46:00 +01:00
|
|
|
suppress_statsd = True
|
|
|
|
statsd_path = ''
|
2013-11-08 21:40:44 +01:00
|
|
|
|
|
|
|
time_delta = -1
|
|
|
|
# A time duration of -1 means the StartLogRequests middleware
|
|
|
|
# didn't run for some reason
|
|
|
|
optional_orig_delta = ""
|
|
|
|
if 'time_started' in log_data:
|
|
|
|
time_delta = time.time() - log_data['time_started']
|
|
|
|
if 'time_stopped' in log_data:
|
|
|
|
orig_time_delta = time_delta
|
|
|
|
time_delta = ((log_data['time_stopped'] - log_data['time_started']) +
|
|
|
|
(time.time() - log_data['time_restarted']))
|
2020-06-10 06:41:04 +02:00
|
|
|
optional_orig_delta = f" (lp: {format_timedelta(orig_time_delta)})"
|
2016-03-31 03:28:24 +02:00
|
|
|
remote_cache_output = ""
|
2016-03-31 03:23:21 +02:00
|
|
|
if 'remote_cache_time_start' in log_data:
|
|
|
|
remote_cache_time_delta = get_remote_cache_time() - log_data['remote_cache_time_start']
|
2016-03-31 03:26:47 +02:00
|
|
|
remote_cache_count_delta = get_remote_cache_requests() - log_data['remote_cache_requests_start']
|
2016-03-31 03:24:05 +02:00
|
|
|
if 'remote_cache_requests_stopped' in log_data:
|
2013-11-08 21:40:44 +01:00
|
|
|
# (now - restarted) + (stopped - start) = (now - start) + (stopped - restarted)
|
2016-03-31 03:23:21 +02:00
|
|
|
remote_cache_time_delta += (log_data['remote_cache_time_stopped'] -
|
2016-12-03 00:04:17 +01:00
|
|
|
log_data['remote_cache_time_restarted'])
|
2016-03-31 03:26:47 +02:00
|
|
|
remote_cache_count_delta += (log_data['remote_cache_requests_stopped'] -
|
2016-12-03 00:04:17 +01:00
|
|
|
log_data['remote_cache_requests_restarted'])
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2016-03-31 03:23:21 +02:00
|
|
|
if (remote_cache_time_delta > 0.005):
|
2020-06-10 06:41:04 +02:00
|
|
|
remote_cache_output = f" (mem: {format_timedelta(remote_cache_time_delta)}/{remote_cache_count_delta})"
|
2013-11-08 21:40:44 +01:00
|
|
|
|
|
|
|
if not suppress_statsd:
|
2020-06-10 06:41:04 +02:00
|
|
|
statsd.timing(f"{statsd_path}.remote_cache.time", timedelta_ms(remote_cache_time_delta))
|
|
|
|
statsd.incr(f"{statsd_path}.remote_cache.querycount", remote_cache_count_delta)
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2013-11-18 19:34:37 +01:00
|
|
|
startup_output = ""
|
|
|
|
if 'startup_time_delta' in log_data and log_data["startup_time_delta"] > 0.005:
|
2020-06-10 06:41:04 +02:00
|
|
|
startup_output = " (+start: {})".format(format_timedelta(log_data["startup_time_delta"]))
|
2013-11-18 19:34:37 +01:00
|
|
|
|
2020-06-26 23:06:05 +02:00
|
|
|
markdown_output = ""
|
|
|
|
if 'markdown_time_start' in log_data:
|
|
|
|
markdown_time_delta = get_markdown_time() - log_data['markdown_time_start']
|
|
|
|
markdown_count_delta = get_markdown_requests() - log_data['markdown_requests_start']
|
|
|
|
if 'markdown_requests_stopped' in log_data:
|
2013-11-08 21:40:44 +01:00
|
|
|
# (now - restarted) + (stopped - start) = (now - start) + (stopped - restarted)
|
2020-06-26 23:06:05 +02:00
|
|
|
markdown_time_delta += (log_data['markdown_time_stopped'] -
|
|
|
|
log_data['markdown_time_restarted'])
|
|
|
|
markdown_count_delta += (log_data['markdown_requests_stopped'] -
|
|
|
|
log_data['markdown_requests_restarted'])
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2020-06-26 23:06:05 +02:00
|
|
|
if (markdown_time_delta > 0.005):
|
|
|
|
markdown_output = f" (md: {format_timedelta(markdown_time_delta)}/{markdown_count_delta})"
|
2013-11-08 21:40:44 +01:00
|
|
|
|
|
|
|
if not suppress_statsd:
|
2020-06-26 23:06:05 +02:00
|
|
|
statsd.timing(f"{statsd_path}.markdown.time", timedelta_ms(markdown_time_delta))
|
|
|
|
statsd.incr(f"{statsd_path}.markdown.count", markdown_count_delta)
|
2013-11-08 21:40:44 +01:00
|
|
|
|
|
|
|
# Get the amount of time spent doing database queries
|
|
|
|
db_time_output = ""
|
2014-01-07 22:20:29 +01:00
|
|
|
queries = connection.connection.queries if connection.connection is not None else []
|
|
|
|
if len(queries) > 0:
|
|
|
|
query_time = sum(float(query.get('time', 0)) for query in queries)
|
2020-06-10 06:41:04 +02:00
|
|
|
db_time_output = f" (db: {format_timedelta(query_time)}/{len(queries)}q)"
|
2013-11-08 21:40:44 +01:00
|
|
|
|
|
|
|
if not suppress_statsd:
|
|
|
|
# Log ms, db ms, and num queries to statsd
|
2020-06-10 06:41:04 +02:00
|
|
|
statsd.timing(f"{statsd_path}.dbtime", timedelta_ms(query_time))
|
|
|
|
statsd.incr(f"{statsd_path}.dbq", len(queries))
|
|
|
|
statsd.timing(f"{statsd_path}.total", timedelta_ms(time_delta))
|
2013-11-08 21:40:44 +01:00
|
|
|
|
|
|
|
if 'extra' in log_data:
|
2020-06-10 06:41:04 +02:00
|
|
|
extra_request_data = " {}".format(log_data['extra'])
|
2013-11-08 21:40:44 +01:00
|
|
|
else:
|
|
|
|
extra_request_data = ""
|
2020-06-10 06:41:04 +02:00
|
|
|
logger_client = f"({requestor_for_logs} via {client_name})"
|
2020-06-26 23:06:05 +02:00
|
|
|
logger_timing = f'{format_timedelta(time_delta):>5}{optional_orig_delta}{remote_cache_output}{markdown_output}{db_time_output}{startup_output} {path}'
|
2020-06-14 02:57:50 +02:00
|
|
|
logger_line = f'{remote_ip:<15} {method:<7} {status_code:3} {logger_timing}{extra_request_data} {logger_client}'
|
2015-12-14 06:54:38 +01:00
|
|
|
if (status_code in [200, 304] and method == "GET" and path.startswith("/static")):
|
|
|
|
logger.debug(logger_line)
|
|
|
|
else:
|
|
|
|
logger.info(logger_line)
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2013-12-26 15:01:46 +01:00
|
|
|
if (is_slow_query(time_delta, path)):
|
2020-05-08 16:37:58 +02:00
|
|
|
slow_query_logger.info(logger_line)
|
2013-11-08 21:40:44 +01:00
|
|
|
|
2013-11-18 18:55:19 +01:00
|
|
|
if settings.PROFILE_ALL_REQUESTS:
|
|
|
|
log_data["prof"].disable()
|
2020-06-10 06:41:04 +02:00
|
|
|
profile_path = "/tmp/profile.data.{}.{}".format(path.split("/")[-1], int(time_delta * 1000))
|
2013-11-18 18:55:19 +01:00
|
|
|
log_data["prof"].dump_stats(profile_path)
|
|
|
|
|
2013-11-08 21:40:44 +01:00
|
|
|
# Log some additional data whenever we return certain 40x errors
|
|
|
|
if 400 <= status_code < 500 and status_code not in [401, 404, 405]:
|
2017-02-11 05:26:24 +01:00
|
|
|
assert error_content_iter is not None
|
2016-07-10 00:15:36 +02:00
|
|
|
error_content_list = list(error_content_iter)
|
2019-07-25 23:16:41 +02:00
|
|
|
if not error_content_list:
|
2020-04-09 21:51:58 +02:00
|
|
|
error_data = ''
|
2018-05-11 01:39:17 +02:00
|
|
|
elif isinstance(error_content_list[0], str):
|
2020-04-09 21:51:58 +02:00
|
|
|
error_data = ''.join(error_content_list)
|
2017-11-09 09:03:33 +01:00
|
|
|
elif isinstance(error_content_list[0], bytes):
|
2016-07-10 00:15:36 +02:00
|
|
|
error_data = repr(b''.join(error_content_list))
|
2019-07-25 23:16:41 +02:00
|
|
|
if len(error_data) > 200:
|
2020-04-09 21:51:58 +02:00
|
|
|
error_data = "[content more than 200 characters]"
|
2020-05-02 08:44:14 +02:00
|
|
|
logger.info('status=%3d, data=%s, uid=%s', status_code, error_data, requestor_for_logs)
|
2013-04-23 19:36:50 +02:00
|
|
|
|
2017-05-18 11:56:03 +02:00
|
|
|
class LogRequests(MiddlewareMixin):
|
2013-11-18 19:34:37 +01:00
|
|
|
# We primarily are doing logging using the process_view hook, but
|
|
|
|
# for some views, process_view isn't run, so we call the start
|
|
|
|
# method here too
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_request(self, request: HttpRequest) -> None:
|
2017-10-04 01:29:53 +02:00
|
|
|
maybe_tracemalloc_listen()
|
tornado: Rewrite Django integration to duplicate less code.
Since essentially the first use of Tornado in Zulip, we've been
maintaining our Tornado+Django system, AsyncDjangoHandler, with
several hundred lines of Django code copied into it.
The goal for that code was simple: We wanted a way to use our Django
middleware (for code sharing reasons) inside a Tornado process (since
we wanted to use Tornado for our async events system).
As part of the Django 2.2.x upgrade, I looked at upgrading this
implementation to be based off modern Django, and it's definitely
possible to do that:
* Continue forking load_middleware to save response middleware.
* Continue manually running the Django response middleware.
* Continue working out a hack involving copying all of _get_response
to change a couple lines allowing us our Tornado code to not
actually return the Django HttpResponse so we can long-poll. The
previous hack of returning None stopped being viable with the Django 2.2
MiddlewareMixin.__call__ implementation.
But I decided to take this opportunity to look at trying to avoid
copying material Django code, and there is a way to do it:
* Replace RespondAsynchronously with a response.asynchronous attribute
on the HttpResponse; this allows Django to run its normal plumbing
happily in a way that should be stable over time, and then we
proceed to discard the response inside the Tornado `get()` method to
implement long-polling. (Better yet might be raising an
exception?). This lets us eliminate maintaining a patched copy of
_get_response.
* Removing the @asynchronous decorator, which didn't add anything now
that we only have one API endpoint backend (with two frontend call
points) that could call into this. Combined with the last bullet,
this lets us remove a significant hack from our
never_cache_responses function.
* Calling the normal Django `get_response` method from zulip_finish
after creating a duplicate request to process, rather than writing
totally custom code to do that. This lets us eliminate maintaining
a patched copy of Django's load_middleware.
* Adding detailed comments explaining how this is supposed to work,
what problems we encounter, and how we solve various problems, which
is critical to being able to modify this code in the future.
A key advantage of these changes is that the exact same code should
work on Django 1.11, Django 2.2, and Django 3.x, because we're no
longer copying large blocks of core Django code and thus should be
much less vulnerable to refactors.
There may be a modest performance downside, in that we now run both
request and response middleware twice when longpolling (once for the
request we discard). We may be able to avoid the expensive part of
it, Zulip's own request/response middleware, with a bit of additional
custom code to save work for requests where we're planning to discard
the response. Profiling will be important to understanding what's
worth doing here.
2020-02-06 22:09:10 +01:00
|
|
|
|
|
|
|
if hasattr(request, "_log_data"):
|
|
|
|
# Sanity check to ensure this is being called from the
|
|
|
|
# Tornado code path that returns responses asynchronously.
|
|
|
|
assert getattr(request, "saved_response", False)
|
|
|
|
|
|
|
|
# Avoid re-initializing request._log_data if it's already there.
|
|
|
|
return
|
|
|
|
|
2013-11-08 20:18:02 +01:00
|
|
|
request._log_data = dict()
|
2013-11-08 21:40:44 +01:00
|
|
|
record_request_start_data(request._log_data)
|
2012-11-14 21:00:26 +01:00
|
|
|
|
2018-03-14 23:16:27 +01:00
|
|
|
def process_view(self, request: HttpRequest, view_func: ViewFuncT,
|
2017-11-27 07:33:05 +01:00
|
|
|
args: List[str], kwargs: Dict[str, Any]) -> None:
|
tornado: Rewrite Django integration to duplicate less code.
Since essentially the first use of Tornado in Zulip, we've been
maintaining our Tornado+Django system, AsyncDjangoHandler, with
several hundred lines of Django code copied into it.
The goal for that code was simple: We wanted a way to use our Django
middleware (for code sharing reasons) inside a Tornado process (since
we wanted to use Tornado for our async events system).
As part of the Django 2.2.x upgrade, I looked at upgrading this
implementation to be based off modern Django, and it's definitely
possible to do that:
* Continue forking load_middleware to save response middleware.
* Continue manually running the Django response middleware.
* Continue working out a hack involving copying all of _get_response
to change a couple lines allowing us our Tornado code to not
actually return the Django HttpResponse so we can long-poll. The
previous hack of returning None stopped being viable with the Django 2.2
MiddlewareMixin.__call__ implementation.
But I decided to take this opportunity to look at trying to avoid
copying material Django code, and there is a way to do it:
* Replace RespondAsynchronously with a response.asynchronous attribute
on the HttpResponse; this allows Django to run its normal plumbing
happily in a way that should be stable over time, and then we
proceed to discard the response inside the Tornado `get()` method to
implement long-polling. (Better yet might be raising an
exception?). This lets us eliminate maintaining a patched copy of
_get_response.
* Removing the @asynchronous decorator, which didn't add anything now
that we only have one API endpoint backend (with two frontend call
points) that could call into this. Combined with the last bullet,
this lets us remove a significant hack from our
never_cache_responses function.
* Calling the normal Django `get_response` method from zulip_finish
after creating a duplicate request to process, rather than writing
totally custom code to do that. This lets us eliminate maintaining
a patched copy of Django's load_middleware.
* Adding detailed comments explaining how this is supposed to work,
what problems we encounter, and how we solve various problems, which
is critical to being able to modify this code in the future.
A key advantage of these changes is that the exact same code should
work on Django 1.11, Django 2.2, and Django 3.x, because we're no
longer copying large blocks of core Django code and thus should be
much less vulnerable to refactors.
There may be a modest performance downside, in that we now run both
request and response middleware twice when longpolling (once for the
request we discard). We may be able to avoid the expensive part of
it, Zulip's own request/response middleware, with a bit of additional
custom code to save work for requests where we're planning to discard
the response. Profiling will be important to understanding what's
worth doing here.
2020-02-06 22:09:10 +01:00
|
|
|
if hasattr(request, "saved_response"):
|
|
|
|
# The below logging adjustments are unnecessary (because
|
|
|
|
# we've already imported everything) and incorrect
|
|
|
|
# (because they'll overwrite data from pre-long-poll
|
|
|
|
# request processing) when returning a saved response.
|
|
|
|
return
|
|
|
|
|
2013-11-18 19:34:37 +01:00
|
|
|
# process_request was already run; we save the initialization
|
|
|
|
# time (i.e. the time between receiving the request and
|
|
|
|
# figuring out which view function to call, which is primarily
|
|
|
|
# importing modules on the first start)
|
|
|
|
request._log_data["startup_time_delta"] = time.time() - request._log_data["time_started"]
|
|
|
|
# And then completely reset our tracking to only cover work
|
|
|
|
# done as part of this request
|
|
|
|
record_request_start_data(request._log_data)
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_response(self, request: HttpRequest,
|
|
|
|
response: StreamingHttpResponse) -> StreamingHttpResponse:
|
tornado: Rewrite Django integration to duplicate less code.
Since essentially the first use of Tornado in Zulip, we've been
maintaining our Tornado+Django system, AsyncDjangoHandler, with
several hundred lines of Django code copied into it.
The goal for that code was simple: We wanted a way to use our Django
middleware (for code sharing reasons) inside a Tornado process (since
we wanted to use Tornado for our async events system).
As part of the Django 2.2.x upgrade, I looked at upgrading this
implementation to be based off modern Django, and it's definitely
possible to do that:
* Continue forking load_middleware to save response middleware.
* Continue manually running the Django response middleware.
* Continue working out a hack involving copying all of _get_response
to change a couple lines allowing us our Tornado code to not
actually return the Django HttpResponse so we can long-poll. The
previous hack of returning None stopped being viable with the Django 2.2
MiddlewareMixin.__call__ implementation.
But I decided to take this opportunity to look at trying to avoid
copying material Django code, and there is a way to do it:
* Replace RespondAsynchronously with a response.asynchronous attribute
on the HttpResponse; this allows Django to run its normal plumbing
happily in a way that should be stable over time, and then we
proceed to discard the response inside the Tornado `get()` method to
implement long-polling. (Better yet might be raising an
exception?). This lets us eliminate maintaining a patched copy of
_get_response.
* Removing the @asynchronous decorator, which didn't add anything now
that we only have one API endpoint backend (with two frontend call
points) that could call into this. Combined with the last bullet,
this lets us remove a significant hack from our
never_cache_responses function.
* Calling the normal Django `get_response` method from zulip_finish
after creating a duplicate request to process, rather than writing
totally custom code to do that. This lets us eliminate maintaining
a patched copy of Django's load_middleware.
* Adding detailed comments explaining how this is supposed to work,
what problems we encounter, and how we solve various problems, which
is critical to being able to modify this code in the future.
A key advantage of these changes is that the exact same code should
work on Django 1.11, Django 2.2, and Django 3.x, because we're no
longer copying large blocks of core Django code and thus should be
much less vulnerable to refactors.
There may be a modest performance downside, in that we now run both
request and response middleware twice when longpolling (once for the
request we discard). We may be able to avoid the expensive part of
it, Zulip's own request/response middleware, with a bit of additional
custom code to save work for requests where we're planning to discard
the response. Profiling will be important to understanding what's
worth doing here.
2020-02-06 22:09:10 +01:00
|
|
|
if getattr(response, "asynchronous", False):
|
|
|
|
# This special Tornado "asynchronous" response is
|
|
|
|
# discarded after going through this code path as Tornado
|
|
|
|
# intends to block, so we stop here to avoid unnecessary work.
|
|
|
|
return response
|
|
|
|
|
2020-05-08 20:38:58 +02:00
|
|
|
remote_ip = request.META['REMOTE_ADDR']
|
2012-10-16 23:52:10 +02:00
|
|
|
|
2020-03-09 11:39:20 +01:00
|
|
|
# Get the requestor's identifier and client, if available.
|
2013-02-11 23:15:34 +01:00
|
|
|
try:
|
2020-03-09 11:39:20 +01:00
|
|
|
requestor_for_logs = request._requestor_for_logs
|
2013-02-11 23:15:34 +01:00
|
|
|
except Exception:
|
2020-03-09 12:21:46 +01:00
|
|
|
if hasattr(request, 'user') and hasattr(request.user, 'format_requestor_for_logs'):
|
|
|
|
requestor_for_logs = request.user.format_requestor_for_logs()
|
|
|
|
else:
|
2020-06-10 06:41:04 +02:00
|
|
|
requestor_for_logs = "unauth@{}".format(get_subdomain(request) or 'root')
|
2013-03-15 18:57:58 +01:00
|
|
|
try:
|
2013-03-26 19:40:28 +01:00
|
|
|
client = request.client.name
|
2013-03-15 18:57:58 +01:00
|
|
|
except Exception:
|
|
|
|
client = "?"
|
2013-02-11 23:15:34 +01:00
|
|
|
|
2015-08-19 22:20:27 +02:00
|
|
|
if response.streaming:
|
|
|
|
content_iter = response.streaming_content
|
2015-08-22 23:18:31 +02:00
|
|
|
content = None
|
2015-08-19 22:20:27 +02:00
|
|
|
else:
|
2015-08-22 23:18:31 +02:00
|
|
|
content = response.content
|
2015-08-22 23:38:01 +02:00
|
|
|
content_iter = None
|
2015-08-19 22:20:27 +02:00
|
|
|
|
2013-11-08 21:40:44 +01:00
|
|
|
write_log_line(request._log_data, request.path, request.method,
|
2020-03-09 11:39:20 +01:00
|
|
|
remote_ip, requestor_for_logs, client, status_code=response.status_code,
|
2015-08-22 23:18:31 +02:00
|
|
|
error_content=content, error_content_iter=content_iter)
|
2012-10-16 23:52:10 +02:00
|
|
|
return response
|
2012-12-19 20:19:46 +01:00
|
|
|
|
2017-05-18 11:56:03 +02:00
|
|
|
class JsonErrorHandler(MiddlewareMixin):
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_exception(self, request: HttpRequest, exception: Exception) -> Optional[HttpResponse]:
|
2017-07-20 00:19:42 +02:00
|
|
|
if isinstance(exception, JsonableError):
|
2017-07-21 02:19:52 +02:00
|
|
|
return json_response_from_error(exception)
|
2013-12-17 22:50:49 +01:00
|
|
|
if request.error_format == "JSON":
|
2018-03-01 23:55:37 +01:00
|
|
|
logging.error(traceback.format_exc(), extra=dict(request=request))
|
2016-05-25 15:02:02 +02:00
|
|
|
return json_error(_("Internal server error"), status=500)
|
2012-12-19 20:19:46 +01:00
|
|
|
return None
|
2013-02-12 17:26:12 +01:00
|
|
|
|
2017-05-18 11:56:03 +02:00
|
|
|
class TagRequests(MiddlewareMixin):
|
2018-03-14 23:16:27 +01:00
|
|
|
def process_view(self, request: HttpRequest, view_func: ViewFuncT,
|
2017-11-27 07:33:05 +01:00
|
|
|
args: List[str], kwargs: Dict[str, Any]) -> None:
|
2013-12-17 22:18:13 +01:00
|
|
|
self.process_request(request)
|
2016-11-29 07:22:02 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_request(self, request: HttpRequest) -> None:
|
2013-12-17 22:18:13 +01:00
|
|
|
if request.path.startswith("/api/") or request.path.startswith("/json/"):
|
|
|
|
request.error_format = "JSON"
|
|
|
|
else:
|
|
|
|
request.error_format = "HTML"
|
|
|
|
|
2017-07-25 03:30:13 +02:00
|
|
|
class CsrfFailureError(JsonableError):
|
|
|
|
http_status_code = 403
|
|
|
|
code = ErrorCode.CSRF_FAILED
|
|
|
|
data_fields = ['reason']
|
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def __init__(self, reason: str) -> None:
|
python: Convert assignment type annotations to Python 3.6 style.
This commit was split by tabbott; this piece covers the vast majority
of files in Zulip, but excludes scripts/, tools/, and puppet/ to help
ensure we at least show the right error messages for Xenial systems.
We can likely further refine the remaining pieces with some testing.
Generated by com2ann, with whitespace fixes and various manual fixes
for runtime issues:
- invoiced_through: Optional[LicenseLedger] = models.ForeignKey(
+ invoiced_through: Optional["LicenseLedger"] = models.ForeignKey(
-_apns_client: Optional[APNsClient] = None
+_apns_client: Optional["APNsClient"] = None
- notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- signup_notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ signup_notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- author: Optional[UserProfile] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
+ author: Optional["UserProfile"] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
- bot_owner: Optional[UserProfile] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
+ bot_owner: Optional["UserProfile"] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
- default_sending_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
- default_events_register_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_sending_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_events_register_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
-descriptors_by_handler_id: Dict[int, ClientDescriptor] = {}
+descriptors_by_handler_id: Dict[int, "ClientDescriptor"] = {}
-worker_classes: Dict[str, Type[QueueProcessingWorker]] = {}
-queues: Dict[str, Dict[str, Type[QueueProcessingWorker]]] = {}
+worker_classes: Dict[str, Type["QueueProcessingWorker"]] = {}
+queues: Dict[str, Dict[str, Type["QueueProcessingWorker"]]] = {}
-AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional[LDAPSearch] = None
+AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-22 01:09:50 +02:00
|
|
|
self.reason: str = reason
|
2017-07-25 03:30:13 +02:00
|
|
|
|
|
|
|
@staticmethod
|
2018-05-11 01:39:17 +02:00
|
|
|
def msg_format() -> str:
|
2017-07-25 03:30:13 +02:00
|
|
|
return _("CSRF Error: {reason}")
|
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def csrf_failure(request: HttpRequest, reason: str="") -> HttpResponse:
|
2013-12-17 22:18:13 +01:00
|
|
|
if request.error_format == "JSON":
|
2017-07-25 03:30:13 +02:00
|
|
|
return json_response_from_error(CsrfFailureError(reason))
|
2013-12-17 22:18:13 +01:00
|
|
|
else:
|
|
|
|
return html_csrf_failure(request, reason)
|
|
|
|
|
2017-05-18 11:56:03 +02:00
|
|
|
class RateLimitMiddleware(MiddlewareMixin):
|
2019-12-28 20:23:18 +01:00
|
|
|
def set_response_headers(self, response: HttpResponse,
|
|
|
|
rate_limit_results: List[RateLimitResult]) -> None:
|
|
|
|
# The limit on the action that was requested is the minimum of the limits that get applied:
|
2020-03-04 14:05:25 +01:00
|
|
|
limit = min([result.entity.max_api_calls() for result in rate_limit_results])
|
2019-12-28 20:23:18 +01:00
|
|
|
response['X-RateLimit-Limit'] = str(limit)
|
|
|
|
# Same principle applies to remaining api calls:
|
2020-04-01 13:50:27 +02:00
|
|
|
remaining_api_calls = min([result.remaining for result in rate_limit_results])
|
|
|
|
response['X-RateLimit-Remaining'] = str(remaining_api_calls)
|
2019-12-28 20:23:18 +01:00
|
|
|
|
|
|
|
# The full reset time is the maximum of the reset times for the limits that get applied:
|
|
|
|
reset_time = time.time() + max([result.secs_to_freedom for result in rate_limit_results])
|
|
|
|
response['X-RateLimit-Reset'] = str(int(reset_time))
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
|
2013-05-29 23:58:07 +02:00
|
|
|
if not settings.RATE_LIMITING:
|
|
|
|
return response
|
|
|
|
|
|
|
|
# Add X-RateLimit-*** headers
|
2020-04-01 13:31:20 +02:00
|
|
|
if hasattr(request, '_ratelimits_applied'):
|
|
|
|
self.set_response_headers(response, request._ratelimits_applied)
|
2019-12-28 20:23:18 +01:00
|
|
|
|
2013-05-29 23:58:07 +02:00
|
|
|
return response
|
|
|
|
|
2019-07-26 23:57:18 +02:00
|
|
|
def process_exception(self, request: HttpRequest,
|
2019-08-01 18:48:41 +02:00
|
|
|
exception: Exception) -> Optional[HttpResponse]:
|
2015-11-01 17:10:16 +01:00
|
|
|
if isinstance(exception, RateLimited):
|
2020-04-01 13:13:06 +02:00
|
|
|
secs_to_freedom = float(str(exception)) # secs_to_freedom is passed to RateLimited when raising
|
2017-05-22 20:12:59 +02:00
|
|
|
resp = json_error(
|
|
|
|
_("API usage exceeded rate limit"),
|
2020-04-01 13:13:06 +02:00
|
|
|
data={'retry-after': secs_to_freedom},
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
status=429,
|
2017-05-22 20:12:59 +02:00
|
|
|
)
|
2020-04-01 13:13:06 +02:00
|
|
|
resp['Retry-After'] = secs_to_freedom
|
2013-05-29 23:58:07 +02:00
|
|
|
return resp
|
2017-08-02 17:21:46 +02:00
|
|
|
return None
|
2013-11-08 21:13:34 +01:00
|
|
|
|
2017-05-18 11:56:03 +02:00
|
|
|
class FlushDisplayRecipientCache(MiddlewareMixin):
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
|
2013-12-18 23:00:14 +01:00
|
|
|
# We flush the per-request caches after every request, so they
|
|
|
|
# are not shared at all between requests.
|
|
|
|
flush_per_request_caches()
|
2013-11-08 21:13:34 +01:00
|
|
|
return response
|
2015-01-16 05:59:20 +01:00
|
|
|
|
2020-04-06 23:32:50 +02:00
|
|
|
class HostDomainMiddleware(MiddlewareMixin):
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
|
tornado: Rewrite Django integration to duplicate less code.
Since essentially the first use of Tornado in Zulip, we've been
maintaining our Tornado+Django system, AsyncDjangoHandler, with
several hundred lines of Django code copied into it.
The goal for that code was simple: We wanted a way to use our Django
middleware (for code sharing reasons) inside a Tornado process (since
we wanted to use Tornado for our async events system).
As part of the Django 2.2.x upgrade, I looked at upgrading this
implementation to be based off modern Django, and it's definitely
possible to do that:
* Continue forking load_middleware to save response middleware.
* Continue manually running the Django response middleware.
* Continue working out a hack involving copying all of _get_response
to change a couple lines allowing us our Tornado code to not
actually return the Django HttpResponse so we can long-poll. The
previous hack of returning None stopped being viable with the Django 2.2
MiddlewareMixin.__call__ implementation.
But I decided to take this opportunity to look at trying to avoid
copying material Django code, and there is a way to do it:
* Replace RespondAsynchronously with a response.asynchronous attribute
on the HttpResponse; this allows Django to run its normal plumbing
happily in a way that should be stable over time, and then we
proceed to discard the response inside the Tornado `get()` method to
implement long-polling. (Better yet might be raising an
exception?). This lets us eliminate maintaining a patched copy of
_get_response.
* Removing the @asynchronous decorator, which didn't add anything now
that we only have one API endpoint backend (with two frontend call
points) that could call into this. Combined with the last bullet,
this lets us remove a significant hack from our
never_cache_responses function.
* Calling the normal Django `get_response` method from zulip_finish
after creating a duplicate request to process, rather than writing
totally custom code to do that. This lets us eliminate maintaining
a patched copy of Django's load_middleware.
* Adding detailed comments explaining how this is supposed to work,
what problems we encounter, and how we solve various problems, which
is critical to being able to modify this code in the future.
A key advantage of these changes is that the exact same code should
work on Django 1.11, Django 2.2, and Django 3.x, because we're no
longer copying large blocks of core Django code and thus should be
much less vulnerable to refactors.
There may be a modest performance downside, in that we now run both
request and response middleware twice when longpolling (once for the
request we discard). We may be able to avoid the expensive part of
it, Zulip's own request/response middleware, with a bit of additional
custom code to save work for requests where we're planning to discard
the response. Profiling will be important to understanding what's
worth doing here.
2020-02-06 22:09:10 +01:00
|
|
|
if getattr(response, "asynchronous", False):
|
|
|
|
# This special Tornado "asynchronous" response is
|
|
|
|
# discarded after going through this code path as Tornado
|
|
|
|
# intends to block, so we stop here to avoid unnecessary work.
|
|
|
|
return response
|
|
|
|
|
2017-01-30 05:17:48 +01:00
|
|
|
try:
|
|
|
|
request.get_host()
|
|
|
|
except DisallowedHost:
|
|
|
|
# If we get a DisallowedHost exception trying to access
|
|
|
|
# the host, (1) the request is failed anyway and so the
|
|
|
|
# below code will do nothing, and (2) the below will
|
|
|
|
# trigger a recursive exception, breaking things, so we
|
|
|
|
# just return here.
|
|
|
|
return response
|
|
|
|
|
2017-10-02 08:32:09 +02:00
|
|
|
if (not request.path.startswith("/static/") and not request.path.startswith("/api/") and
|
|
|
|
not request.path.startswith("/json/")):
|
|
|
|
subdomain = get_subdomain(request)
|
2017-10-20 02:56:49 +02:00
|
|
|
if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
|
2019-05-04 04:47:44 +02:00
|
|
|
try:
|
|
|
|
get_realm(subdomain)
|
|
|
|
except Realm.DoesNotExist:
|
2019-03-12 01:56:52 +01:00
|
|
|
return render(request, "zerver/invalid_realm.html", status=404)
|
2015-01-16 05:59:20 +01:00
|
|
|
return response
|
2017-01-30 23:19:38 +01:00
|
|
|
|
2017-05-18 11:56:03 +02:00
|
|
|
class SetRemoteAddrFromForwardedFor(MiddlewareMixin):
|
2017-01-30 23:19:38 +01:00
|
|
|
"""
|
|
|
|
Middleware that sets REMOTE_ADDR based on the HTTP_X_FORWARDED_FOR.
|
|
|
|
|
|
|
|
This middleware replicates Django's former SetRemoteAddrFromForwardedFor middleware.
|
|
|
|
Because Zulip sits behind a NGINX reverse proxy, if the HTTP_X_FORWARDED_FOR
|
|
|
|
is set in the request, then it has properly been set by NGINX.
|
|
|
|
Therefore HTTP_X_FORWARDED_FOR's value is trusted.
|
|
|
|
"""
|
2020-04-22 01:45:30 +02:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_request(self, request: HttpRequest) -> None:
|
2017-01-30 23:19:38 +01:00
|
|
|
try:
|
|
|
|
real_ip = request.META['HTTP_X_FORWARDED_FOR']
|
|
|
|
except KeyError:
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
# HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
|
|
|
|
# For NGINX reverse proxy servers, the client's IP will be the first one.
|
|
|
|
real_ip = real_ip.split(",")[0].strip()
|
|
|
|
request.META['REMOTE_ADDR'] = real_ip
|
2018-12-14 23:28:00 +01:00
|
|
|
|
2019-02-28 02:30:16 +01:00
|
|
|
def alter_content(request: HttpRequest, content: bytes) -> bytes:
|
|
|
|
first_paragraph_text = get_content_description(content, request)
|
|
|
|
return content.replace(request.placeholder_open_graph_description.encode("utf-8"),
|
2019-04-24 03:37:34 +02:00
|
|
|
first_paragraph_text.encode("utf-8"))
|
2018-12-14 23:28:00 +01:00
|
|
|
|
2019-02-28 02:30:16 +01:00
|
|
|
class FinalizeOpenGraphDescription(MiddlewareMixin):
|
|
|
|
def process_response(self, request: HttpRequest,
|
|
|
|
response: StreamingHttpResponse) -> StreamingHttpResponse:
|
2018-12-14 23:28:00 +01:00
|
|
|
|
|
|
|
if getattr(request, "placeholder_open_graph_description", None) is not None:
|
|
|
|
assert not response.streaming
|
2019-02-28 02:30:16 +01:00
|
|
|
response.content = alter_content(request, response.content)
|
2018-12-14 23:28:00 +01:00
|
|
|
return response
|
2020-02-14 20:29:05 +01:00
|
|
|
|
|
|
|
class ZulipCommonMiddleware(CommonMiddleware):
|
|
|
|
"""
|
|
|
|
Patched version of CommonMiddleware to disable the APPEND_SLASH
|
|
|
|
redirect behavior inside Tornado.
|
|
|
|
|
|
|
|
While this has some correctness benefit in encouraging clients
|
|
|
|
to implement the API correctly, this also saves about 600us in
|
|
|
|
the runtime of every GET /events query, as the APPEND_SLASH
|
|
|
|
route resolution logic is surprisingly expensive.
|
|
|
|
|
|
|
|
TODO: We should probably extend this behavior to apply to all of
|
|
|
|
our API routes. The APPEND_SLASH behavior is really only useful
|
|
|
|
for non-API endpoints things like /login. But doing that
|
|
|
|
transition will require more careful testing.
|
|
|
|
"""
|
2020-04-22 01:45:30 +02:00
|
|
|
|
2020-02-14 20:29:05 +01:00
|
|
|
def should_redirect_with_slash(self, request: HttpRequest) -> bool:
|
|
|
|
if settings.RUNNING_INSIDE_TORNADO:
|
|
|
|
return False
|
|
|
|
return super().should_redirect_with_slash(request)
|