Exemplo n.º 1
0
    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if self.allow_any or scope["type"] not in (
            "http",
            "websocket",
        ):  # pragma: no cover
            await self.app(scope, receive, send)
            return

        headers = Headers(scope=scope)
        host = headers.get("host", "").split(":")[0]
        is_valid_host = False
        found_www_redirect = False
        for pattern in self.allowed_hosts:
            if host == pattern or (
                pattern.startswith("*") and host.endswith(pattern[1:])
            ):
                is_valid_host = True
                break
            elif "www." + host == pattern:
                found_www_redirect = True

        if is_valid_host:
            await self.app(scope, receive, send)
        else:
            response: Response
            if found_www_redirect and self.www_redirect:
                url = URL(scope=scope)
                redirect_url = url.replace(netloc="www." + url.netloc)
                response = RedirectResponse(url=str(redirect_url))
            else:
                response = PlainTextResponse("Invalid host header", status_code=400)
            await response(scope, receive, send)
Exemplo n.º 2
0
    async def __call__(
            self, scope, receive, send
    ) -> None:
        if scope["type"] != "http":  # pragma: no cover
            handler = await self.app(scope, receive, send)
            await handler.__call__(receive, send)
            return

        method = scope["method"]
        headers = Headers(scope=scope)
        origin = headers.get("origin")

        if origin is None:
            handler = await self.app(scope, receive, send)
            await handler.__call__(receive, send)
            return

        if method == "OPTIONS" and "access-control-request-method" in headers:
            response = self.preflight_response(request_headers=headers)
            await response(scope, receive, send)
            return

        await self.simple_response(
            scope, receive, send, request_headers=headers
        )
Exemplo n.º 3
0
 def __init__(self, function: Callable[..., Any],
              callback: Union[Dict[str, Any], bool]) -> None:
     self.__function = function
     self.__attribute_finders = self.__prepare_and_validate_finders(
         callback)
     self.__headers = Headers()
     self.__params: Dict[str, str] = {}
     self.__invalid_callback_object = ""
Exemplo n.º 4
0
 async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
     if scope["type"] == "http":
         headers = Headers(scope=scope)
         if "gzip" in headers.get("Accept-Encoding", ""):
             responder = GZipResponder(self.app, self.minimum_size)
             await responder(scope, receive, send)
             return
     await self.app(scope, receive, send)
Exemplo n.º 5
0
    def __call__(self, scope: Scope) -> ASGIInstance:
        if scope["type"] in ("http", "websocket") and not self.allow_any:
            headers = Headers(scope=scope)
            host = headers.get("host")
            if host not in self.allowed_hosts:
                return PlainTextResponse("Invalid host header",
                                         status_code=400)

        return self.app(scope)
Exemplo n.º 6
0
 def is_not_modified(self, stat_headers: typing.Dict[str, str]) -> bool:
     etag = stat_headers["etag"]
     last_modified = stat_headers["last-modified"]
     req_headers = Headers(scope=self.scope)
     if etag == req_headers.get("if-none-match"):
         return True
     if "if-modified-since" not in req_headers:
         return False
     last_req_time = req_headers["if-modified-since"]
     return parsedate(last_req_time) >= parsedate(last_modified)  # type: ignore
Exemplo n.º 7
0
 def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
     headers = Headers(scope=scope)
     host = headers.get("host", "").split(":")[0]
     match = self.host_regex.match(host)
     if match:
         matched_params = match.groupdict()
         for key, value in matched_params.items():
             matched_params[key] = self.param_convertors[key].convert(value)
         path_params = dict(scope.get("path_params", {}))
         path_params.update(matched_params)
         child_scope = {"path_params": path_params, "endpoint": self.app}
         return Match.FULL, child_scope
     return Match.NONE, {}
