downscoped.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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.auth import exceptions
  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_PATTERN = "https://sts.{}/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. InvalidType: If any of the rules are not a valid type.
  74. InvalidValue: 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. InvalidType: If any of the rules are not a valid type.
  97. InvalidValue: If the provided rules exceed the maximum allowed.
  98. """
  99. if len(value) > _MAX_ACCESS_BOUNDARY_RULES_COUNT:
  100. raise exceptions.InvalidValue(
  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 exceptions.InvalidType(
  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. InvalidType: If any of the rules are not a valid type.
  120. InvalidValue: If the provided rules exceed the maximum allowed.
  121. """
  122. if len(self.rules) == _MAX_ACCESS_BOUNDARY_RULES_COUNT:
  123. raise exceptions.InvalidValue(
  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 exceptions.InvalidType(
  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. InvalidType: If any of the parameters are not of the expected types.
  170. InvalidValue: 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. google.auth.exceptions.InvalidType: If the value is not a string.
  189. """
  190. if not isinstance(value, str):
  191. raise exceptions.InvalidType(
  192. "The provided available_resource is not a string."
  193. )
  194. self._available_resource = value
  195. @property
  196. def available_permissions(self):
  197. """Returns the current available permissions.
  198. Returns:
  199. Tuple[str, ...]: The current available permissions. These are returned
  200. as an immutable tuple to prevent modification.
  201. """
  202. return tuple(self._available_permissions)
  203. @available_permissions.setter
  204. def available_permissions(self, value):
  205. """Updates the current available permissions.
  206. Args:
  207. value (Sequence[str]): The updated value of the available permissions.
  208. Raises:
  209. InvalidType: If the value is not a list of strings.
  210. InvalidValue: If the value is not valid.
  211. """
  212. for available_permission in value:
  213. if not isinstance(available_permission, str):
  214. raise exceptions.InvalidType(
  215. "Provided available_permissions are not a list of strings."
  216. )
  217. if available_permission.find("inRole:") != 0:
  218. raise exceptions.InvalidValue(
  219. "available_permissions must be prefixed with 'inRole:'."
  220. )
  221. # Make a copy of the original list.
  222. self._available_permissions = list(value)
  223. @property
  224. def availability_condition(self):
  225. """Returns the current availability condition.
  226. Returns:
  227. Optional[google.auth.downscoped.AvailabilityCondition]: The current
  228. availability condition.
  229. """
  230. return self._availability_condition
  231. @availability_condition.setter
  232. def availability_condition(self, value):
  233. """Updates the current availability condition.
  234. Args:
  235. value (Optional[google.auth.downscoped.AvailabilityCondition]): The updated
  236. value of the availability condition.
  237. Raises:
  238. google.auth.exceptions.InvalidType: If the value is not of type google.auth.downscoped.AvailabilityCondition
  239. or None.
  240. """
  241. if not isinstance(value, AvailabilityCondition) and value is not None:
  242. raise exceptions.InvalidType(
  243. "The provided availability_condition is not a 'google.auth.downscoped.AvailabilityCondition' or None."
  244. )
  245. self._availability_condition = value
  246. def to_json(self):
  247. """Generates the dictionary representation of the access boundary rule.
  248. This uses the format expected by the Security Token Service API as documented in
  249. `Defining a Credential Access Boundary`_.
  250. .. _Defining a Credential Access Boundary:
  251. https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary
  252. Returns:
  253. Mapping: The access boundary rule represented in a dictionary object.
  254. """
  255. json = {
  256. "availablePermissions": list(self.available_permissions),
  257. "availableResource": self.available_resource,
  258. }
  259. if self.availability_condition:
  260. json["availabilityCondition"] = self.availability_condition.to_json()
  261. return json
  262. class AvailabilityCondition(object):
  263. """An optional condition that can be used as part of a Credential Access Boundary
  264. to further restrict permissions."""
  265. def __init__(self, expression, title=None, description=None):
  266. """Instantiates an availability condition using the provided expression and
  267. optional title or description.
  268. Args:
  269. expression (str): A condition expression that specifies the Cloud Storage
  270. objects where permissions are available. For example, this expression
  271. makes permissions available for objects whose name starts with "customer-a":
  272. "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a')"
  273. title (Optional[str]): An optional short string that identifies the purpose of
  274. the condition.
  275. description (Optional[str]): Optional details about the purpose of the condition.
  276. Raises:
  277. InvalidType: If any of the parameters are not of the expected types.
  278. InvalidValue: If any of the parameters are not of the expected values.
  279. """
  280. self.expression = expression
  281. self.title = title
  282. self.description = description
  283. @property
  284. def expression(self):
  285. """Returns the current condition expression.
  286. Returns:
  287. str: The current conditon expression.
  288. """
  289. return self._expression
  290. @expression.setter
  291. def expression(self, value):
  292. """Updates the current condition expression.
  293. Args:
  294. value (str): The updated value of the condition expression.
  295. Raises:
  296. google.auth.exceptions.InvalidType: If the value is not of type string.
  297. """
  298. if not isinstance(value, str):
  299. raise exceptions.InvalidType("The provided expression is not a string.")
  300. self._expression = value
  301. @property
  302. def title(self):
  303. """Returns the current title.
  304. Returns:
  305. Optional[str]: The current title.
  306. """
  307. return self._title
  308. @title.setter
  309. def title(self, value):
  310. """Updates the current title.
  311. Args:
  312. value (Optional[str]): The updated value of the title.
  313. Raises:
  314. google.auth.exceptions.InvalidType: If the value is not of type string or None.
  315. """
  316. if not isinstance(value, str) and value is not None:
  317. raise exceptions.InvalidType("The provided title is not a string or None.")
  318. self._title = value
  319. @property
  320. def description(self):
  321. """Returns the current description.
  322. Returns:
  323. Optional[str]: The current description.
  324. """
  325. return self._description
  326. @description.setter
  327. def description(self, value):
  328. """Updates the current description.
  329. Args:
  330. value (Optional[str]): The updated value of the description.
  331. Raises:
  332. google.auth.exceptions.InvalidType: If the value is not of type string or None.
  333. """
  334. if not isinstance(value, str) and value is not None:
  335. raise exceptions.InvalidType(
  336. "The provided description is not a string or None."
  337. )
  338. self._description = value
  339. def to_json(self):
  340. """Generates the dictionary representation of the availability condition.
  341. This uses the format expected by the Security Token Service API as documented in
  342. `Defining a Credential Access Boundary`_.
  343. .. _Defining a Credential Access Boundary:
  344. https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary
  345. Returns:
  346. Mapping[str, str]: The availability condition represented in a dictionary
  347. object.
  348. """
  349. json = {"expression": self.expression}
  350. if self.title:
  351. json["title"] = self.title
  352. if self.description:
  353. json["description"] = self.description
  354. return json
  355. class Credentials(credentials.CredentialsWithQuotaProject):
  356. """Defines a set of Google credentials that are downscoped from an existing set
  357. of Google OAuth2 credentials. This is useful to restrict the Identity and Access
  358. Management (IAM) permissions that a short-lived credential can use.
  359. The common pattern of usage is to have a token broker with elevated access
  360. generate these downscoped credentials from higher access source credentials and
  361. pass the downscoped short-lived access tokens to a token consumer via some
  362. secure authenticated channel for limited access to Google Cloud Storage
  363. resources.
  364. """
  365. def __init__(
  366. self,
  367. source_credentials,
  368. credential_access_boundary,
  369. quota_project_id=None,
  370. universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
  371. ):
  372. """Instantiates a downscoped credentials object using the provided source
  373. credentials and credential access boundary rules.
  374. To downscope permissions of a source credential, a Credential Access Boundary
  375. that specifies which resources the new credential can access, as well as an
  376. upper bound on the permissions that are available on each resource, has to be
  377. defined. A downscoped credential can then be instantiated using the source
  378. credential and the Credential Access Boundary.
  379. Args:
  380. source_credentials (google.auth.credentials.Credentials): The source credentials
  381. to be downscoped based on the provided Credential Access Boundary rules.
  382. credential_access_boundary (google.auth.downscoped.CredentialAccessBoundary):
  383. The Credential Access Boundary which contains a list of access boundary
  384. rules. Each rule contains information on the resource that the rule applies to,
  385. the upper bound of the permissions that are available on that resource and an
  386. optional condition to further restrict permissions.
  387. quota_project_id (Optional[str]): The optional quota project ID.
  388. universe_domain (Optional[str]): The universe domain value, default is googleapis.com
  389. Raises:
  390. google.auth.exceptions.RefreshError: If the source credentials
  391. return an error on token refresh.
  392. google.auth.exceptions.OAuthError: If the STS token exchange
  393. endpoint returned an error during downscoped token generation.
  394. """
  395. super(Credentials, self).__init__()
  396. self._source_credentials = source_credentials
  397. self._credential_access_boundary = credential_access_boundary
  398. self._quota_project_id = quota_project_id
  399. self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
  400. self._sts_client = sts.Client(
  401. _STS_TOKEN_URL_PATTERN.format(self.universe_domain)
  402. )
  403. @_helpers.copy_docstring(credentials.Credentials)
  404. def refresh(self, request):
  405. # Generate an access token from the source credentials.
  406. self._source_credentials.refresh(request)
  407. now = _helpers.utcnow()
  408. # Exchange the access token for a downscoped access token.
  409. response_data = self._sts_client.exchange_token(
  410. request=request,
  411. grant_type=_STS_GRANT_TYPE,
  412. subject_token=self._source_credentials.token,
  413. subject_token_type=_STS_SUBJECT_TOKEN_TYPE,
  414. requested_token_type=_STS_REQUESTED_TOKEN_TYPE,
  415. additional_options=self._credential_access_boundary.to_json(),
  416. )
  417. self.token = response_data.get("access_token")
  418. # For downscoping CAB flow, the STS endpoint may not return the expiration
  419. # field for some flows. The generated downscoped token should always have
  420. # the same expiration time as the source credentials. When no expires_in
  421. # field is returned in the response, we can just get the expiration time
  422. # from the source credentials.
  423. if response_data.get("expires_in"):
  424. lifetime = datetime.timedelta(seconds=response_data.get("expires_in"))
  425. self.expiry = now + lifetime
  426. else:
  427. self.expiry = self._source_credentials.expiry
  428. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  429. def with_quota_project(self, quota_project_id):
  430. return self.__class__(
  431. self._source_credentials,
  432. self._credential_access_boundary,
  433. quota_project_id=quota_project_id,
  434. )