sts.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # Copyright 2020 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """OAuth 2.0 Token Exchange Spec.
  15. This module defines a token exchange utility based on the `OAuth 2.0 Token
  16. Exchange`_ spec. This will be mainly used to exchange external credentials
  17. for GCP access tokens in workload identity pools to access Google APIs.
  18. The implementation will support various types of client authentication as
  19. allowed in the spec.
  20. A deviation on the spec will be for additional Google specific options that
  21. cannot be easily mapped to parameters defined in the RFC.
  22. The returned dictionary response will be based on the `rfc8693 section 2.2.1`_
  23. spec JSON response.
  24. .. _OAuth 2.0 Token Exchange: https://tools.ietf.org/html/rfc8693
  25. .. _rfc8693 section 2.2.1: https://tools.ietf.org/html/rfc8693#section-2.2.1
  26. """
  27. import json
  28. from six.moves import http_client
  29. from six.moves import urllib
  30. from google.oauth2 import utils
  31. _URLENCODED_HEADERS = {"Content-Type": "application/x-www-form-urlencoded"}
  32. class Client(utils.OAuthClientAuthHandler):
  33. """Implements the OAuth 2.0 token exchange spec based on
  34. https://tools.ietf.org/html/rfc8693.
  35. """
  36. def __init__(self, token_exchange_endpoint, client_authentication=None):
  37. """Initializes an STS client instance.
  38. Args:
  39. token_exchange_endpoint (str): The token exchange endpoint.
  40. client_authentication (Optional(google.oauth2.oauth2_utils.ClientAuthentication)):
  41. The optional OAuth client authentication credentials if available.
  42. """
  43. super(Client, self).__init__(client_authentication)
  44. self._token_exchange_endpoint = token_exchange_endpoint
  45. def exchange_token(
  46. self,
  47. request,
  48. grant_type,
  49. subject_token,
  50. subject_token_type,
  51. resource=None,
  52. audience=None,
  53. scopes=None,
  54. requested_token_type=None,
  55. actor_token=None,
  56. actor_token_type=None,
  57. additional_options=None,
  58. additional_headers=None,
  59. ):
  60. """Exchanges the provided token for another type of token based on the
  61. rfc8693 spec.
  62. Args:
  63. request (google.auth.transport.Request): A callable used to make
  64. HTTP requests.
  65. grant_type (str): The OAuth 2.0 token exchange grant type.
  66. subject_token (str): The OAuth 2.0 token exchange subject token.
  67. subject_token_type (str): The OAuth 2.0 token exchange subject token type.
  68. resource (Optional[str]): The optional OAuth 2.0 token exchange resource field.
  69. audience (Optional[str]): The optional OAuth 2.0 token exchange audience field.
  70. scopes (Optional[Sequence[str]]): The optional list of scopes to use.
  71. requested_token_type (Optional[str]): The optional OAuth 2.0 token exchange requested
  72. token type.
  73. actor_token (Optional[str]): The optional OAuth 2.0 token exchange actor token.
  74. actor_token_type (Optional[str]): The optional OAuth 2.0 token exchange actor token type.
  75. additional_options (Optional[Mapping[str, str]]): The optional additional
  76. non-standard Google specific options.
  77. additional_headers (Optional[Mapping[str, str]]): The optional additional
  78. headers to pass to the token exchange endpoint.
  79. Returns:
  80. Mapping[str, str]: The token exchange JSON-decoded response data containing
  81. the requested token and its expiration time.
  82. Raises:
  83. google.auth.exceptions.OAuthError: If the token endpoint returned
  84. an error.
  85. """
  86. # Initialize request headers.
  87. headers = _URLENCODED_HEADERS.copy()
  88. # Inject additional headers.
  89. if additional_headers:
  90. for k, v in dict(additional_headers).items():
  91. headers[k] = v
  92. # Initialize request body.
  93. request_body = {
  94. "grant_type": grant_type,
  95. "resource": resource,
  96. "audience": audience,
  97. "scope": " ".join(scopes or []),
  98. "requested_token_type": requested_token_type,
  99. "subject_token": subject_token,
  100. "subject_token_type": subject_token_type,
  101. "actor_token": actor_token,
  102. "actor_token_type": actor_token_type,
  103. "options": None,
  104. }
  105. # Add additional non-standard options.
  106. if additional_options:
  107. request_body["options"] = urllib.parse.quote(json.dumps(additional_options))
  108. # Remove empty fields in request body.
  109. for k, v in dict(request_body).items():
  110. if v is None or v == "":
  111. del request_body[k]
  112. # Apply OAuth client authentication.
  113. self.apply_client_authentication_options(headers, request_body)
  114. # Execute request.
  115. response = request(
  116. url=self._token_exchange_endpoint,
  117. method="POST",
  118. headers=headers,
  119. body=urllib.parse.urlencode(request_body).encode("utf-8"),
  120. )
  121. response_body = (
  122. response.data.decode("utf-8")
  123. if hasattr(response.data, "decode")
  124. else response.data
  125. )
  126. # If non-200 response received, translate to OAuthError exception.
  127. if response.status != http_client.OK:
  128. utils.handle_error_response(response_body)
  129. response_data = json.loads(response_body)
  130. # Return successful response.
  131. return response_data