Exemplo n.º 8
0
 async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
     headers = Headers(scope=scope)
     self.should_decode_from_msgpack_to_json = (
         "application/x-msgpack" in headers.get("content-type", "")
     )
     # Take an initial guess, although we eventually may not
     # be able to do the conversion.
     self.should_encode_from_json_to_msgpack = (
         "application/x-msgpack" in headers.getlist("accept")
     )
     self.receive = receive
     self.send = send
     await self.app(scope, self.receive_with_msgpack, self.send_with_msgpack)
Exemplo n.º 9
0
    def __call__(self, scope: Scope) -> ASGIInstance:
        if scope["type"] == "http":
            method = scope["method"]
            headers = Headers(scope=scope)
            origin = headers.get("origin")

            if origin is not None:
                if method == "OPTIONS" and "access-control-request-method" in headers:
                    return self.preflight_response(request_headers=headers)
                else:
                    return functools.partial(self.simple_response,
                                             scope=scope,
                                             request_headers=headers)

        return self.app(scope)
Exemplo n.º 10
0
 async def __call__(self, scope: Scope, receive: Receive,
                    send: Send) -> None:
     if scope["type"] == "http":
         headers = Headers(scope=scope)
         accepted = {
             item.strip()
             for item in headers.get("accept-encoding", "").split(",")
             if item
         }
         responder = CompressionResponder(self.app, self.minimum_size,
                                          accepted,
                                          self.compression_registry)
         await responder(scope, receive, send)
         return
     await self.app(scope, receive, send)
Exemplo n.º 11
0
    def __call__(self, scope: Scope) -> ASGIInstance:
        if scope["type"] in ("http", "websocket") and not self.allow_any:
            headers = Headers(scope=scope)
            host = headers.get("host", "").split(":")[0]
            for pattern in self.allowed_hosts:
                if (
                    host == pattern
                    or pattern.startswith("*")
                    and host.endswith(pattern[1:])
                ):
                    break
            else:
                return PlainTextResponse("Invalid host header", status_code=400)

        return self.app(scope)
Exemplo n.º 12
0
def test_player_json(service, steam_id, mod_date):
    resp = service.get("/player/{0}.json".format(steam_id))

    obj_defacto = resp.json()
    obj_expected = read_json_sample("player_{}".format(steam_id))
    assert obj_defacto == obj_expected

    resp = service.get("/player/{0}".format(steam_id))
    assert resp.template.name == "player_stats.html"
    context = resp.context
    assert "request" in context
    assert "steam_id" in context
    assert context["steam_id"] == steam_id

    del context["request"]
    del context["steam_id"]
    obj_defacto = context
    assert obj_defacto == obj_expected

    assert resp.headers["last-modified"] == mod_date

    service.get(
        "/player/{0}.json".format(steam_id),
        304,
        headers=Headers({"If-Modified-Since": mod_date}),
    )
Exemplo n.º 13
0
    def client_response_hook(self, span, resp_data):
        """used to capture the response data
        this function is called twice, once during each resp_phase"""
        resp_phase = resp_data['type']
        if resp_phase == "http.response.start":
            status_code = resp_data["status"]
            set_status_code(span, status_code)
            headers = dict(Headers(raw=resp_data['headers']))
            should_capture_body = self._capture_headers(
                self._process_response_headers,
                self.HTTP_RESPONSE_HEADER_PREFIX, span, headers,
                self._process_response_body)
            span.set_attribute('hypertrace.capture', should_capture_body)

        elif resp_phase == 'http.response.body':
            should_capture = span.attributes.get('hypertrace.capture')
            if should_capture:
                body_data = resp_data['body']
                body_str = None
                if isinstance(body_data, bytes):
                    body_str = body_data.decode('UTF8', 'backslashreplace')
                else:
                    body_str = body_data

                resp_body_str = self.grab_first_n_bytes(body_str)
                span.set_attribute('http.response.body', resp_body_str)
