resource.py 7.2 KB

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