Pass requester to SynapseRequest

pull/8616/head
Erik Johnston 2020-10-27 10:42:06 +00:00
parent c87bf0d84b
commit 6a063043e3
5 changed files with 46 additions and 34 deletions

View File

@ -193,11 +193,6 @@ class Auth:
user_id, app_service = await self._get_appservice_user_id(request) user_id, app_service = await self._get_appservice_user_id(request)
if user_id: if user_id:
request.authenticated_entity = user_id
opentracing.set_tag("authenticated_entity", user_id)
opentracing.set_tag("target_user", user_id)
opentracing.set_tag("appservice_id", app_service.id)
if ip_addr and self._track_appservice_user_ips: if ip_addr and self._track_appservice_user_ips:
await self.store.insert_client_ip( await self.store.insert_client_ip(
user_id=user_id, user_id=user_id,
@ -207,7 +202,16 @@ class Auth:
device_id="dummy-device", # stubbed device_id="dummy-device", # stubbed
) )
return synapse.types.create_requester(user_id, app_service=app_service) requester = synapse.types.create_requester(
user_id, app_service=app_service
)
request.requester = user_id
opentracing.set_tag("authenticated_entity", user_id)
opentracing.set_tag("target_user", user_id)
opentracing.set_tag("appservice_id", app_service.id)
return requester
user_info = await self.get_user_by_access_token( user_info = await self.get_user_by_access_token(
access_token, rights, allow_expired=allow_expired access_token, rights, allow_expired=allow_expired
@ -244,14 +248,7 @@ class Auth:
errcode=Codes.GUEST_ACCESS_FORBIDDEN, errcode=Codes.GUEST_ACCESS_FORBIDDEN,
) )
request.authenticated_entity = user_info.token_owner requester = synapse.types.create_requester(
request.target_user = user_info.user_id
opentracing.set_tag("authenticated_entity", user_info.token_owner)
opentracing.set_tag("target_user", user_info.user_id)
if device_id:
opentracing.set_tag("device_id", device_id)
return synapse.types.create_requester(
user, user,
token_id, token_id,
is_guest, is_guest,
@ -260,6 +257,14 @@ class Auth:
app_service=app_service, app_service=app_service,
authenticated_entity=user_info.token_owner, authenticated_entity=user_info.token_owner,
) )
request.requester = requester
opentracing.set_tag("authenticated_entity", user_info.token_owner)
opentracing.set_tag("target_user", user_info.user_id)
if device_id:
opentracing.set_tag("device_id", device_id)
return requester
except KeyError: except KeyError:
raise MissingClientTokenError() raise MissingClientTokenError()
@ -478,7 +483,7 @@ class Auth:
if not service: if not service:
logger.warning("Unrecognised appservice access token.") logger.warning("Unrecognised appservice access token.")
raise InvalidClientTokenError() raise InvalidClientTokenError()
request.authenticated_entity = service.sender request.requester = service.sender
return service return service
async def is_server_admin(self, user: UserID) -> bool: async def is_server_admin(self, user: UserID) -> bool:

View File

@ -154,7 +154,7 @@ class Authenticator:
) )
logger.debug("Request from %s", origin) logger.debug("Request from %s", origin)
request.authenticated_entity = origin request.requester = origin
# If we get a valid signed request from the other side, its probably # If we get a valid signed request from the other side, its probably
# alive # alive

View File