Exemplo n.º 14
0
 async def __call__(self, scope: Scope, receive: Receive,
                    send: Send) -> None:
     headers = Headers(scope=scope)
     url = URL(scope=scope)
     log_debug(message=f'[API Server] {url}',
               data={'headers': f'{headers}'})
     await self.app(scope, receive, send)
Exemplo n.º 15
0
 async def __call__(self, scope: Scope, receive: Receive,
                    send: Send) -> None:
     if scope["type"] == "http":
         headers = Headers(scope=scope)
         if "br" in headers.get("Accept-Encoding", ""):
             responder = BrotliResponder(
                 self.app,
                 self.quality,
                 self.mode,
                 self.lgwin,
                 self.lgblock,
                 self.minimum_size,
             )
             await responder(scope, receive, send)
             return
     await self.app(scope, receive, send)
Exemplo n.º 16
0
async def get_sequence(checksum: str,
                       start: int = 0,
                       end: int = 0,
                       accept: str = ""):
    """
    Return Refget sequence based on checksum value.
    str start: Start point of the sequence defined in checksum.
    str end: End point of the sequence defined in checksum.
    """
    headers = Headers()
    params = {"accept": accept}

    if start < end:
        params["start"] = start
        params["end"] = end
    url_path = "sequence/" + checksum
    try:
        result = await create_request_coroutine(
            url_list=metadata_url_list(checksum),
            url_path=url_path,
            headers=headers,
            params=params,
        )
        if result == "":
            return HTTPException(status_code=HTTP_404_NOT_FOUND,
                                 detail="Not Found")

        return result
    except Exception as e:
        logger.log("DEBUG", "Unhandled exception in get_sequence " + str(e))
Exemplo n.º 17
0
 async def get_response(self, path: str, scope: Scope) -> Response:
     response = await super().get_response(path, scope)
     if isinstance(response, FileResponse):
         etag = await _hash_file(response.path)
         response.headers["etag"] = etag
         if self.is_not_modified(response.headers, Headers(scope=scope)):
             return NotModifiedResponse(response.headers)
     return response
Exemplo n.º 18
0
 def __init__(self, request: HTTPConnection):
     super().__init__(
         request.scope["method"],
         str(URL(scope=request.scope)),
         None,
         Headers(scope=request.scope),
     )
     self._orig_request = request
Exemplo n.º 19
0
    async def gzippable_app(scope: Scope, receive: Receive,
                            send: Send) -> None:
        headers = Headers(scope=scope)

        if "gzip" in headers.getlist("accept-encoding"):
            body = gzip.compress(b"Hello, world!")
            response = PlainTextResponse(
                content=body,
                headers={
                    "Content-Encoding": "gzip",
                    "Content-Length": str(len(body))
                },
            )
        else:
            response = PlainTextResponse("Hello, world!")

        response.headers["Vary"] = "Accept-Encoding"
        await response(scope, receive, send)
Exemplo n.º 20
0
Arquivo: span.py Projeto: nbashev/noc
 async def __call__(self, scope: Scope, receive: Receive,
                    send: Send) -> None:
     if scope["type"] != "http":
         await self.app(scope, receive, send)
         return
     headers = Headers(scope=scope)
     span_ctx = headers.get("x-noc-span-ctx", 0)
     span_id = headers.get("x-noc-span", 0)
     sample = 1 if span_ctx and span_id else 0
     with Span(
             server=self.service_name,
             service="api",
             sample=sample,
             parent=span_id,
             context=span_ctx,
             in_label=scope["path"],
     ):
         await self.app(scope, receive, send)
Exemplo n.º 21
0
 def __init__(self, headers: Headers):
     super().__init__(
         status_code=304,
         headers={
             name: value
             for name, value in headers.items()
             if name in self.NOT_MODIFIED_HEADERS
         },
     )
