Ejemplo n.º 1
0
    def _listen_http(self, listener_config: ListenerConfig) -> None:
        port = listener_config.port
        bind_addresses = listener_config.bind_addresses

        assert listener_config.http_options is not None

        site_tag = listener_config.http_options.tag
        if site_tag is None:
            site_tag = str(port)

        # We always include a health resource.
        resources: Dict[str, Resource] = {"/health": HealthResource()}

        for res in listener_config.http_options.resources:
            for name in res.names:
                if name == "metrics":
                    resources[METRICS_PREFIX] = MetricsResource(RegistryProxy)
                elif name == "client":
                    resource = JsonResource(self, canonical_json=False)

                    RegisterRestServlet(self).register(resource)
                    RegistrationTokenValidityRestServlet(self).register(resource)
                    login.register_servlets(self, resource)
                    ThreepidRestServlet(self).register(resource)
                    WhoamiRestServlet(self).register(resource)
                    DevicesRestServlet(self).register(resource)

                    # Read-only
                    KeyUploadServlet(self).register(resource)
                    KeyQueryServlet(self).register(resource)
                    KeyChangesServlet(self).register(resource)
                    OneTimeKeyServlet(self).register(resource)

                    voip.register_servlets(self, resource)
                    push_rule.register_servlets(self, resource)
                    versions.register_servlets(self, resource)

                    profile.register_servlets(self, resource)

                    sync.register_servlets(self, resource)
                    events.register_servlets(self, resource)
                    room.register_servlets(self, resource, is_worker=True)
                    room.register_deprecated_servlets(self, resource)
                    initial_sync.register_servlets(self, resource)
                    room_batch.register_servlets(self, resource)
                    room_keys.register_servlets(self, resource)
                    tags.register_servlets(self, resource)
                    account_data.register_servlets(self, resource)
                    receipts.register_servlets(self, resource)
                    read_marker.register_servlets(self, resource)

                    sendtodevice.register_servlets(self, resource)

                    user_directory.register_servlets(self, resource)

                    presence.register_servlets(self, resource)

                    resources.update({CLIENT_API_PREFIX: resource})

                    resources.update(build_synapse_client_resource_tree(self))
                    resources.update({"/.well-known": well_known_resource(self)})

                elif name == "federation":
                    resources.update({FEDERATION_PREFIX: TransportLayerServer(self)})
                elif name == "media":
                    if self.config.media.can_load_media_repo:
                        media_repo = self.get_media_repository_resource()

                        # We need to serve the admin servlets for media on the
                        # worker.
                        admin_resource = JsonResource(self, canonical_json=False)
                        register_servlets_for_media_repo(self, admin_resource)

                        resources.update(
                            {
                                MEDIA_R0_PREFIX: media_repo,
                                MEDIA_V3_PREFIX: media_repo,
                                LEGACY_MEDIA_PREFIX: media_repo,
                                "/_synapse/admin": admin_resource,
                            }
                        )
                    else:
                        logger.warning(
                            "A 'media' listener is configured but the media"
                            " repository is disabled. Ignoring."
                        )

                if name == "openid" and "federation" not in res.names:
                    # Only load the openid resource separately if federation resource
                    # is not specified since federation resource includes openid
                    # resource.
                    resources.update(
                        {
                            FEDERATION_PREFIX: TransportLayerServer(
                                self, servlet_groups=["openid"]
                            )
                        }
                    )

                if name in ["keys", "federation"]:
                    resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self)

                if name == "replication":
                    resources[REPLICATION_PREFIX] = ReplicationRestResource(self)

        # Attach additional resources registered by modules.
        resources.update(self._module_web_resources)
        self._module_web_resources_consumed = True

        root_resource = create_resource_tree(resources, OptionsResource())

        _base.listen_tcp(
            bind_addresses,
            port,
            SynapseSite(
                "synapse.access.http.%s" % (site_tag,),
                site_tag,
                listener_config,
                root_resource,
                self.version_string,
                max_request_body_size=max_request_body_size(self.config),
                reactor=self.get_reactor(),
            ),
            reactor=self.get_reactor(),
        )

        logger.info("Synapse worker now listening on port %d", port)
