651a87cf3f30ca65c10d533b86f83dedb73cbec5
[twitter-api-cdsw] / oauthlib / oauth1 / rfc5849 / endpoints / resource.py
1 # -*- coding: utf-8 -*-
2 """
3 oauthlib.oauth1.rfc5849.endpoints.resource
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
6 This module is an implementation of the resource protection provider logic of
7 OAuth 1.0 RFC 5849.
8 """
9 from __future__ import absolute_import, unicode_literals
10
11 import logging
12
13 from .base import BaseEndpoint
14 from .. import errors
15
16 log = logging.getLogger(__name__)
17
18
19 class ResourceEndpoint(BaseEndpoint):
20
21     """An endpoint responsible for protecting resources.
22
23     Typical use is to instantiate with a request validator and invoke the
24     ``validate_protected_resource_request`` in a decorator around a view
25     function. If the request is valid, invoke and return the response of the
26     view. If invalid create and return an error response directly from the
27     decorator.
28
29     See :doc:`/oauth1/validator` for details on which validator methods to implement
30     for this endpoint.
31
32     An example decorator::
33
34         from functools import wraps
35         from your_validator import your_validator
36         from oauthlib.oauth1 import ResourceEndpoint
37         endpoint = ResourceEndpoint(your_validator)
38
39         def require_oauth(realms=None):
40             def decorator(f):
41                 @wraps(f)
42                 def wrapper(request, *args, **kwargs):
43                     v, r = provider.validate_protected_resource_request(
44                             request.url,
45                             http_method=request.method,
46                             body=request.data,
47                             headers=request.headers,
48                             realms=realms or [])
49                     if v:
50                         return f(*args, **kwargs)
51                     else:
52                         return abort(403)
53     """
54
55     def validate_protected_resource_request(self, uri, http_method='GET',
56                                             body=None, headers=None, realms=None):
57         """Create a request token response, with a new request token if valid.
58
59         :param uri: The full URI of the token request.
60         :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
61         :param body: The request body as a string.
62         :param headers: The request headers as a dict.
63         :param realms: A list of realms the resource is protected under.
64                        This will be supplied to the ``validate_realms``
65                        method of the request validator.
66         :returns: A tuple of 2 elements.
67                   1. True if valid, False otherwise.
68                   2. An oauthlib.common.Request object.
69         """
70         try:
71             request = self._create_request(uri, http_method, body, headers)
72         except errors.OAuth1Error:
73             return False, None
74
75         try:
76             self._check_transport_security(request)
77             self._check_mandatory_parameters(request)
78         except errors.OAuth1Error:
79             return False, request
80
81         if not request.resource_owner_key:
82             return False, request
83
84         if not self.request_validator.check_access_token(
85                 request.resource_owner_key):
86             return False, request
87
88         if not self.request_validator.validate_timestamp_and_nonce(
89                 request.client_key, request.timestamp, request.nonce, request,
90                 access_token=request.resource_owner_key):
91             return False, request
92
93         # The server SHOULD return a 401 (Unauthorized) status code when
94         # receiving a request with invalid client credentials.
95         # Note: This is postponed in order to avoid timing attacks, instead
96         # a dummy client is assigned and used to maintain near constant
97         # time request verification.
98         #
99         # Note that early exit would enable client enumeration
100         valid_client = self.request_validator.validate_client_key(
101             request.client_key, request)
102         if not valid_client:
103             request.client_key = self.request_validator.dummy_client
104
105         # The server SHOULD return a 401 (Unauthorized) status code when
106         # receiving a request with invalid or expired token.
107         # Note: This is postponed in order to avoid timing attacks, instead
108         # a dummy token is assigned and used to maintain near constant
109         # time request verification.
110         #
111         # Note that early exit would enable resource owner enumeration
112         valid_resource_owner = self.request_validator.validate_access_token(
113             request.client_key, request.resource_owner_key, request)
114         if not valid_resource_owner:
115             request.resource_owner_key = self.request_validator.dummy_access_token
116
117         # Note that `realm`_ is only used in authorization headers and how
118         # it should be interepreted is not included in the OAuth spec.
119         # However they could be seen as a scope or realm to which the
120         # client has access and as such every client should be checked
121         # to ensure it is authorized access to that scope or realm.
122         # .. _`realm`: http://tools.ietf.org/html/rfc2617#section-1.2
123         #
124         # Note that early exit would enable client realm access enumeration.
125         #
126         # The require_realm indicates this is the first step in the OAuth
127         # workflow where a client requests access to a specific realm.
128         # This first step (obtaining request token) need not require a realm
129         # and can then be identified by checking the require_resource_owner
130         # flag and abscence of realm.
131         #
132         # Clients obtaining an access token will not supply a realm and it will
133         # not be checked. Instead the previously requested realm should be
134         # transferred from the request token to the access token.
135         #
136         # Access to protected resources will always validate the realm but note
137         # that the realm is now tied to the access token and not provided by
138         # the client.
139         valid_realm = self.request_validator.validate_realms(request.client_key,
140                                                              request.resource_owner_key, request, uri=request.uri,
141                                                              realms=realms)
142
143         valid_signature = self._check_signature(request)
144
145         # We delay checking validity until the very end, using dummy values for
146         # calculations and fetching secrets/keys to ensure the flow of every
147         # request remains almost identical regardless of whether valid values
148         # have been supplied. This ensures near constant time execution and
149         # prevents malicious users from guessing sensitive information
150         v = all((valid_client, valid_resource_owner, valid_realm,
151                  valid_signature))
152         if not v:
153             log.info("[Failure] request verification failed.")
154             log.info("Valid client: %s", valid_client)
155             log.info("Valid token: %s", valid_resource_owner)
156             log.info("Valid realm: %s", valid_realm)
157             log.info("Valid signature: %s", valid_signature)
158         return v, request

Benjamin Mako Hill || Want to submit a patch?