Esempio n. 1
0
    async def _async_render_POST(self, request: Request) -> None:
        version = parse_string(request, "v", required=True)
        username = parse_string(request, "u", required=True)
        args: Dict[bytes, List[bytes]] = request.args  # type: ignore
        userhmac = parse_bytes_from_args(args, "h", required=True)

        self._check_hash(username, userhmac)

        if username.startswith("@"):
            qualified_user_id = username
        else:
            qualified_user_id = UserID(username, self.hs.hostname).to_string()

        try:
            await self.store.user_set_consent_version(qualified_user_id, version)
        except StoreError as e:
            if e.code != 404:
                raise
            raise NotFoundError("Unknown user")
        await self.registration_handler.post_consent_actions(qualified_user_id)

        try:
            self._render_template(request, "success.html")
        except TemplateNotFound:
            raise NotFoundError("success.html not found")
Esempio n. 2
0
    async def _async_render_POST(self, request: SynapseRequest) -> None:
        requester = await self.auth.get_user_by_req(request)
        content_length = request.getHeader("Content-Length")
        if content_length is None:
            raise SynapseError(msg="Request must specify a Content-Length",
                               code=400)
        if int(content_length) > self.max_upload_size:
            raise SynapseError(
                msg="Upload request body is too large",
                code=413,
                errcode=Codes.TOO_LARGE,
            )

        args = request.args  # type: Dict[bytes, List[bytes]]  # type: ignore
        upload_name_bytes = parse_bytes_from_args(args, "filename")
        if upload_name_bytes:
            try:
                upload_name = upload_name_bytes.decode(
                    "utf8")  # type: Optional[str]
            except UnicodeDecodeError:
                raise SynapseError(msg="Invalid UTF-8 filename parameter: %r" %
                                   (upload_name),
                                   code=400)

        # If the name is falsey (e.g. an empty byte string) ensure it is None.
        else:
            upload_name = None

        headers = request.requestHeaders

        if headers.hasHeader(b"Content-Type"):
            content_type_headers = headers.getRawHeaders(b"Content-Type")
            assert content_type_headers  # for mypy
            media_type = content_type_headers[0].decode("ascii")
        else:
            raise SynapseError(msg="Upload request missing 'Content-Type'",
                               code=400)

        # if headers.hasHeader(b"Content-Disposition"):
        #     disposition = headers.getRawHeaders(b"Content-Disposition")[0]
        # TODO(markjh): parse content-dispostion

        try:
            content = request.content  # type: IO  # type: ignore
            content_uri = await self.media_repo.create_content(
                media_type, upload_name, content, content_length,
                requester.user)
        except SpamMediaException:
            # For uploading of media we want to respond with a 400, instead of
            # the default 404, as that would just be confusing.
            raise SynapseError(400, "Bad content")

        logger.info("Uploaded content with URI %r", content_uri)

        respond_with_json(request,
                          200, {"content_uri": content_uri},
                          send_cors=True)
Esempio n. 3
0
    async def _async_render_GET(self, request):
        """
        Args:
            request (twisted.web.http.Request):
        """
        version = parse_string(request,
                               "v",
                               default=self._default_consent_version)
        username = parse_string(request, "u", default="")
        userhmac = None
        has_consented = False
        public_version = username == ""
        if not public_version:
            args: Dict[bytes, List[bytes]] = request.args
            userhmac_bytes = parse_bytes_from_args(args, "h", required=True)

            self._check_hash(username, userhmac_bytes)

            if username.startswith("@"):
                qualified_user_id = username
            else:
                qualified_user_id = UserID(username,
                                           self.hs.hostname).to_string()

            u = await self.store.get_user_by_id(qualified_user_id)
            if u is None:
                raise NotFoundError("Unknown user")

            has_consented = u["consent_version"] == version
            userhmac = userhmac_bytes.decode("ascii")

        try:
            self._render_template(
                request,
                "%s.html" % (version, ),
                user=username,
                userhmac=userhmac,
                version=version,
                has_consented=has_consented,
                public_version=public_version,
            )
        except TemplateNotFound:
            raise NotFoundError("Unknown policy version")
Esempio n. 4
0
    async def on_GET(self,
                     request: SynapseRequest,
                     idp_id: Optional[str] = None) -> None:
        if not self._public_baseurl:
            raise SynapseError(400, "SSO requires a valid public_baseurl")

        # if this isn't the expected hostname, redirect to the right one, so that we
        # get our cookies back.
        requested_uri = get_request_uri(request)
        baseurl_bytes = self._public_baseurl.encode("utf-8")
        if not requested_uri.startswith(baseurl_bytes):
            # swap out the incorrect base URL for the right one.
            #
            # The idea here is to redirect from
            #    https://foo.bar/whatever/_matrix/...
            # to
            #    https://public.baseurl/_matrix/...
            #
            i = requested_uri.index(b"/_matrix")
            new_uri = baseurl_bytes[:-1] + requested_uri[i:]
            logger.info(
                "Requested URI %s is not canonical: redirecting to %s",
                requested_uri.decode("utf-8", errors="replace"),
                new_uri.decode("utf-8", errors="replace"),
            )
            request.redirect(new_uri)
            finish_request(request)
            return

        args: Dict[bytes, List[bytes]] = request.args  # type: ignore
        client_redirect_url = parse_bytes_from_args(args,
                                                    "redirectUrl",
                                                    required=True)
        sso_url = await self._sso_handler.handle_redirect_request(
            request,
            client_redirect_url,
            idp_id,
        )
        logger.info("Redirecting to %s", sso_url)
        request.redirect(sso_url)
        finish_request(request)