downscoped.py 21 KB

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