Exemplo n.º 22
0
    async def __call__(self, scope: Scope, receive: Receive, send: Send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        method = scope["method"]
        headers = Headers(scope=scope)

        await self.response(scope, receive, send, request_headers=headers)
Exemplo n.º 23
0
def test_partial():
    from starlette.datastructures import Headers

    class Header(Model):
        token: str

    header = Header(**Headers({"token": "123", "test": "12345g"}))
    assert header.token == "123"
    assert header.dict() == {"token": "123"}
Exemplo n.º 24
0
    async def asgi(self, receive: Receive, send: Send, scope: Scope, path: str) -> None:
        if not self.config_checked:
            await self.check_config()
            self.config_checked = True

        method = scope["method"]
        headers = Headers(scope=scope)
        response = await self.get_response(path, method, headers)
        await response(receive, send)
    async def send_with_logging(self, message: Message) -> None:

        if message["type"] == "http.response.start":
            self._response_status_code = message.get("status")
            headers = Headers(raw=message["headers"])
            self.should_log_response_body = "application/json" in headers.get(
                "content-type", "")

            await self.send(message)

        elif message["type"] == "http.response.body":
            if not self.should_log_response_body:
                await self.send(message)
                return

            body: bytes = message.get("body", b"")
            self._response_body.extend(body)

            await self.send(message)
Exemplo n.º 26
0
    def get_jwt(self, header: Headers) -> str:
        if "Authorization" not in header:
            return

        token = header.get("Authorization")
        scheme, jwt = token.split()
        if scheme.lower() != "bearer":
            raise InvalidAuthorizationToken("header dose not start \
                with 'Bearer'")

        return jwt
Exemplo n.º 27
0
    def get_context(self, scope):
        request_method = scope.get("method")
        if request_method:
            trace_name = f"starlette_http_{request_method.lower()}"
        else:
            trace_name = "starlette_http"

        headers = Headers(scope=scope)

        return {
            "name": trace_name,
            "type": "http_server",
            "request.host": headers.get("host"),
            "request.method": request_method,
            "request.path": scope.get("path"),
            "request.content_length": int(headers.get("content-length", 0)),
            "request.user_agent": headers.get("user-agent"),
            "request.scheme": scope.get("scheme"),
            "request.query": scope.get("query_string").decode("ascii"),
        }
def test_check_auth_error_auth_error():
    """Test: check_auth(request: Request) -> None
    Error: Auth error."""

    scope = {'type': 'http'}
    request = Request(scope)
    request._headers = Headers(headers={'X-Key': 'fake-key'})
    with pytest.raises(HTTPException) as ex:
        check_auth(request)
    assert ex.value.status_code == 400
    assert ex.value.detail == 'Auth error'
Exemplo n.º 29
0
    def __call__(self, scope: Scope) -> ASGIInstance:
        if scope["type"] in ("http", "websocket") and not self.allow_any:
            headers = Headers(scope=scope)
            host = headers.get("host", "").split(":")[0]
            found_www_redirect = False
            for pattern in self.allowed_hosts:
                if host == pattern or (pattern.startswith("*")
                                       and host.endswith(pattern[1:])):
                    break
                elif "www." + host == pattern:
                    found_www_redirect = True
            else:
                if found_www_redirect and self.www_redirect:
                    url = URL(scope=scope)
                    redirect_url = url.replace(netloc="www." + url.netloc)
                    return RedirectResponse(url=str(redirect_url))
                return PlainTextResponse("Invalid host header",
                                         status_code=400)

        return self.app(scope)
Exemplo n.º 30
0
async def get_data_from_response(message: dict, config: Config, event_type: str) -> dict:
    """Loads data from response for APM capturing.

    Args:
        message (dict)
        config (Config)
        event_type (str)

    Returns:
        dict
    """
    result = {}

    if "status_code" in message:
        result["status_code"] = message["status"]

    if config.capture_headers and "headers" in message:
        headers = Headers(raw=message["headers"])
        result["headers"] = {key: ";".join(headers.getlist(key)) for key in compat.iterkeys(headers)}

    return result