2016-04-22 11:09:55 -04:00
|
|
|
#
|
2023-11-21 15:29:58 -05:00
|
|
|
# This file is licensed under the Affero General Public License (AGPL) version 3.
|
|
|
|
#
|
2024-01-23 06:26:48 -05:00
|
|
|
# Copyright 2016 OpenMarket Ltd
|
2023-11-21 15:29:58 -05:00
|
|
|
# Copyright (C) 2023 New Vector, Ltd
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Affero General Public License as
|
|
|
|
# published by the Free Software Foundation, either version 3 of the
|
|
|
|
# License, or (at your option) any later version.
|
|
|
|
#
|
|
|
|
# See the GNU Affero General Public License for more details:
|
|
|
|
# <https://www.gnu.org/licenses/agpl-3.0.html>.
|
|
|
|
#
|
|
|
|
# Originally licensed under the Apache License, Version 2.0:
|
|
|
|
# <http://www.apache.org/licenses/LICENSE-2.0>.
|
|
|
|
#
|
|
|
|
# [This file includes modifications made by New Vector Limited]
|
2016-04-22 11:09:55 -04:00
|
|
|
#
|
|
|
|
#
|
|
|
|
import contextlib
|
|
|
|
import logging
|
|
|
|
import time
|
2021-12-20 12:45:03 -05:00
|
|
|
from typing import TYPE_CHECKING, Any, Generator, Optional, Tuple, Union
|
2016-04-22 11:09:55 -04:00
|
|
|
|
2021-02-24 13:11:33 -05:00
|
|
|
import attr
|
|
|
|
from zope.interface import implementer
|
|
|
|
|
2023-04-03 05:27:51 -04:00
|
|
|
from twisted.internet.address import UNIXAddress
|
2022-05-10 09:06:08 -04:00
|
|
|
from twisted.internet.defer import Deferred
|
2023-07-18 04:49:21 -04:00
|
|
|
from twisted.internet.interfaces import IAddress
|
2020-05-14 12:07:24 -04:00
|
|
|
from twisted.python.failure import Failure
|
2021-09-24 06:01:25 -04:00
|
|
|
from twisted.web.http import HTTPChannel
|
2021-09-21 12:41:27 -04:00
|
|
|
from twisted.web.resource import IResource, Resource
|
2023-07-18 04:49:21 -04:00
|
|
|
from twisted.web.server import Request
|
2018-05-09 18:05:14 -04:00
|
|
|
|
2020-06-16 07:44:07 -04:00
|
|
|
from synapse.config.server import ListenerConfig
|
2021-01-12 07:34:16 -05:00
|
|
|
from synapse.http import get_request_user_agent, redact_uri
|
2023-07-18 04:49:21 -04:00
|
|
|
from synapse.http.proxy import ProxySite
|
2018-08-15 03:49:59 -04:00
|
|
|
from synapse.http.request_metrics import RequestMetrics, requests_counter
|
2021-04-08 08:01:14 -04:00
|
|
|
from synapse.logging.context import (
|
|
|
|
ContextRequest,
|
|
|
|
LoggingContext,
|
|
|
|
PreserveLoggingContext,
|
|
|
|
)
|
2023-07-18 04:49:21 -04:00
|
|
|
from synapse.types import ISynapseReactor, Requester
|
2018-05-09 18:05:14 -04:00
|
|
|
|
2021-12-20 12:45:03 -05:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
import opentracing
|
|
|
|
|
2023-07-18 04:49:21 -04:00
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
|
|
|
|
2018-05-09 18:05:14 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2018-05-09 18:00:11 -04:00
|
|
|
_next_request_seq = 0
|
|
|
|
|
2016-04-22 11:09:55 -04:00
|
|
|
|
|
|
|
class SynapseRequest(Request):
|
2018-05-09 18:05:14 -04:00
|
|
|
"""Class which encapsulates an HTTP request to synapse.
|
|
|
|
|
|
|
|
All of the requests processed in synapse are of this type.
|
|
|
|
|
|
|
|
It extends twisted's twisted.web.server.Request, and adds:
|
|
|
|
* Unique request ID
|
2018-08-15 03:49:59 -04:00
|
|
|
* A log context associated with the request
|
2018-05-09 18:05:14 -04:00
|
|
|
* Redaction of access_token query-params in __repr__
|
|
|
|
* Logging at start and end
|
|
|
|
* Metrics to record CPU, wallclock and DB time by endpoint.
|
2021-04-23 14:20:44 -04:00
|
|
|
* A limit to the size of request which will be accepted
|
2018-05-09 18:05:14 -04:00
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
It also provides a method `processing`, which returns a context manager. If this
|
|
|
|
method is called, the request won't be logged until the context manager is closed;
|
|
|
|
this is useful for asynchronous request handlers which may go on processing the
|
|
|
|
request even after the client has disconnected.
|
2018-05-09 18:05:14 -04:00
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
Attributes:
|
2020-05-22 05:12:17 -04:00
|
|
|
logcontext: the log context for this request
|
2018-05-09 18:05:14 -04:00
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
|
2021-09-24 06:01:25 -04:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
channel: HTTPChannel,
|
|
|
|
site: "SynapseSite",
|
2021-12-14 07:00:47 -05:00
|
|
|
*args: Any,
|
2021-09-24 06:01:25 -04:00
|
|
|
max_request_body_size: int = 1024,
|
2022-09-15 16:32:25 -04:00
|
|
|
request_id_header: Optional[str] = None,
|
2021-12-14 07:00:47 -05:00
|
|
|
**kw: Any,
|
2021-09-24 06:01:25 -04:00
|
|
|
):
|
|
|
|
super().__init__(channel, *args, **kw)
|
2021-04-23 14:20:44 -04:00
|
|
|
self._max_request_body_size = max_request_body_size
|
2022-09-15 16:32:25 -04:00
|
|
|
self.request_id_header = request_id_header
|
2021-09-24 06:01:25 -04:00
|
|
|
self.synapse_site = site
|
|
|
|
self.reactor = site.reactor
|
2018-08-15 03:49:59 -04:00
|
|
|
self._channel = channel # this is used by the tests
|
2020-05-22 05:12:17 -04:00
|
|
|
self.start_time = 0.0
|
2022-10-18 11:52:25 -04:00
|
|
|
self.experimental_cors_msc3886 = site.experimental_cors_msc3886
|
2016-04-22 11:09:55 -04:00
|
|
|
|
2020-10-29 11:58:44 -04:00
|
|
|
# The requester, if authenticated. For federation requests this is the
|
|
|
|
# server name, for client requests this is the Requester object.
|
2021-07-15 06:02:43 -04:00
|
|
|
self._requester: Optional[Union[Requester, str]] = None
|
2020-10-29 11:58:44 -04:00
|
|
|
|
2021-12-20 12:45:03 -05:00
|
|
|
# An opentracing span for this request. Will be closed when the request is
|
|
|
|
# completely processed.
|
|
|
|
self._opentracing_span: "Optional[opentracing.Span]" = None
|
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
# we can't yet create the logcontext, as we don't know the method.
|
2021-07-15 06:02:43 -04:00
|
|
|
self.logcontext: Optional[LoggingContext] = None
|
2018-08-15 03:49:59 -04:00
|
|
|
|
2022-05-10 15:39:05 -04:00
|
|
|
# The `Deferred` to cancel if the client disconnects early and
|
|
|
|
# `is_render_cancellable` is set. Expected to be set by `Resource.render`.
|
2022-05-10 09:06:08 -04:00
|
|
|
self.render_deferred: Optional["Deferred[None]"] = None
|
2022-05-10 15:39:05 -04:00
|
|
|
# A boolean indicating whether `render_deferred` should be cancelled if the
|
|
|
|
# client disconnects early. Expected to be set by the coroutine started by
|
|
|
|
# `Resource.render`, if rendering is asynchronous.
|
2023-07-18 04:49:21 -04:00
|
|
|
self.is_render_cancellable: bool = False
|
2022-05-10 09:06:08 -04:00
|
|
|
|
2018-05-09 18:00:11 -04:00
|
|
|
global _next_request_seq
|
|
|
|
self.request_seq = _next_request_seq
|
|
|
|
_next_request_seq += 1
|
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
# whether an asynchronous request handler has called processing()
|
|
|
|
self._is_processing = False
|
|
|
|
|
|
|
|
# the time when the asynchronous request handler completed its processing
|
2021-09-21 12:41:27 -04:00
|
|
|
self._processing_finished_time: Optional[float] = None
|
2018-08-15 03:49:59 -04:00
|
|
|
|
|
|
|
# what time we finished sending the response to the client (or the connection
|
|
|
|
# dropped)
|
2021-09-21 12:41:27 -04:00
|
|
|
self.finish_time: Optional[float] = None
|
2018-08-15 03:49:59 -04:00
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def __repr__(self) -> str:
|
2016-04-22 11:09:55 -04:00
|
|
|
# We overwrite this so that we don't log ``access_token``
|
2018-04-30 08:36:39 -04:00
|
|
|
return "<%s at 0x%x method=%r uri=%r clientproto=%r site=%r>" % (
|
2016-04-22 11:09:55 -04:00
|
|
|
self.__class__.__name__,
|
|
|
|
id(self),
|
2018-10-02 06:49:39 -04:00
|
|
|
self.get_method(),
|
2016-04-22 11:09:55 -04:00
|
|
|
self.get_redacted_uri(),
|
2018-09-20 02:28:18 -04:00
|
|
|
self.clientproto.decode("ascii", errors="replace"),
|
2021-09-24 06:01:25 -04:00
|
|
|
self.synapse_site.site_tag,
|
2016-04-22 11:09:55 -04:00
|
|
|
)
|
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def handleContentChunk(self, data: bytes) -> None:
|
2021-04-23 14:20:44 -04:00
|
|
|
# we should have a `content` by now.
|
|
|
|
assert self.content, "handleContentChunk() called before gotLength()"
|
|
|
|
if self.content.tell() + len(data) > self._max_request_body_size:
|
|
|
|
logger.warning(
|
2021-05-28 10:57:53 -04:00
|
|
|
"Aborting connection from %s because the request exceeds maximum size: %s %s",
|
2021-04-23 14:20:44 -04:00
|
|
|
self.client,
|
2021-05-28 10:57:53 -04:00
|
|
|
self.get_method(),
|
|
|
|
self.get_redacted_uri(),
|
2021-04-23 14:20:44 -04:00
|
|
|
)
|
2024-04-11 11:03:45 -04:00
|
|
|
if self.channel:
|
|
|
|
self.channel.forceAbortClient()
|
2021-04-23 14:20:44 -04:00
|
|
|
return
|
|
|
|
super().handleContentChunk(data)
|
|
|
|
|
2021-04-08 08:01:14 -04:00
|
|
|
@property
|
|
|
|
def requester(self) -> Optional[Union[Requester, str]]:
|
|
|
|
return self._requester
|
|
|
|
|
|
|
|
@requester.setter
|
|
|
|
def requester(self, value: Union[Requester, str]) -> None:
|
|
|
|
# Store the requester, and update some properties based on it.
|
|
|
|
|
|
|
|
# This should only be called once.
|
|
|
|
assert self._requester is None
|
|
|
|
|
|
|
|
self._requester = value
|
|
|
|
|
|
|
|
# A logging context should exist by now (and have a ContextRequest).
|
|
|
|
assert self.logcontext is not None
|
|
|
|
assert self.logcontext.request is not None
|
|
|
|
|
|
|
|
(
|
|
|
|
requester,
|
|
|
|
authenticated_entity,
|
|
|
|
) = self.get_authenticated_entity()
|
|
|
|
self.logcontext.request.requester = requester
|
|
|
|
# If there's no authenticated entity, it was the requester.
|
|
|
|
self.logcontext.request.authenticated_entity = authenticated_entity or requester
|
|
|
|
|
2021-12-20 12:45:03 -05:00
|
|
|
def set_opentracing_span(self, span: "opentracing.Span") -> None:
|
|
|
|
"""attach an opentracing span to this request
|
|
|
|
|
|
|
|
Doing so will cause the span to be closed when we finish processing the request
|
|
|
|
"""
|
|
|
|
self._opentracing_span = span
|
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def get_request_id(self) -> str:
|
2022-09-15 16:32:25 -04:00
|
|
|
request_id_value = None
|
|
|
|
if self.request_id_header:
|
|
|
|
request_id_value = self.getHeader(self.request_id_header)
|
|
|
|
|
|
|
|
if request_id_value is None:
|
|
|
|
request_id_value = str(self.request_seq)
|
|
|
|
|
|
|
|
return "%s-%s" % (self.get_method(), request_id_value)
|
2018-05-09 18:00:11 -04:00
|
|
|
|
2021-03-03 15:47:38 -05:00
|
|
|
def get_redacted_uri(self) -> str:
|
|
|
|
"""Gets the redacted URI associated with the request (or placeholder if the URI
|
|
|
|
has not yet been received).
|
|
|
|
|
|
|
|
Note: This is necessary as the placeholder value in twisted is str
|
|
|
|
rather than bytes, so we need to sanitise `self.uri`.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The redacted URI as a string.
|
|
|
|
"""
|
2021-07-15 06:02:43 -04:00
|
|
|
uri: Union[bytes, str] = self.uri
|
2018-09-13 13:57:02 -04:00
|
|
|
if isinstance(uri, bytes):
|
2021-03-03 15:47:38 -05:00
|
|
|
uri = uri.decode("ascii", errors="replace")
|
2018-09-13 13:57:02 -04:00
|
|
|
return redact_uri(uri)
|
2016-04-22 11:09:55 -04:00
|
|
|
|
2021-03-03 15:47:38 -05:00
|
|
|
def get_method(self) -> str:
|
|
|
|
"""Gets the method associated with the request (or placeholder if method
|
|
|
|
has not yet been received).
|
2018-10-02 06:49:39 -04:00
|
|
|
|
|
|
|
Note: This is necessary as the placeholder value in twisted is str
|
|
|
|
rather than bytes, so we need to sanitise `self.method`.
|
|
|
|
|
|
|
|
Returns:
|
2021-03-03 15:47:38 -05:00
|
|
|
The request method as a string.
|
2018-10-02 06:49:39 -04:00
|
|
|
"""
|
2021-07-15 06:02:43 -04:00
|
|
|
method: Union[bytes, str] = self.method
|
2018-10-02 06:49:39 -04:00
|
|
|
if isinstance(method, bytes):
|
2021-03-03 15:47:38 -05:00
|
|
|
return self.method.decode("ascii")
|
2018-10-02 06:49:39 -04:00
|
|
|
return method
|
|
|
|
|
2021-04-08 08:01:14 -04:00
|
|
|
def get_authenticated_entity(self) -> Tuple[Optional[str], Optional[str]]:
|
|
|
|
"""
|
|
|
|
Get the "authenticated" entity of the request, which might be the user
|
|
|
|
performing the action, or a user being puppeted by a server admin.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A tuple:
|
|
|
|
The first item is a string representing the user making the request.
|
|
|
|
|
|
|
|
The second item is a string or None representing the user who
|
|
|
|
authenticated when making this request. See
|
|
|
|
Requester.authenticated_entity.
|
|
|
|
"""
|
|
|
|
# Convert the requester into a string that we can log
|
|
|
|
if isinstance(self._requester, str):
|
|
|
|
return self._requester, None
|
|
|
|
elif isinstance(self._requester, Requester):
|
|
|
|
requester = self._requester.user.to_string()
|
|
|
|
authenticated_entity = self._requester.authenticated_entity
|
|
|
|
|
|
|
|
# If this is a request where the target user doesn't match the user who
|
|
|
|
# authenticated (e.g. and admin is puppetting a user) then we return both.
|
2022-08-22 09:17:59 -04:00
|
|
|
if requester != authenticated_entity:
|
2021-04-08 08:01:14 -04:00
|
|
|
return requester, authenticated_entity
|
|
|
|
|
|
|
|
return requester, None
|
|
|
|
elif self._requester is not None:
|
|
|
|
# This shouldn't happen, but we log it so we don't lose information
|
|
|
|
# and can see that we're doing something wrong.
|
|
|
|
return repr(self._requester), None # type: ignore[unreachable]
|
|
|
|
|
|
|
|
return None, None
|
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def render(self, resrc: Resource) -> None:
|
2018-08-15 03:49:59 -04:00
|
|
|
# this is called once a Resource has been found to serve the request; in our
|
|
|
|
# case the Resource in question will normally be a JsonResource.
|
|
|
|
|
|
|
|
# create a LogContext for this request
|
|
|
|
request_id = self.get_request_id()
|
2021-04-08 08:01:14 -04:00
|
|
|
self.logcontext = LoggingContext(
|
|
|
|
request_id,
|
|
|
|
request=ContextRequest(
|
|
|
|
request_id=request_id,
|
2023-04-03 05:27:51 -04:00
|
|
|
ip_address=self.get_client_ip_if_available(),
|
2021-09-24 06:01:25 -04:00
|
|
|
site_tag=self.synapse_site.site_tag,
|
2021-04-08 08:01:14 -04:00
|
|
|
# The requester is going to be unknown at this point.
|
|
|
|
requester=None,
|
|
|
|
authenticated_entity=None,
|
|
|
|
method=self.get_method(),
|
|
|
|
url=self.get_redacted_uri(),
|
|
|
|
protocol=self.clientproto.decode("ascii", errors="replace"),
|
|
|
|
user_agent=get_request_user_agent(self),
|
|
|
|
),
|
|
|
|
)
|
2018-08-15 03:49:59 -04:00
|
|
|
|
2018-05-10 13:46:59 -04:00
|
|
|
# override the Server header which is set by twisted
|
2021-09-24 06:01:25 -04:00
|
|
|
self.setHeader("Server", self.synapse_site.server_version_string)
|
2018-08-15 03:49:59 -04:00
|
|
|
|
|
|
|
with PreserveLoggingContext(self.logcontext):
|
|
|
|
# we start the request metrics timer here with an initial stab
|
|
|
|
# at the servlet name. For most requests that name will be
|
|
|
|
# JsonResource (or a subclass), and JsonResource._async_render
|
|
|
|
# will update it once it picks a servlet.
|
|
|
|
servlet_name = resrc.__class__.__name__
|
|
|
|
self._started_processing(servlet_name)
|
|
|
|
|
|
|
|
Request.render(self, resrc)
|
|
|
|
|
|
|
|
# record the arrival of the request *after*
|
|
|
|
# dispatching to the handler, so that the handler
|
|
|
|
# can update the servlet name in the request
|
|
|
|
# metrics
|
2018-10-02 06:49:39 -04:00
|
|
|
requests_counter.labels(self.get_method(), self.request_metrics.name).inc()
|
2018-08-15 03:49:59 -04:00
|
|
|
|
|
|
|
@contextlib.contextmanager
|
2021-09-24 06:01:25 -04:00
|
|
|
def processing(self) -> Generator[None, None, None]:
|
2018-08-15 03:49:59 -04:00
|
|
|
"""Record the fact that we are processing this request.
|
|
|
|
|
|
|
|
Returns a context manager; the correct way to use this is:
|
|
|
|
|
2020-08-06 08:20:42 -04:00
|
|
|
async def handle_request(request):
|
2018-08-15 03:49:59 -04:00
|
|
|
with request.processing("FooServlet"):
|
2020-08-06 08:20:42 -04:00
|
|
|
await really_handle_the_request()
|
2018-08-15 03:49:59 -04:00
|
|
|
|
|
|
|
Once the context manager is closed, the completion of the request will be logged,
|
|
|
|
and the various metrics will be updated.
|
|
|
|
"""
|
|
|
|
if self._is_processing:
|
|
|
|
raise RuntimeError("Request is already processing")
|
|
|
|
self._is_processing = True
|
|
|
|
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
except Exception:
|
|
|
|
# this should already have been caught, and sent back to the client as a 500.
|
2020-10-23 12:38:40 -04:00
|
|
|
logger.exception(
|
|
|
|
"Asynchronous message handler raised an uncaught exception"
|
|
|
|
)
|
2018-08-15 03:49:59 -04:00
|
|
|
finally:
|
|
|
|
# the request handler has finished its work and either sent the whole response
|
|
|
|
# back, or handed over responsibility to a Producer.
|
|
|
|
|
|
|
|
self._processing_finished_time = time.time()
|
|
|
|
self._is_processing = False
|
|
|
|
|
2021-12-20 12:45:03 -05:00
|
|
|
if self._opentracing_span:
|
|
|
|
self._opentracing_span.log_kv({"event": "finished processing"})
|
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
# if we've already sent the response, log it now; otherwise, we wait for the
|
|
|
|
# response to be sent.
|
|
|
|
if self.finish_time is not None:
|
|
|
|
self._finished_processing()
|
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def finish(self) -> None:
|
2018-08-15 03:49:59 -04:00
|
|
|
"""Called when all response data has been written to this Request.
|
|
|
|
|
|
|
|
Overrides twisted.web.server.Request.finish to record the finish time and do
|
|
|
|
logging.
|
|
|
|
"""
|
|
|
|
self.finish_time = time.time()
|
|
|
|
Request.finish(self)
|
2021-12-20 12:45:03 -05:00
|
|
|
if self._opentracing_span:
|
|
|
|
self._opentracing_span.log_kv({"event": "response sent"})
|
2018-08-15 03:49:59 -04:00
|
|
|
if not self._is_processing:
|
2020-05-22 05:12:17 -04:00
|
|
|
assert self.logcontext is not None
|
2018-08-15 03:49:59 -04:00
|
|
|
with PreserveLoggingContext(self.logcontext):
|
|
|
|
self._finished_processing()
|
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def connectionLost(self, reason: Union[Failure, Exception]) -> None:
|
2018-08-15 03:49:59 -04:00
|
|
|
"""Called when the client connection is closed before the response is written.
|
|
|
|
|
|
|
|
Overrides twisted.web.server.Request.connectionLost to record the finish time and
|
|
|
|
do logging.
|
|
|
|
"""
|
2020-05-14 12:07:24 -04:00
|
|
|
# There is a bug in Twisted where reason is not wrapped in a Failure object
|
|
|
|
# Detect this and wrap it manually as a workaround
|
|
|
|
# More information: https://github.com/matrix-org/synapse/issues/7441
|
|
|
|
if not isinstance(reason, Failure):
|
|
|
|
reason = Failure(reason)
|
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
self.finish_time = time.time()
|
|
|
|
Request.connectionLost(self, reason)
|
|
|
|
|
2020-03-31 10:18:41 -04:00
|
|
|
if self.logcontext is None:
|
|
|
|
logger.info(
|
|
|
|
"Connection from %s lost before request headers were read", self.client
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
# we only get here if the connection to the client drops before we send
|
|
|
|
# the response.
|
|
|
|
#
|
|
|
|
# It's useful to log it here so that we can get an idea of when
|
|
|
|
# the client disconnects.
|
|
|
|
with PreserveLoggingContext(self.logcontext):
|
2020-07-24 04:55:47 -04:00
|
|
|
logger.info("Connection from client lost before response was sent")
|
2018-08-15 03:49:59 -04:00
|
|
|
|
2021-12-20 12:45:03 -05:00
|
|
|
if self._opentracing_span:
|
|
|
|
self._opentracing_span.log_kv(
|
|
|
|
{"event": "client connection lost", "reason": str(reason.value)}
|
|
|
|
)
|
|
|
|
|
2022-05-10 09:06:08 -04:00
|
|
|
if self._is_processing:
|
|
|
|
if self.is_render_cancellable:
|
|
|
|
if self.render_deferred is not None:
|
|
|
|
# Throw a cancellation into the request processing, in the hope
|
|
|
|
# that it will finish up sooner than it normally would.
|
|
|
|
# The `self.processing()` context manager will call
|
|
|
|
# `_finished_processing()` when done.
|
|
|
|
with PreserveLoggingContext():
|
|
|
|
self.render_deferred.cancel()
|
|
|
|
else:
|
|
|
|
logger.error(
|
|
|
|
"Connection from client lost, but have no Deferred to "
|
|
|
|
"cancel even though the request is marked as cancellable."
|
|
|
|
)
|
|
|
|
else:
|
2018-08-15 03:49:59 -04:00
|
|
|
self._finished_processing()
|
2018-05-10 13:46:59 -04:00
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def _started_processing(self, servlet_name: str) -> None:
|
2018-08-15 03:49:59 -04:00
|
|
|
"""Record the fact that we are processing this request.
|
|
|
|
|
|
|
|
This will log the request's arrival. Once the request completes,
|
|
|
|
be sure to call finished_processing.
|
|
|
|
|
|
|
|
Args:
|
2022-11-16 10:25:24 -05:00
|
|
|
servlet_name: the name of the servlet which will be
|
2018-08-15 03:49:59 -04:00
|
|
|
processing this request. This is used in the metrics.
|
|
|
|
|
|
|
|
It is possible to update this afterwards by updating
|
|
|
|
self.request_metrics.name.
|
|
|
|
"""
|
2018-05-28 05:10:27 -04:00
|
|
|
self.start_time = time.time()
|
2018-05-09 18:05:14 -04:00
|
|
|
self.request_metrics = RequestMetrics()
|
2018-05-21 11:03:39 -04:00
|
|
|
self.request_metrics.start(
|
2018-10-02 06:49:39 -04:00
|
|
|
self.start_time, name=servlet_name, method=self.get_method()
|
2018-05-21 11:03:39 -04:00
|
|
|
)
|
2018-05-09 18:05:14 -04:00
|
|
|
|
2021-09-24 06:01:25 -04:00
|
|
|
self.synapse_site.access_logger.debug(
|
2016-04-22 11:09:55 -04:00
|
|
|
"%s - %s - Received request: %s %s",
|
2023-04-03 05:27:51 -04:00
|
|
|
self.get_client_ip_if_available(),
|
2021-09-24 06:01:25 -04:00
|
|
|
self.synapse_site.site_tag,
|
2018-10-02 06:49:39 -04:00
|
|
|
self.get_method(),
|
2016-04-22 11:09:55 -04:00
|
|
|
self.get_redacted_uri(),
|
|
|
|
)
|
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def _finished_processing(self) -> None:
|
2018-08-15 03:49:59 -04:00
|
|
|
"""Log the completion of this request and update the metrics"""
|
2020-05-22 05:12:17 -04:00
|
|
|
assert self.logcontext is not None
|
2021-09-21 12:41:27 -04:00
|
|
|
assert self.finish_time is not None
|
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
usage = self.logcontext.get_resource_usage()
|
|
|
|
|
|
|
|
if self._processing_finished_time is None:
|
|
|
|
# we completed the request without anything calling processing()
|
|
|
|
self._processing_finished_time = time.time()
|
2016-04-22 11:09:55 -04:00
|
|
|
|
2018-08-15 03:49:59 -04:00
|
|
|
# the time between receiving the request and the request handler finishing
|
|
|
|
processing_time = self._processing_finished_time - self.start_time
|
|
|
|
|
|
|
|
# the time between the request handler finishing and the response being sent
|
|
|
|
# to the client (nb may be negative)
|
|
|
|
response_send_time = self.finish_time - self._processing_finished_time
|
2018-05-09 18:05:14 -04:00
|
|
|
|
2021-01-12 07:34:16 -05:00
|
|
|
user_agent = get_request_user_agent(self, "-")
|
2018-08-15 03:49:59 -04:00
|
|
|
|
2022-01-26 07:47:34 -05:00
|
|
|
# int(self.code) looks redundant, because self.code is already an int.
|
|
|
|
# But self.code might be an HTTPStatus (which inherits from int)---which has
|
|
|
|
# a different string representation. So ensure we really have an integer.
|
|
|
|
code = str(int(self.code))
|
2018-08-15 03:49:59 -04:00
|
|
|
if not self.finished:
|
|
|
|
# we didn't send the full response before we gave up (presumably because
|
|
|
|
# the connection dropped)
|
|
|
|
code += "!"
|
2018-07-01 06:56:33 -04:00
|
|
|
|
2020-08-07 09:21:24 -04:00
|
|
|
log_level = logging.INFO if self._should_log_request() else logging.DEBUG
|
2021-04-08 08:01:14 -04:00
|
|
|
|
|
|
|
# If this is a request where the target user doesn't match the user who
|
|
|
|
# authenticated (e.g. and admin is puppetting a user) then we log both.
|
|
|
|
requester, authenticated_entity = self.get_authenticated_entity()
|
|
|
|
if authenticated_entity:
|
2021-09-08 08:59:15 -04:00
|
|
|
requester = f"{authenticated_entity}|{requester}"
|
2021-04-08 08:01:14 -04:00
|
|
|
|
2021-09-24 06:01:25 -04:00
|
|
|
self.synapse_site.access_logger.log(
|
2020-08-07 09:21:24 -04:00
|
|
|
log_level,
|
2016-04-22 11:09:55 -04:00
|
|
|
"%s - %s - {%s}"
|
2018-08-15 03:49:59 -04:00
|
|
|
" Processed request: %.3fsec/%.3fsec (%.3fsec, %.3fsec) (%.3fsec/%.3fsec/%d)"
|
2018-06-21 01:15:03 -04:00
|
|
|
' %sB %s "%s %s %s" "%s" [%d dbevts]',
|
2023-04-03 05:27:51 -04:00
|
|
|
self.get_client_ip_if_available(),
|
2021-09-24 06:01:25 -04:00
|
|
|
self.synapse_site.site_tag,
|
2021-04-08 08:01:14 -04:00
|
|
|
requester,
|
2018-08-15 03:49:59 -04:00
|
|
|
processing_time,
|
|
|
|
response_send_time,
|
2018-07-10 08:56:07 -04:00
|
|
|
usage.ru_utime,
|
|
|
|
usage.ru_stime,
|
|
|
|
usage.db_sched_duration_sec,
|
|
|
|
usage.db_txn_duration_sec,
|
|
|
|
int(usage.db_txn_count),
|
2016-04-22 11:09:55 -04:00
|
|
|
self.sentLength,
|
2018-08-15 03:49:59 -04:00
|
|
|
code,
|
2018-10-02 06:49:39 -04:00
|
|
|
self.get_method(),
|
2016-04-22 11:09:55 -04:00
|
|
|
self.get_redacted_uri(),
|
2018-09-17 11:15:42 -04:00
|
|
|
self.clientproto.decode("ascii", errors="replace"),
|
2018-07-01 06:56:33 -04:00
|
|
|
user_agent,
|
2018-07-10 08:56:07 -04:00
|
|
|
usage.evt_db_fetch_count,
|
2016-04-22 11:09:55 -04:00
|
|
|
)
|
|
|
|
|
2021-12-20 12:45:03 -05:00
|
|
|
# complete the opentracing span, if any.
|
|
|
|
if self._opentracing_span:
|
|
|
|
self._opentracing_span.finish()
|
|
|
|
|
2018-05-09 18:05:14 -04:00
|
|
|
try:
|
2018-09-17 12:16:50 -04:00
|
|
|
self.request_metrics.stop(self.finish_time, self.code, self.sentLength)
|
2018-05-09 18:05:14 -04:00
|
|
|
except Exception as e:
|
2019-10-31 06:23:24 -04:00
|
|
|
logger.warning("Failed to stop metrics: %r", e)
|
2018-05-09 18:05:14 -04:00
|
|
|
|
2020-08-07 09:21:24 -04:00
|
|
|
def _should_log_request(self) -> bool:
|
|
|
|
"""Whether we should log at INFO that we processed the request."""
|
2020-08-07 09:53:05 -04:00
|
|
|
if self.path == b"/health":
|
|
|
|
return False
|
|
|
|
|
|
|
|
if self.method == b"OPTIONS":
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
2020-08-07 09:21:24 -04:00
|
|
|
|
2023-04-03 05:27:51 -04:00
|
|
|
def get_client_ip_if_available(self) -> str:
|
|
|
|
"""Logging helper. Return something useful when a client IP is not retrievable
|
|
|
|
from a unix socket.
|
|
|
|
|
|
|
|
In practice, this returns the socket file path on a SynapseRequest if using a
|
|
|
|
unix socket and the normal IP address for TCP sockets.
|
|
|
|
|
|
|
|
"""
|
|
|
|
# getClientAddress().host returns a proper IP address for a TCP socket. But
|
|
|
|
# unix sockets have no concept of IP addresses or ports and return a
|
|
|
|
# UNIXAddress containing a 'None' value. In order to get something usable for
|
|
|
|
# logs(where this is used) get the unix socket file. getHost() returns a
|
|
|
|
# UNIXAddress containing a value of the socket file and has an instance
|
|
|
|
# variable of 'name' encoded as a byte string containing the path we want.
|
|
|
|
# Decode to utf-8 so it looks nice.
|
|
|
|
if isinstance(self.getClientAddress(), UNIXAddress):
|
|
|
|
return self.getHost().name.decode("utf-8")
|
|
|
|
else:
|
|
|
|
return self.getClientAddress().host
|
|
|
|
|
2023-06-26 10:12:20 -04:00
|
|
|
def request_info(self) -> "RequestInfo":
|
|
|
|
h = self.getHeader(b"User-Agent")
|
|
|
|
user_agent = h.decode("ascii", "replace") if h else None
|
|
|
|
return RequestInfo(user_agent=user_agent, ip=self.get_client_ip_if_available())
|
|
|
|
|
2016-04-22 11:09:55 -04:00
|
|
|
|
|
|
|
class XForwardedForRequest(SynapseRequest):
|
2021-02-24 13:11:33 -05:00
|
|
|
"""Request object which honours proxy headers
|
2016-04-22 11:09:55 -04:00
|
|
|
|
2021-02-24 13:11:33 -05:00
|
|
|
Extends SynapseRequest to replace getClientIP, getClientAddress, and isSecure with
|
|
|
|
information from request headers.
|
2016-04-22 11:09:55 -04:00
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
|
2021-02-24 13:11:33 -05:00
|
|
|
# the client IP and ssl flag, as extracted from the headers.
|
2021-07-15 06:02:43 -04:00
|
|
|
_forwarded_for: "Optional[_XForwardedForAddress]" = None
|
|
|
|
_forwarded_https: bool = False
|
2021-02-24 13:11:33 -05:00
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def requestReceived(self, command: bytes, path: bytes, version: bytes) -> None:
|
2021-02-24 13:11:33 -05:00
|
|
|
# this method is called by the Channel once the full request has been
|
|
|
|
# received, to dispatch the request to a resource.
|
|
|
|
# We can use it to set the IP address and protocol according to the
|
|
|
|
# headers.
|
|
|
|
self._process_forwarded_headers()
|
|
|
|
return super().requestReceived(command, path, version)
|
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def _process_forwarded_headers(self) -> None:
|
2021-02-24 13:11:33 -05:00
|
|
|
headers = self.requestHeaders.getRawHeaders(b"x-forwarded-for")
|
|
|
|
if not headers:
|
|
|
|
return
|
|
|
|
|
|
|
|
# for now, we just use the first x-forwarded-for header. Really, we ought
|
|
|
|
# to start from the client IP address, and check whether it is trusted; if it
|
|
|
|
# is, work backwards through the headers until we find an untrusted address.
|
|
|
|
# see https://github.com/matrix-org/synapse/issues/9471
|
|
|
|
self._forwarded_for = _XForwardedForAddress(
|
|
|
|
headers[0].split(b",")[0].strip().decode("ascii")
|
|
|
|
)
|
|
|
|
|
|
|
|
# if we got an x-forwarded-for header, also look for an x-forwarded-proto header
|
|
|
|
header = self.getHeader(b"x-forwarded-proto")
|
|
|
|
if header is not None:
|
|
|
|
self._forwarded_https = header.lower() == b"https"
|
|
|
|
else:
|
|
|
|
# this is done largely for backwards-compatibility so that people that
|
|
|
|
# haven't set an x-forwarded-proto header don't get a redirect loop.
|
|
|
|
logger.warning(
|
|
|
|
"forwarded request lacks an x-forwarded-proto header: assuming https"
|
|
|
|
)
|
|
|
|
self._forwarded_https = True
|
|
|
|
|
2021-09-21 12:41:27 -04:00
|
|
|
def isSecure(self) -> bool:
|
2021-02-24 13:11:33 -05:00
|
|
|
if self._forwarded_https:
|
|
|
|
return True
|
|
|
|
return super().isSecure()
|
|
|
|
|
|
|
|
def getClientIP(self) -> str:
|
2016-04-22 11:09:55 -04:00
|
|
|
"""
|
2021-02-24 13:11:33 -05:00
|
|
|
Return the IP address of the client who submitted this request.
|
|
|
|
|
|
|
|
This method is deprecated. Use getClientAddress() instead.
|
2016-04-22 11:09:55 -04:00
|
|
|
"""
|
2021-02-24 13:11:33 -05:00
|
|
|
if self._forwarded_for is not None:
|
|
|
|
return self._forwarded_for.host
|
|
|
|
return super().getClientIP()
|
|
|
|
|
|
|
|
def getClientAddress(self) -> IAddress:
|
|
|
|
"""
|
|
|
|
Return the address of the client who submitted this request.
|
|
|
|
"""
|
|
|
|
if self._forwarded_for is not None:
|
|
|
|
return self._forwarded_for
|
|
|
|
return super().getClientAddress()
|
|
|
|
|
|
|
|
|
|
|
|
@implementer(IAddress)
|
2022-01-13 08:49:28 -05:00
|
|
|
@attr.s(frozen=True, slots=True, auto_attribs=True)
|
2021-02-24 13:11:33 -05:00
|
|
|
class _XForwardedForAddress:
|
2022-01-13 08:49:28 -05:00
|
|
|
host: str
|
2016-04-22 11:09:55 -04:00
|
|
|
|
|
|
|
|
2023-07-18 04:49:21 -04:00
|
|
|
class SynapseSite(ProxySite):
|
2016-04-22 11:09:55 -04:00
|
|
|
"""
|
2021-04-23 12:06:47 -04:00
|
|
|
Synapse-specific twisted http Site
|
|
|
|
|
|
|
|
This does two main things.
|
|
|
|
|
|
|
|
First, it replaces the requestFactory in use so that we build SynapseRequests
|
|
|
|
instead of regular t.w.server.Requests. All of the constructor params are really
|
|
|
|
just parameters for SynapseRequest.
|
|
|
|
|
|
|
|
Second, it inhibits the log() method called by Request.finish, since SynapseRequest
|
|
|
|
does its own logging.
|
2016-04-22 11:09:55 -04:00
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
|
2018-05-10 13:46:59 -04:00
|
|
|
def __init__(
|
|
|
|
self,
|
2021-04-23 12:06:47 -04:00
|
|
|
logger_name: str,
|
|
|
|
site_tag: str,
|
2020-06-16 07:44:07 -04:00
|
|
|
config: ListenerConfig,
|
2021-04-23 12:06:47 -04:00
|
|
|
resource: IResource,
|
2021-09-24 06:01:25 -04:00
|
|
|
server_version_string: str,
|
2021-04-23 14:20:44 -04:00
|
|
|
max_request_body_size: int,
|
2023-07-18 04:49:21 -04:00
|
|
|
reactor: ISynapseReactor,
|
|
|
|
hs: "HomeServer",
|
2018-05-10 13:46:59 -04:00
|
|
|
):
|
2021-04-23 12:06:47 -04:00
|
|
|
"""
|
|
|
|
|
|
|
|
Args:
|
|
|
|
logger_name: The name of the logger to use for access logs.
|
|
|
|
site_tag: A tag to use for this site - mostly in access logs.
|
|
|
|
config: Configuration for the HTTP listener corresponding to this site
|
|
|
|
resource: The base of the resource tree to be used for serving requests on
|
|
|
|
this site
|
|
|
|
server_version_string: A string to present for the Server header
|
2021-04-23 14:20:44 -04:00
|
|
|
max_request_body_size: Maximum request body length to allow before
|
|
|
|
dropping the connection
|
2021-04-23 12:06:47 -04:00
|
|
|
reactor: reactor to be used to manage connection timeouts
|
|
|
|
"""
|
2023-07-18 04:49:21 -04:00
|
|
|
super().__init__(
|
|
|
|
resource=resource,
|
|
|
|
reactor=reactor,
|
|
|
|
hs=hs,
|
|
|
|
)
|
2016-04-22 11:09:55 -04:00
|
|
|
|
|
|
|
self.site_tag = site_tag
|
2024-08-13 09:06:17 -04:00
|
|
|
self.reactor: ISynapseReactor = reactor
|
2016-04-22 11:09:55 -04:00
|
|
|
|
2020-06-16 07:44:07 -04:00
|
|
|
assert config.http_options is not None
|
|
|
|
proxied = config.http_options.x_forwarded
|
2021-04-23 14:20:44 -04:00
|
|
|
request_class = XForwardedForRequest if proxied else SynapseRequest
|
|
|
|
|
2022-09-15 16:32:25 -04:00
|
|
|
request_id_header = config.http_options.request_id_header
|
|
|
|
|
2023-07-18 04:49:21 -04:00
|
|
|
self.experimental_cors_msc3886: bool = (
|
|
|
|
config.http_options.experimental_cors_msc3886
|
|
|
|
)
|
2022-10-18 11:52:25 -04:00
|
|
|
|
2021-12-14 07:00:47 -05:00
|
|
|
def request_factory(channel: HTTPChannel, queued: bool) -> Request:
|
2021-04-23 14:20:44 -04:00
|
|
|
return request_class(
|
2021-09-21 12:41:27 -04:00
|
|
|
channel,
|
2021-09-24 06:01:25 -04:00
|
|
|
self,
|
2021-09-21 12:41:27 -04:00
|
|
|
max_request_body_size=max_request_body_size,
|
|
|
|
queued=queued,
|
2022-09-15 16:32:25 -04:00
|
|
|
request_id_header=request_id_header,
|
2021-04-23 14:20:44 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
self.requestFactory = request_factory # type: ignore
|
2016-04-22 11:09:55 -04:00
|
|
|
self.access_logger = logging.getLogger(logger_name)
|
2018-08-20 09:54:49 -04:00
|
|
|
self.server_version_string = server_version_string.encode("ascii")
|
2016-04-22 11:09:55 -04:00
|
|
|
|
2024-07-30 10:23:23 -04:00
|
|
|
def log(self, request: SynapseRequest) -> None: # type: ignore[override]
|
2016-04-22 11:09:55 -04:00
|
|
|
pass
|
2023-06-26 10:12:20 -04:00
|
|
|
|
|
|
|
|
|
|
|
@attr.s(auto_attribs=True, frozen=True, slots=True)
|
|
|
|
class RequestInfo:
|
|
|
|
user_agent: Optional[str]
|
|
|
|
ip: str
|