1# -*- coding: utf-8 -*- 
    2""" 
    3oauthlib.oauth1.rfc5849.endpoints.request_token 
    4~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    5 
    6This module is an implementation of the request token provider logic of 
    7OAuth 1.0 RFC 5849. It validates the correctness of request token requests, 
    8creates and persists tokens as well as create the proper response to be 
    9returned to the client. 
    10""" 
    11import logging 
    12 
    13from oauthlib.common import urlencode 
    14 
    15from .. import errors 
    16from .base import BaseEndpoint 
    17 
    18log = logging.getLogger(__name__) 
    19 
    20 
    21class RequestTokenEndpoint(BaseEndpoint): 
    22 
    23    """An endpoint responsible for providing OAuth 1 request tokens. 
    24 
    25    Typical use is to instantiate with a request validator and invoke the 
    26    ``create_request_token_response`` from a view function. The tuple returned 
    27    has all information necessary (body, status, headers) to quickly form 
    28    and return a proper response. See :doc:`/oauth1/validator` for details on which 
    29    validator methods to implement for this endpoint. 
    30    """ 
    31 
    32    def create_request_token(self, request, credentials): 
    33        """Create and save a new request token. 
    34 
    35        :param request: OAuthlib request. 
    36        :type request: oauthlib.common.Request 
    37        :param credentials: A dict of extra token credentials. 
    38        :returns: The token as an urlencoded string. 
    39        """ 
    40        token = { 
    41            'oauth_token': self.token_generator(), 
    42            'oauth_token_secret': self.token_generator(), 
    43            'oauth_callback_confirmed': 'true' 
    44        } 
    45        token.update(credentials) 
    46        self.request_validator.save_request_token(token, request) 
    47        return urlencode(token.items()) 
    48 
    49    def create_request_token_response(self, uri, http_method='GET', body=None, 
    50                                      headers=None, credentials=None): 
    51        """Create a request token response, with a new request token if valid. 
    52 
    53        :param uri: The full URI of the token request. 
    54        :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. 
    55        :param body: The request body as a string. 
    56        :param headers: The request headers as a dict. 
    57        :param credentials: A list of extra credentials to include in the token. 
    58        :returns: A tuple of 3 elements. 
    59                  1. A dict of headers to set on the response. 
    60                  2. The response body as a string. 
    61                  3. The response status code as an integer. 
    62 
    63        An example of a valid request:: 
    64 
    65            >>> from your_validator import your_validator 
    66            >>> from oauthlib.oauth1 import RequestTokenEndpoint 
    67            >>> endpoint = RequestTokenEndpoint(your_validator) 
    68            >>> h, b, s = endpoint.create_request_token_response( 
    69            ...     'https://your.provider/request_token?foo=bar', 
    70            ...     headers={ 
    71            ...         'Authorization': 'OAuth realm=movies user, oauth_....' 
    72            ...     }, 
    73            ...     credentials={ 
    74            ...         'my_specific': 'argument', 
    75            ...     }) 
    76            >>> h 
    77            {'Content-Type': 'application/x-www-form-urlencoded'} 
    78            >>> b 
    79            'oauth_token=lsdkfol23w54jlksdef&oauth_token_secret=qwe089234lkjsdf&oauth_callback_confirmed=true&my_specific=argument' 
    80            >>> s 
    81            200 
    82 
    83        An response to invalid request would have a different body and status:: 
    84 
    85            >>> b 
    86            'error=invalid_request&description=missing+callback+uri' 
    87            >>> s 
    88            400 
    89 
    90        The same goes for an an unauthorized request: 
    91 
    92            >>> b 
    93            '' 
    94            >>> s 
    95            401 
    96        """ 
    97        resp_headers = {'Content-Type': 'application/x-www-form-urlencoded'} 
    98        try: 
    99            request = self._create_request(uri, http_method, body, headers) 
    100            valid, processed_request = self.validate_request_token_request( 
    101                request) 
    102            if valid: 
    103                token = self.create_request_token(request, credentials or {}) 
    104                return resp_headers, token, 200 
    105            else: 
    106                return {}, None, 401 
    107        except errors.OAuth1Error as e: 
    108            return resp_headers, e.urlencoded, e.status_code 
    109 
    110    def validate_request_token_request(self, request): 
    111        """Validate a request token request. 
    112 
    113        :param request: OAuthlib request. 
    114        :type request: oauthlib.common.Request 
    115        :raises: OAuth1Error if the request is invalid. 
    116        :returns: A tuple of 2 elements. 
    117                  1. The validation result (True or False). 
    118                  2. The request object. 
    119        """ 
    120        self._check_transport_security(request) 
    121        self._check_mandatory_parameters(request) 
    122 
    123        if request.realm: 
    124            request.realms = request.realm.split(' ') 
    125        else: 
    126            request.realms = self.request_validator.get_default_realms( 
    127                request.client_key, request) 
    128        if not self.request_validator.check_realms(request.realms): 
    129            raise errors.InvalidRequestError( 
    130                description='Invalid realm {}. Allowed are {!r}.'.format( 
    131                    request.realms, self.request_validator.realms)) 
    132 
    133        if not request.redirect_uri: 
    134            raise errors.InvalidRequestError( 
    135                description='Missing callback URI.') 
    136 
    137        if not self.request_validator.validate_timestamp_and_nonce( 
    138                request.client_key, request.timestamp, request.nonce, request, 
    139                request_token=request.resource_owner_key): 
    140            return False, request 
    141 
    142        # The server SHOULD return a 401 (Unauthorized) status code when 
    143        # receiving a request with invalid client credentials. 
    144        # Note: This is postponed in order to avoid timing attacks, instead 
    145        # a dummy client is assigned and used to maintain near constant 
    146        # time request verification. 
    147        # 
    148        # Note that early exit would enable client enumeration 
    149        valid_client = self.request_validator.validate_client_key( 
    150            request.client_key, request) 
    151        if not valid_client: 
    152            request.client_key = self.request_validator.dummy_client 
    153 
    154        # Note that `realm`_ is only used in authorization headers and how 
    155        # it should be interpreted is not included in the OAuth spec. 
    156        # However they could be seen as a scope or realm to which the 
    157        # client has access and as such every client should be checked 
    158        # to ensure it is authorized access to that scope or realm. 
    159        # .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2 
    160        # 
    161        # Note that early exit would enable client realm access enumeration. 
    162        # 
    163        # The require_realm indicates this is the first step in the OAuth 
    164        # workflow where a client requests access to a specific realm. 
    165        # This first step (obtaining request token) need not require a realm 
    166        # and can then be identified by checking the require_resource_owner 
    167        # flag and absence of realm. 
    168        # 
    169        # Clients obtaining an access token will not supply a realm and it will 
    170        # not be checked. Instead the previously requested realm should be 
    171        # transferred from the request token to the access token. 
    172        # 
    173        # Access to protected resources will always validate the realm but note 
    174        # that the realm is now tied to the access token and not provided by 
    175        # the client. 
    176        valid_realm = self.request_validator.validate_requested_realms( 
    177            request.client_key, request.realms, request) 
    178 
    179        # Callback is normally never required, except for requests for 
    180        # a Temporary Credential as described in `Section 2.1`_ 
    181        # .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1 
    182        valid_redirect = self.request_validator.validate_redirect_uri( 
    183            request.client_key, request.redirect_uri, request) 
    184        if not request.redirect_uri: 
    185            raise NotImplementedError('Redirect URI must either be provided ' 
    186                                      'or set to a default during validation.') 
    187 
    188        valid_signature = self._check_signature(request) 
    189 
    190        # log the results to the validator_log 
    191        # this lets us handle internal reporting and analysis 
    192        request.validator_log['client'] = valid_client 
    193        request.validator_log['realm'] = valid_realm 
    194        request.validator_log['callback'] = valid_redirect 
    195        request.validator_log['signature'] = valid_signature 
    196 
    197        # We delay checking validity until the very end, using dummy values for 
    198        # calculations and fetching secrets/keys to ensure the flow of every 
    199        # request remains almost identical regardless of whether valid values 
    200        # have been supplied. This ensures near constant time execution and 
    201        # prevents malicious users from guessing sensitive information 
    202        v = all((valid_client, valid_realm, valid_redirect, valid_signature)) 
    203        if not v: 
    204            log.info("[Failure] request verification failed.") 
    205            log.info("Valid client: %s.", valid_client) 
    206            log.info("Valid realm: %s.", valid_realm) 
    207            log.info("Valid callback: %s.", valid_redirect) 
    208            log.info("Valid signature: %s.", valid_signature) 
    209        return v, request