@ -14,7 +14,7 @@
import contextlib import contextlib
import logging import logging
import time import time
from typing import Optional from typing import Optional, Union
from twisted.python.failure import Failure from twisted.python.failure import Failure
from twisted.web.server import Request, Site from twisted.web.server import Request, Site
@ -23,6 +23,7 @@ from synapse.config.server import ListenerConfig
from synapse.http import redact_uri from synapse.http import redact_uri
from synapse.http.request_metrics import RequestMetrics, requests_counter from synapse.http.request_metrics import RequestMetrics, requests_counter
from synapse.logging.context import LoggingContext, PreserveLoggingContext from synapse.logging.context import LoggingContext, PreserveLoggingContext
from synapse.types import Requester
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -54,10 +55,12 @@ class SynapseRequest(Request):
Request.__init__(self, channel, *args, **kw) Request.__init__(self, channel, *args, **kw)
self.site = channel.site self.site = channel.site
self._channel = channel # this is used by the tests self._channel = channel # this is used by the tests
self.authenticated_entity = None
self.target_user = None
self.start_time = 0.0 self.start_time = 0.0
# The requester, if authenticated. For federation requests this is the
# server name, for client requests this is the Requester object.
self.requester = None # type: Optional[Union[Requester, str]]
# we can't yet create the logcontext, as we don't know the method. # we can't yet create the logcontext, as we don't know the method.
self.logcontext = None # type: Optional[LoggingContext] self.logcontext = None # type: Optional[LoggingContext]
@ -264,16 +267,23 @@ class SynapseRequest(Request):
# to the client (nb may be negative) # to the client (nb may be negative)
response_send_time = self.finish_time - self._processing_finished_time response_send_time = self.finish_time - self._processing_finished_time
# need to decode as it could be raw utf-8 bytes # Convert the requester into a string that we can log
# from a IDN servname in an auth header authenticated_entity = None
authenticated_entity = self.authenticated_entity if isinstance(self.requester, str):
if authenticated_entity is not None and isinstance(authenticated_entity, bytes): authenticated_entity = self.requester
authenticated_entity = authenticated_entity.decode("utf-8", "replace") elif isinstance(self.requester, Requester):
authenticated_entity = self.requester.authenticated_entity
if self.target_user: # If this is a request where the target user doesn't match the user who
authenticated_entity = "{} as {}".format( # authenticated (e.g. and admin is puppetting a user) then we log both.
authenticated_entity, self.target_user, if self.requester.user.to_string() != authenticated_entity:
) authenticated_entity = "{} as {}".format(
authenticated_entity, self.requester.user.to_string(),
)
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.
authenticated_entity = repr(self.requester)
# ...or could be raw utf-8 bytes in the User-Agent header. # ...or could be raw utf-8 bytes in the User-Agent header.
# N.B. if you don't do this, the logger explodes cryptically # N.B. if you don't do this, the logger explodes cryptically

View File

@ -77,8 +77,7 @@ class ReplicationRemoteJoinRestServlet(ReplicationEndpoint):
requester = Requester.deserialize(self.store, content["requester"]) requester = Requester.deserialize(self.store, content["requester"])
if requester.user: request.requester = requester
request.authenticated_entity = requester.user.to_string()
logger.info("remote_join: %s into room: %s", user_id, room_id) logger.info("remote_join: %s into room: %s", user_id, room_id)
@ -142,8 +141,7 @@ class ReplicationRemoteRejectInviteRestServlet(ReplicationEndpoint):
requester = Requester.deserialize(self.store, content["requester"]) requester = Requester.deserialize(self.store, content["requester"])
if requester.user: request.requester = requester
request.authenticated_entity = requester.user.to_string()
# hopefully we're now on the master, so this won't recurse! # hopefully we're now on the master, so this won't recurse!
event_id, stream_id = await self.member_handler.remote_reject_invite( event_id, stream_id = await self.member_handler.remote_reject_invite(

View File

@ -115,8 +115,7 @@ class ReplicationSendEventRestServlet(ReplicationEndpoint):
ratelimit = content["ratelimit"] ratelimit = content["ratelimit"]
extra_users = [UserID.from_string(u) for u in content["extra_users"]] extra_users = [UserID.from_string(u) for u in content["extra_users"]]
if requester.user: request.requester = requester
request.authenticated_entity = requester.user.to_string()
logger.info( logger.info(
"Got event to send with ID: %s into room: %s", event.event_id, event.room_id "Got event to send with ID: %s into room: %s", event.event_id, event.room_id