Beispiel #1
0
 def apply_to_headers(self, headers: Headers) -> Headers:
     """
     Apply access control headerst to the supplied headers and return them.
     """
     headers.add('Access-Control-Allow-Headers', self._allowed_headers)
     headers.add('Access-Control-Allow-Methods', self._ALLOWED_METHODS),
     headers.add('Access-Control-Allow-Credentials',
                 self._ALLOW_CREDENTIALS)
     return headers
Beispiel #2
0
    def __init__(self,
                 headers: Headers,
                 request_body: bytes,
                 max_content_length: int = 10000) -> None:

        length = headers.value_for('content-length')
        if length is None:
            raise BadRequest('No content-length header found in your request.')

        try:
            content_length = int(length)
        except ValueError:
            raise BadRequest('Invalid content-length header value')

        if content_length > max_content_length:
            raise NozomiError(
                'Content too large, max: {s}'.format(
                    s=str(max_content_length)),
                HTTPStatusCode.PAYLOAD_TOO_LARGE.value)

        try:
            string_data = request_body.decode('utf-8')
        except Exception:
            raise BadRequest('Unable to decode the body of your request with t\
he UTF-8 character set. UTF-8 required.')

        content_type = headers.value_for('content-type')
        if content_type is None:
            raise BadRequest('Could not find a content-type header in your req\
uest.')

        try:
            content_type_value = content_type.lower().split(';')[0]
        except Exception:
            raise BadRequest('Unable to parse your request\'s content-type hea\
der.')

        if content_type_value == 'application/json':
            try:
                json_data = json.loads(string_data)
            except Exception:
                raise BadRequest('Unable to parse your request body as json. P\
lease check the syntax of your request body.')
            return super().__init__(raw=json_data)

        if content_type_value == 'application/xml':
            try:
                xml_data = XML.xmlstring_to_data(string_data)
            except Exception:
                raise BadRequest('Unable to parse your request body as xml. Pl\
ease check the syntax of your request body.')
            return super().__init__(raw=xml_data)

        raise BadRequest('Invalid content type. Valid content types are applic\
ation/json and application/xml only.')
    def from_headers(cls: Type[T], headers: Headers,
                     configuration: Configuration) -> Optional[T]:
        """Extract credentials from request headers"""

        session_id = headers.value_for(configuration.session_id_name)
        if session_id is None:
            return None

        api_key = headers.value_for(configuration.session_api_key_name)

        if api_key is None:
            return None

        return cls(session_id, api_key)
Beispiel #4
0
    def __init__(self,
                 session: Session,
                 configuration: Configuration,
                 existing: Optional[Headers] = None) -> None:

        assert isinstance(session, Session)
        self._debug = configuration.debug
        self._configuration = configuration
        self._session = session

        headers = Headers()
        if existing is not None:
            assert isinstance(existing, Headers)
            headers = existing

        headers.add('Set-Cookie', self._generate_session_cookie(self._debug))
        headers.add('Set-Cookie', self._generate_key_cookie(self._debug))
        headers.add(
            'Set-Cookie',
            self.generate_flag_cookie(logged_in=True,
                                      debug=configuration.debug,
                                      configuration=configuration))

        self._raw = headers.dictionary

        super().__init__(headers)
        return
Beispiel #5
0
    def derive_from_headers(
        cls: Type[T],
        available_languages: Optional[List[T]],
        headers: Headers,
        fallback_to: Optional[T] = None
    ) -> Optional[T]:

        if available_languages is None or len(available_languages) < 1:
            return fallback_to

        raw_value = headers.value_for(cls._ACCEPT_HEADER)
        accepted = AcceptLanguage.many_from_header(header=raw_value)
        priority_order = AcceptLanguage.in_priority_order(accepted)

        for acceptable_language in priority_order:
            candidate = cls.with_iso_639_1_and_variant(
                languages=available_languages,
                iso_639_1=acceptable_language.primary,
                variant_code=acceptable_language.variant,
                fallback=None
            )
            if candidate is not None:
                return candidate
            candidate = cls.with_iso_639_1(
                languages=available_languages,
                iso_639_1=acceptable_language.primary,
                fallback=None
            )
            if candidate is not None:
                return candidate
            continue

        return fallback_to
Beispiel #6
0
 def matches_headers(self, headers: Headers) -> bool:
     """
     Return true if the supplied headers authenticate a request as
     coming from an internal application.
     """
     credential = headers.value_for(self._header_key)
     if credential is None:
         return False
     return self.matches(credential)
Beispiel #7
0
    def flag_signout(cls: Type[T],
                     debug: bool,
                     configuration: Configuration,
                     existing_headers: Optional[Headers] = None) -> Headers:

        existing = existing_headers

        headers = Headers()
        if existing is not None:
            assert isinstance(existing, Headers)
            headers = existing

        headers.add(
            'Set-Cookie',
            cls.generate_flag_cookie(logged_in=False,
                                     debug=debug,
                                     configuration=configuration))

        return headers
Beispiel #8
0
    def from_headers(
        cls: Type[T],
        headers: Headers,
        fallback_to: str = 'Unavailable'
    ) -> T:

        body = headers.value_for('User-Agent')
        if body is None:
            return cls(body=fallback_to)

        return cls(body=body)
    def from_headers(cls: Type[T],
                     internal_key: InternalKey,
                     headers: Headers,
                     datastore: Datastore,
                     configuration: Configuration,
                     agent_id_type: Optional[Type] = None) -> T:

        assert isinstance(internal_key, InternalKey)
        assert isinstance(headers, Headers)

        if not internal_key.matches_headers(headers):
            raise NotAuthorised

        forwarded_agent_id = headers.value_for(
            configuration.forwarded_agent_header)
        if forwarded_agent_id is None:
            raise NotAuthorised

        return cls(forwarded_agent_id, agent_id_type=agent_id_type)
    def from_headers(cls: Type[T],
                     headers: Headers,
                     boundary_ip_header: str,
                     debug: bool = False,
                     debug_address: Optional[str] = None) -> T:

        if debug is True:
            assert isinstance(debug_address, str)
            return cls(debug_address)

        addresses = headers.getlist(boundary_ip_header)

        # We presume that headers are being set by HAProxy. If these checks
        # fail, HAProxy is not configured properly.

        if len(addresses) != 1:
            raise NozomiError('Internal error', HTTPStatusCode.INTERNAL_ERROR)

        if len(addresses[0].split(',')) != 1:
            raise NozomiError('Internal error', HTTPStatusCode.INTERNAL_ERROR)

        return cls(addresses[0])
    def from_headers(cls: Type[T], headers: Headers) -> Optional[T]:
        raw = headers.get('accept-language')
        if raw is None:
            return None

        return cls.from_header_item(raw)
Beispiel #12
0
 def apply_to_headers(self, headers: Headers) -> Headers:
     """Return Headers with CORS policy applied"""
     headers.add(self._HEADER_KEY, self.allowed_origin)
     return headers
Beispiel #13
0
 def from_headers(cls: Type[T], headers: Headers) -> Optional[T]:
     """Return Cookies parsed from request headers"""
     raw_cookies = headers.value_for('Cookie')
     if raw_cookies is None:
         return None
     return cls(raw_cookies)
 def apply_to_headers(self, headers: Headers) -> Headers:
     """Apply server name to headers and return them"""
     headers.add('Server', self._configuration.server_name)
     return headers
Beispiel #15
0
 def simulate_cookie_headers(self, debug: bool = True) -> Headers:
     headers = Headers()
     headers.add('Cookie', self.simulate_cookie(debug))
     return headers