Ejemplo n.º 2
0
    def _configure_named_resource(self,
                                  name: str,
                                  compress: bool = False
                                  ) -> Dict[str, Resource]:
        """Build a resource map for a named resource

        Args:
            name: named resource: one of "client", "federation", etc
            compress: whether to enable gzip compression for this resource

        Returns:
            map from path to HTTP resource
        """
        resources: Dict[str, Resource] = {}
        if name == "client":
            client_resource: Resource = ClientRestResource(self)
            if compress:
                client_resource = gz_wrap(client_resource)

            resources.update({
                CLIENT_API_PREFIX: client_resource,
                "/.well-known": well_known_resource(self),
                "/_synapse/admin": AdminRestResource(self),
                **build_synapse_client_resource_tree(self),
            })

            if self.config.email.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
                from synapse.rest.synapse.client.password_reset import (
                    PasswordResetSubmitTokenResource, )

                resources[
                    "/_synapse/client/password_reset/email/submit_token"] = PasswordResetSubmitTokenResource(
                        self)

        if name == "consent":
            from synapse.rest.consent.consent_resource import ConsentResource

            consent_resource: Resource = ConsentResource(self)
            if compress:
                consent_resource = gz_wrap(consent_resource)
            resources.update({"/_matrix/consent": consent_resource})

        if name == "federation":
            resources.update({FEDERATION_PREFIX: TransportLayerServer(self)})

        if name == "openid":
            resources.update({
                FEDERATION_PREFIX:
                TransportLayerServer(self, servlet_groups=["openid"])
            })

        if name in ["static", "client"]:
            resources.update({
                STATIC_PREFIX:
                StaticResource(
                    os.path.join(os.path.dirname(synapse.__file__), "static"))
            })

        if name in ["media", "federation", "client"]:
            if self.config.server.enable_media_repo:
                media_repo = self.get_media_repository_resource()
                resources.update({
                    MEDIA_R0_PREFIX: media_repo,
                    MEDIA_V3_PREFIX: media_repo,
                    LEGACY_MEDIA_PREFIX: media_repo,
                })
            elif name == "media":
                raise ConfigError(
                    "'media' resource conflicts with enable_media_repo=False")

        if name in ["keys", "federation"]:
            resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self)

        if name == "metrics" and self.config.metrics.enable_metrics:
            metrics_resource: Resource = MetricsResource(RegistryProxy)
            if compress:
                metrics_resource = gz_wrap(metrics_resource)
            resources[METRICS_PREFIX] = metrics_resource

        if name == "replication":
            resources[REPLICATION_PREFIX] = ReplicationRestResource(self)

        return resources
Ejemplo n.º 3
0
    def _configure_named_resource(self, name, compress=False):
        """Build a resource map for a named resource

        Args:
            name (str): named resource: one of "client", "federation", etc
            compress (bool): whether to enable gzip compression for this
                resource

        Returns:
            dict[str, Resource]: map from path to HTTP resource
        """
        resources = {}
        if name == "client":
            client_resource = ClientRestResource(self)
            if compress:
                client_resource = gz_wrap(client_resource)

            resources.update({
                "/_matrix/client/api/v1": client_resource,
                "/_matrix/client/r0": client_resource,
                "/_matrix/client/unstable": client_resource,
                "/_matrix/client/v2_alpha": client_resource,
                "/_matrix/client/versions": client_resource,
                "/.well-known": well_known_resource(self),
                "/_synapse/admin": AdminRestResource(self),
                **build_synapse_client_resource_tree(self),
            })

            if self.config.email.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
                from synapse.rest.synapse.client.password_reset import (
                    PasswordResetSubmitTokenResource, )

                resources[
                    "/_synapse/client/password_reset/email/submit_token"] = PasswordResetSubmitTokenResource(
                        self)

        if name == "consent":
            from synapse.rest.consent.consent_resource import ConsentResource

            consent_resource = ConsentResource(self)
            if compress:
                consent_resource = gz_wrap(consent_resource)
            resources.update({"/_matrix/consent": consent_resource})

        if name == "federation":
            resources.update({FEDERATION_PREFIX: TransportLayerServer(self)})

        if name == "openid":
            resources.update({
                FEDERATION_PREFIX:
                TransportLayerServer(self, servlet_groups=["openid"])
            })

        if name in ["static", "client"]:
            resources.update({
                STATIC_PREFIX:
                StaticResource(
                    os.path.join(os.path.dirname(synapse.__file__), "static"))
            })

        if name in ["media", "federation", "client"]:
            if self.config.server.enable_media_repo:
                media_repo = self.get_media_repository_resource()
                resources.update({
                    MEDIA_PREFIX: media_repo,
                    LEGACY_MEDIA_PREFIX: media_repo
                })
            elif name == "media":
                raise ConfigError(
                    "'media' resource conflicts with enable_media_repo=False")

        if name in ["keys", "federation"]:
            resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self)

        if name == "webclient":
            webclient_loc = self.config.server.web_client_location

            if webclient_loc is None:
                logger.warning(
                    "Not enabling webclient resource, as web_client_location is unset."
                )
            elif webclient_loc.startswith(
                    "http://") or webclient_loc.startswith("https://"):
                resources[WEB_CLIENT_PREFIX] = RootRedirect(webclient_loc)
            else:
                logger.warning(
                    "Running webclient on the same domain is not recommended: "
                    "https://github.com/matrix-org/synapse#security-note - "
                    "after you move webclient to different host you can set "
                    "web_client_location to its full URL to enable redirection."
                )
                # GZip is disabled here due to
                # https://twistedmatrix.com/trac/ticket/7678
                resources[WEB_CLIENT_PREFIX] = File(webclient_loc)

        if name == "metrics" and self.config.metrics.enable_metrics:
            resources[METRICS_PREFIX] = MetricsResource(RegistryProxy)

        if name == "replication":
            resources[REPLICATION_PREFIX] = ReplicationRestResource(self)

        return resources
Ejemplo n.º 4
0
 def create_test_resource(self) -> Resource:
     # replace the JsonResource with a Resource wrapping the WellKnownResource
     res = Resource()
     res.putChild(b".well-known", well_known_resource(self.hs))
     return res