downscoped.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. # Copyright 2021 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. """Downscoping with Credential Access Boundaries
  15. This module provides the ability to downscope credentials using
  16. `Downscoping with Credential Access Boundaries`_. This is useful to restrict the
  17. Identity and Access Management (IAM) permissions that a short-lived credential
  18. can use.
  19. To downscope permissions of a source credential, a Credential Access Boundary
  20. that specifies which resources the new credential can access, as well as
  21. an upper bound on the permissions that are available on each resource, has to
  22. be defined. A downscoped credential can then be instantiated using the source
  23. credential and the Credential Access Boundary.
  24. The common pattern of usage is to have a token broker with elevated access
  25. generate these downscoped credentials from higher access source credentials and
  26. pass the downscoped short-lived access tokens to a token consumer via some
  27. secure authenticated channel for limited access to Google Cloud Storage
  28. resources.
  29. For example, a token broker can be set up on a server in a private network.
  30. Various workloads (token consumers) in the same network will send authenticated
  31. requests to that broker for downscoped tokens to access or modify specific google
  32. cloud storage buckets.
  33. The broker will instantiate downscoped credentials instances that can be used to
  34. generate short lived downscoped access tokens that can be passed to the token
  35. consumer. These downscoped access tokens can be injected by the consumer into
  36. google.oauth2.Credentials and used to initialize a storage client instance to
  37. access Google Cloud Storage resources with restricted access.
  38. Note: Only Cloud Storage supports Credential Access Boundaries. Other Google
  39. Cloud services do not support this feature.
  40. .. _Downscoping with Credential Access Boundaries: https://cloud.google.com/iam/docs/downscoping-short-lived-credentials
  41. """
  42. import datetime
  43. import six
  44. from google.auth import _helpers
  45. from google.auth import credentials
  46. from google.oauth2 import sts
  47. # The maximum number of access boundary rules a Credential Access Boundary can
  48. # contain.
  49. _MAX_ACCESS_BOUNDARY_RULES_COUNT = 10
  50. # The token exchange grant_type used for exchanging credentials.
  51. _STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
  52. # The token exchange requested_token_type. This is always an access_token.
  53. _STS_REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
  54. # The STS token URL used to exchanged a short lived access token for a downscoped one.
  55. _STS_TOKEN_URL = "https://sts.googleapis.com/v1/token"
  56. # The subject token type to use when exchanging a short lived access token for a
  57. # downscoped token.
  58. _STS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
  59. class CredentialAccessBoundary(object):
  60. """Defines a Credential Access Boundary which contains a list of access boundary
  61. rules. Each rule contains information on the resource that the rule applies to,
  62. the upper bound of the permissions that are available on that resource and an
  63. optional condition to further restrict permissions.
  64. """
  65. def __init__(self, rules=[]):
  66. """Instantiates a Credential Access Boundary. A Credential Access Boundary
  67. can contain up to 10 access boundary rules.
  68. Args:
  69. rules (Sequence[google.auth.downscoped.AccessBoundaryRule]): The list of
  70. access boundary rules limiting the access that a downscoped credential
  71. will have.
  72. Raises:
  73. TypeError: If any of the rules are not a valid type.
  74. ValueError: If the provided rules exceed the maximum allowed.
  75. """
  76. self.rules = rules
  77. @property
  78. def rules(self):
  79. """Returns the list of access boundary rules defined on the Credential
  80. Access Boundary.
  81. Returns:
  82. Tuple[google.auth.downscoped.AccessBoundaryRule, ...]: The list of access
  83. boundary rules defined on the Credential Access Boundary. These are returned
  84. as an immutable tuple to prevent modification.
  85. """
  86. return tuple(self._rules)
  87. @rules.setter
  88. def rules(self, value):
  89. """Updates the current rules on the Credential Access Boundary. This will overwrite
  90. the existing set of rules.
  91. Args:
  92. value (Sequence[google.auth.downscoped.AccessBoundaryRule]): The list of
  93. access boundary rules limiting the access that a downscoped credential
  94. will have.
  95. Raises:
  96. TypeError: If any of the rules are not a valid type.
  97. ValueError: If the provided rules exceed the maximum allowed.
  98. """
  99. if len(value) > _MAX_ACCESS_BOUNDARY_RULES_COUNT:
  100. raise ValueError(
  101. "Credential access boundary rules can have a maximum of {} rules.".format(
  102. _MAX_ACCESS_BOUNDARY_RULES_COUNT
  103. )
  104. )
  105. for access_boundary_rule in value:
  106. if not isinstance(access_boundary_rule, AccessBoundaryRule):
  107. raise TypeError(
  108. "List of rules provided do not contain a valid 'google.auth.downscoped.AccessBoundaryRule'."
  109. )
  110. # Make a copy of the original list.
  111. self._rules = list(value)
  112. def add_rule(self, rule):
  113. """Adds a single access boundary rule to the existing rules.
  114. Args:
  115. rule (google.auth.downscoped.AccessBoundaryRule): The access boundary rule,
  116. limiting the access that a downscoped credential will have, to be added to
  117. the existing rules.
  118. Raises:
  119. TypeError: If any of the rules are not a valid type.
  120. ValueError: If the provided rules exceed the maximum allowed.
  121. """
  122. if len(self.rules) == _MAX_ACCESS_BOUNDARY_RULES_COUNT:
  123. raise ValueError(
  124. "Credential access boundary rules can have a maximum of {} rules.".format(
  125. _MAX_ACCESS_BOUNDARY_RULES_COUNT
  126. )
  127. )
  128. if not isinstance(rule, AccessBoundaryRule):
  129. raise TypeError(
  130. "The provided rule does not contain a valid 'google.auth.downscoped.AccessBoundaryRule'."
  131. )
  132. self._rules.append(rule)
  133. def to_json(self):
  134. """Generates the dictionary representation of the Credential Access Boundary.
  135. This uses the format expected by the Security Token Service API as documented in
  136. `Defining a Credential Access Boundary`_.
  137. .. _Defining a Credential Access Boundary:
  138. https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary
  139. Returns:
  140. Mapping: Credential Access Boundary Rule represented in a dictionary object.
  141. """
  142. rules = []
  143. for access_boundary_rule in self.rules:
  144. rules.append(access_boundary_rule.to_json())
  145. return {"accessBoundary": {"accessBoundaryRules": rules}}
  146. class AccessBoundaryRule(object):
  147. """Defines an access boundary rule which contains information on the resource that
  148. the rule applies to, the upper bound of the permissions that are available on that
  149. resource and an optional condition to further restrict permissions.
  150. """
  151. def __init__(
  152. self, available_resource, available_permissions, availability_condition=None
  153. ):
  154. """Instantiates a single access boundary rule.
  155. Args:
  156. available_resource (str): The full resource name of the Cloud Storage bucket
  157. that the rule applies to. Use the format
  158. "//storage.googleapis.com/projects/_/buckets/bucket-name".
  159. available_permissions (Sequence[str]): A list defining the upper bound that
  160. the downscoped token will have on the available permissions for the
  161. resource. Each value is the identifier for an IAM predefined role or
  162. custom role, with the prefix "inRole:". For example:
  163. "inRole:roles/storage.objectViewer".
  164. Only the permissions in these roles will be available.
  165. availability_condition (Optional[google.auth.downscoped.AvailabilityCondition]):
  166. Optional condition that restricts the availability of permissions to
  167. specific Cloud Storage objects.
  168. Raises:
  169. TypeError: If any of the parameters are not of the expected types.
  170. ValueError: If any of the parameters are not of the expected values.
  171. """
  172. self.available_resource = available_resource
  173. self.available_permissions = available_permissions
  174. self.availability_condition = availability_condition
  175. @property
  176. def available_resource(self):
  177. """Returns the current available resource.
  178. Returns:
  179. str: The current available resource.
  180. """
  181. return self._available_resource
  182. @available_resource.setter
  183. def available_resource(self, value):
  184. """Updates the current available resource.
  185. Args:
  186. value (str): The updated value of the available resource.
  187. Raises:
  188. TypeError: If the value is not a string.
  189. """
  190. if not isinstance(value, six.string_types):
  191. raise TypeError("The provided available_resource is not a string.")
  192. self._available_resource = value
  193. @property
  194. def available_permissions(self):
  195. """Returns the current available permissions.
  196. Returns:
  197. Tuple[str, ...]: The current available permissions. These are returned
  198. as an immutable tuple to prevent modification.
  199. """
  200. return tuple(self._available_permissions)
  201. @available_permissions.setter
  202. def available_permissions(self, value):
  203. """Updates the current available permissions.
  204. Args:
  205. value (Sequence[str]): The updated value of the available permissions.
  206. Raises:
  207. TypeError: If the value is not a list of strings.
  208. ValueError: If the value is not valid.
  209. """
  210. for available_permission in value:
  211. if not isinstance(available_permission, six.string_types):
  212. raise TypeError(
  213. "Provided available_permissions are not a list of strings."
  214. )
  215. if available_permission.find("inRole:") != 0:
  216. raise ValueError(
  217. "available_permissions must be prefixed with 'inRole:'."
  218. )
  219. # Make a copy of the original list.
  220. self._available_permissions = list(value)
  221. @property
  222. def availability_condition(self):
  223. """Returns the current availability condition.
  224. Returns:
  225. Optional[google.auth.downscoped.AvailabilityCondition]: The current
  226. availability condition.
  227. """
  228. return self._availability_condition
  229. @availability_condition.setter
  230. def availability_condition(self, value):
  231. """Updates the current availability condition.
  232. Args:
  233. value (Optional[google.auth.downscoped.AvailabilityCondition]): The updated
  234. value of the availability condition.
  235. Raises:
  236. TypeError: If the value is not of type google.auth.downscoped.AvailabilityCondition
  237. or None.
  238. """
  239. if not isinstance(value, AvailabilityCondition) and value is not None:
  240. raise TypeError(
  241. "The provided availability_condition is not a 'google.auth.downscoped.AvailabilityCondition' or None."
  242. )
  243. self._availability_condition = value
  244. def to_json(self):
  245. """Generates the dictionary representation of the access boundary rule.
  246. This uses the format expected by the Security Token Service API as documented in
  247. `Defining a Credential Access Boundary`_.
  248. .. _Defining a Credential Access Boundary:
  249. https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary
  250. Returns:
  251. Mapping: The access boundary rule represented in a dictionary object.
  252. """
  253. json = {
  254. "availablePermissions": list(self.available_permissions),
  255. "availableResource": self.available_resource,
  256. }
  257. if self.availability_condition:
  258. json["availabilityCondition"] = self.availability_condition.to_json()
  259. return json
  260. class AvailabilityCondition(object):
  261. """An optional condition that can be used as part of a Credential Access Boundary
  262. to further restrict permissions."""
  263. def __init__(self, expression, title=None, description=None):
  264. """Instantiates an availability condition using the provided expression and
  265. optional title or description.
  266. Args:
  267. expression (str): A condition expression that specifies the Cloud Storage
  268. objects where permissions are available. For example, this expression
  269. makes permissions available for objects whose name starts with "customer-a":
  270. "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a')"
  271. title (Optional[str]): An optional short string that identifies the purpose of
  272. the condition.
  273. description (Optional[str]): Optional details about the purpose of the condition.
  274. Raises:
  275. TypeError: If any of the parameters are not of the expected types.
  276. ValueError: If any of the parameters are not of the expected values.
  277. """
  278. self.expression = expression
  279. self.title = title
  280. self.description = description
  281. @property
  282. def expression(self):
  283. """Returns the current condition expression.
  284. Returns:
  285. str: The current conditon expression.
  286. """
  287. return self._expression
  288. @expression.setter
  289. def expression(self, value):
  290. """Updates the current condition expression.
  291. Args:
  292. value (str): The updated value of the condition expression.
  293. Raises:
  294. TypeError: If the value is not of type string.
  295. """
  296. if not isinstance(value, six.string_types):
  297. raise TypeError("The provided expression is not a string.")
  298. self._expression = value
  299. @property
  300. def title(self):
  301. """Returns the current title.
  302. Returns:
  303. Optional[str]: The current title.
  304. """
  305. return self._title
  306. @title.setter
  307. def title(self, value):
  308. """Updates the current title.
  309. Args:
  310. value (Optional[str]): The updated value of the title.
  311. Raises:
  312. TypeError: If the value is not of type string or None.
  313. """
  314. if not isinstance(value, six.string_types) and value is not None:
  315. raise TypeError("The provided title is not a string or None.")
  316. self._title = value
  317. @property
  318. def description(self):
  319. """Returns the current description.
  320. Returns:
  321. Optional[str]: The current description.
  322. """
  323. return self._description
  324. @description.setter
  325. def description(self, value):
  326. """Updates the current description.
  327. Args:
  328. value (Optional[str]): The updated value of the description.
  329. Raises:
  330. TypeError: If the value is not of type string or None.
  331. """
  332. if not isinstance(value, six.string_types) and value is not None:
  333. raise TypeError("The provided description is not a string or None.")
  334. self._description = value
  335. def to_json(self):
  336. """Generates the dictionary representation of the availability condition.
  337. This uses the format expected by the Security Token Service API as documented in
  338. `Defining a Credential Access Boundary`_.
  339. .. _Defining a Credential Access Boundary:
  340. https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary
  341. Returns:
  342. Mapping[str, str]: The availability condition represented in a dictionary
  343. object.
  344. """
  345. json = {"expression": self.expression}
  346. if self.title:
  347. json["title"] = self.title
  348. if self.description:
  349. json["description"] = self.description
  350. return json
  351. class Credentials(credentials.CredentialsWithQuotaProject):
  352. """Defines a set of Google credentials that are downscoped from an existing set
  353. of Google OAuth2 credentials. This is useful to restrict the Identity and Access
  354. Management (IAM) permissions that a short-lived credential can use.
  355. The common pattern of usage is to have a token broker with elevated access
  356. generate these downscoped credentials from higher access source credentials and
  357. pass the downscoped short-lived access tokens to a token consumer via some
  358. secure authenticated channel for limited access to Google Cloud Storage
  359. resources.
  360. """
  361. def __init__(
  362. self, source_credentials, credential_access_boundary, quota_project_id=None
  363. ):
  364. """Instantiates a downscoped credentials object using the provided source
  365. credentials and credential access boundary rules.
  366. To downscope permissions of a source credential, a Credential Access Boundary
  367. that specifies which resources the new credential can access, as well as an
  368. upper bound on the permissions that are available on each resource, has to be
  369. defined. A downscoped credential can then be instantiated using the source
  370. credential and the Credential Access Boundary.
  371. Args:
  372. source_credentials (google.auth.credentials.Credentials): The source credentials
  373. to be downscoped based on the provided Credential Access Boundary rules.
  374. credential_access_boundary (google.auth.downscoped.CredentialAccessBoundary):
  375. The Credential Access Boundary which contains a list of access boundary
  376. rules. Each rule contains information on the resource that the rule applies to,
  377. the upper bound of the permissions that are available on that resource and an
  378. optional condition to further restrict permissions.
  379. quota_project_id (Optional[str]): The optional quota project ID.
  380. Raises:
  381. google.auth.exceptions.RefreshError: If the source credentials
  382. return an error on token refresh.
  383. google.auth.exceptions.OAuthError: If the STS token exchange
  384. endpoint returned an error during downscoped token generation.
  385. """
  386. super(Credentials, self).__init__()
  387. self._source_credentials = source_credentials
  388. self._credential_access_boundary = credential_access_boundary
  389. self._quota_project_id = quota_project_id
  390. self._sts_client = sts.Client(_STS_TOKEN_URL)
  391. @_helpers.copy_docstring(credentials.Credentials)
  392. def refresh(self, request):
  393. # Generate an access token from the source credentials.
  394. self._source_credentials.refresh(request)
  395. now = _helpers.utcnow()
  396. # Exchange the access token for a downscoped access token.
  397. response_data = self._sts_client.exchange_token(
  398. request=request,
  399. grant_type=_STS_GRANT_TYPE,
  400. subject_token=self._source_credentials.token,
  401. subject_token_type=_STS_SUBJECT_TOKEN_TYPE,
  402. requested_token_type=_STS_REQUESTED_TOKEN_TYPE,
  403. additional_options=self._credential_access_boundary.to_json(),
  404. )
  405. self.token = response_data.get("access_token")
  406. # For downscoping CAB flow, the STS endpoint may not return the expiration
  407. # field for some flows. The generated downscoped token should always have
  408. # the same expiration time as the source credentials. When no expires_in
  409. # field is returned in the response, we can just get the expiration time
  410. # from the source credentials.
  411. if response_data.get("expires_in"):
  412. lifetime = datetime.timedelta(seconds=response_data.get("expires_in"))
  413. self.expiry = now + lifetime
  414. else:
  415. self.expiry = self._source_credentials.expiry
  416. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  417. def with_quota_project(self, quota_project_id):
  418. return self.__class__(
  419. self._source_credentials,
  420. self._credential_access_boundary,
  421. quota_project_id=quota_project_id,
  422. )