2021-08-16 10:14:31 -04:00
|
|
|
# Copyright 2021 The Matrix.org Foundation C.I.C.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
import functools
|
|
|
|
import logging
|
|
|
|
import re
|
2022-02-03 07:29:16 -05:00
|
|
|
import time
|
2022-04-19 11:23:53 -04:00
|
|
|
from http import HTTPStatus
|
|
|
|
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, Tuple, cast
|
2021-08-16 10:14:31 -04:00
|
|
|
|
|
|
|
from synapse.api.errors import Codes, FederationDeniedError, SynapseError
|
|
|
|
from synapse.api.urls import FEDERATION_V1_PREFIX
|
2022-05-11 09:52:26 -04:00
|
|
|
from synapse.http.server import HttpServer, ServletCallback, is_method_cancellable
|
2021-08-16 10:14:31 -04:00
|
|
|
from synapse.http.servlet import parse_json_object_from_request
|
2021-12-02 11:18:10 -05:00
|
|
|
from synapse.http.site import SynapseRequest
|
2021-08-16 10:14:31 -04:00
|
|
|
from synapse.logging.context import run_in_background
|
|
|
|
from synapse.logging.opentracing import (
|
2022-02-03 07:29:16 -05:00
|
|
|
active_span,
|
2021-12-20 12:45:03 -05:00
|
|
|
set_tag,
|
|
|
|
span_context_from_request,
|
2022-02-03 07:29:16 -05:00
|
|
|
start_active_span,
|
2021-12-20 12:45:03 -05:00
|
|
|
start_active_span_follows_from,
|
2021-08-16 10:14:31 -04:00
|
|
|
whitelisted_homeserver,
|
|
|
|
)
|
2021-12-02 11:18:10 -05:00
|
|
|
from synapse.types import JsonDict
|
2021-08-16 10:14:31 -04:00
|
|
|
from synapse.util.ratelimitutils import FederationRateLimiter
|
|
|
|
from synapse.util.stringutils import parse_and_validate_server_name
|
|
|
|
|
2022-01-25 07:06:29 -05:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
2021-08-16 10:14:31 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class AuthenticationError(SynapseError):
|
|
|
|
"""There was a problem authenticating the request"""
|
|
|
|
|
|
|
|
|
|
|
|
class NoAuthenticationError(AuthenticationError):
|
|
|
|
"""The request had no authentication information"""
|
|
|
|
|
|
|
|
|
|
|
|
class Authenticator:
|
2022-01-25 07:06:29 -05:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2021-08-16 10:14:31 -04:00
|
|
|
self._clock = hs.get_clock()
|
|
|
|
self.keyring = hs.get_keyring()
|
|
|
|
self.server_name = hs.hostname
|
2022-02-23 06:04:02 -05:00
|
|
|
self.store = hs.get_datastores().main
|
2021-09-23 12:03:01 -04:00
|
|
|
self.federation_domain_whitelist = (
|
|
|
|
hs.config.federation.federation_domain_whitelist
|
|
|
|
)
|
2021-08-16 10:14:31 -04:00
|
|
|
self.notifier = hs.get_notifier()
|
|
|
|
|
|
|
|
self.replication_client = None
|
|
|
|
if hs.config.worker.worker_app:
|
2022-03-10 08:01:56 -05:00
|
|
|
self.replication_client = hs.get_replication_command_handler()
|
2021-08-16 10:14:31 -04:00
|
|
|
|
|
|
|
# A method just so we can pass 'self' as the authenticator to the Servlets
|
2021-12-02 11:18:10 -05:00
|
|
|
async def authenticate_request(
|
|
|
|
self, request: SynapseRequest, content: Optional[JsonDict]
|
|
|
|
) -> str:
|
2021-08-16 10:14:31 -04:00
|
|
|
now = self._clock.time_msec()
|
2021-12-02 11:18:10 -05:00
|
|
|
json_request: JsonDict = {
|
2021-08-16 10:14:31 -04:00
|
|
|
"method": request.method.decode("ascii"),
|
|
|
|
"uri": request.uri.decode("ascii"),
|
|
|
|
"destination": self.server_name,
|
|
|
|
"signatures": {},
|
|
|
|
}
|
|
|
|
|
|
|
|
if content is not None:
|
|
|
|
json_request["content"] = content
|
|
|
|
|
|
|
|
origin = None
|
|
|
|
|
|
|
|
auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
|
|
|
|
|
|
|
|
if not auth_headers:
|
|
|
|
raise NoAuthenticationError(
|
2022-04-19 11:23:53 -04:00
|
|
|
HTTPStatus.UNAUTHORIZED,
|
|
|
|
"Missing Authorization headers",
|
|
|
|
Codes.UNAUTHORIZED,
|
2021-08-16 10:14:31 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
for auth in auth_headers:
|
|
|
|
if auth.startswith(b"X-Matrix"):
|
2022-04-19 11:23:53 -04:00
|
|
|
(origin, key, sig, destination) = _parse_auth_header(auth)
|
2021-08-16 10:14:31 -04:00
|
|
|
json_request["origin"] = origin
|
|
|
|
json_request["signatures"].setdefault(origin, {})[key] = sig
|
|
|
|
|
2022-04-19 11:23:53 -04:00
|
|
|
# if the origin_server sent a destination along it needs to match our own server_name
|
|
|
|
if destination is not None and destination != self.server_name:
|
|
|
|
raise AuthenticationError(
|
|
|
|
HTTPStatus.UNAUTHORIZED,
|
|
|
|
"Destination mismatch in auth header",
|
|
|
|
Codes.UNAUTHORIZED,
|
|
|
|
)
|
2021-08-16 10:14:31 -04:00
|
|
|
if (
|
|
|
|
self.federation_domain_whitelist is not None
|
|
|
|
and origin not in self.federation_domain_whitelist
|
|
|
|
):
|
|
|
|
raise FederationDeniedError(origin)
|
|
|
|
|
|
|
|
if origin is None or not json_request["signatures"]:
|
|
|
|
raise NoAuthenticationError(
|
2022-04-19 11:23:53 -04:00
|
|
|
HTTPStatus.UNAUTHORIZED,
|
|
|
|
"Missing Authorization headers",
|
|
|
|
Codes.UNAUTHORIZED,
|
2021-08-16 10:14:31 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
await self.keyring.verify_json_for_server(
|
|
|
|
origin,
|
|
|
|
json_request,
|
|
|
|
now,
|
|
|
|
)
|
|
|
|
|
|
|
|
logger.debug("Request from %s", origin)
|
|
|
|
request.requester = origin
|
|
|
|
|
|
|
|
# If we get a valid signed request from the other side, its probably
|
|
|
|
# alive
|
|
|
|
retry_timings = await self.store.get_destination_retry_timings(origin)
|
|
|
|
if retry_timings and retry_timings.retry_last_ts:
|
2022-01-25 07:06:29 -05:00
|
|
|
run_in_background(self.reset_retry_timings, origin)
|
2021-08-16 10:14:31 -04:00
|
|
|
|
|
|
|
return origin
|
|
|
|
|
2022-01-25 07:06:29 -05:00
|
|
|
async def reset_retry_timings(self, origin: str) -> None:
|
2021-08-16 10:14:31 -04:00
|
|
|
try:
|
|
|
|
logger.info("Marking origin %r as up", origin)
|
|
|
|
await self.store.set_destination_retry_timings(origin, None, 0, 0)
|
|
|
|
|
|
|
|
# Inform the relevant places that the remote server is back up.
|
|
|
|
self.notifier.notify_remote_server_up(origin)
|
|
|
|
if self.replication_client:
|
|
|
|
# If we're on a worker we try and inform master about this. The
|
|
|
|
# replication client doesn't hook into the notifier to avoid
|
|
|
|
# infinite loops where we send a `REMOTE_SERVER_UP` command to
|
|
|
|
# master, which then echoes it back to us which in turn pokes
|
|
|
|
# the notifier.
|
|
|
|
self.replication_client.send_remote_server_up(origin)
|
|
|
|
|
|
|
|
except Exception:
|
|
|
|
logger.exception("Error resetting retry timings on %s", origin)
|
|
|
|
|
|
|
|
|
2022-04-19 11:23:53 -04:00
|
|
|
def _parse_auth_header(header_bytes: bytes) -> Tuple[str, str, str, Optional[str]]:
|
2021-08-16 10:14:31 -04:00
|
|
|
"""Parse an X-Matrix auth header
|
|
|
|
|
|
|
|
Args:
|
2021-12-02 11:18:10 -05:00
|
|
|
header_bytes: header value
|
2021-08-16 10:14:31 -04:00
|
|
|
|
|
|
|
Returns:
|
2022-04-19 11:23:53 -04:00
|
|
|
origin, key id, signature, destination.
|
2021-12-02 11:18:10 -05:00
|
|
|
origin, key id, signature.
|
2021-08-16 10:14:31 -04:00
|
|
|
|
|
|
|
Raises:
|
|
|
|
AuthenticationError if the header could not be parsed
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
header_str = header_bytes.decode("utf-8")
|
|
|
|
params = header_str.split(" ")[1].split(",")
|
2022-04-19 11:23:53 -04:00
|
|
|
param_dict: Dict[str, str] = {
|
|
|
|
k: v for k, v in [param.split("=", maxsplit=1) for param in params]
|
|
|
|
}
|
2021-08-16 10:14:31 -04:00
|
|
|
|
2021-12-02 11:18:10 -05:00
|
|
|
def strip_quotes(value: str) -> str:
|
2021-08-16 10:14:31 -04:00
|
|
|
if value.startswith('"'):
|
|
|
|
return value[1:-1]
|
|
|
|
else:
|
|
|
|
return value
|
|
|
|
|
|
|
|
origin = strip_quotes(param_dict["origin"])
|
|
|
|
|
|
|
|
# ensure that the origin is a valid server name
|
|
|
|
parse_and_validate_server_name(origin)
|
|
|
|
|
|
|
|
key = strip_quotes(param_dict["key"])
|
|
|
|
sig = strip_quotes(param_dict["sig"])
|
2022-04-19 11:23:53 -04:00
|
|
|
|
|
|
|
# get the destination server_name from the auth header if it exists
|
|
|
|
destination = param_dict.get("destination")
|
|
|
|
if destination is not None:
|
|
|
|
destination = strip_quotes(destination)
|
|
|
|
else:
|
|
|
|
destination = None
|
|
|
|
|
|
|
|
return origin, key, sig, destination
|
2021-08-16 10:14:31 -04:00
|
|
|
except Exception as e:
|
|
|
|
logger.warning(
|
|
|
|
"Error parsing auth header '%s': %s",
|
|
|
|
header_bytes.decode("ascii", "replace"),
|
|
|
|
e,
|
|
|
|
)
|
|
|
|
raise AuthenticationError(
|
2022-04-19 11:23:53 -04:00
|
|
|
HTTPStatus.BAD_REQUEST, "Malformed Authorization header", Codes.UNAUTHORIZED
|
2021-08-16 10:14:31 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class BaseFederationServlet:
|
|
|
|
"""Abstract base class for federation servlet classes.
|
|
|
|
|
|
|
|
The servlet object should have a PATH attribute which takes the form of a regexp to
|
|
|
|
match against the request path (excluding the /federation/v1 prefix).
|
|
|
|
|
|
|
|
The servlet should also implement one or more of on_GET, on_POST, on_PUT, to match
|
|
|
|
the appropriate HTTP method. These methods must be *asynchronous* and have the
|
|
|
|
signature:
|
|
|
|
|
|
|
|
on_<METHOD>(self, origin, content, query, **kwargs)
|
|
|
|
|
|
|
|
With arguments:
|
|
|
|
|
|
|
|
origin (unicode|None): The authenticated server_name of the calling server,
|
|
|
|
unless REQUIRE_AUTH is set to False and authentication failed.
|
|
|
|
|
|
|
|
content (unicode|None): decoded json body of the request. None if the
|
|
|
|
request was a GET.
|
|
|
|
|
|
|
|
query (dict[bytes, list[bytes]]): Query params from the request. url-decoded
|
|
|
|
(ie, '+' and '%xx' are decoded) but note that it is *not* utf8-decoded
|
|
|
|
yet.
|
|
|
|
|
|
|
|
**kwargs (dict[unicode, unicode]): the dict mapping keys to path
|
|
|
|
components as specified in the path match regexp.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Optional[Tuple[int, object]]: either (response code, response object) to
|
|
|
|
return a JSON response, or None if the request has already been handled.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
SynapseError: to return an error code
|
|
|
|
|
|
|
|
Exception: other exceptions will be caught, logged, and a 500 will be
|
|
|
|
returned.
|
|
|
|
"""
|
|
|
|
|
|
|
|
PATH = "" # Overridden in subclasses, the regex to match against the path.
|
|
|
|
|
|
|
|
REQUIRE_AUTH = True
|
|
|
|
|
|
|
|
PREFIX = FEDERATION_V1_PREFIX # Allows specifying the API version
|
|
|
|
|
|
|
|
RATELIMIT = True # Whether to rate limit requests or not
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2022-01-25 07:06:29 -05:00
|
|
|
hs: "HomeServer",
|
2021-08-16 10:14:31 -04:00
|
|
|
authenticator: Authenticator,
|
|
|
|
ratelimiter: FederationRateLimiter,
|
|
|
|
server_name: str,
|
|
|
|
):
|
|
|
|
self.hs = hs
|
|
|
|
self.authenticator = authenticator
|
|
|
|
self.ratelimiter = ratelimiter
|
|
|
|
self.server_name = server_name
|
|
|
|
|
2021-12-02 11:18:10 -05:00
|
|
|
def _wrap(self, func: Callable[..., Awaitable[Tuple[int, Any]]]) -> ServletCallback:
|
2021-08-16 10:14:31 -04:00
|
|
|
authenticator = self.authenticator
|
|
|
|
ratelimiter = self.ratelimiter
|
|
|
|
|
|
|
|
@functools.wraps(func)
|
2021-12-02 11:18:10 -05:00
|
|
|
async def new_func(
|
|
|
|
request: SynapseRequest, *args: Any, **kwargs: str
|
|
|
|
) -> Optional[Tuple[int, Any]]:
|
2021-08-16 10:14:31 -04:00
|
|
|
"""A callback which can be passed to HttpServer.RegisterPaths
|
|
|
|
|
|
|
|
Args:
|
2021-12-02 11:18:10 -05:00
|
|
|
request:
|
2021-08-16 10:14:31 -04:00
|
|
|
*args: unused?
|
2021-12-02 11:18:10 -05:00
|
|
|
**kwargs: the dict mapping keys to path components as specified
|
|
|
|
in the path match regexp.
|
2021-08-16 10:14:31 -04:00
|
|
|
|
|
|
|
Returns:
|
2021-12-02 11:18:10 -05:00
|
|
|
(response code, response object) as returned by the callback method.
|
|
|
|
None if the request has already been handled.
|
2021-08-16 10:14:31 -04:00
|
|
|
"""
|
|
|
|
content = None
|
|
|
|
if request.method in [b"PUT", b"POST"]:
|
|
|
|
# TODO: Handle other method types? other content types?
|
|
|
|
content = parse_json_object_from_request(request)
|
|
|
|
|
|
|
|
try:
|
2022-02-03 07:29:16 -05:00
|
|
|
with start_active_span("authenticate_request"):
|
|
|
|
origin: Optional[str] = await authenticator.authenticate_request(
|
|
|
|
request, content
|
|
|
|
)
|
2021-08-16 10:14:31 -04:00
|
|
|
except NoAuthenticationError:
|
|
|
|
origin = None
|
|
|
|
if self.REQUIRE_AUTH:
|
|
|
|
logger.warning(
|
|
|
|
"authenticate_request failed: missing authentication"
|
|
|
|
)
|
|
|
|
raise
|
|
|
|
except Exception as e:
|
|
|
|
logger.warning("authenticate_request failed: %s", e)
|
|
|
|
raise
|
|
|
|
|
2021-12-20 12:45:03 -05:00
|
|
|
# update the active opentracing span with the authenticated entity
|
|
|
|
set_tag("authenticated_entity", origin)
|
|
|
|
|
2022-02-03 07:29:16 -05:00
|
|
|
# if the origin is authenticated and whitelisted, use its span context
|
|
|
|
# as the parent.
|
2021-12-20 12:45:03 -05:00
|
|
|
context = None
|
2021-08-16 10:14:31 -04:00
|
|
|
if origin and whitelisted_homeserver(origin):
|
2021-12-20 12:45:03 -05:00
|
|
|
context = span_context_from_request(request)
|
2021-08-16 10:14:31 -04:00
|
|
|
|
2022-02-03 07:29:16 -05:00
|
|
|
if context:
|
|
|
|
servlet_span = active_span()
|
|
|
|
# a scope which uses the origin's context as a parent
|
|
|
|
processing_start_time = time.time()
|
|
|
|
scope = start_active_span_follows_from(
|
|
|
|
"incoming-federation-request",
|
|
|
|
child_of=context,
|
|
|
|
contexts=(servlet_span,),
|
|
|
|
start_time=processing_start_time,
|
|
|
|
)
|
2021-08-16 10:14:31 -04:00
|
|
|
|
2022-02-03 07:29:16 -05:00
|
|
|
else:
|
|
|
|
# just use our context as a parent
|
|
|
|
scope = start_active_span(
|
|
|
|
"incoming-federation-request",
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
|
|
|
with scope:
|
|
|
|
if origin and self.RATELIMIT:
|
|
|
|
with ratelimiter.ratelimit(origin) as d:
|
|
|
|
await d
|
|
|
|
if request._disconnected:
|
|
|
|
logger.warning(
|
|
|
|
"client disconnected before we started processing "
|
|
|
|
"request"
|
|
|
|
)
|
|
|
|
return None
|
|
|
|
response = await func(
|
|
|
|
origin, content, request.args, *args, **kwargs
|
2021-08-16 10:14:31 -04:00
|
|
|
)
|
2022-02-03 07:29:16 -05:00
|
|
|
else:
|
2021-08-16 10:14:31 -04:00
|
|
|
response = await func(
|
|
|
|
origin, content, request.args, *args, **kwargs
|
|
|
|
)
|
2022-02-03 07:29:16 -05:00
|
|
|
finally:
|
|
|
|
# if we used the origin's context as the parent, add a new span using
|
|
|
|
# the servlet span as a parent, so that we have a link
|
|
|
|
if context:
|
|
|
|
scope2 = start_active_span_follows_from(
|
|
|
|
"process-federation_request",
|
|
|
|
contexts=(scope.span,),
|
|
|
|
start_time=processing_start_time,
|
2021-08-16 10:14:31 -04:00
|
|
|
)
|
2022-02-03 07:29:16 -05:00
|
|
|
scope2.close()
|
2021-08-16 10:14:31 -04:00
|
|
|
|
|
|
|
return response
|
|
|
|
|
2021-12-02 11:18:10 -05:00
|
|
|
return cast(ServletCallback, new_func)
|
2021-08-16 10:14:31 -04:00
|
|
|
|
2021-12-02 11:18:10 -05:00
|
|
|
def register(self, server: HttpServer) -> None:
|
2021-08-16 10:14:31 -04:00
|
|
|
pattern = re.compile("^" + self.PREFIX + self.PATH + "$")
|
|
|
|
|
|
|
|
for method in ("GET", "PUT", "POST"):
|
|
|
|
code = getattr(self, "on_%s" % (method), None)
|
|
|
|
if code is None:
|
|
|
|
continue
|
|
|
|
|
2022-05-11 09:52:26 -04:00
|
|
|
if is_method_cancellable(code):
|
|
|
|
# The wrapper added by `self._wrap` will inherit the cancellable flag,
|
|
|
|
# but the wrapper itself does not support cancellation yet.
|
|
|
|
# Once resolved, the cancellation tests in
|
|
|
|
# `tests/federation/transport/server/test__base.py` can be re-enabled.
|
|
|
|
raise Exception(
|
|
|
|
f"{self.__class__.__name__}.on_{method} has been marked as "
|
|
|
|
"cancellable, but federation servlets do not support cancellation "
|
|
|
|
"yet."
|
|
|
|
)
|
|
|
|
|
2021-08-16 10:14:31 -04:00
|
|
|
server.register_paths(
|
|
|
|
method,
|
|
|
|
(pattern,),
|
|
|
|
self._wrap(code),
|
|
|
|
self.__class__.__name__,
|
|
|
|
)
|