nnilayy commited on
Commit
f6edc64
·
verified ·
1 Parent(s): 108dd1b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/INSTALLER +1 -0
  2. lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/METADATA +295 -0
  3. lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/RECORD +9 -0
  4. lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/REQUESTED +0 -0
  5. lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/WHEEL +4 -0
  6. lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE +21 -0
  7. lib/python3.10/site-packages/attrs/__init__.py +69 -0
  8. lib/python3.10/site-packages/attrs/__init__.pyi +263 -0
  9. lib/python3.10/site-packages/attrs/converters.py +3 -0
  10. lib/python3.10/site-packages/attrs/exceptions.py +3 -0
  11. lib/python3.10/site-packages/attrs/filters.py +3 -0
  12. lib/python3.10/site-packages/attrs/py.typed +0 -0
  13. lib/python3.10/site-packages/attrs/setters.py +3 -0
  14. lib/python3.10/site-packages/attrs/validators.py +3 -0
  15. lib/python3.10/site-packages/google/auth/__init__.py +53 -0
  16. lib/python3.10/site-packages/google/auth/_credentials_async.py +171 -0
  17. lib/python3.10/site-packages/google/auth/_credentials_base.py +75 -0
  18. lib/python3.10/site-packages/google/auth/_exponential_backoff.py +164 -0
  19. lib/python3.10/site-packages/google/auth/_jwt_async.py +164 -0
  20. lib/python3.10/site-packages/google/auth/_oauth2client.py +167 -0
  21. lib/python3.10/site-packages/google/auth/_service_account_info.py +80 -0
  22. lib/python3.10/site-packages/google/auth/aio/__init__.py +25 -0
  23. lib/python3.10/site-packages/google/auth/aio/credentials.py +143 -0
  24. lib/python3.10/site-packages/google/auth/aio/transport/__init__.py +144 -0
  25. lib/python3.10/site-packages/google/auth/aio/transport/aiohttp.py +184 -0
  26. lib/python3.10/site-packages/google/auth/aio/transport/sessions.py +268 -0
  27. lib/python3.10/site-packages/google/auth/app_engine.py +180 -0
  28. lib/python3.10/site-packages/google/auth/compute_engine/__init__.py +22 -0
  29. lib/python3.10/site-packages/google/auth/compute_engine/_metadata.py +375 -0
  30. lib/python3.10/site-packages/google/auth/compute_engine/credentials.py +496 -0
  31. lib/python3.10/site-packages/google/auth/crypt/__init__.py +98 -0
  32. lib/python3.10/site-packages/google/auth/crypt/_cryptography_rsa.py +151 -0
  33. lib/python3.10/site-packages/google/auth/crypt/_helpers.py +0 -0
  34. lib/python3.10/site-packages/google/auth/crypt/_python_rsa.py +175 -0
  35. lib/python3.10/site-packages/google/auth/crypt/base.py +127 -0
  36. lib/python3.10/site-packages/google/auth/crypt/es256.py +175 -0
  37. lib/python3.10/site-packages/google/auth/crypt/rsa.py +30 -0
  38. lib/python3.10/site-packages/google/auth/downscoped.py +512 -0
  39. lib/python3.10/site-packages/google/auth/exceptions.py +108 -0
  40. lib/python3.10/site-packages/google/auth/external_account.py +628 -0
  41. lib/python3.10/site-packages/google/auth/external_account_authorized_user.py +380 -0
  42. lib/python3.10/site-packages/google/auth/iam.py +136 -0
  43. lib/python3.10/site-packages/google/auth/impersonated_credentials.py +579 -0
  44. lib/python3.10/site-packages/google/auth/metrics.py +154 -0
  45. lib/python3.10/site-packages/google/auth/py.typed +2 -0
  46. lib/python3.10/site-packages/google/auth/transport/__init__.py +103 -0
  47. lib/python3.10/site-packages/google/auth/transport/_aiohttp_requests.py +391 -0
  48. lib/python3.10/site-packages/google/auth/transport/_custom_tls_signer.py +283 -0
  49. lib/python3.10/site-packages/google/auth/transport/_http_client.py +113 -0
  50. lib/python3.10/site-packages/google/auth/transport/_mtls_helper.py +407 -0
lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/METADATA ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.3
2
+ Name: annotated-types
3
+ Version: 0.7.0
4
+ Summary: Reusable constraint types to use with typing.Annotated
5
+ Project-URL: Homepage, https://github.com/annotated-types/annotated-types
6
+ Project-URL: Source, https://github.com/annotated-types/annotated-types
7
+ Project-URL: Changelog, https://github.com/annotated-types/annotated-types/releases
8
+ Author-email: Adrian Garcia Badaracco <[email protected]>, Samuel Colvin <[email protected]>, Zac Hatfield-Dodds <[email protected]>
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Environment :: MacOS X
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Information Technology
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: Unix
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.8
27
+ Requires-Dist: typing-extensions>=4.0.0; python_version < '3.9'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # annotated-types
31
+
32
+ [![CI](https://github.com/annotated-types/annotated-types/workflows/CI/badge.svg?event=push)](https://github.com/annotated-types/annotated-types/actions?query=event%3Apush+branch%3Amain+workflow%3ACI)
33
+ [![pypi](https://img.shields.io/pypi/v/annotated-types.svg)](https://pypi.python.org/pypi/annotated-types)
34
+ [![versions](https://img.shields.io/pypi/pyversions/annotated-types.svg)](https://github.com/annotated-types/annotated-types)
35
+ [![license](https://img.shields.io/github/license/annotated-types/annotated-types.svg)](https://github.com/annotated-types/annotated-types/blob/main/LICENSE)
36
+
37
+ [PEP-593](https://peps.python.org/pep-0593/) added `typing.Annotated` as a way of
38
+ adding context-specific metadata to existing types, and specifies that
39
+ `Annotated[T, x]` _should_ be treated as `T` by any tool or library without special
40
+ logic for `x`.
41
+
42
+ This package provides metadata objects which can be used to represent common
43
+ constraints such as upper and lower bounds on scalar values and collection sizes,
44
+ a `Predicate` marker for runtime checks, and
45
+ descriptions of how we intend these metadata to be interpreted. In some cases,
46
+ we also note alternative representations which do not require this package.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install annotated-types
52
+ ```
53
+
54
+ ## Examples
55
+
56
+ ```python
57
+ from typing import Annotated
58
+ from annotated_types import Gt, Len, Predicate
59
+
60
+ class MyClass:
61
+ age: Annotated[int, Gt(18)] # Valid: 19, 20, ...
62
+ # Invalid: 17, 18, "19", 19.0, ...
63
+ factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5, 7, 11, ...
64
+ # Invalid: 4, 8, -2, 5.0, "prime", ...
65
+
66
+ my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10, 20, 30, 40, 50]
67
+ # Invalid: (1, 2), ["abc"], [0] * 20
68
+ ```
69
+
70
+ ## Documentation
71
+
72
+ _While `annotated-types` avoids runtime checks for performance, users should not
73
+ construct invalid combinations such as `MultipleOf("non-numeric")` or `Annotated[int, Len(3)]`.
74
+ Downstream implementors may choose to raise an error, emit a warning, silently ignore
75
+ a metadata item, etc., if the metadata objects described below are used with an
76
+ incompatible type - or for any other reason!_
77
+
78
+ ### Gt, Ge, Lt, Le
79
+
80
+ Express inclusive and/or exclusive bounds on orderable values - which may be numbers,
81
+ dates, times, strings, sets, etc. Note that the boundary value need not be of the
82
+ same type that was annotated, so long as they can be compared: `Annotated[int, Gt(1.5)]`
83
+ is fine, for example, and implies that the value is an integer x such that `x > 1.5`.
84
+
85
+ We suggest that implementors may also interpret `functools.partial(operator.le, 1.5)`
86
+ as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime dependency on
87
+ the `annotated-types` package.
88
+
89
+ To be explicit, these types have the following meanings:
90
+
91
+ * `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive minimum
92
+ * `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to inclusive minimum
93
+ * `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum
94
+ * `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to inclusive maximum
95
+
96
+ ### Interval
97
+
98
+ `Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound with a single
99
+ metadata object. `None` attributes should be ignored, and non-`None` attributes
100
+ treated as per the single bounds above.
101
+
102
+ ### MultipleOf
103
+
104
+ `MultipleOf(multiple_of=x)` might be interpreted in two ways:
105
+
106
+ 1. Python semantics, implying `value % multiple_of == 0`, or
107
+ 2. [JSONschema semantics](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1),
108
+ where `int(value / multiple_of) == value / multiple_of`.
109
+
110
+ We encourage users to be aware of these two common interpretations and their
111
+ distinct behaviours, especially since very large or non-integer numbers make
112
+ it easy to cause silent data corruption due to floating-point imprecision.
113
+
114
+ We encourage libraries to carefully document which interpretation they implement.
115
+
116
+ ### MinLen, MaxLen, Len
117
+
118
+ `Len()` implies that `min_length <= len(value) <= max_length` - lower and upper bounds are inclusive.
119
+
120
+ As well as `Len()` which can optionally include upper and lower bounds, we also
121
+ provide `MinLen(x)` and `MaxLen(y)` which are equivalent to `Len(min_length=x)`
122
+ and `Len(max_length=y)` respectively.
123
+
124
+ `Len`, `MinLen`, and `MaxLen` may be used with any type which supports `len(value)`.
125
+
126
+ Examples of usage:
127
+
128
+ * `Annotated[list, MaxLen(10)]` (or `Annotated[list, Len(max_length=10))`) - list must have a length of 10 or less
129
+ * `Annotated[str, MaxLen(10)]` - string must have a length of 10 or less
130
+ * `Annotated[list, MinLen(3))` (or `Annotated[list, Len(min_length=3))`) - list must have a length of 3 or more
131
+ * `Annotated[list, Len(4, 6)]` - list must have a length of 4, 5, or 6
132
+ * `Annotated[list, Len(8, 8)]` - list must have a length of exactly 8
133
+
134
+ #### Changed in v0.4.0
135
+
136
+ * `min_inclusive` has been renamed to `min_length`, no change in meaning
137
+ * `max_exclusive` has been renamed to `max_length`, upper bound is now **inclusive** instead of **exclusive**
138
+ * The recommendation that slices are interpreted as `Len` has been removed due to ambiguity and different semantic
139
+ meaning of the upper bound in slices vs. `Len`
140
+
141
+ See [issue #23](https://github.com/annotated-types/annotated-types/issues/23) for discussion.
142
+
143
+ ### Timezone
144
+
145
+ `Timezone` can be used with a `datetime` or a `time` to express which timezones
146
+ are allowed. `Annotated[datetime, Timezone(None)]` must be a naive datetime.
147
+ `Timezone[...]` ([literal ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis))
148
+ expresses that any timezone-aware datetime is allowed. You may also pass a specific
149
+ timezone string or [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects)
150
+ object such as `Timezone(timezone.utc)` or `Timezone("Africa/Abidjan")` to express that you only
151
+ allow a specific timezone, though we note that this is often a symptom of fragile design.
152
+
153
+ #### Changed in v0.x.x
154
+
155
+ * `Timezone` accepts [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) objects instead of
156
+ `timezone`, extending compatibility to [`zoneinfo`](https://docs.python.org/3/library/zoneinfo.html) and third party libraries.
157
+
158
+ ### Unit
159
+
160
+ `Unit(unit: str)` expresses that the annotated numeric value is the magnitude of
161
+ a quantity with the specified unit. For example, `Annotated[float, Unit("m/s")]`
162
+ would be a float representing a velocity in meters per second.
163
+
164
+ Please note that `annotated_types` itself makes no attempt to parse or validate
165
+ the unit string in any way. That is left entirely to downstream libraries,
166
+ such as [`pint`](https://pint.readthedocs.io) or
167
+ [`astropy.units`](https://docs.astropy.org/en/stable/units/).
168
+
169
+ An example of how a library might use this metadata:
170
+
171
+ ```python
172
+ from annotated_types import Unit
173
+ from typing import Annotated, TypeVar, Callable, Any, get_origin, get_args
174
+
175
+ # given a type annotated with a unit:
176
+ Meters = Annotated[float, Unit("m")]
177
+
178
+
179
+ # you can cast the annotation to a specific unit type with any
180
+ # callable that accepts a string and returns the desired type
181
+ T = TypeVar("T")
182
+ def cast_unit(tp: Any, unit_cls: Callable[[str], T]) -> T | None:
183
+ if get_origin(tp) is Annotated:
184
+ for arg in get_args(tp):
185
+ if isinstance(arg, Unit):
186
+ return unit_cls(arg.unit)
187
+ return None
188
+
189
+
190
+ # using `pint`
191
+ import pint
192
+ pint_unit = cast_unit(Meters, pint.Unit)
193
+
194
+
195
+ # using `astropy.units`
196
+ import astropy.units as u
197
+ astropy_unit = cast_unit(Meters, u.Unit)
198
+ ```
199
+
200
+ ### Predicate
201
+
202
+ `Predicate(func: Callable)` expresses that `func(value)` is truthy for valid values.
203
+ Users should prefer the statically inspectable metadata above, but if you need
204
+ the full power and flexibility of arbitrary runtime predicates... here it is.
205
+
206
+ For some common constraints, we provide generic types:
207
+
208
+ * `IsLower = Annotated[T, Predicate(str.islower)]`
209
+ * `IsUpper = Annotated[T, Predicate(str.isupper)]`
210
+ * `IsDigit = Annotated[T, Predicate(str.isdigit)]`
211
+ * `IsFinite = Annotated[T, Predicate(math.isfinite)]`
212
+ * `IsNotFinite = Annotated[T, Predicate(Not(math.isfinite))]`
213
+ * `IsNan = Annotated[T, Predicate(math.isnan)]`
214
+ * `IsNotNan = Annotated[T, Predicate(Not(math.isnan))]`
215
+ * `IsInfinite = Annotated[T, Predicate(math.isinf)]`
216
+ * `IsNotInfinite = Annotated[T, Predicate(Not(math.isinf))]`
217
+
218
+ so that you can write e.g. `x: IsFinite[float] = 2.0` instead of the longer
219
+ (but exactly equivalent) `x: Annotated[float, Predicate(math.isfinite)] = 2.0`.
220
+
221
+ Some libraries might have special logic to handle known or understandable predicates,
222
+ for example by checking for `str.isdigit` and using its presence to both call custom
223
+ logic to enforce digit-only strings, and customise some generated external schema.
224
+ Users are therefore encouraged to avoid indirection like `lambda s: s.lower()`, in
225
+ favor of introspectable methods such as `str.lower` or `re.compile("pattern").search`.
226
+
227
+ To enable basic negation of commonly used predicates like `math.isnan` without introducing introspection that makes it impossible for implementers to introspect the predicate we provide a `Not` wrapper that simply negates the predicate in an introspectable manner. Several of the predicates listed above are created in this manner.
228
+
229
+ We do not specify what behaviour should be expected for predicates that raise
230
+ an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
231
+ skip invalid constraints, or statically raise an error; or it might try calling it
232
+ and then propagate or discard the resulting
233
+ `TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object`
234
+ exception. We encourage libraries to document the behaviour they choose.
235
+
236
+ ### Doc
237
+
238
+ `doc()` can be used to add documentation information in `Annotated`, for function and method parameters, variables, class attributes, return types, and any place where `Annotated` can be used.
239
+
240
+ It expects a value that can be statically analyzed, as the main use case is for static analysis, editors, documentation generators, and similar tools.
241
+
242
+ It returns a `DocInfo` class with a single attribute `documentation` containing the value passed to `doc()`.
243
+
244
+ This is the early adopter's alternative form of the [`typing-doc` proposal](https://github.com/tiangolo/fastapi/blob/typing-doc/typing_doc.md).
245
+
246
+ ### Integrating downstream types with `GroupedMetadata`
247
+
248
+ Implementers may choose to provide a convenience wrapper that groups multiple pieces of metadata.
249
+ This can help reduce verbosity and cognitive overhead for users.
250
+ For example, an implementer like Pydantic might provide a `Field` or `Meta` type that accepts keyword arguments and transforms these into low-level metadata:
251
+
252
+ ```python
253
+ from dataclasses import dataclass
254
+ from typing import Iterator
255
+ from annotated_types import GroupedMetadata, Ge
256
+
257
+ @dataclass
258
+ class Field(GroupedMetadata):
259
+ ge: int | None = None
260
+ description: str | None = None
261
+
262
+ def __iter__(self) -> Iterator[object]:
263
+ # Iterating over a GroupedMetadata object should yield annotated-types
264
+ # constraint metadata objects which describe it as fully as possible,
265
+ # and may include other unknown objects too.
266
+ if self.ge is not None:
267
+ yield Ge(self.ge)
268
+ if self.description is not None:
269
+ yield Description(self.description)
270
+ ```
271
+
272
+ Libraries consuming annotated-types constraints should check for `GroupedMetadata` and unpack it by iterating over the object and treating the results as if they had been "unpacked" in the `Annotated` type. The same logic should be applied to the [PEP 646 `Unpack` type](https://peps.python.org/pep-0646/), so that `Annotated[T, Field(...)]`, `Annotated[T, Unpack[Field(...)]]` and `Annotated[T, *Field(...)]` are all treated consistently.
273
+
274
+ Libraries consuming annotated-types should also ignore any metadata they do not recongize that came from unpacking a `GroupedMetadata`, just like they ignore unrecognized metadata in `Annotated` itself.
275
+
276
+ Our own `annotated_types.Interval` class is a `GroupedMetadata` which unpacks itself into `Gt`, `Lt`, etc., so this is not an abstract concern. Similarly, `annotated_types.Len` is a `GroupedMetadata` which unpacks itself into `MinLen` (optionally) and `MaxLen`.
277
+
278
+ ### Consuming metadata
279
+
280
+ We intend to not be prescriptive as to _how_ the metadata and constraints are used, but as an example of how one might parse constraints from types annotations see our [implementation in `test_main.py`](https://github.com/annotated-types/annotated-types/blob/f59cf6d1b5255a0fe359b93896759a180bec30ae/tests/test_main.py#L94-L103).
281
+
282
+ It is up to the implementer to determine how this metadata is used.
283
+ You could use the metadata for runtime type checking, for generating schemas or to generate example data, amongst other use cases.
284
+
285
+ ## Design & History
286
+
287
+ This package was designed at the PyCon 2022 sprints by the maintainers of Pydantic
288
+ and Hypothesis, with the goal of making it as easy as possible for end-users to
289
+ provide more informative annotations for use by runtime libraries.
290
+
291
+ It is deliberately minimal, and following PEP-593 allows considerable downstream
292
+ discretion in what (if anything!) they choose to support. Nonetheless, we expect
293
+ that staying simple and covering _only_ the most common use-cases will give users
294
+ and maintainers the best experience we can. If you'd like more constraints for your
295
+ types - follow our lead, by defining them and documenting them downstream!
lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/RECORD ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ annotated_types-0.7.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
2
+ annotated_types-0.7.0.dist-info/METADATA,sha256=7ltqxksJJ0wCYFGBNIQCWTlWQGeAH0hRFdnK3CB895E,15046
3
+ annotated_types-0.7.0.dist-info/RECORD,,
4
+ annotated_types-0.7.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ annotated_types-0.7.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
6
+ annotated_types-0.7.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083
7
+ annotated_types/__init__.py,sha256=RynLsRKUEGI0KimXydlD1fZEfEzWwDo0Uon3zOKhG1Q,13819
8
+ annotated_types/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ annotated_types/test_cases.py,sha256=zHFX6EpcMbGJ8FzBYDbO56bPwx_DYIVSKbZM-4B3_lg,6421
lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/REQUESTED ADDED
File without changes
lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.24.2
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 the contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
lib/python3.10/site-packages/attrs/__init__.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from attr import (
4
+ NOTHING,
5
+ Attribute,
6
+ AttrsInstance,
7
+ Converter,
8
+ Factory,
9
+ NothingType,
10
+ _make_getattr,
11
+ assoc,
12
+ cmp_using,
13
+ define,
14
+ evolve,
15
+ field,
16
+ fields,
17
+ fields_dict,
18
+ frozen,
19
+ has,
20
+ make_class,
21
+ mutable,
22
+ resolve_types,
23
+ validate,
24
+ )
25
+ from attr._next_gen import asdict, astuple
26
+
27
+ from . import converters, exceptions, filters, setters, validators
28
+
29
+
30
+ __all__ = [
31
+ "NOTHING",
32
+ "Attribute",
33
+ "AttrsInstance",
34
+ "Converter",
35
+ "Factory",
36
+ "NothingType",
37
+ "__author__",
38
+ "__copyright__",
39
+ "__description__",
40
+ "__doc__",
41
+ "__email__",
42
+ "__license__",
43
+ "__title__",
44
+ "__url__",
45
+ "__version__",
46
+ "__version_info__",
47
+ "asdict",
48
+ "assoc",
49
+ "astuple",
50
+ "cmp_using",
51
+ "converters",
52
+ "define",
53
+ "evolve",
54
+ "exceptions",
55
+ "field",
56
+ "fields",
57
+ "fields_dict",
58
+ "filters",
59
+ "frozen",
60
+ "has",
61
+ "make_class",
62
+ "mutable",
63
+ "resolve_types",
64
+ "setters",
65
+ "validate",
66
+ "validators",
67
+ ]
68
+
69
+ __getattr__ = _make_getattr(__name__)
lib/python3.10/site-packages/attrs/__init__.pyi ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ from typing import (
4
+ Any,
5
+ Callable,
6
+ Mapping,
7
+ Sequence,
8
+ overload,
9
+ TypeVar,
10
+ )
11
+
12
+ # Because we need to type our own stuff, we have to make everything from
13
+ # attr explicitly public too.
14
+ from attr import __author__ as __author__
15
+ from attr import __copyright__ as __copyright__
16
+ from attr import __description__ as __description__
17
+ from attr import __email__ as __email__
18
+ from attr import __license__ as __license__
19
+ from attr import __title__ as __title__
20
+ from attr import __url__ as __url__
21
+ from attr import __version__ as __version__
22
+ from attr import __version_info__ as __version_info__
23
+ from attr import assoc as assoc
24
+ from attr import Attribute as Attribute
25
+ from attr import AttrsInstance as AttrsInstance
26
+ from attr import cmp_using as cmp_using
27
+ from attr import converters as converters
28
+ from attr import Converter as Converter
29
+ from attr import evolve as evolve
30
+ from attr import exceptions as exceptions
31
+ from attr import Factory as Factory
32
+ from attr import fields as fields
33
+ from attr import fields_dict as fields_dict
34
+ from attr import filters as filters
35
+ from attr import has as has
36
+ from attr import make_class as make_class
37
+ from attr import NOTHING as NOTHING
38
+ from attr import resolve_types as resolve_types
39
+ from attr import setters as setters
40
+ from attr import validate as validate
41
+ from attr import validators as validators
42
+ from attr import attrib, asdict as asdict, astuple as astuple
43
+ from attr import NothingType as NothingType
44
+
45
+ if sys.version_info >= (3, 11):
46
+ from typing import dataclass_transform
47
+ else:
48
+ from typing_extensions import dataclass_transform
49
+
50
+ _T = TypeVar("_T")
51
+ _C = TypeVar("_C", bound=type)
52
+
53
+ _EqOrderType = bool | Callable[[Any], Any]
54
+ _ValidatorType = Callable[[Any, "Attribute[_T]", _T], Any]
55
+ _CallableConverterType = Callable[[Any], Any]
56
+ _ConverterType = _CallableConverterType | Converter[Any, Any]
57
+ _ReprType = Callable[[Any], str]
58
+ _ReprArgType = bool | _ReprType
59
+ _OnSetAttrType = Callable[[Any, "Attribute[Any]", Any], Any]
60
+ _OnSetAttrArgType = _OnSetAttrType | list[_OnSetAttrType] | setters._NoOpType
61
+ _FieldTransformer = Callable[
62
+ [type, list["Attribute[Any]"]], list["Attribute[Any]"]
63
+ ]
64
+ # FIXME: in reality, if multiple validators are passed they must be in a list
65
+ # or tuple, but those are invariant and so would prevent subtypes of
66
+ # _ValidatorType from working when passed in a list or tuple.
67
+ _ValidatorArgType = _ValidatorType[_T] | Sequence[_ValidatorType[_T]]
68
+
69
+ @overload
70
+ def field(
71
+ *,
72
+ default: None = ...,
73
+ validator: None = ...,
74
+ repr: _ReprArgType = ...,
75
+ hash: bool | None = ...,
76
+ init: bool = ...,
77
+ metadata: Mapping[Any, Any] | None = ...,
78
+ converter: None = ...,
79
+ factory: None = ...,
80
+ kw_only: bool = ...,
81
+ eq: bool | None = ...,
82
+ order: bool | None = ...,
83
+ on_setattr: _OnSetAttrArgType | None = ...,
84
+ alias: str | None = ...,
85
+ type: type | None = ...,
86
+ ) -> Any: ...
87
+
88
+ # This form catches an explicit None or no default and infers the type from the
89
+ # other arguments.
90
+ @overload
91
+ def field(
92
+ *,
93
+ default: None = ...,
94
+ validator: _ValidatorArgType[_T] | None = ...,
95
+ repr: _ReprArgType = ...,
96
+ hash: bool | None = ...,
97
+ init: bool = ...,
98
+ metadata: Mapping[Any, Any] | None = ...,
99
+ converter: _ConverterType
100
+ | list[_ConverterType]
101
+ | tuple[_ConverterType]
102
+ | None = ...,
103
+ factory: Callable[[], _T] | None = ...,
104
+ kw_only: bool = ...,
105
+ eq: _EqOrderType | None = ...,
106
+ order: _EqOrderType | None = ...,
107
+ on_setattr: _OnSetAttrArgType | None = ...,
108
+ alias: str | None = ...,
109
+ type: type | None = ...,
110
+ ) -> _T: ...
111
+
112
+ # This form catches an explicit default argument.
113
+ @overload
114
+ def field(
115
+ *,
116
+ default: _T,
117
+ validator: _ValidatorArgType[_T] | None = ...,
118
+ repr: _ReprArgType = ...,
119
+ hash: bool | None = ...,
120
+ init: bool = ...,
121
+ metadata: Mapping[Any, Any] | None = ...,
122
+ converter: _ConverterType
123
+ | list[_ConverterType]
124
+ | tuple[_ConverterType]
125
+ | None = ...,
126
+ factory: Callable[[], _T] | None = ...,
127
+ kw_only: bool = ...,
128
+ eq: _EqOrderType | None = ...,
129
+ order: _EqOrderType | None = ...,
130
+ on_setattr: _OnSetAttrArgType | None = ...,
131
+ alias: str | None = ...,
132
+ type: type | None = ...,
133
+ ) -> _T: ...
134
+
135
+ # This form covers type=non-Type: e.g. forward references (str), Any
136
+ @overload
137
+ def field(
138
+ *,
139
+ default: _T | None = ...,
140
+ validator: _ValidatorArgType[_T] | None = ...,
141
+ repr: _ReprArgType = ...,
142
+ hash: bool | None = ...,
143
+ init: bool = ...,
144
+ metadata: Mapping[Any, Any] | None = ...,
145
+ converter: _ConverterType
146
+ | list[_ConverterType]
147
+ | tuple[_ConverterType]
148
+ | None = ...,
149
+ factory: Callable[[], _T] | None = ...,
150
+ kw_only: bool = ...,
151
+ eq: _EqOrderType | None = ...,
152
+ order: _EqOrderType | None = ...,
153
+ on_setattr: _OnSetAttrArgType | None = ...,
154
+ alias: str | None = ...,
155
+ type: type | None = ...,
156
+ ) -> Any: ...
157
+ @overload
158
+ @dataclass_transform(field_specifiers=(attrib, field))
159
+ def define(
160
+ maybe_cls: _C,
161
+ *,
162
+ these: dict[str, Any] | None = ...,
163
+ repr: bool = ...,
164
+ unsafe_hash: bool | None = ...,
165
+ hash: bool | None = ...,
166
+ init: bool = ...,
167
+ slots: bool = ...,
168
+ frozen: bool = ...,
169
+ weakref_slot: bool = ...,
170
+ str: bool = ...,
171
+ auto_attribs: bool = ...,
172
+ kw_only: bool = ...,
173
+ cache_hash: bool = ...,
174
+ auto_exc: bool = ...,
175
+ eq: bool | None = ...,
176
+ order: bool | None = ...,
177
+ auto_detect: bool = ...,
178
+ getstate_setstate: bool | None = ...,
179
+ on_setattr: _OnSetAttrArgType | None = ...,
180
+ field_transformer: _FieldTransformer | None = ...,
181
+ match_args: bool = ...,
182
+ ) -> _C: ...
183
+ @overload
184
+ @dataclass_transform(field_specifiers=(attrib, field))
185
+ def define(
186
+ maybe_cls: None = ...,
187
+ *,
188
+ these: dict[str, Any] | None = ...,
189
+ repr: bool = ...,
190
+ unsafe_hash: bool | None = ...,
191
+ hash: bool | None = ...,
192
+ init: bool = ...,
193
+ slots: bool = ...,
194
+ frozen: bool = ...,
195
+ weakref_slot: bool = ...,
196
+ str: bool = ...,
197
+ auto_attribs: bool = ...,
198
+ kw_only: bool = ...,
199
+ cache_hash: bool = ...,
200
+ auto_exc: bool = ...,
201
+ eq: bool | None = ...,
202
+ order: bool | None = ...,
203
+ auto_detect: bool = ...,
204
+ getstate_setstate: bool | None = ...,
205
+ on_setattr: _OnSetAttrArgType | None = ...,
206
+ field_transformer: _FieldTransformer | None = ...,
207
+ match_args: bool = ...,
208
+ ) -> Callable[[_C], _C]: ...
209
+
210
+ mutable = define
211
+
212
+ @overload
213
+ @dataclass_transform(frozen_default=True, field_specifiers=(attrib, field))
214
+ def frozen(
215
+ maybe_cls: _C,
216
+ *,
217
+ these: dict[str, Any] | None = ...,
218
+ repr: bool = ...,
219
+ unsafe_hash: bool | None = ...,
220
+ hash: bool | None = ...,
221
+ init: bool = ...,
222
+ slots: bool = ...,
223
+ frozen: bool = ...,
224
+ weakref_slot: bool = ...,
225
+ str: bool = ...,
226
+ auto_attribs: bool = ...,
227
+ kw_only: bool = ...,
228
+ cache_hash: bool = ...,
229
+ auto_exc: bool = ...,
230
+ eq: bool | None = ...,
231
+ order: bool | None = ...,
232
+ auto_detect: bool = ...,
233
+ getstate_setstate: bool | None = ...,
234
+ on_setattr: _OnSetAttrArgType | None = ...,
235
+ field_transformer: _FieldTransformer | None = ...,
236
+ match_args: bool = ...,
237
+ ) -> _C: ...
238
+ @overload
239
+ @dataclass_transform(frozen_default=True, field_specifiers=(attrib, field))
240
+ def frozen(
241
+ maybe_cls: None = ...,
242
+ *,
243
+ these: dict[str, Any] | None = ...,
244
+ repr: bool = ...,
245
+ unsafe_hash: bool | None = ...,
246
+ hash: bool | None = ...,
247
+ init: bool = ...,
248
+ slots: bool = ...,
249
+ frozen: bool = ...,
250
+ weakref_slot: bool = ...,
251
+ str: bool = ...,
252
+ auto_attribs: bool = ...,
253
+ kw_only: bool = ...,
254
+ cache_hash: bool = ...,
255
+ auto_exc: bool = ...,
256
+ eq: bool | None = ...,
257
+ order: bool | None = ...,
258
+ auto_detect: bool = ...,
259
+ getstate_setstate: bool | None = ...,
260
+ on_setattr: _OnSetAttrArgType | None = ...,
261
+ field_transformer: _FieldTransformer | None = ...,
262
+ match_args: bool = ...,
263
+ ) -> Callable[[_C], _C]: ...
lib/python3.10/site-packages/attrs/converters.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from attr.converters import * # noqa: F403
lib/python3.10/site-packages/attrs/exceptions.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from attr.exceptions import * # noqa: F403
lib/python3.10/site-packages/attrs/filters.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from attr.filters import * # noqa: F403
lib/python3.10/site-packages/attrs/py.typed ADDED
File without changes
lib/python3.10/site-packages/attrs/setters.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from attr.setters import * # noqa: F403
lib/python3.10/site-packages/attrs/validators.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from attr.validators import * # noqa: F403
lib/python3.10/site-packages/google/auth/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Google Auth Library for Python."""
16
+
17
+ import logging
18
+ import sys
19
+ import warnings
20
+
21
+ from google.auth import version as google_auth_version
22
+ from google.auth._default import (
23
+ default,
24
+ load_credentials_from_dict,
25
+ load_credentials_from_file,
26
+ )
27
+
28
+
29
+ __version__ = google_auth_version.__version__
30
+
31
+
32
+ __all__ = ["default", "load_credentials_from_file", "load_credentials_from_dict"]
33
+
34
+
35
+ class Python37DeprecationWarning(DeprecationWarning): # pragma: NO COVER
36
+ """
37
+ Deprecation warning raised when Python 3.7 runtime is detected.
38
+ Python 3.7 support will be dropped after January 1, 2024.
39
+ """
40
+
41
+ pass
42
+
43
+
44
+ # Checks if the current runtime is Python 3.7.
45
+ if sys.version_info.major == 3 and sys.version_info.minor == 7: # pragma: NO COVER
46
+ message = (
47
+ "After January 1, 2024, new releases of this library will drop support "
48
+ "for Python 3.7."
49
+ )
50
+ warnings.warn(message, Python37DeprecationWarning)
51
+
52
+ # Set default logging handler to avoid "No handler found" warnings.
53
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
lib/python3.10/site-packages/google/auth/_credentials_async.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+
16
+ """Interfaces for credentials."""
17
+
18
+ import abc
19
+ import inspect
20
+
21
+ from google.auth import credentials
22
+
23
+
24
+ class Credentials(credentials.Credentials, metaclass=abc.ABCMeta):
25
+ """Async inherited credentials class from google.auth.credentials.
26
+ The added functionality is the before_request call which requires
27
+ async/await syntax.
28
+ All credentials have a :attr:`token` that is used for authentication and
29
+ may also optionally set an :attr:`expiry` to indicate when the token will
30
+ no longer be valid.
31
+
32
+ Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
33
+ Credentials can do this automatically before the first HTTP request in
34
+ :meth:`before_request`.
35
+
36
+ Although the token and expiration will change as the credentials are
37
+ :meth:`refreshed <refresh>` and used, credentials should be considered
38
+ immutable. Various credentials will accept configuration such as private
39
+ keys, scopes, and other options. These options are not changeable after
40
+ construction. Some classes will provide mechanisms to copy the credentials
41
+ with modifications such as :meth:`ScopedCredentials.with_scopes`.
42
+ """
43
+
44
+ async def before_request(self, request, method, url, headers):
45
+ """Performs credential-specific before request logic.
46
+
47
+ Refreshes the credentials if necessary, then calls :meth:`apply` to
48
+ apply the token to the authentication header.
49
+
50
+ Args:
51
+ request (google.auth.transport.Request): The object used to make
52
+ HTTP requests.
53
+ method (str): The request's HTTP method or the RPC method being
54
+ invoked.
55
+ url (str): The request's URI or the RPC service's URI.
56
+ headers (Mapping): The request's headers.
57
+ """
58
+ # pylint: disable=unused-argument
59
+ # (Subclasses may use these arguments to ascertain information about
60
+ # the http request.)
61
+
62
+ if not self.valid:
63
+ if inspect.iscoroutinefunction(self.refresh):
64
+ await self.refresh(request)
65
+ else:
66
+ self.refresh(request)
67
+ self.apply(headers)
68
+
69
+
70
+ class CredentialsWithQuotaProject(credentials.CredentialsWithQuotaProject):
71
+ """Abstract base for credentials supporting ``with_quota_project`` factory"""
72
+
73
+
74
+ class AnonymousCredentials(credentials.AnonymousCredentials, Credentials):
75
+ """Credentials that do not provide any authentication information.
76
+
77
+ These are useful in the case of services that support anonymous access or
78
+ local service emulators that do not use credentials. This class inherits
79
+ from the sync anonymous credentials file, but is kept if async credentials
80
+ is initialized and we would like anonymous credentials.
81
+ """
82
+
83
+
84
+ class ReadOnlyScoped(credentials.ReadOnlyScoped, metaclass=abc.ABCMeta):
85
+ """Interface for credentials whose scopes can be queried.
86
+
87
+ OAuth 2.0-based credentials allow limiting access using scopes as described
88
+ in `RFC6749 Section 3.3`_.
89
+ If a credential class implements this interface then the credentials either
90
+ use scopes in their implementation.
91
+
92
+ Some credentials require scopes in order to obtain a token. You can check
93
+ if scoping is necessary with :attr:`requires_scopes`::
94
+
95
+ if credentials.requires_scopes:
96
+ # Scoping is required.
97
+ credentials = _credentials_async.with_scopes(scopes=['one', 'two'])
98
+
99
+ Credentials that require scopes must either be constructed with scopes::
100
+
101
+ credentials = SomeScopedCredentials(scopes=['one', 'two'])
102
+
103
+ Or must copy an existing instance using :meth:`with_scopes`::
104
+
105
+ scoped_credentials = _credentials_async.with_scopes(scopes=['one', 'two'])
106
+
107
+ Some credentials have scopes but do not allow or require scopes to be set,
108
+ these credentials can be used as-is.
109
+
110
+ .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
111
+ """
112
+
113
+
114
+ class Scoped(credentials.Scoped):
115
+ """Interface for credentials whose scopes can be replaced while copying.
116
+
117
+ OAuth 2.0-based credentials allow limiting access using scopes as described
118
+ in `RFC6749 Section 3.3`_.
119
+ If a credential class implements this interface then the credentials either
120
+ use scopes in their implementation.
121
+
122
+ Some credentials require scopes in order to obtain a token. You can check
123
+ if scoping is necessary with :attr:`requires_scopes`::
124
+
125
+ if credentials.requires_scopes:
126
+ # Scoping is required.
127
+ credentials = _credentials_async.create_scoped(['one', 'two'])
128
+
129
+ Credentials that require scopes must either be constructed with scopes::
130
+
131
+ credentials = SomeScopedCredentials(scopes=['one', 'two'])
132
+
133
+ Or must copy an existing instance using :meth:`with_scopes`::
134
+
135
+ scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
136
+
137
+ Some credentials have scopes but do not allow or require scopes to be set,
138
+ these credentials can be used as-is.
139
+
140
+ .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
141
+ """
142
+
143
+
144
+ def with_scopes_if_required(credentials, scopes):
145
+ """Creates a copy of the credentials with scopes if scoping is required.
146
+
147
+ This helper function is useful when you do not know (or care to know) the
148
+ specific type of credentials you are using (such as when you use
149
+ :func:`google.auth.default`). This function will call
150
+ :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
151
+ the credentials require scoping. Otherwise, it will return the credentials
152
+ as-is.
153
+
154
+ Args:
155
+ credentials (google.auth.credentials.Credentials): The credentials to
156
+ scope if necessary.
157
+ scopes (Sequence[str]): The list of scopes to use.
158
+
159
+ Returns:
160
+ google.auth._credentials_async.Credentials: Either a new set of scoped
161
+ credentials, or the passed in credentials instance if no scoping
162
+ was required.
163
+ """
164
+ if isinstance(credentials, Scoped) and credentials.requires_scopes:
165
+ return credentials.with_scopes(scopes)
166
+ else:
167
+ return credentials
168
+
169
+
170
+ class Signing(credentials.Signing, metaclass=abc.ABCMeta):
171
+ """Interface for credentials that can cryptographically sign messages."""
lib/python3.10/site-packages/google/auth/_credentials_base.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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
+
15
+
16
+ """Interface for base credentials."""
17
+
18
+ import abc
19
+
20
+ from google.auth import _helpers
21
+
22
+
23
+ class _BaseCredentials(metaclass=abc.ABCMeta):
24
+ """Base class for all credentials.
25
+
26
+ All credentials have a :attr:`token` that is used for authentication and
27
+ may also optionally set an :attr:`expiry` to indicate when the token will
28
+ no longer be valid.
29
+
30
+ Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
31
+ Credentials can do this automatically before the first HTTP request in
32
+ :meth:`before_request`.
33
+
34
+ Although the token and expiration will change as the credentials are
35
+ :meth:`refreshed <refresh>` and used, credentials should be considered
36
+ immutable. Various credentials will accept configuration such as private
37
+ keys, scopes, and other options. These options are not changeable after
38
+ construction. Some classes will provide mechanisms to copy the credentials
39
+ with modifications such as :meth:`ScopedCredentials.with_scopes`.
40
+
41
+ Attributes:
42
+ token (Optional[str]): The bearer token that can be used in HTTP headers to make
43
+ authenticated requests.
44
+ """
45
+
46
+ def __init__(self):
47
+ self.token = None
48
+
49
+ @abc.abstractmethod
50
+ def refresh(self, request):
51
+ """Refreshes the access token.
52
+
53
+ Args:
54
+ request (google.auth.transport.Request): The object used to make
55
+ HTTP requests.
56
+
57
+ Raises:
58
+ google.auth.exceptions.RefreshError: If the credentials could
59
+ not be refreshed.
60
+ """
61
+ # pylint: disable=missing-raises-doc
62
+ # (pylint doesn't recognize that this is abstract)
63
+ raise NotImplementedError("Refresh must be implemented")
64
+
65
+ def _apply(self, headers, token=None):
66
+ """Apply the token to the authentication header.
67
+
68
+ Args:
69
+ headers (Mapping): The HTTP request headers.
70
+ token (Optional[str]): If specified, overrides the current access
71
+ token.
72
+ """
73
+ headers["authorization"] = "Bearer {}".format(
74
+ _helpers.from_bytes(token or self.token)
75
+ )
lib/python3.10/site-packages/google/auth/_exponential_backoff.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+
15
+ import asyncio
16
+ import random
17
+ import time
18
+
19
+ from google.auth import exceptions
20
+
21
+ # The default amount of retry attempts
22
+ _DEFAULT_RETRY_TOTAL_ATTEMPTS = 3
23
+
24
+ # The default initial backoff period (1.0 second).
25
+ _DEFAULT_INITIAL_INTERVAL_SECONDS = 1.0
26
+
27
+ # The default randomization factor (0.1 which results in a random period ranging
28
+ # between 10% below and 10% above the retry interval).
29
+ _DEFAULT_RANDOMIZATION_FACTOR = 0.1
30
+
31
+ # The default multiplier value (2 which is 100% increase per back off).
32
+ _DEFAULT_MULTIPLIER = 2.0
33
+
34
+ """Exponential Backoff Utility
35
+
36
+ This is a private module that implements the exponential back off algorithm.
37
+ It can be used as a utility for code that needs to retry on failure, for example
38
+ an HTTP request.
39
+ """
40
+
41
+
42
+ class _BaseExponentialBackoff:
43
+ """An exponential backoff iterator base class.
44
+
45
+ Args:
46
+ total_attempts Optional[int]:
47
+ The maximum amount of retries that should happen.
48
+ The default value is 3 attempts.
49
+ initial_wait_seconds Optional[int]:
50
+ The amount of time to sleep in the first backoff. This parameter
51
+ should be in seconds.
52
+ The default value is 1 second.
53
+ randomization_factor Optional[float]:
54
+ The amount of jitter that should be in each backoff. For example,
55
+ a value of 0.1 will introduce a jitter range of 10% to the
56
+ current backoff period.
57
+ The default value is 0.1.
58
+ multiplier Optional[float]:
59
+ The backoff multipler. This adjusts how much each backoff will
60
+ increase. For example a value of 2.0 leads to a 200% backoff
61
+ on each attempt. If the initial_wait is 1.0 it would look like
62
+ this sequence [1.0, 2.0, 4.0, 8.0].
63
+ The default value is 2.0.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ total_attempts=_DEFAULT_RETRY_TOTAL_ATTEMPTS,
69
+ initial_wait_seconds=_DEFAULT_INITIAL_INTERVAL_SECONDS,
70
+ randomization_factor=_DEFAULT_RANDOMIZATION_FACTOR,
71
+ multiplier=_DEFAULT_MULTIPLIER,
72
+ ):
73
+ if total_attempts < 1:
74
+ raise exceptions.InvalidValue(
75
+ f"total_attempts must be greater than or equal to 1 but was {total_attempts}"
76
+ )
77
+
78
+ self._total_attempts = total_attempts
79
+ self._initial_wait_seconds = initial_wait_seconds
80
+
81
+ self._current_wait_in_seconds = self._initial_wait_seconds
82
+
83
+ self._randomization_factor = randomization_factor
84
+ self._multiplier = multiplier
85
+ self._backoff_count = 0
86
+
87
+ @property
88
+ def total_attempts(self):
89
+ """The total amount of backoff attempts that will be made."""
90
+ return self._total_attempts
91
+
92
+ @property
93
+ def backoff_count(self):
94
+ """The current amount of backoff attempts that have been made."""
95
+ return self._backoff_count
96
+
97
+ def _reset(self):
98
+ self._backoff_count = 0
99
+ self._current_wait_in_seconds = self._initial_wait_seconds
100
+
101
+ def _calculate_jitter(self):
102
+ jitter_variance = self._current_wait_in_seconds * self._randomization_factor
103
+ jitter = random.uniform(
104
+ self._current_wait_in_seconds - jitter_variance,
105
+ self._current_wait_in_seconds + jitter_variance,
106
+ )
107
+
108
+ return jitter
109
+
110
+
111
+ class ExponentialBackoff(_BaseExponentialBackoff):
112
+ """An exponential backoff iterator. This can be used in a for loop to
113
+ perform requests with exponential backoff.
114
+ """
115
+
116
+ def __init__(self, *args, **kwargs):
117
+ super(ExponentialBackoff, self).__init__(*args, **kwargs)
118
+
119
+ def __iter__(self):
120
+ self._reset()
121
+ return self
122
+
123
+ def __next__(self):
124
+ if self._backoff_count >= self._total_attempts:
125
+ raise StopIteration
126
+ self._backoff_count += 1
127
+
128
+ if self._backoff_count <= 1:
129
+ return self._backoff_count
130
+
131
+ jitter = self._calculate_jitter()
132
+
133
+ time.sleep(jitter)
134
+
135
+ self._current_wait_in_seconds *= self._multiplier
136
+ return self._backoff_count
137
+
138
+
139
+ class AsyncExponentialBackoff(_BaseExponentialBackoff):
140
+ """An async exponential backoff iterator. This can be used in a for loop to
141
+ perform async requests with exponential backoff.
142
+ """
143
+
144
+ def __init__(self, *args, **kwargs):
145
+ super(AsyncExponentialBackoff, self).__init__(*args, **kwargs)
146
+
147
+ def __aiter__(self):
148
+ self._reset()
149
+ return self
150
+
151
+ async def __anext__(self):
152
+ if self._backoff_count >= self._total_attempts:
153
+ raise StopAsyncIteration
154
+ self._backoff_count += 1
155
+
156
+ if self._backoff_count <= 1:
157
+ return self._backoff_count
158
+
159
+ jitter = self._calculate_jitter()
160
+
161
+ await asyncio.sleep(jitter)
162
+
163
+ self._current_wait_in_seconds *= self._multiplier
164
+ return self._backoff_count
lib/python3.10/site-packages/google/auth/_jwt_async.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ """JSON Web Tokens
16
+
17
+ Provides support for creating (encoding) and verifying (decoding) JWTs,
18
+ especially JWTs generated and consumed by Google infrastructure.
19
+
20
+ See `rfc7519`_ for more details on JWTs.
21
+
22
+ To encode a JWT use :func:`encode`::
23
+
24
+ from google.auth import crypt
25
+ from google.auth import jwt_async
26
+
27
+ signer = crypt.Signer(private_key)
28
+ payload = {'some': 'payload'}
29
+ encoded = jwt_async.encode(signer, payload)
30
+
31
+ To decode a JWT and verify claims use :func:`decode`::
32
+
33
+ claims = jwt_async.decode(encoded, certs=public_certs)
34
+
35
+ You can also skip verification::
36
+
37
+ claims = jwt_async.decode(encoded, verify=False)
38
+
39
+ .. _rfc7519: https://tools.ietf.org/html/rfc7519
40
+
41
+
42
+ NOTE: This async support is experimental and marked internal. This surface may
43
+ change in minor releases.
44
+ """
45
+
46
+ from google.auth import _credentials_async
47
+ from google.auth import jwt
48
+
49
+
50
+ def encode(signer, payload, header=None, key_id=None):
51
+ """Make a signed JWT.
52
+
53
+ Args:
54
+ signer (google.auth.crypt.Signer): The signer used to sign the JWT.
55
+ payload (Mapping[str, str]): The JWT payload.
56
+ header (Mapping[str, str]): Additional JWT header payload.
57
+ key_id (str): The key id to add to the JWT header. If the
58
+ signer has a key id it will be used as the default. If this is
59
+ specified it will override the signer's key id.
60
+
61
+ Returns:
62
+ bytes: The encoded JWT.
63
+ """
64
+ return jwt.encode(signer, payload, header, key_id)
65
+
66
+
67
+ def decode(token, certs=None, verify=True, audience=None):
68
+ """Decode and verify a JWT.
69
+
70
+ Args:
71
+ token (str): The encoded JWT.
72
+ certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): The
73
+ certificate used to validate the JWT signature. If bytes or string,
74
+ it must the the public key certificate in PEM format. If a mapping,
75
+ it must be a mapping of key IDs to public key certificates in PEM
76
+ format. The mapping must contain the same key ID that's specified
77
+ in the token's header.
78
+ verify (bool): Whether to perform signature and claim validation.
79
+ Verification is done by default.
80
+ audience (str): The audience claim, 'aud', that this JWT should
81
+ contain. If None then the JWT's 'aud' parameter is not verified.
82
+
83
+ Returns:
84
+ Mapping[str, str]: The deserialized JSON payload in the JWT.
85
+
86
+ Raises:
87
+ ValueError: if any verification checks failed.
88
+ """
89
+
90
+ return jwt.decode(token, certs, verify, audience)
91
+
92
+
93
+ class Credentials(
94
+ jwt.Credentials, _credentials_async.Signing, _credentials_async.Credentials
95
+ ):
96
+ """Credentials that use a JWT as the bearer token.
97
+
98
+ These credentials require an "audience" claim. This claim identifies the
99
+ intended recipient of the bearer token.
100
+
101
+ The constructor arguments determine the claims for the JWT that is
102
+ sent with requests. Usually, you'll construct these credentials with
103
+ one of the helper constructors as shown in the next section.
104
+
105
+ To create JWT credentials using a Google service account private key
106
+ JSON file::
107
+
108
+ audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher'
109
+ credentials = jwt_async.Credentials.from_service_account_file(
110
+ 'service-account.json',
111
+ audience=audience)
112
+
113
+ If you already have the service account file loaded and parsed::
114
+
115
+ service_account_info = json.load(open('service_account.json'))
116
+ credentials = jwt_async.Credentials.from_service_account_info(
117
+ service_account_info,
118
+ audience=audience)
119
+
120
+ Both helper methods pass on arguments to the constructor, so you can
121
+ specify the JWT claims::
122
+
123
+ credentials = jwt_async.Credentials.from_service_account_file(
124
+ 'service-account.json',
125
+ audience=audience,
126
+ additional_claims={'meta': 'data'})
127
+
128
+ You can also construct the credentials directly if you have a
129
+ :class:`~google.auth.crypt.Signer` instance::
130
+
131
+ credentials = jwt_async.Credentials(
132
+ signer,
133
+ issuer='your-issuer',
134
+ subject='your-subject',
135
+ audience=audience)
136
+
137
+ The claims are considered immutable. If you want to modify the claims,
138
+ you can easily create another instance using :meth:`with_claims`::
139
+
140
+ new_audience = (
141
+ 'https://pubsub.googleapis.com/google.pubsub.v1.Subscriber')
142
+ new_credentials = credentials.with_claims(audience=new_audience)
143
+ """
144
+
145
+
146
+ class OnDemandCredentials(
147
+ jwt.OnDemandCredentials, _credentials_async.Signing, _credentials_async.Credentials
148
+ ):
149
+ """On-demand JWT credentials.
150
+
151
+ Like :class:`Credentials`, this class uses a JWT as the bearer token for
152
+ authentication. However, this class does not require the audience at
153
+ construction time. Instead, it will generate a new token on-demand for
154
+ each request using the request URI as the audience. It caches tokens
155
+ so that multiple requests to the same URI do not incur the overhead
156
+ of generating a new token every time.
157
+
158
+ This behavior is especially useful for `gRPC`_ clients. A gRPC service may
159
+ have multiple audience and gRPC clients may not know all of the audiences
160
+ required for accessing a particular service. With these credentials,
161
+ no knowledge of the audiences is required ahead of time.
162
+
163
+ .. _grpc: http://www.grpc.io/
164
+ """
lib/python3.10/site-packages/google/auth/_oauth2client.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Helpers for transitioning from oauth2client to google-auth.
16
+
17
+ .. warning::
18
+ This module is private as it is intended to assist first-party downstream
19
+ clients with the transition from oauth2client to google-auth.
20
+ """
21
+
22
+ from __future__ import absolute_import
23
+
24
+ from google.auth import _helpers
25
+ import google.auth.app_engine
26
+ import google.auth.compute_engine
27
+ import google.oauth2.credentials
28
+ import google.oauth2.service_account
29
+
30
+ try:
31
+ import oauth2client.client # type: ignore
32
+ import oauth2client.contrib.gce # type: ignore
33
+ import oauth2client.service_account # type: ignore
34
+ except ImportError as caught_exc:
35
+ raise ImportError("oauth2client is not installed.") from caught_exc
36
+
37
+ try:
38
+ import oauth2client.contrib.appengine # type: ignore
39
+
40
+ _HAS_APPENGINE = True
41
+ except ImportError:
42
+ _HAS_APPENGINE = False
43
+
44
+
45
+ _CONVERT_ERROR_TMPL = "Unable to convert {} to a google-auth credentials class."
46
+
47
+
48
+ def _convert_oauth2_credentials(credentials):
49
+ """Converts to :class:`google.oauth2.credentials.Credentials`.
50
+
51
+ Args:
52
+ credentials (Union[oauth2client.client.OAuth2Credentials,
53
+ oauth2client.client.GoogleCredentials]): The credentials to
54
+ convert.
55
+
56
+ Returns:
57
+ google.oauth2.credentials.Credentials: The converted credentials.
58
+ """
59
+ new_credentials = google.oauth2.credentials.Credentials(
60
+ token=credentials.access_token,
61
+ refresh_token=credentials.refresh_token,
62
+ token_uri=credentials.token_uri,
63
+ client_id=credentials.client_id,
64
+ client_secret=credentials.client_secret,
65
+ scopes=credentials.scopes,
66
+ )
67
+
68
+ new_credentials._expires = credentials.token_expiry
69
+
70
+ return new_credentials
71
+
72
+
73
+ def _convert_service_account_credentials(credentials):
74
+ """Converts to :class:`google.oauth2.service_account.Credentials`.
75
+
76
+ Args:
77
+ credentials (Union[
78
+ oauth2client.service_account.ServiceAccountCredentials,
79
+ oauth2client.service_account._JWTAccessCredentials]): The
80
+ credentials to convert.
81
+
82
+ Returns:
83
+ google.oauth2.service_account.Credentials: The converted credentials.
84
+ """
85
+ info = credentials.serialization_data.copy()
86
+ info["token_uri"] = credentials.token_uri
87
+ return google.oauth2.service_account.Credentials.from_service_account_info(info)
88
+
89
+
90
+ def _convert_gce_app_assertion_credentials(credentials):
91
+ """Converts to :class:`google.auth.compute_engine.Credentials`.
92
+
93
+ Args:
94
+ credentials (oauth2client.contrib.gce.AppAssertionCredentials): The
95
+ credentials to convert.
96
+
97
+ Returns:
98
+ google.oauth2.service_account.Credentials: The converted credentials.
99
+ """
100
+ return google.auth.compute_engine.Credentials(
101
+ service_account_email=credentials.service_account_email
102
+ )
103
+
104
+
105
+ def _convert_appengine_app_assertion_credentials(credentials):
106
+ """Converts to :class:`google.auth.app_engine.Credentials`.
107
+
108
+ Args:
109
+ credentials (oauth2client.contrib.app_engine.AppAssertionCredentials):
110
+ The credentials to convert.
111
+
112
+ Returns:
113
+ google.oauth2.service_account.Credentials: The converted credentials.
114
+ """
115
+ # pylint: disable=invalid-name
116
+ return google.auth.app_engine.Credentials(
117
+ scopes=_helpers.string_to_scopes(credentials.scope),
118
+ service_account_id=credentials.service_account_id,
119
+ )
120
+
121
+
122
+ _CLASS_CONVERSION_MAP = {
123
+ oauth2client.client.OAuth2Credentials: _convert_oauth2_credentials,
124
+ oauth2client.client.GoogleCredentials: _convert_oauth2_credentials,
125
+ oauth2client.service_account.ServiceAccountCredentials: _convert_service_account_credentials,
126
+ oauth2client.service_account._JWTAccessCredentials: _convert_service_account_credentials,
127
+ oauth2client.contrib.gce.AppAssertionCredentials: _convert_gce_app_assertion_credentials,
128
+ }
129
+
130
+ if _HAS_APPENGINE:
131
+ _CLASS_CONVERSION_MAP[
132
+ oauth2client.contrib.appengine.AppAssertionCredentials
133
+ ] = _convert_appengine_app_assertion_credentials
134
+
135
+
136
+ def convert(credentials):
137
+ """Convert oauth2client credentials to google-auth credentials.
138
+
139
+ This class converts:
140
+
141
+ - :class:`oauth2client.client.OAuth2Credentials` to
142
+ :class:`google.oauth2.credentials.Credentials`.
143
+ - :class:`oauth2client.client.GoogleCredentials` to
144
+ :class:`google.oauth2.credentials.Credentials`.
145
+ - :class:`oauth2client.service_account.ServiceAccountCredentials` to
146
+ :class:`google.oauth2.service_account.Credentials`.
147
+ - :class:`oauth2client.service_account._JWTAccessCredentials` to
148
+ :class:`google.oauth2.service_account.Credentials`.
149
+ - :class:`oauth2client.contrib.gce.AppAssertionCredentials` to
150
+ :class:`google.auth.compute_engine.Credentials`.
151
+ - :class:`oauth2client.contrib.appengine.AppAssertionCredentials` to
152
+ :class:`google.auth.app_engine.Credentials`.
153
+
154
+ Returns:
155
+ google.auth.credentials.Credentials: The converted credentials.
156
+
157
+ Raises:
158
+ ValueError: If the credentials could not be converted.
159
+ """
160
+
161
+ credentials_class = type(credentials)
162
+
163
+ try:
164
+ return _CLASS_CONVERSION_MAP[credentials_class](credentials)
165
+ except KeyError as caught_exc:
166
+ new_exc = ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
167
+ raise new_exc from caught_exc
lib/python3.10/site-packages/google/auth/_service_account_info.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Helper functions for loading data from a Google service account file."""
16
+
17
+ import io
18
+ import json
19
+
20
+ from google.auth import crypt
21
+ from google.auth import exceptions
22
+
23
+
24
+ def from_dict(data, require=None, use_rsa_signer=True):
25
+ """Validates a dictionary containing Google service account data.
26
+
27
+ Creates and returns a :class:`google.auth.crypt.Signer` instance from the
28
+ private key specified in the data.
29
+
30
+ Args:
31
+ data (Mapping[str, str]): The service account data
32
+ require (Sequence[str]): List of keys required to be present in the
33
+ info.
34
+ use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer.
35
+ We use RSA signer by default.
36
+
37
+ Returns:
38
+ google.auth.crypt.Signer: A signer created from the private key in the
39
+ service account file.
40
+
41
+ Raises:
42
+ MalformedError: if the data was in the wrong format, or if one of the
43
+ required keys is missing.
44
+ """
45
+ keys_needed = set(require if require is not None else [])
46
+
47
+ missing = keys_needed.difference(data.keys())
48
+
49
+ if missing:
50
+ raise exceptions.MalformedError(
51
+ "Service account info was not in the expected format, missing "
52
+ "fields {}.".format(", ".join(missing))
53
+ )
54
+
55
+ # Create a signer.
56
+ if use_rsa_signer:
57
+ signer = crypt.RSASigner.from_service_account_info(data)
58
+ else:
59
+ signer = crypt.ES256Signer.from_service_account_info(data)
60
+
61
+ return signer
62
+
63
+
64
+ def from_filename(filename, require=None, use_rsa_signer=True):
65
+ """Reads a Google service account JSON file and returns its parsed info.
66
+
67
+ Args:
68
+ filename (str): The path to the service account .json file.
69
+ require (Sequence[str]): List of keys required to be present in the
70
+ info.
71
+ use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer.
72
+ We use RSA signer by default.
73
+
74
+ Returns:
75
+ Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified
76
+ info and a signer instance.
77
+ """
78
+ with io.open(filename, "r", encoding="utf-8") as json_file:
79
+ data = json.load(json_file)
80
+ return data, from_dict(data, require=require, use_rsa_signer=use_rsa_signer)
lib/python3.10/site-packages/google/auth/aio/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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
+
15
+ """Google Auth AIO Library for Python."""
16
+
17
+ import logging
18
+
19
+ from google.auth import version as google_auth_version
20
+
21
+
22
+ __version__ = google_auth_version.__version__
23
+
24
+ # Set default logging handler to avoid "No handler found" warnings.
25
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
lib/python3.10/site-packages/google/auth/aio/credentials.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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
+
15
+
16
+ """Interfaces for asynchronous credentials."""
17
+
18
+
19
+ from google.auth import _helpers
20
+ from google.auth import exceptions
21
+ from google.auth._credentials_base import _BaseCredentials
22
+
23
+
24
+ class Credentials(_BaseCredentials):
25
+ """Base class for all asynchronous credentials.
26
+
27
+ All credentials have a :attr:`token` that is used for authentication and
28
+ may also optionally set an :attr:`expiry` to indicate when the token will
29
+ no longer be valid.
30
+
31
+ Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
32
+ Credentials can do this automatically before the first HTTP request in
33
+ :meth:`before_request`.
34
+
35
+ Although the token and expiration will change as the credentials are
36
+ :meth:`refreshed <refresh>` and used, credentials should be considered
37
+ immutable. Various credentials will accept configuration such as private
38
+ keys, scopes, and other options. These options are not changeable after
39
+ construction. Some classes will provide mechanisms to copy the credentials
40
+ with modifications such as :meth:`ScopedCredentials.with_scopes`.
41
+ """
42
+
43
+ def __init__(self):
44
+ super(Credentials, self).__init__()
45
+
46
+ async def apply(self, headers, token=None):
47
+ """Apply the token to the authentication header.
48
+
49
+ Args:
50
+ headers (Mapping): The HTTP request headers.
51
+ token (Optional[str]): If specified, overrides the current access
52
+ token.
53
+ """
54
+ self._apply(headers, token=token)
55
+
56
+ async def refresh(self, request):
57
+ """Refreshes the access token.
58
+
59
+ Args:
60
+ request (google.auth.aio.transport.Request): The object used to make
61
+ HTTP requests.
62
+
63
+ Raises:
64
+ google.auth.exceptions.RefreshError: If the credentials could
65
+ not be refreshed.
66
+ """
67
+ raise NotImplementedError("Refresh must be implemented")
68
+
69
+ async def before_request(self, request, method, url, headers):
70
+ """Performs credential-specific before request logic.
71
+
72
+ Refreshes the credentials if necessary, then calls :meth:`apply` to
73
+ apply the token to the authentication header.
74
+
75
+ Args:
76
+ request (google.auth.aio.transport.Request): The object used to make
77
+ HTTP requests.
78
+ method (str): The request's HTTP method or the RPC method being
79
+ invoked.
80
+ url (str): The request's URI or the RPC service's URI.
81
+ headers (Mapping): The request's headers.
82
+ """
83
+ await self.apply(headers)
84
+
85
+
86
+ class StaticCredentials(Credentials):
87
+ """Asynchronous Credentials representing an immutable access token.
88
+
89
+ The credentials are considered immutable except the tokens which can be
90
+ configured in the constructor ::
91
+
92
+ credentials = StaticCredentials(token="token123")
93
+
94
+ StaticCredentials does not support :meth `refresh` and assumes that the configured
95
+ token is valid and not expired. StaticCredentials will never attempt to
96
+ refresh the token.
97
+ """
98
+
99
+ def __init__(self, token):
100
+ """
101
+ Args:
102
+ token (str): The access token.
103
+ """
104
+ super(StaticCredentials, self).__init__()
105
+ self.token = token
106
+
107
+ @_helpers.copy_docstring(Credentials)
108
+ async def refresh(self, request):
109
+ raise exceptions.InvalidOperation("Static credentials cannot be refreshed.")
110
+
111
+ # Note: before_request should never try to refresh access tokens.
112
+ # StaticCredentials intentionally does not support it.
113
+ @_helpers.copy_docstring(Credentials)
114
+ async def before_request(self, request, method, url, headers):
115
+ await self.apply(headers)
116
+
117
+
118
+ class AnonymousCredentials(Credentials):
119
+ """Asynchronous Credentials that do not provide any authentication information.
120
+
121
+ These are useful in the case of services that support anonymous access or
122
+ local service emulators that do not use credentials.
123
+ """
124
+
125
+ async def refresh(self, request):
126
+ """Raises :class:``InvalidOperation``, anonymous credentials cannot be
127
+ refreshed."""
128
+ raise exceptions.InvalidOperation("Anonymous credentials cannot be refreshed.")
129
+
130
+ async def apply(self, headers, token=None):
131
+ """Anonymous credentials do nothing to the request.
132
+
133
+ The optional ``token`` argument is not supported.
134
+
135
+ Raises:
136
+ google.auth.exceptions.InvalidValue: If a token was specified.
137
+ """
138
+ if token is not None:
139
+ raise exceptions.InvalidValue("Anonymous credentials don't support tokens.")
140
+
141
+ async def before_request(self, request, method, url, headers):
142
+ """Anonymous credentials do nothing to the request."""
143
+ pass
lib/python3.10/site-packages/google/auth/aio/transport/__init__.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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
+
15
+ """Transport - Asynchronous HTTP client library support.
16
+
17
+ :mod:`google.auth.aio` is designed to work with various asynchronous client libraries such
18
+ as aiohttp. In order to work across these libraries with different
19
+ interfaces some abstraction is needed.
20
+
21
+ This module provides two interfaces that are implemented by transport adapters
22
+ to support HTTP libraries. :class:`Request` defines the interface expected by
23
+ :mod:`google.auth` to make asynchronous requests. :class:`Response` defines the interface
24
+ for the return value of :class:`Request`.
25
+ """
26
+
27
+ import abc
28
+ from typing import AsyncGenerator, Mapping, Optional
29
+
30
+ import google.auth.transport
31
+
32
+
33
+ _DEFAULT_TIMEOUT_SECONDS = 180
34
+
35
+ DEFAULT_RETRYABLE_STATUS_CODES = google.auth.transport.DEFAULT_RETRYABLE_STATUS_CODES
36
+ """Sequence[int]: HTTP status codes indicating a request can be retried.
37
+ """
38
+
39
+
40
+ DEFAULT_MAX_RETRY_ATTEMPTS = 3
41
+ """int: How many times to retry a request."""
42
+
43
+
44
+ class Response(metaclass=abc.ABCMeta):
45
+ """Asynchronous HTTP Response Interface."""
46
+
47
+ @property
48
+ @abc.abstractmethod
49
+ def status_code(self) -> int:
50
+ """
51
+ The HTTP response status code.
52
+
53
+ Returns:
54
+ int: The HTTP response status code.
55
+
56
+ """
57
+ raise NotImplementedError("status_code must be implemented.")
58
+
59
+ @property
60
+ @abc.abstractmethod
61
+ def headers(self) -> Mapping[str, str]:
62
+ """The HTTP response headers.
63
+
64
+ Returns:
65
+ Mapping[str, str]: The HTTP response headers.
66
+ """
67
+ raise NotImplementedError("headers must be implemented.")
68
+
69
+ @abc.abstractmethod
70
+ async def content(self, chunk_size: int) -> AsyncGenerator[bytes, None]:
71
+ """The raw response content.
72
+
73
+ Args:
74
+ chunk_size (int): The size of each chunk.
75
+
76
+ Yields:
77
+ AsyncGenerator[bytes, None]: An asynchronous generator yielding
78
+ response chunks as bytes.
79
+ """
80
+ raise NotImplementedError("content must be implemented.")
81
+
82
+ @abc.abstractmethod
83
+ async def read(self) -> bytes:
84
+ """Read the entire response content as bytes.
85
+
86
+ Returns:
87
+ bytes: The entire response content.
88
+ """
89
+ raise NotImplementedError("read must be implemented.")
90
+
91
+ @abc.abstractmethod
92
+ async def close(self):
93
+ """Close the response after it is fully consumed to resource."""
94
+ raise NotImplementedError("close must be implemented.")
95
+
96
+
97
+ class Request(metaclass=abc.ABCMeta):
98
+ """Interface for a callable that makes HTTP requests.
99
+
100
+ Specific transport implementations should provide an implementation of
101
+ this that adapts their specific request / response API.
102
+
103
+ .. automethod:: __call__
104
+ """
105
+
106
+ @abc.abstractmethod
107
+ async def __call__(
108
+ self,
109
+ url: str,
110
+ method: str,
111
+ body: Optional[bytes],
112
+ headers: Optional[Mapping[str, str]],
113
+ timeout: float,
114
+ **kwargs
115
+ ) -> Response:
116
+ """Make an HTTP request.
117
+
118
+ Args:
119
+ url (str): The URI to be requested.
120
+ method (str): The HTTP method to use for the request. Defaults
121
+ to 'GET'.
122
+ body (Optional[bytes]): The payload / body in HTTP request.
123
+ headers (Mapping[str, str]): Request headers.
124
+ timeout (float): The number of seconds to wait for a
125
+ response from the server. If not specified or if None, the
126
+ transport-specific default timeout will be used.
127
+ kwargs: Additional arguments passed on to the transport's
128
+ request method.
129
+
130
+ Returns:
131
+ google.auth.aio.transport.Response: The HTTP response.
132
+
133
+ Raises:
134
+ google.auth.exceptions.TransportError: If any exception occurred.
135
+ """
136
+ # pylint: disable=redundant-returns-doc, missing-raises-doc
137
+ # (pylint doesn't play well with abstract docstrings.)
138
+ raise NotImplementedError("__call__ must be implemented.")
139
+
140
+ async def close(self) -> None:
141
+ """
142
+ Close the underlying session.
143
+ """
144
+ raise NotImplementedError("close must be implemented.")
lib/python3.10/site-packages/google/auth/aio/transport/aiohttp.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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
+
15
+ """Transport adapter for Asynchronous HTTP Requests based on aiohttp.
16
+ """
17
+
18
+ import asyncio
19
+ from typing import AsyncGenerator, Mapping, Optional
20
+
21
+ try:
22
+ import aiohttp # type: ignore
23
+ except ImportError as caught_exc: # pragma: NO COVER
24
+ raise ImportError(
25
+ "The aiohttp library is not installed from please install the aiohttp package to use the aiohttp transport."
26
+ ) from caught_exc
27
+
28
+ from google.auth import _helpers
29
+ from google.auth import exceptions
30
+ from google.auth.aio import transport
31
+
32
+
33
+ class Response(transport.Response):
34
+ """
35
+ Represents an HTTP response and its data. It is returned by ``google.auth.aio.transport.sessions.AsyncAuthorizedSession``.
36
+
37
+ Args:
38
+ response (aiohttp.ClientResponse): An instance of aiohttp.ClientResponse.
39
+
40
+ Attributes:
41
+ status_code (int): The HTTP status code of the response.
42
+ headers (Mapping[str, str]): The HTTP headers of the response.
43
+ """
44
+
45
+ def __init__(self, response: aiohttp.ClientResponse):
46
+ self._response = response
47
+
48
+ @property
49
+ @_helpers.copy_docstring(transport.Response)
50
+ def status_code(self) -> int:
51
+ return self._response.status
52
+
53
+ @property
54
+ @_helpers.copy_docstring(transport.Response)
55
+ def headers(self) -> Mapping[str, str]:
56
+ return {key: value for key, value in self._response.headers.items()}
57
+
58
+ @_helpers.copy_docstring(transport.Response)
59
+ async def content(self, chunk_size: int = 1024) -> AsyncGenerator[bytes, None]:
60
+ try:
61
+ async for chunk in self._response.content.iter_chunked(
62
+ chunk_size
63
+ ): # pragma: no branch
64
+ yield chunk
65
+ except aiohttp.ClientPayloadError as exc:
66
+ raise exceptions.ResponseError(
67
+ "Failed to read from the payload stream."
68
+ ) from exc
69
+
70
+ @_helpers.copy_docstring(transport.Response)
71
+ async def read(self) -> bytes:
72
+ try:
73
+ return await self._response.read()
74
+ except aiohttp.ClientResponseError as exc:
75
+ raise exceptions.ResponseError("Failed to read the response body.") from exc
76
+
77
+ @_helpers.copy_docstring(transport.Response)
78
+ async def close(self):
79
+ self._response.close()
80
+
81
+
82
+ class Request(transport.Request):
83
+ """Asynchronous Requests request adapter.
84
+
85
+ This class is used internally for making requests using aiohttp
86
+ in a consistent way. If you use :class:`google.auth.aio.transport.sessions.AsyncAuthorizedSession`
87
+ you do not need to construct or use this class directly.
88
+
89
+ This class can be useful if you want to configure a Request callable
90
+ with a custom ``aiohttp.ClientSession`` in :class:`AuthorizedSession` or if
91
+ you want to manually refresh a :class:`~google.auth.aio.credentials.Credentials` instance::
92
+
93
+ import aiohttp
94
+ import google.auth.aio.transport.aiohttp
95
+
96
+ # Default example:
97
+ request = google.auth.aio.transport.aiohttp.Request()
98
+ await credentials.refresh(request)
99
+
100
+ # Custom aiohttp Session Example:
101
+ session = session=aiohttp.ClientSession(auto_decompress=False)
102
+ request = google.auth.aio.transport.aiohttp.Request(session=session)
103
+ auth_sesion = google.auth.aio.transport.sessions.AsyncAuthorizedSession(auth_request=request)
104
+
105
+ Args:
106
+ session (aiohttp.ClientSession): An instance :class:`aiohttp.ClientSession` used
107
+ to make HTTP requests. If not specified, a session will be created.
108
+
109
+ .. automethod:: __call__
110
+ """
111
+
112
+ def __init__(self, session: aiohttp.ClientSession = None):
113
+ self._session = session
114
+ self._closed = False
115
+
116
+ async def __call__(
117
+ self,
118
+ url: str,
119
+ method: str = "GET",
120
+ body: Optional[bytes] = None,
121
+ headers: Optional[Mapping[str, str]] = None,
122
+ timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
123
+ **kwargs,
124
+ ) -> transport.Response:
125
+ """
126
+ Make an HTTP request using aiohttp.
127
+
128
+ Args:
129
+ url (str): The URL to be requested.
130
+ method (Optional[str]):
131
+ The HTTP method to use for the request. Defaults to 'GET'.
132
+ body (Optional[bytes]):
133
+ The payload or body in HTTP request.
134
+ headers (Optional[Mapping[str, str]]):
135
+ Request headers.
136
+ timeout (float): The number of seconds to wait for a
137
+ response from the server. If not specified or if None, the
138
+ requests default timeout will be used.
139
+ kwargs: Additional arguments passed through to the underlying
140
+ aiohttp :meth:`aiohttp.Session.request` method.
141
+
142
+ Returns:
143
+ google.auth.aio.transport.Response: The HTTP response.
144
+
145
+ Raises:
146
+ - google.auth.exceptions.TransportError: If the request fails or if the session is closed.
147
+ - google.auth.exceptions.TimeoutError: If the request times out.
148
+ """
149
+
150
+ try:
151
+ if self._closed:
152
+ raise exceptions.TransportError("session is closed.")
153
+
154
+ if not self._session:
155
+ self._session = aiohttp.ClientSession()
156
+
157
+ client_timeout = aiohttp.ClientTimeout(total=timeout)
158
+ response = await self._session.request(
159
+ method,
160
+ url,
161
+ data=body,
162
+ headers=headers,
163
+ timeout=client_timeout,
164
+ **kwargs,
165
+ )
166
+ return Response(response)
167
+
168
+ except aiohttp.ClientError as caught_exc:
169
+ client_exc = exceptions.TransportError(f"Failed to send request to {url}.")
170
+ raise client_exc from caught_exc
171
+
172
+ except asyncio.TimeoutError as caught_exc:
173
+ timeout_exc = exceptions.TimeoutError(
174
+ f"Request timed out after {timeout} seconds."
175
+ )
176
+ raise timeout_exc from caught_exc
177
+
178
+ async def close(self) -> None:
179
+ """
180
+ Close the underlying aiohttp session to release the acquired resources.
181
+ """
182
+ if not self._closed and self._session:
183
+ await self._session.close()
184
+ self._closed = True
lib/python3.10/site-packages/google/auth/aio/transport/sessions.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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
+
15
+ import asyncio
16
+ from contextlib import asynccontextmanager
17
+ import functools
18
+ import time
19
+ from typing import Mapping, Optional
20
+
21
+ from google.auth import _exponential_backoff, exceptions
22
+ from google.auth.aio import transport
23
+ from google.auth.aio.credentials import Credentials
24
+ from google.auth.exceptions import TimeoutError
25
+
26
+ try:
27
+ from google.auth.aio.transport.aiohttp import Request as AiohttpRequest
28
+
29
+ AIOHTTP_INSTALLED = True
30
+ except ImportError: # pragma: NO COVER
31
+ AIOHTTP_INSTALLED = False
32
+
33
+
34
+ @asynccontextmanager
35
+ async def timeout_guard(timeout):
36
+ """
37
+ timeout_guard is an asynchronous context manager to apply a timeout to an asynchronous block of code.
38
+
39
+ Args:
40
+ timeout (float): The time in seconds before the context manager times out.
41
+
42
+ Raises:
43
+ google.auth.exceptions.TimeoutError: If the code within the context exceeds the provided timeout.
44
+
45
+ Usage:
46
+ async with timeout_guard(10) as with_timeout:
47
+ await with_timeout(async_function())
48
+ """
49
+ start = time.monotonic()
50
+ total_timeout = timeout
51
+
52
+ def _remaining_time():
53
+ elapsed = time.monotonic() - start
54
+ remaining = total_timeout - elapsed
55
+ if remaining <= 0:
56
+ raise TimeoutError(
57
+ f"Context manager exceeded the configured timeout of {total_timeout}s."
58
+ )
59
+ return remaining
60
+
61
+ async def with_timeout(coro):
62
+ try:
63
+ remaining = _remaining_time()
64
+ response = await asyncio.wait_for(coro, remaining)
65
+ return response
66
+ except (asyncio.TimeoutError, TimeoutError) as e:
67
+ raise TimeoutError(
68
+ f"The operation {coro} exceeded the configured timeout of {total_timeout}s."
69
+ ) from e
70
+
71
+ try:
72
+ yield with_timeout
73
+
74
+ finally:
75
+ _remaining_time()
76
+
77
+
78
+ class AsyncAuthorizedSession:
79
+ """This is an asynchronous implementation of :class:`google.auth.requests.AuthorizedSession` class.
80
+ We utilize an instance of a class that implements :class:`google.auth.aio.transport.Request` configured
81
+ by the caller or otherwise default to `google.auth.aio.transport.aiohttp.Request` if the external aiohttp
82
+ package is installed.
83
+
84
+ A Requests Session class with credentials.
85
+
86
+ This class is used to perform asynchronous requests to API endpoints that require
87
+ authorization::
88
+
89
+ import aiohttp
90
+ from google.auth.aio.transport import sessions
91
+
92
+ async with sessions.AsyncAuthorizedSession(credentials) as authed_session:
93
+ response = await authed_session.request(
94
+ 'GET', 'https://www.googleapis.com/storage/v1/b')
95
+
96
+ The underlying :meth:`request` implementation handles adding the
97
+ credentials' headers to the request and refreshing credentials as needed.
98
+
99
+ Args:
100
+ credentials (google.auth.aio.credentials.Credentials):
101
+ The credentials to add to the request.
102
+ auth_request (Optional[google.auth.aio.transport.Request]):
103
+ An instance of a class that implements
104
+ :class:`~google.auth.aio.transport.Request` used to make requests
105
+ and refresh credentials. If not passed,
106
+ an instance of :class:`~google.auth.aio.transport.aiohttp.Request`
107
+ is created.
108
+
109
+ Raises:
110
+ - google.auth.exceptions.TransportError: If `auth_request` is `None`
111
+ and the external package `aiohttp` is not installed.
112
+ - google.auth.exceptions.InvalidType: If the provided credentials are
113
+ not of type `google.auth.aio.credentials.Credentials`.
114
+ """
115
+
116
+ def __init__(
117
+ self, credentials: Credentials, auth_request: Optional[transport.Request] = None
118
+ ):
119
+ if not isinstance(credentials, Credentials):
120
+ raise exceptions.InvalidType(
121
+ f"The configured credentials of type {type(credentials)} are invalid and must be of type `google.auth.aio.credentials.Credentials`"
122
+ )
123
+ self._credentials = credentials
124
+ _auth_request = auth_request
125
+ if not _auth_request and AIOHTTP_INSTALLED:
126
+ _auth_request = AiohttpRequest()
127
+ if _auth_request is None:
128
+ raise exceptions.TransportError(
129
+ "`auth_request` must either be configured or the external package `aiohttp` must be installed to use the default value."
130
+ )
131
+ self._auth_request = _auth_request
132
+
133
+ async def request(
134
+ self,
135
+ method: str,
136
+ url: str,
137
+ data: Optional[bytes] = None,
138
+ headers: Optional[Mapping[str, str]] = None,
139
+ max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
140
+ timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
141
+ **kwargs,
142
+ ) -> transport.Response:
143
+ """
144
+ Args:
145
+ method (str): The http method used to make the request.
146
+ url (str): The URI to be requested.
147
+ data (Optional[bytes]): The payload or body in HTTP request.
148
+ headers (Optional[Mapping[str, str]]): Request headers.
149
+ timeout (float):
150
+ The amount of time in seconds to wait for the server response
151
+ with each individual request.
152
+ max_allowed_time (float):
153
+ If the method runs longer than this, a ``Timeout`` exception is
154
+ automatically raised. Unlike the ``timeout`` parameter, this
155
+ value applies to the total method execution time, even if
156
+ multiple requests are made under the hood.
157
+
158
+ Mind that it is not guaranteed that the timeout error is raised
159
+ at ``max_allowed_time``. It might take longer, for example, if
160
+ an underlying request takes a lot of time, but the request
161
+ itself does not timeout, e.g. if a large file is being
162
+ transmitted. The timout error will be raised after such
163
+ request completes.
164
+
165
+ Returns:
166
+ google.auth.aio.transport.Response: The HTTP response.
167
+
168
+ Raises:
169
+ google.auth.exceptions.TimeoutError: If the method does not complete within
170
+ the configured `max_allowed_time` or the request exceeds the configured
171
+ `timeout`.
172
+ """
173
+
174
+ retries = _exponential_backoff.AsyncExponentialBackoff(
175
+ total_attempts=transport.DEFAULT_MAX_RETRY_ATTEMPTS
176
+ )
177
+ async with timeout_guard(max_allowed_time) as with_timeout:
178
+ await with_timeout(
179
+ # Note: before_request will attempt to refresh credentials if expired.
180
+ self._credentials.before_request(
181
+ self._auth_request, method, url, headers
182
+ )
183
+ )
184
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
185
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
186
+ async for _ in retries: # pragma: no branch
187
+ response = await with_timeout(
188
+ self._auth_request(url, method, data, headers, timeout, **kwargs)
189
+ )
190
+ if response.status_code not in transport.DEFAULT_RETRYABLE_STATUS_CODES:
191
+ break
192
+ return response
193
+
194
+ @functools.wraps(request)
195
+ async def get(
196
+ self,
197
+ url: str,
198
+ data: Optional[bytes] = None,
199
+ headers: Optional[Mapping[str, str]] = None,
200
+ max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
201
+ timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
202
+ **kwargs,
203
+ ) -> transport.Response:
204
+ return await self.request(
205
+ "GET", url, data, headers, max_allowed_time, timeout, **kwargs
206
+ )
207
+
208
+ @functools.wraps(request)
209
+ async def post(
210
+ self,
211
+ url: str,
212
+ data: Optional[bytes] = None,
213
+ headers: Optional[Mapping[str, str]] = None,
214
+ max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
215
+ timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
216
+ **kwargs,
217
+ ) -> transport.Response:
218
+ return await self.request(
219
+ "POST", url, data, headers, max_allowed_time, timeout, **kwargs
220
+ )
221
+
222
+ @functools.wraps(request)
223
+ async def put(
224
+ self,
225
+ url: str,
226
+ data: Optional[bytes] = None,
227
+ headers: Optional[Mapping[str, str]] = None,
228
+ max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
229
+ timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
230
+ **kwargs,
231
+ ) -> transport.Response:
232
+ return await self.request(
233
+ "PUT", url, data, headers, max_allowed_time, timeout, **kwargs
234
+ )
235
+
236
+ @functools.wraps(request)
237
+ async def patch(
238
+ self,
239
+ url: str,
240
+ data: Optional[bytes] = None,
241
+ headers: Optional[Mapping[str, str]] = None,
242
+ max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
243
+ timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
244
+ **kwargs,
245
+ ) -> transport.Response:
246
+ return await self.request(
247
+ "PATCH", url, data, headers, max_allowed_time, timeout, **kwargs
248
+ )
249
+
250
+ @functools.wraps(request)
251
+ async def delete(
252
+ self,
253
+ url: str,
254
+ data: Optional[bytes] = None,
255
+ headers: Optional[Mapping[str, str]] = None,
256
+ max_allowed_time: float = transport._DEFAULT_TIMEOUT_SECONDS,
257
+ timeout: float = transport._DEFAULT_TIMEOUT_SECONDS,
258
+ **kwargs,
259
+ ) -> transport.Response:
260
+ return await self.request(
261
+ "DELETE", url, data, headers, max_allowed_time, timeout, **kwargs
262
+ )
263
+
264
+ async def close(self) -> None:
265
+ """
266
+ Close the underlying auth request session.
267
+ """
268
+ await self._auth_request.close()
lib/python3.10/site-packages/google/auth/app_engine.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Google App Engine standard environment support.
16
+
17
+ This module provides authentication and signing for applications running on App
18
+ Engine in the standard environment using the `App Identity API`_.
19
+
20
+
21
+ .. _App Identity API:
22
+ https://cloud.google.com/appengine/docs/python/appidentity/
23
+ """
24
+
25
+ import datetime
26
+
27
+ from google.auth import _helpers
28
+ from google.auth import credentials
29
+ from google.auth import crypt
30
+ from google.auth import exceptions
31
+
32
+ # pytype: disable=import-error
33
+ try:
34
+ from google.appengine.api import app_identity # type: ignore
35
+ except ImportError:
36
+ app_identity = None # type: ignore
37
+ # pytype: enable=import-error
38
+
39
+
40
+ class Signer(crypt.Signer):
41
+ """Signs messages using the App Engine App Identity service.
42
+
43
+ This can be used in place of :class:`google.auth.crypt.Signer` when
44
+ running in the App Engine standard environment.
45
+ """
46
+
47
+ @property
48
+ def key_id(self):
49
+ """Optional[str]: The key ID used to identify this private key.
50
+
51
+ .. warning::
52
+ This is always ``None``. The key ID used by App Engine can not
53
+ be reliably determined ahead of time.
54
+ """
55
+ return None
56
+
57
+ @_helpers.copy_docstring(crypt.Signer)
58
+ def sign(self, message):
59
+ message = _helpers.to_bytes(message)
60
+ _, signature = app_identity.sign_blob(message)
61
+ return signature
62
+
63
+
64
+ def get_project_id():
65
+ """Gets the project ID for the current App Engine application.
66
+
67
+ Returns:
68
+ str: The project ID
69
+
70
+ Raises:
71
+ google.auth.exceptions.OSError: If the App Engine APIs are unavailable.
72
+ """
73
+ # pylint: disable=missing-raises-doc
74
+ # Pylint rightfully thinks google.auth.exceptions.OSError is OSError, but doesn't
75
+ # realize it's a valid alias.
76
+ if app_identity is None:
77
+ raise exceptions.OSError("The App Engine APIs are not available.")
78
+ return app_identity.get_application_id()
79
+
80
+
81
+ class Credentials(
82
+ credentials.Scoped, credentials.Signing, credentials.CredentialsWithQuotaProject
83
+ ):
84
+ """App Engine standard environment credentials.
85
+
86
+ These credentials use the App Engine App Identity API to obtain access
87
+ tokens.
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ scopes=None,
93
+ default_scopes=None,
94
+ service_account_id=None,
95
+ quota_project_id=None,
96
+ ):
97
+ """
98
+ Args:
99
+ scopes (Sequence[str]): Scopes to request from the App Identity
100
+ API.
101
+ default_scopes (Sequence[str]): Default scopes passed by a
102
+ Google client library. Use 'scopes' for user-defined scopes.
103
+ service_account_id (str): The service account ID passed into
104
+ :func:`google.appengine.api.app_identity.get_access_token`.
105
+ If not specified, the default application service account
106
+ ID will be used.
107
+ quota_project_id (Optional[str]): The project ID used for quota
108
+ and billing.
109
+
110
+ Raises:
111
+ google.auth.exceptions.OSError: If the App Engine APIs are unavailable.
112
+ """
113
+ # pylint: disable=missing-raises-doc
114
+ # Pylint rightfully thinks google.auth.exceptions.OSError is OSError, but doesn't
115
+ # realize it's a valid alias.
116
+ if app_identity is None:
117
+ raise exceptions.OSError("The App Engine APIs are not available.")
118
+
119
+ super(Credentials, self).__init__()
120
+ self._scopes = scopes
121
+ self._default_scopes = default_scopes
122
+ self._service_account_id = service_account_id
123
+ self._signer = Signer()
124
+ self._quota_project_id = quota_project_id
125
+
126
+ @_helpers.copy_docstring(credentials.Credentials)
127
+ def refresh(self, request):
128
+ scopes = self._scopes if self._scopes is not None else self._default_scopes
129
+ # pylint: disable=unused-argument
130
+ token, ttl = app_identity.get_access_token(scopes, self._service_account_id)
131
+ expiry = datetime.datetime.utcfromtimestamp(ttl)
132
+
133
+ self.token, self.expiry = token, expiry
134
+
135
+ @property
136
+ def service_account_email(self):
137
+ """The service account email."""
138
+ if self._service_account_id is None:
139
+ self._service_account_id = app_identity.get_service_account_name()
140
+ return self._service_account_id
141
+
142
+ @property
143
+ def requires_scopes(self):
144
+ """Checks if the credentials requires scopes.
145
+
146
+ Returns:
147
+ bool: True if there are no scopes set otherwise False.
148
+ """
149
+ return not self._scopes and not self._default_scopes
150
+
151
+ @_helpers.copy_docstring(credentials.Scoped)
152
+ def with_scopes(self, scopes, default_scopes=None):
153
+ return self.__class__(
154
+ scopes=scopes,
155
+ default_scopes=default_scopes,
156
+ service_account_id=self._service_account_id,
157
+ quota_project_id=self.quota_project_id,
158
+ )
159
+
160
+ @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
161
+ def with_quota_project(self, quota_project_id):
162
+ return self.__class__(
163
+ scopes=self._scopes,
164
+ service_account_id=self._service_account_id,
165
+ quota_project_id=quota_project_id,
166
+ )
167
+
168
+ @_helpers.copy_docstring(credentials.Signing)
169
+ def sign_bytes(self, message):
170
+ return self._signer.sign(message)
171
+
172
+ @property # type: ignore
173
+ @_helpers.copy_docstring(credentials.Signing)
174
+ def signer_email(self):
175
+ return self.service_account_email
176
+
177
+ @property # type: ignore
178
+ @_helpers.copy_docstring(credentials.Signing)
179
+ def signer(self):
180
+ return self._signer
lib/python3.10/site-packages/google/auth/compute_engine/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Google Compute Engine authentication."""
16
+
17
+ from google.auth.compute_engine._metadata import detect_gce_residency_linux
18
+ from google.auth.compute_engine.credentials import Credentials
19
+ from google.auth.compute_engine.credentials import IDTokenCredentials
20
+
21
+
22
+ __all__ = ["Credentials", "IDTokenCredentials", "detect_gce_residency_linux"]
lib/python3.10/site-packages/google/auth/compute_engine/_metadata.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Provides helper methods for talking to the Compute Engine metadata server.
16
+
17
+ See https://cloud.google.com/compute/docs/metadata for more details.
18
+ """
19
+
20
+ import datetime
21
+ import http.client as http_client
22
+ import json
23
+ import logging
24
+ import os
25
+ from urllib.parse import urljoin
26
+
27
+ from google.auth import _helpers
28
+ from google.auth import environment_vars
29
+ from google.auth import exceptions
30
+ from google.auth import metrics
31
+ from google.auth import transport
32
+ from google.auth._exponential_backoff import ExponentialBackoff
33
+
34
+ _LOGGER = logging.getLogger(__name__)
35
+
36
+ # Environment variable GCE_METADATA_HOST is originally named
37
+ # GCE_METADATA_ROOT. For compatibility reasons, here it checks
38
+ # the new variable first; if not set, the system falls back
39
+ # to the old variable.
40
+ _GCE_METADATA_HOST = os.getenv(environment_vars.GCE_METADATA_HOST, None)
41
+ if not _GCE_METADATA_HOST:
42
+ _GCE_METADATA_HOST = os.getenv(
43
+ environment_vars.GCE_METADATA_ROOT, "metadata.google.internal"
44
+ )
45
+ _METADATA_ROOT = "http://{}/computeMetadata/v1/".format(_GCE_METADATA_HOST)
46
+
47
+ # This is used to ping the metadata server, it avoids the cost of a DNS
48
+ # lookup.
49
+ _METADATA_IP_ROOT = "http://{}".format(
50
+ os.getenv(environment_vars.GCE_METADATA_IP, "169.254.169.254")
51
+ )
52
+ _METADATA_FLAVOR_HEADER = "metadata-flavor"
53
+ _METADATA_FLAVOR_VALUE = "Google"
54
+ _METADATA_HEADERS = {_METADATA_FLAVOR_HEADER: _METADATA_FLAVOR_VALUE}
55
+
56
+ # Timeout in seconds to wait for the GCE metadata server when detecting the
57
+ # GCE environment.
58
+ try:
59
+ _METADATA_DEFAULT_TIMEOUT = int(os.getenv("GCE_METADATA_TIMEOUT", 3))
60
+ except ValueError: # pragma: NO COVER
61
+ _METADATA_DEFAULT_TIMEOUT = 3
62
+
63
+ # Detect GCE Residency
64
+ _GOOGLE = "Google"
65
+ _GCE_PRODUCT_NAME_FILE = "/sys/class/dmi/id/product_name"
66
+
67
+
68
+ def is_on_gce(request):
69
+ """Checks to see if the code runs on Google Compute Engine
70
+
71
+ Args:
72
+ request (google.auth.transport.Request): A callable used to make
73
+ HTTP requests.
74
+
75
+ Returns:
76
+ bool: True if the code runs on Google Compute Engine, False otherwise.
77
+ """
78
+ if ping(request):
79
+ return True
80
+
81
+ if os.name == "nt":
82
+ # TODO: implement GCE residency detection on Windows
83
+ return False
84
+
85
+ # Detect GCE residency on Linux
86
+ return detect_gce_residency_linux()
87
+
88
+
89
+ def detect_gce_residency_linux():
90
+ """Detect Google Compute Engine residency by smbios check on Linux
91
+
92
+ Returns:
93
+ bool: True if the GCE product name file is detected, False otherwise.
94
+ """
95
+ try:
96
+ with open(_GCE_PRODUCT_NAME_FILE, "r") as file_obj:
97
+ content = file_obj.read().strip()
98
+
99
+ except Exception:
100
+ return False
101
+
102
+ return content.startswith(_GOOGLE)
103
+
104
+
105
+ def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3):
106
+ """Checks to see if the metadata server is available.
107
+
108
+ Args:
109
+ request (google.auth.transport.Request): A callable used to make
110
+ HTTP requests.
111
+ timeout (int): How long to wait for the metadata server to respond.
112
+ retry_count (int): How many times to attempt connecting to metadata
113
+ server using above timeout.
114
+
115
+ Returns:
116
+ bool: True if the metadata server is reachable, False otherwise.
117
+ """
118
+ # NOTE: The explicit ``timeout`` is a workaround. The underlying
119
+ # issue is that resolving an unknown host on some networks will take
120
+ # 20-30 seconds; making this timeout short fixes the issue, but
121
+ # could lead to false negatives in the event that we are on GCE, but
122
+ # the metadata resolution was particularly slow. The latter case is
123
+ # "unlikely".
124
+ headers = _METADATA_HEADERS.copy()
125
+ headers[metrics.API_CLIENT_HEADER] = metrics.mds_ping()
126
+
127
+ backoff = ExponentialBackoff(total_attempts=retry_count)
128
+
129
+ for attempt in backoff:
130
+ try:
131
+ response = request(
132
+ url=_METADATA_IP_ROOT, method="GET", headers=headers, timeout=timeout
133
+ )
134
+
135
+ metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER)
136
+ return (
137
+ response.status == http_client.OK
138
+ and metadata_flavor == _METADATA_FLAVOR_VALUE
139
+ )
140
+
141
+ except exceptions.TransportError as e:
142
+ _LOGGER.warning(
143
+ "Compute Engine Metadata server unavailable on "
144
+ "attempt %s of %s. Reason: %s",
145
+ attempt,
146
+ retry_count,
147
+ e,
148
+ )
149
+
150
+ return False
151
+
152
+
153
+ def get(
154
+ request,
155
+ path,
156
+ root=_METADATA_ROOT,
157
+ params=None,
158
+ recursive=False,
159
+ retry_count=5,
160
+ headers=None,
161
+ return_none_for_not_found_error=False,
162
+ ):
163
+ """Fetch a resource from the metadata server.
164
+
165
+ Args:
166
+ request (google.auth.transport.Request): A callable used to make
167
+ HTTP requests.
168
+ path (str): The resource to retrieve. For example,
169
+ ``'instance/service-accounts/default'``.
170
+ root (str): The full path to the metadata server root.
171
+ params (Optional[Mapping[str, str]]): A mapping of query parameter
172
+ keys to values.
173
+ recursive (bool): Whether to do a recursive query of metadata. See
174
+ https://cloud.google.com/compute/docs/metadata#aggcontents for more
175
+ details.
176
+ retry_count (int): How many times to attempt connecting to metadata
177
+ server using above timeout.
178
+ headers (Optional[Mapping[str, str]]): Headers for the request.
179
+ return_none_for_not_found_error (Optional[bool]): If True, returns None
180
+ for 404 error instead of throwing an exception.
181
+
182
+ Returns:
183
+ Union[Mapping, str]: If the metadata server returns JSON, a mapping of
184
+ the decoded JSON is returned. Otherwise, the response content is
185
+ returned as a string.
186
+
187
+ Raises:
188
+ google.auth.exceptions.TransportError: if an error occurred while
189
+ retrieving metadata.
190
+ """
191
+ base_url = urljoin(root, path)
192
+ query_params = {} if params is None else params
193
+
194
+ headers_to_use = _METADATA_HEADERS.copy()
195
+ if headers:
196
+ headers_to_use.update(headers)
197
+
198
+ if recursive:
199
+ query_params["recursive"] = "true"
200
+
201
+ url = _helpers.update_query(base_url, query_params)
202
+
203
+ backoff = ExponentialBackoff(total_attempts=retry_count)
204
+ failure_reason = None
205
+ for attempt in backoff:
206
+ try:
207
+ response = request(url=url, method="GET", headers=headers_to_use)
208
+ if response.status in transport.DEFAULT_RETRYABLE_STATUS_CODES:
209
+ _LOGGER.warning(
210
+ "Compute Engine Metadata server unavailable on "
211
+ "attempt %s of %s. Response status: %s",
212
+ attempt,
213
+ retry_count,
214
+ response.status,
215
+ )
216
+ failure_reason = (
217
+ response.data.decode("utf-8")
218
+ if hasattr(response.data, "decode")
219
+ else response.data
220
+ )
221
+ continue
222
+ else:
223
+ break
224
+
225
+ except exceptions.TransportError as e:
226
+ _LOGGER.warning(
227
+ "Compute Engine Metadata server unavailable on "
228
+ "attempt %s of %s. Reason: %s",
229
+ attempt,
230
+ retry_count,
231
+ e,
232
+ )
233
+ failure_reason = e
234
+ else:
235
+ raise exceptions.TransportError(
236
+ "Failed to retrieve {} from the Google Compute Engine "
237
+ "metadata service. Compute Engine Metadata server unavailable due to {}".format(
238
+ url, failure_reason
239
+ )
240
+ )
241
+
242
+ content = _helpers.from_bytes(response.data)
243
+
244
+ if response.status == http_client.NOT_FOUND and return_none_for_not_found_error:
245
+ return None
246
+
247
+ if response.status == http_client.OK:
248
+ if (
249
+ _helpers.parse_content_type(response.headers["content-type"])
250
+ == "application/json"
251
+ ):
252
+ try:
253
+ return json.loads(content)
254
+ except ValueError as caught_exc:
255
+ new_exc = exceptions.TransportError(
256
+ "Received invalid JSON from the Google Compute Engine "
257
+ "metadata service: {:.20}".format(content)
258
+ )
259
+ raise new_exc from caught_exc
260
+ else:
261
+ return content
262
+
263
+ raise exceptions.TransportError(
264
+ "Failed to retrieve {} from the Google Compute Engine "
265
+ "metadata service. Status: {} Response:\n{}".format(
266
+ url, response.status, response.data
267
+ ),
268
+ response,
269
+ )
270
+
271
+
272
+ def get_project_id(request):
273
+ """Get the Google Cloud Project ID from the metadata server.
274
+
275
+ Args:
276
+ request (google.auth.transport.Request): A callable used to make
277
+ HTTP requests.
278
+
279
+ Returns:
280
+ str: The project ID
281
+
282
+ Raises:
283
+ google.auth.exceptions.TransportError: if an error occurred while
284
+ retrieving metadata.
285
+ """
286
+ return get(request, "project/project-id")
287
+
288
+
289
+ def get_universe_domain(request):
290
+ """Get the universe domain value from the metadata server.
291
+
292
+ Args:
293
+ request (google.auth.transport.Request): A callable used to make
294
+ HTTP requests.
295
+
296
+ Returns:
297
+ str: The universe domain value. If the universe domain endpoint is not
298
+ not found, return the default value, which is googleapis.com
299
+
300
+ Raises:
301
+ google.auth.exceptions.TransportError: if an error other than
302
+ 404 occurs while retrieving metadata.
303
+ """
304
+ universe_domain = get(
305
+ request, "universe/universe-domain", return_none_for_not_found_error=True
306
+ )
307
+ if not universe_domain:
308
+ return "googleapis.com"
309
+ return universe_domain
310
+
311
+
312
+ def get_service_account_info(request, service_account="default"):
313
+ """Get information about a service account from the metadata server.
314
+
315
+ Args:
316
+ request (google.auth.transport.Request): A callable used to make
317
+ HTTP requests.
318
+ service_account (str): The string 'default' or a service account email
319
+ address. The determines which service account for which to acquire
320
+ information.
321
+
322
+ Returns:
323
+ Mapping: The service account's information, for example::
324
+
325
+ {
326
+ 'email': '...',
327
+ 'scopes': ['scope', ...],
328
+ 'aliases': ['default', '...']
329
+ }
330
+
331
+ Raises:
332
+ google.auth.exceptions.TransportError: if an error occurred while
333
+ retrieving metadata.
334
+ """
335
+ path = "instance/service-accounts/{0}/".format(service_account)
336
+ # See https://cloud.google.com/compute/docs/metadata#aggcontents
337
+ # for more on the use of 'recursive'.
338
+ return get(request, path, params={"recursive": "true"})
339
+
340
+
341
+ def get_service_account_token(request, service_account="default", scopes=None):
342
+ """Get the OAuth 2.0 access token for a service account.
343
+
344
+ Args:
345
+ request (google.auth.transport.Request): A callable used to make
346
+ HTTP requests.
347
+ service_account (str): The string 'default' or a service account email
348
+ address. The determines which service account for which to acquire
349
+ an access token.
350
+ scopes (Optional[Union[str, List[str]]]): Optional string or list of
351
+ strings with auth scopes.
352
+ Returns:
353
+ Tuple[str, datetime]: The access token and its expiration.
354
+
355
+ Raises:
356
+ google.auth.exceptions.TransportError: if an error occurred while
357
+ retrieving metadata.
358
+ """
359
+ if scopes:
360
+ if not isinstance(scopes, str):
361
+ scopes = ",".join(scopes)
362
+ params = {"scopes": scopes}
363
+ else:
364
+ params = None
365
+
366
+ metrics_header = {
367
+ metrics.API_CLIENT_HEADER: metrics.token_request_access_token_mds()
368
+ }
369
+
370
+ path = "instance/service-accounts/{0}/token".format(service_account)
371
+ token_json = get(request, path, params=params, headers=metrics_header)
372
+ token_expiry = _helpers.utcnow() + datetime.timedelta(
373
+ seconds=token_json["expires_in"]
374
+ )
375
+ return token_json["access_token"], token_expiry
lib/python3.10/site-packages/google/auth/compute_engine/credentials.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Google Compute Engine credentials.
16
+
17
+ This module provides authentication for an application running on Google
18
+ Compute Engine using the Compute Engine metadata server.
19
+
20
+ """
21
+
22
+ import datetime
23
+
24
+ from google.auth import _helpers
25
+ from google.auth import credentials
26
+ from google.auth import exceptions
27
+ from google.auth import iam
28
+ from google.auth import jwt
29
+ from google.auth import metrics
30
+ from google.auth.compute_engine import _metadata
31
+ from google.oauth2 import _client
32
+
33
+
34
+ class Credentials(
35
+ credentials.Scoped,
36
+ credentials.CredentialsWithQuotaProject,
37
+ credentials.CredentialsWithUniverseDomain,
38
+ ):
39
+ """Compute Engine Credentials.
40
+
41
+ These credentials use the Google Compute Engine metadata server to obtain
42
+ OAuth 2.0 access tokens associated with the instance's service account,
43
+ and are also used for Cloud Run, Flex and App Engine (except for the Python
44
+ 2.7 runtime, which is supported only on older versions of this library).
45
+
46
+ For more information about Compute Engine authentication, including how
47
+ to configure scopes, see the `Compute Engine authentication
48
+ documentation`_.
49
+
50
+ .. note:: On Compute Engine the metadata server ignores requested scopes.
51
+ On Cloud Run, Flex and App Engine the server honours requested scopes.
52
+
53
+ .. _Compute Engine authentication documentation:
54
+ https://cloud.google.com/compute/docs/authentication#using
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ service_account_email="default",
60
+ quota_project_id=None,
61
+ scopes=None,
62
+ default_scopes=None,
63
+ universe_domain=None,
64
+ ):
65
+ """
66
+ Args:
67
+ service_account_email (str): The service account email to use, or
68
+ 'default'. A Compute Engine instance may have multiple service
69
+ accounts.
70
+ quota_project_id (Optional[str]): The project ID used for quota and
71
+ billing.
72
+ scopes (Optional[Sequence[str]]): The list of scopes for the credentials.
73
+ default_scopes (Optional[Sequence[str]]): Default scopes passed by a
74
+ Google client library. Use 'scopes' for user-defined scopes.
75
+ universe_domain (Optional[str]): The universe domain. If not
76
+ provided or None, credential will attempt to fetch the value
77
+ from metadata server. If metadata server doesn't have universe
78
+ domain endpoint, then the default googleapis.com will be used.
79
+ """
80
+ super(Credentials, self).__init__()
81
+ self._service_account_email = service_account_email
82
+ self._quota_project_id = quota_project_id
83
+ self._scopes = scopes
84
+ self._default_scopes = default_scopes
85
+ self._universe_domain_cached = False
86
+ if universe_domain:
87
+ self._universe_domain = universe_domain
88
+ self._universe_domain_cached = True
89
+
90
+ def _retrieve_info(self, request):
91
+ """Retrieve information about the service account.
92
+
93
+ Updates the scopes and retrieves the full service account email.
94
+
95
+ Args:
96
+ request (google.auth.transport.Request): The object used to make
97
+ HTTP requests.
98
+ """
99
+ info = _metadata.get_service_account_info(
100
+ request, service_account=self._service_account_email
101
+ )
102
+
103
+ self._service_account_email = info["email"]
104
+
105
+ # Don't override scopes requested by the user.
106
+ if self._scopes is None:
107
+ self._scopes = info["scopes"]
108
+
109
+ def _metric_header_for_usage(self):
110
+ return metrics.CRED_TYPE_SA_MDS
111
+
112
+ def refresh(self, request):
113
+ """Refresh the access token and scopes.
114
+
115
+ Args:
116
+ request (google.auth.transport.Request): The object used to make
117
+ HTTP requests.
118
+
119
+ Raises:
120
+ google.auth.exceptions.RefreshError: If the Compute Engine metadata
121
+ service can't be reached if if the instance has not
122
+ credentials.
123
+ """
124
+ scopes = self._scopes if self._scopes is not None else self._default_scopes
125
+ try:
126
+ self._retrieve_info(request)
127
+ self.token, self.expiry = _metadata.get_service_account_token(
128
+ request, service_account=self._service_account_email, scopes=scopes
129
+ )
130
+ except exceptions.TransportError as caught_exc:
131
+ new_exc = exceptions.RefreshError(caught_exc)
132
+ raise new_exc from caught_exc
133
+
134
+ @property
135
+ def service_account_email(self):
136
+ """The service account email.
137
+
138
+ .. note:: This is not guaranteed to be set until :meth:`refresh` has been
139
+ called.
140
+ """
141
+ return self._service_account_email
142
+
143
+ @property
144
+ def requires_scopes(self):
145
+ return not self._scopes
146
+
147
+ @property
148
+ def universe_domain(self):
149
+ if self._universe_domain_cached:
150
+ return self._universe_domain
151
+
152
+ from google.auth.transport import requests as google_auth_requests
153
+
154
+ self._universe_domain = _metadata.get_universe_domain(
155
+ google_auth_requests.Request()
156
+ )
157
+ self._universe_domain_cached = True
158
+ return self._universe_domain
159
+
160
+ @_helpers.copy_docstring(credentials.Credentials)
161
+ def get_cred_info(self):
162
+ return {
163
+ "credential_source": "metadata server",
164
+ "credential_type": "VM credentials",
165
+ "principal": self.service_account_email,
166
+ }
167
+
168
+ @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
169
+ def with_quota_project(self, quota_project_id):
170
+ creds = self.__class__(
171
+ service_account_email=self._service_account_email,
172
+ quota_project_id=quota_project_id,
173
+ scopes=self._scopes,
174
+ default_scopes=self._default_scopes,
175
+ )
176
+ creds._universe_domain = self._universe_domain
177
+ creds._universe_domain_cached = self._universe_domain_cached
178
+ return creds
179
+
180
+ @_helpers.copy_docstring(credentials.Scoped)
181
+ def with_scopes(self, scopes, default_scopes=None):
182
+ # Compute Engine credentials can not be scoped (the metadata service
183
+ # ignores the scopes parameter). App Engine, Cloud Run and Flex support
184
+ # requesting scopes.
185
+ creds = self.__class__(
186
+ scopes=scopes,
187
+ default_scopes=default_scopes,
188
+ service_account_email=self._service_account_email,
189
+ quota_project_id=self._quota_project_id,
190
+ )
191
+ creds._universe_domain = self._universe_domain
192
+ creds._universe_domain_cached = self._universe_domain_cached
193
+ return creds
194
+
195
+ @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
196
+ def with_universe_domain(self, universe_domain):
197
+ return self.__class__(
198
+ scopes=self._scopes,
199
+ default_scopes=self._default_scopes,
200
+ service_account_email=self._service_account_email,
201
+ quota_project_id=self._quota_project_id,
202
+ universe_domain=universe_domain,
203
+ )
204
+
205
+
206
+ _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
207
+ _DEFAULT_TOKEN_URI = "https://www.googleapis.com/oauth2/v4/token"
208
+
209
+
210
+ class IDTokenCredentials(
211
+ credentials.CredentialsWithQuotaProject,
212
+ credentials.Signing,
213
+ credentials.CredentialsWithTokenUri,
214
+ ):
215
+ """Open ID Connect ID Token-based service account credentials.
216
+
217
+ These credentials relies on the default service account of a GCE instance.
218
+
219
+ ID token can be requested from `GCE metadata server identity endpoint`_, IAM
220
+ token endpoint or other token endpoints you specify. If metadata server
221
+ identity endpoint is not used, the GCE instance must have been started with
222
+ a service account that has access to the IAM Cloud API.
223
+
224
+ .. _GCE metadata server identity endpoint:
225
+ https://cloud.google.com/compute/docs/instances/verifying-instance-identity
226
+ """
227
+
228
+ def __init__(
229
+ self,
230
+ request,
231
+ target_audience,
232
+ token_uri=None,
233
+ additional_claims=None,
234
+ service_account_email=None,
235
+ signer=None,
236
+ use_metadata_identity_endpoint=False,
237
+ quota_project_id=None,
238
+ ):
239
+ """
240
+ Args:
241
+ request (google.auth.transport.Request): The object used to make
242
+ HTTP requests.
243
+ target_audience (str): The intended audience for these credentials,
244
+ used when requesting the ID Token. The ID Token's ``aud`` claim
245
+ will be set to this string.
246
+ token_uri (str): The OAuth 2.0 Token URI.
247
+ additional_claims (Mapping[str, str]): Any additional claims for
248
+ the JWT assertion used in the authorization grant.
249
+ service_account_email (str): Optional explicit service account to
250
+ use to sign JWT tokens.
251
+ By default, this is the default GCE service account.
252
+ signer (google.auth.crypt.Signer): The signer used to sign JWTs.
253
+ In case the signer is specified, the request argument will be
254
+ ignored.
255
+ use_metadata_identity_endpoint (bool): Whether to use GCE metadata
256
+ identity endpoint. For backward compatibility the default value
257
+ is False. If set to True, ``token_uri``, ``additional_claims``,
258
+ ``service_account_email``, ``signer`` argument should not be set;
259
+ otherwise ValueError will be raised.
260
+ quota_project_id (Optional[str]): The project ID used for quota and
261
+ billing.
262
+
263
+ Raises:
264
+ ValueError:
265
+ If ``use_metadata_identity_endpoint`` is set to True, and one of
266
+ ``token_uri``, ``additional_claims``, ``service_account_email``,
267
+ ``signer`` arguments is set.
268
+ """
269
+ super(IDTokenCredentials, self).__init__()
270
+
271
+ self._quota_project_id = quota_project_id
272
+ self._use_metadata_identity_endpoint = use_metadata_identity_endpoint
273
+ self._target_audience = target_audience
274
+
275
+ if use_metadata_identity_endpoint:
276
+ if token_uri or additional_claims or service_account_email or signer:
277
+ raise exceptions.MalformedError(
278
+ "If use_metadata_identity_endpoint is set, token_uri, "
279
+ "additional_claims, service_account_email, signer arguments"
280
+ " must not be set"
281
+ )
282
+ self._token_uri = None
283
+ self._additional_claims = None
284
+ self._signer = None
285
+
286
+ if service_account_email is None:
287
+ sa_info = _metadata.get_service_account_info(request)
288
+ self._service_account_email = sa_info["email"]
289
+ else:
290
+ self._service_account_email = service_account_email
291
+
292
+ if not use_metadata_identity_endpoint:
293
+ if signer is None:
294
+ signer = iam.Signer(
295
+ request=request,
296
+ credentials=Credentials(),
297
+ service_account_email=self._service_account_email,
298
+ )
299
+ self._signer = signer
300
+ self._token_uri = token_uri or _DEFAULT_TOKEN_URI
301
+
302
+ if additional_claims is not None:
303
+ self._additional_claims = additional_claims
304
+ else:
305
+ self._additional_claims = {}
306
+
307
+ def with_target_audience(self, target_audience):
308
+ """Create a copy of these credentials with the specified target
309
+ audience.
310
+ Args:
311
+ target_audience (str): The intended audience for these credentials,
312
+ used when requesting the ID Token.
313
+ Returns:
314
+ google.auth.service_account.IDTokenCredentials: A new credentials
315
+ instance.
316
+ """
317
+ # since the signer is already instantiated,
318
+ # the request is not needed
319
+ if self._use_metadata_identity_endpoint:
320
+ return self.__class__(
321
+ None,
322
+ target_audience=target_audience,
323
+ use_metadata_identity_endpoint=True,
324
+ quota_project_id=self._quota_project_id,
325
+ )
326
+ else:
327
+ return self.__class__(
328
+ None,
329
+ service_account_email=self._service_account_email,
330
+ token_uri=self._token_uri,
331
+ target_audience=target_audience,
332
+ additional_claims=self._additional_claims.copy(),
333
+ signer=self.signer,
334
+ use_metadata_identity_endpoint=False,
335
+ quota_project_id=self._quota_project_id,
336
+ )
337
+
338
+ @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
339
+ def with_quota_project(self, quota_project_id):
340
+
341
+ # since the signer is already instantiated,
342
+ # the request is not needed
343
+ if self._use_metadata_identity_endpoint:
344
+ return self.__class__(
345
+ None,
346
+ target_audience=self._target_audience,
347
+ use_metadata_identity_endpoint=True,
348
+ quota_project_id=quota_project_id,
349
+ )
350
+ else:
351
+ return self.__class__(
352
+ None,
353
+ service_account_email=self._service_account_email,
354
+ token_uri=self._token_uri,
355
+ target_audience=self._target_audience,
356
+ additional_claims=self._additional_claims.copy(),
357
+ signer=self.signer,
358
+ use_metadata_identity_endpoint=False,
359
+ quota_project_id=quota_project_id,
360
+ )
361
+
362
+ @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
363
+ def with_token_uri(self, token_uri):
364
+
365
+ # since the signer is already instantiated,
366
+ # the request is not needed
367
+ if self._use_metadata_identity_endpoint:
368
+ raise exceptions.MalformedError(
369
+ "If use_metadata_identity_endpoint is set, token_uri" " must not be set"
370
+ )
371
+ else:
372
+ return self.__class__(
373
+ None,
374
+ service_account_email=self._service_account_email,
375
+ token_uri=token_uri,
376
+ target_audience=self._target_audience,
377
+ additional_claims=self._additional_claims.copy(),
378
+ signer=self.signer,
379
+ use_metadata_identity_endpoint=False,
380
+ quota_project_id=self.quota_project_id,
381
+ )
382
+
383
+ def _make_authorization_grant_assertion(self):
384
+ """Create the OAuth 2.0 assertion.
385
+ This assertion is used during the OAuth 2.0 grant to acquire an
386
+ ID token.
387
+ Returns:
388
+ bytes: The authorization grant assertion.
389
+ """
390
+ now = _helpers.utcnow()
391
+ lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
392
+ expiry = now + lifetime
393
+
394
+ payload = {
395
+ "iat": _helpers.datetime_to_secs(now),
396
+ "exp": _helpers.datetime_to_secs(expiry),
397
+ # The issuer must be the service account email.
398
+ "iss": self.service_account_email,
399
+ # The audience must be the auth token endpoint's URI
400
+ "aud": self._token_uri,
401
+ # The target audience specifies which service the ID token is
402
+ # intended for.
403
+ "target_audience": self._target_audience,
404
+ }
405
+
406
+ payload.update(self._additional_claims)
407
+
408
+ token = jwt.encode(self._signer, payload)
409
+
410
+ return token
411
+
412
+ def _call_metadata_identity_endpoint(self, request):
413
+ """Request ID token from metadata identity endpoint.
414
+
415
+ Args:
416
+ request (google.auth.transport.Request): The object used to make
417
+ HTTP requests.
418
+
419
+ Returns:
420
+ Tuple[str, datetime.datetime]: The ID token and the expiry of the ID token.
421
+
422
+ Raises:
423
+ google.auth.exceptions.RefreshError: If the Compute Engine metadata
424
+ service can't be reached or if the instance has no credentials.
425
+ ValueError: If extracting expiry from the obtained ID token fails.
426
+ """
427
+ try:
428
+ path = "instance/service-accounts/default/identity"
429
+ params = {"audience": self._target_audience, "format": "full"}
430
+ metrics_header = {
431
+ metrics.API_CLIENT_HEADER: metrics.token_request_id_token_mds()
432
+ }
433
+ id_token = _metadata.get(
434
+ request, path, params=params, headers=metrics_header
435
+ )
436
+ except exceptions.TransportError as caught_exc:
437
+ new_exc = exceptions.RefreshError(caught_exc)
438
+ raise new_exc from caught_exc
439
+
440
+ _, payload, _, _ = jwt._unverified_decode(id_token)
441
+ return id_token, datetime.datetime.utcfromtimestamp(payload["exp"])
442
+
443
+ def refresh(self, request):
444
+ """Refreshes the ID token.
445
+
446
+ Args:
447
+ request (google.auth.transport.Request): The object used to make
448
+ HTTP requests.
449
+
450
+ Raises:
451
+ google.auth.exceptions.RefreshError: If the credentials could
452
+ not be refreshed.
453
+ ValueError: If extracting expiry from the obtained ID token fails.
454
+ """
455
+ if self._use_metadata_identity_endpoint:
456
+ self.token, self.expiry = self._call_metadata_identity_endpoint(request)
457
+ else:
458
+ assertion = self._make_authorization_grant_assertion()
459
+ access_token, expiry, _ = _client.id_token_jwt_grant(
460
+ request, self._token_uri, assertion
461
+ )
462
+ self.token = access_token
463
+ self.expiry = expiry
464
+
465
+ @property # type: ignore
466
+ @_helpers.copy_docstring(credentials.Signing)
467
+ def signer(self):
468
+ return self._signer
469
+
470
+ def sign_bytes(self, message):
471
+ """Signs the given message.
472
+
473
+ Args:
474
+ message (bytes): The message to sign.
475
+
476
+ Returns:
477
+ bytes: The message's cryptographic signature.
478
+
479
+ Raises:
480
+ ValueError:
481
+ Signer is not available if metadata identity endpoint is used.
482
+ """
483
+ if self._use_metadata_identity_endpoint:
484
+ raise exceptions.InvalidOperation(
485
+ "Signer is not available if metadata identity endpoint is used"
486
+ )
487
+ return self._signer.sign(message)
488
+
489
+ @property
490
+ def service_account_email(self):
491
+ """The service account email."""
492
+ return self._service_account_email
493
+
494
+ @property
495
+ def signer_email(self):
496
+ return self._service_account_email
lib/python3.10/site-packages/google/auth/crypt/__init__.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Cryptography helpers for verifying and signing messages.
16
+
17
+ The simplest way to verify signatures is using :func:`verify_signature`::
18
+
19
+ cert = open('certs.pem').read()
20
+ valid = crypt.verify_signature(message, signature, cert)
21
+
22
+ If you're going to verify many messages with the same certificate, you can use
23
+ :class:`RSAVerifier`::
24
+
25
+ cert = open('certs.pem').read()
26
+ verifier = crypt.RSAVerifier.from_string(cert)
27
+ valid = verifier.verify(message, signature)
28
+
29
+ To sign messages use :class:`RSASigner` with a private key::
30
+
31
+ private_key = open('private_key.pem').read()
32
+ signer = crypt.RSASigner.from_string(private_key)
33
+ signature = signer.sign(message)
34
+
35
+ The code above also works for :class:`ES256Signer` and :class:`ES256Verifier`.
36
+ Note that these two classes are only available if your `cryptography` dependency
37
+ version is at least 1.4.0.
38
+ """
39
+
40
+ from google.auth.crypt import base
41
+ from google.auth.crypt import rsa
42
+
43
+ try:
44
+ from google.auth.crypt import es256
45
+ except ImportError: # pragma: NO COVER
46
+ es256 = None # type: ignore
47
+
48
+ if es256 is not None: # pragma: NO COVER
49
+ __all__ = [
50
+ "ES256Signer",
51
+ "ES256Verifier",
52
+ "RSASigner",
53
+ "RSAVerifier",
54
+ "Signer",
55
+ "Verifier",
56
+ ]
57
+ else: # pragma: NO COVER
58
+ __all__ = ["RSASigner", "RSAVerifier", "Signer", "Verifier"]
59
+
60
+
61
+ # Aliases to maintain the v1.0.0 interface, as the crypt module was split
62
+ # into submodules.
63
+ Signer = base.Signer
64
+ Verifier = base.Verifier
65
+ RSASigner = rsa.RSASigner
66
+ RSAVerifier = rsa.RSAVerifier
67
+
68
+ if es256 is not None: # pragma: NO COVER
69
+ ES256Signer = es256.ES256Signer
70
+ ES256Verifier = es256.ES256Verifier
71
+
72
+
73
+ def verify_signature(message, signature, certs, verifier_cls=rsa.RSAVerifier):
74
+ """Verify an RSA or ECDSA cryptographic signature.
75
+
76
+ Checks that the provided ``signature`` was generated from ``bytes`` using
77
+ the private key associated with the ``cert``.
78
+
79
+ Args:
80
+ message (Union[str, bytes]): The plaintext message.
81
+ signature (Union[str, bytes]): The cryptographic signature to check.
82
+ certs (Union[Sequence, str, bytes]): The certificate or certificates
83
+ to use to check the signature.
84
+ verifier_cls (Optional[~google.auth.crypt.base.Signer]): Which verifier
85
+ class to use for verification. This can be used to select different
86
+ algorithms, such as RSA or ECDSA. Default value is :class:`RSAVerifier`.
87
+
88
+ Returns:
89
+ bool: True if the signature is valid, otherwise False.
90
+ """
91
+ if isinstance(certs, (str, bytes)):
92
+ certs = [certs]
93
+
94
+ for cert in certs:
95
+ verifier = verifier_cls.from_string(cert)
96
+ if verifier.verify(message, signature):
97
+ return True
98
+ return False
lib/python3.10/site-packages/google/auth/crypt/_cryptography_rsa.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 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
+
15
+ """RSA verifier and signer that use the ``cryptography`` library.
16
+
17
+ This is a much faster implementation than the default (in
18
+ ``google.auth.crypt._python_rsa``), which depends on the pure-Python
19
+ ``rsa`` library.
20
+ """
21
+
22
+ import cryptography.exceptions
23
+ from cryptography.hazmat import backends
24
+ from cryptography.hazmat.primitives import hashes
25
+ from cryptography.hazmat.primitives import serialization
26
+ from cryptography.hazmat.primitives.asymmetric import padding
27
+ import cryptography.x509
28
+
29
+ from google.auth import _helpers
30
+ from google.auth.crypt import base
31
+
32
+ _CERTIFICATE_MARKER = b"-----BEGIN CERTIFICATE-----"
33
+ _BACKEND = backends.default_backend()
34
+ _PADDING = padding.PKCS1v15()
35
+ _SHA256 = hashes.SHA256()
36
+
37
+
38
+ class RSAVerifier(base.Verifier):
39
+ """Verifies RSA cryptographic signatures using public keys.
40
+
41
+ Args:
42
+ public_key (
43
+ cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey):
44
+ The public key used to verify signatures.
45
+ """
46
+
47
+ def __init__(self, public_key):
48
+ self._pubkey = public_key
49
+
50
+ @_helpers.copy_docstring(base.Verifier)
51
+ def verify(self, message, signature):
52
+ message = _helpers.to_bytes(message)
53
+ try:
54
+ self._pubkey.verify(signature, message, _PADDING, _SHA256)
55
+ return True
56
+ except (ValueError, cryptography.exceptions.InvalidSignature):
57
+ return False
58
+
59
+ @classmethod
60
+ def from_string(cls, public_key):
61
+ """Construct an Verifier instance from a public key or public
62
+ certificate string.
63
+
64
+ Args:
65
+ public_key (Union[str, bytes]): The public key in PEM format or the
66
+ x509 public key certificate.
67
+
68
+ Returns:
69
+ Verifier: The constructed verifier.
70
+
71
+ Raises:
72
+ ValueError: If the public key can't be parsed.
73
+ """
74
+ public_key_data = _helpers.to_bytes(public_key)
75
+
76
+ if _CERTIFICATE_MARKER in public_key_data:
77
+ cert = cryptography.x509.load_pem_x509_certificate(
78
+ public_key_data, _BACKEND
79
+ )
80
+ pubkey = cert.public_key()
81
+
82
+ else:
83
+ pubkey = serialization.load_pem_public_key(public_key_data, _BACKEND)
84
+
85
+ return cls(pubkey)
86
+
87
+
88
+ class RSASigner(base.Signer, base.FromServiceAccountMixin):
89
+ """Signs messages with an RSA private key.
90
+
91
+ Args:
92
+ private_key (
93
+ cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey):
94
+ The private key to sign with.
95
+ key_id (str): Optional key ID used to identify this private key. This
96
+ can be useful to associate the private key with its associated
97
+ public key or certificate.
98
+ """
99
+
100
+ def __init__(self, private_key, key_id=None):
101
+ self._key = private_key
102
+ self._key_id = key_id
103
+
104
+ @property # type: ignore
105
+ @_helpers.copy_docstring(base.Signer)
106
+ def key_id(self):
107
+ return self._key_id
108
+
109
+ @_helpers.copy_docstring(base.Signer)
110
+ def sign(self, message):
111
+ message = _helpers.to_bytes(message)
112
+ return self._key.sign(message, _PADDING, _SHA256)
113
+
114
+ @classmethod
115
+ def from_string(cls, key, key_id=None):
116
+ """Construct a RSASigner from a private key in PEM format.
117
+
118
+ Args:
119
+ key (Union[bytes, str]): Private key in PEM format.
120
+ key_id (str): An optional key id used to identify the private key.
121
+
122
+ Returns:
123
+ google.auth.crypt._cryptography_rsa.RSASigner: The
124
+ constructed signer.
125
+
126
+ Raises:
127
+ ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
128
+ UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
129
+ into a UTF-8 ``str``.
130
+ ValueError: If ``cryptography`` "Could not deserialize key data."
131
+ """
132
+ key = _helpers.to_bytes(key)
133
+ private_key = serialization.load_pem_private_key(
134
+ key, password=None, backend=_BACKEND
135
+ )
136
+ return cls(private_key, key_id=key_id)
137
+
138
+ def __getstate__(self):
139
+ """Pickle helper that serializes the _key attribute."""
140
+ state = self.__dict__.copy()
141
+ state["_key"] = self._key.private_bytes(
142
+ encoding=serialization.Encoding.PEM,
143
+ format=serialization.PrivateFormat.PKCS8,
144
+ encryption_algorithm=serialization.NoEncryption(),
145
+ )
146
+ return state
147
+
148
+ def __setstate__(self, state):
149
+ """Pickle helper that deserializes the _key attribute."""
150
+ state["_key"] = serialization.load_pem_private_key(state["_key"], None)
151
+ self.__dict__.update(state)
lib/python3.10/site-packages/google/auth/crypt/_helpers.py ADDED
File without changes
lib/python3.10/site-packages/google/auth/crypt/_python_rsa.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Pure-Python RSA cryptography implementation.
16
+
17
+ Uses the ``rsa``, ``pyasn1`` and ``pyasn1_modules`` packages
18
+ to parse PEM files storing PKCS#1 or PKCS#8 keys as well as
19
+ certificates. There is no support for p12 files.
20
+ """
21
+
22
+ from __future__ import absolute_import
23
+
24
+ import io
25
+
26
+ from pyasn1.codec.der import decoder # type: ignore
27
+ from pyasn1_modules import pem # type: ignore
28
+ from pyasn1_modules.rfc2459 import Certificate # type: ignore
29
+ from pyasn1_modules.rfc5208 import PrivateKeyInfo # type: ignore
30
+ import rsa # type: ignore
31
+
32
+ from google.auth import _helpers
33
+ from google.auth import exceptions
34
+ from google.auth.crypt import base
35
+
36
+ _POW2 = (128, 64, 32, 16, 8, 4, 2, 1)
37
+ _CERTIFICATE_MARKER = b"-----BEGIN CERTIFICATE-----"
38
+ _PKCS1_MARKER = ("-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----")
39
+ _PKCS8_MARKER = ("-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----")
40
+ _PKCS8_SPEC = PrivateKeyInfo()
41
+
42
+
43
+ def _bit_list_to_bytes(bit_list):
44
+ """Converts an iterable of 1s and 0s to bytes.
45
+
46
+ Combines the list 8 at a time, treating each group of 8 bits
47
+ as a single byte.
48
+
49
+ Args:
50
+ bit_list (Sequence): Sequence of 1s and 0s.
51
+
52
+ Returns:
53
+ bytes: The decoded bytes.
54
+ """
55
+ num_bits = len(bit_list)
56
+ byte_vals = bytearray()
57
+ for start in range(0, num_bits, 8):
58
+ curr_bits = bit_list[start : start + 8]
59
+ char_val = sum(val * digit for val, digit in zip(_POW2, curr_bits))
60
+ byte_vals.append(char_val)
61
+ return bytes(byte_vals)
62
+
63
+
64
+ class RSAVerifier(base.Verifier):
65
+ """Verifies RSA cryptographic signatures using public keys.
66
+
67
+ Args:
68
+ public_key (rsa.key.PublicKey): The public key used to verify
69
+ signatures.
70
+ """
71
+
72
+ def __init__(self, public_key):
73
+ self._pubkey = public_key
74
+
75
+ @_helpers.copy_docstring(base.Verifier)
76
+ def verify(self, message, signature):
77
+ message = _helpers.to_bytes(message)
78
+ try:
79
+ return rsa.pkcs1.verify(message, signature, self._pubkey)
80
+ except (ValueError, rsa.pkcs1.VerificationError):
81
+ return False
82
+
83
+ @classmethod
84
+ def from_string(cls, public_key):
85
+ """Construct an Verifier instance from a public key or public
86
+ certificate string.
87
+
88
+ Args:
89
+ public_key (Union[str, bytes]): The public key in PEM format or the
90
+ x509 public key certificate.
91
+
92
+ Returns:
93
+ google.auth.crypt._python_rsa.RSAVerifier: The constructed verifier.
94
+
95
+ Raises:
96
+ ValueError: If the public_key can't be parsed.
97
+ """
98
+ public_key = _helpers.to_bytes(public_key)
99
+ is_x509_cert = _CERTIFICATE_MARKER in public_key
100
+
101
+ # If this is a certificate, extract the public key info.
102
+ if is_x509_cert:
103
+ der = rsa.pem.load_pem(public_key, "CERTIFICATE")
104
+ asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
105
+ if remaining != b"":
106
+ raise exceptions.InvalidValue("Unused bytes", remaining)
107
+
108
+ cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"]
109
+ key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"])
110
+ pubkey = rsa.PublicKey.load_pkcs1(key_bytes, "DER")
111
+ else:
112
+ pubkey = rsa.PublicKey.load_pkcs1(public_key, "PEM")
113
+ return cls(pubkey)
114
+
115
+
116
+ class RSASigner(base.Signer, base.FromServiceAccountMixin):
117
+ """Signs messages with an RSA private key.
118
+
119
+ Args:
120
+ private_key (rsa.key.PrivateKey): The private key to sign with.
121
+ key_id (str): Optional key ID used to identify this private key. This
122
+ can be useful to associate the private key with its associated
123
+ public key or certificate.
124
+ """
125
+
126
+ def __init__(self, private_key, key_id=None):
127
+ self._key = private_key
128
+ self._key_id = key_id
129
+
130
+ @property # type: ignore
131
+ @_helpers.copy_docstring(base.Signer)
132
+ def key_id(self):
133
+ return self._key_id
134
+
135
+ @_helpers.copy_docstring(base.Signer)
136
+ def sign(self, message):
137
+ message = _helpers.to_bytes(message)
138
+ return rsa.pkcs1.sign(message, self._key, "SHA-256")
139
+
140
+ @classmethod
141
+ def from_string(cls, key, key_id=None):
142
+ """Construct an Signer instance from a private key in PEM format.
143
+
144
+ Args:
145
+ key (str): Private key in PEM format.
146
+ key_id (str): An optional key id used to identify the private key.
147
+
148
+ Returns:
149
+ google.auth.crypt.Signer: The constructed signer.
150
+
151
+ Raises:
152
+ ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in
153
+ PEM format.
154
+ """
155
+ key = _helpers.from_bytes(key) # PEM expects str in Python 3
156
+ marker_id, key_bytes = pem.readPemBlocksFromFile(
157
+ io.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER
158
+ )
159
+
160
+ # Key is in pkcs1 format.
161
+ if marker_id == 0:
162
+ private_key = rsa.key.PrivateKey.load_pkcs1(key_bytes, format="DER")
163
+ # Key is in pkcs8.
164
+ elif marker_id == 1:
165
+ key_info, remaining = decoder.decode(key_bytes, asn1Spec=_PKCS8_SPEC)
166
+ if remaining != b"":
167
+ raise exceptions.InvalidValue("Unused bytes", remaining)
168
+ private_key_info = key_info.getComponentByName("privateKey")
169
+ private_key = rsa.key.PrivateKey.load_pkcs1(
170
+ private_key_info.asOctets(), format="DER"
171
+ )
172
+ else:
173
+ raise exceptions.MalformedError("No key could be detected.")
174
+
175
+ return cls(private_key, key_id=key_id)
lib/python3.10/site-packages/google/auth/crypt/base.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Base classes for cryptographic signers and verifiers."""
16
+
17
+ import abc
18
+ import io
19
+ import json
20
+
21
+ from google.auth import exceptions
22
+
23
+ _JSON_FILE_PRIVATE_KEY = "private_key"
24
+ _JSON_FILE_PRIVATE_KEY_ID = "private_key_id"
25
+
26
+
27
+ class Verifier(metaclass=abc.ABCMeta):
28
+ """Abstract base class for crytographic signature verifiers."""
29
+
30
+ @abc.abstractmethod
31
+ def verify(self, message, signature):
32
+ """Verifies a message against a cryptographic signature.
33
+
34
+ Args:
35
+ message (Union[str, bytes]): The message to verify.
36
+ signature (Union[str, bytes]): The cryptography signature to check.
37
+
38
+ Returns:
39
+ bool: True if message was signed by the private key associated
40
+ with the public key that this object was constructed with.
41
+ """
42
+ # pylint: disable=missing-raises-doc,redundant-returns-doc
43
+ # (pylint doesn't recognize that this is abstract)
44
+ raise NotImplementedError("Verify must be implemented")
45
+
46
+
47
+ class Signer(metaclass=abc.ABCMeta):
48
+ """Abstract base class for cryptographic signers."""
49
+
50
+ @abc.abstractproperty
51
+ def key_id(self):
52
+ """Optional[str]: The key ID used to identify this private key."""
53
+ raise NotImplementedError("Key id must be implemented")
54
+
55
+ @abc.abstractmethod
56
+ def sign(self, message):
57
+ """Signs a message.
58
+
59
+ Args:
60
+ message (Union[str, bytes]): The message to be signed.
61
+
62
+ Returns:
63
+ bytes: The signature of the message.
64
+ """
65
+ # pylint: disable=missing-raises-doc,redundant-returns-doc
66
+ # (pylint doesn't recognize that this is abstract)
67
+ raise NotImplementedError("Sign must be implemented")
68
+
69
+
70
+ class FromServiceAccountMixin(metaclass=abc.ABCMeta):
71
+ """Mix-in to enable factory constructors for a Signer."""
72
+
73
+ @abc.abstractmethod
74
+ def from_string(cls, key, key_id=None):
75
+ """Construct an Signer instance from a private key string.
76
+
77
+ Args:
78
+ key (str): Private key as a string.
79
+ key_id (str): An optional key id used to identify the private key.
80
+
81
+ Returns:
82
+ google.auth.crypt.Signer: The constructed signer.
83
+
84
+ Raises:
85
+ ValueError: If the key cannot be parsed.
86
+ """
87
+ raise NotImplementedError("from_string must be implemented")
88
+
89
+ @classmethod
90
+ def from_service_account_info(cls, info):
91
+ """Creates a Signer instance instance from a dictionary containing
92
+ service account info in Google format.
93
+
94
+ Args:
95
+ info (Mapping[str, str]): The service account info in Google
96
+ format.
97
+
98
+ Returns:
99
+ google.auth.crypt.Signer: The constructed signer.
100
+
101
+ Raises:
102
+ ValueError: If the info is not in the expected format.
103
+ """
104
+ if _JSON_FILE_PRIVATE_KEY not in info:
105
+ raise exceptions.MalformedError(
106
+ "The private_key field was not found in the service account " "info."
107
+ )
108
+
109
+ return cls.from_string(
110
+ info[_JSON_FILE_PRIVATE_KEY], info.get(_JSON_FILE_PRIVATE_KEY_ID)
111
+ )
112
+
113
+ @classmethod
114
+ def from_service_account_file(cls, filename):
115
+ """Creates a Signer instance from a service account .json file
116
+ in Google format.
117
+
118
+ Args:
119
+ filename (str): The path to the service account .json file.
120
+
121
+ Returns:
122
+ google.auth.crypt.Signer: The constructed signer.
123
+ """
124
+ with io.open(filename, "r", encoding="utf-8") as json_file:
125
+ data = json.load(json_file)
126
+
127
+ return cls.from_service_account_info(data)
lib/python3.10/site-packages/google/auth/crypt/es256.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 Google Inc.
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
+
15
+ """ECDSA (ES256) verifier and signer that use the ``cryptography`` library.
16
+ """
17
+
18
+ from cryptography import utils # type: ignore
19
+ import cryptography.exceptions
20
+ from cryptography.hazmat import backends
21
+ from cryptography.hazmat.primitives import hashes
22
+ from cryptography.hazmat.primitives import serialization
23
+ from cryptography.hazmat.primitives.asymmetric import ec
24
+ from cryptography.hazmat.primitives.asymmetric import padding
25
+ from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
26
+ from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
27
+ import cryptography.x509
28
+
29
+ from google.auth import _helpers
30
+ from google.auth.crypt import base
31
+
32
+
33
+ _CERTIFICATE_MARKER = b"-----BEGIN CERTIFICATE-----"
34
+ _BACKEND = backends.default_backend()
35
+ _PADDING = padding.PKCS1v15()
36
+
37
+
38
+ class ES256Verifier(base.Verifier):
39
+ """Verifies ECDSA cryptographic signatures using public keys.
40
+
41
+ Args:
42
+ public_key (
43
+ cryptography.hazmat.primitives.asymmetric.ec.ECDSAPublicKey):
44
+ The public key used to verify signatures.
45
+ """
46
+
47
+ def __init__(self, public_key):
48
+ self._pubkey = public_key
49
+
50
+ @_helpers.copy_docstring(base.Verifier)
51
+ def verify(self, message, signature):
52
+ # First convert (r||s) raw signature to ASN1 encoded signature.
53
+ sig_bytes = _helpers.to_bytes(signature)
54
+ if len(sig_bytes) != 64:
55
+ return False
56
+ r = (
57
+ int.from_bytes(sig_bytes[:32], byteorder="big")
58
+ if _helpers.is_python_3()
59
+ else utils.int_from_bytes(sig_bytes[:32], byteorder="big")
60
+ )
61
+ s = (
62
+ int.from_bytes(sig_bytes[32:], byteorder="big")
63
+ if _helpers.is_python_3()
64
+ else utils.int_from_bytes(sig_bytes[32:], byteorder="big")
65
+ )
66
+ asn1_sig = encode_dss_signature(r, s)
67
+
68
+ message = _helpers.to_bytes(message)
69
+ try:
70
+ self._pubkey.verify(asn1_sig, message, ec.ECDSA(hashes.SHA256()))
71
+ return True
72
+ except (ValueError, cryptography.exceptions.InvalidSignature):
73
+ return False
74
+
75
+ @classmethod
76
+ def from_string(cls, public_key):
77
+ """Construct an Verifier instance from a public key or public
78
+ certificate string.
79
+
80
+ Args:
81
+ public_key (Union[str, bytes]): The public key in PEM format or the
82
+ x509 public key certificate.
83
+
84
+ Returns:
85
+ Verifier: The constructed verifier.
86
+
87
+ Raises:
88
+ ValueError: If the public key can't be parsed.
89
+ """
90
+ public_key_data = _helpers.to_bytes(public_key)
91
+
92
+ if _CERTIFICATE_MARKER in public_key_data:
93
+ cert = cryptography.x509.load_pem_x509_certificate(
94
+ public_key_data, _BACKEND
95
+ )
96
+ pubkey = cert.public_key()
97
+
98
+ else:
99
+ pubkey = serialization.load_pem_public_key(public_key_data, _BACKEND)
100
+
101
+ return cls(pubkey)
102
+
103
+
104
+ class ES256Signer(base.Signer, base.FromServiceAccountMixin):
105
+ """Signs messages with an ECDSA private key.
106
+
107
+ Args:
108
+ private_key (
109
+ cryptography.hazmat.primitives.asymmetric.ec.ECDSAPrivateKey):
110
+ The private key to sign with.
111
+ key_id (str): Optional key ID used to identify this private key. This
112
+ can be useful to associate the private key with its associated
113
+ public key or certificate.
114
+ """
115
+
116
+ def __init__(self, private_key, key_id=None):
117
+ self._key = private_key
118
+ self._key_id = key_id
119
+
120
+ @property # type: ignore
121
+ @_helpers.copy_docstring(base.Signer)
122
+ def key_id(self):
123
+ return self._key_id
124
+
125
+ @_helpers.copy_docstring(base.Signer)
126
+ def sign(self, message):
127
+ message = _helpers.to_bytes(message)
128
+ asn1_signature = self._key.sign(message, ec.ECDSA(hashes.SHA256()))
129
+
130
+ # Convert ASN1 encoded signature to (r||s) raw signature.
131
+ (r, s) = decode_dss_signature(asn1_signature)
132
+ return (
133
+ (r.to_bytes(32, byteorder="big") + s.to_bytes(32, byteorder="big"))
134
+ if _helpers.is_python_3()
135
+ else (utils.int_to_bytes(r, 32) + utils.int_to_bytes(s, 32))
136
+ )
137
+
138
+ @classmethod
139
+ def from_string(cls, key, key_id=None):
140
+ """Construct a RSASigner from a private key in PEM format.
141
+
142
+ Args:
143
+ key (Union[bytes, str]): Private key in PEM format.
144
+ key_id (str): An optional key id used to identify the private key.
145
+
146
+ Returns:
147
+ google.auth.crypt._cryptography_rsa.RSASigner: The
148
+ constructed signer.
149
+
150
+ Raises:
151
+ ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
152
+ UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
153
+ into a UTF-8 ``str``.
154
+ ValueError: If ``cryptography`` "Could not deserialize key data."
155
+ """
156
+ key = _helpers.to_bytes(key)
157
+ private_key = serialization.load_pem_private_key(
158
+ key, password=None, backend=_BACKEND
159
+ )
160
+ return cls(private_key, key_id=key_id)
161
+
162
+ def __getstate__(self):
163
+ """Pickle helper that serializes the _key attribute."""
164
+ state = self.__dict__.copy()
165
+ state["_key"] = self._key.private_bytes(
166
+ encoding=serialization.Encoding.PEM,
167
+ format=serialization.PrivateFormat.PKCS8,
168
+ encryption_algorithm=serialization.NoEncryption(),
169
+ )
170
+ return state
171
+
172
+ def __setstate__(self, state):
173
+ """Pickle helper that deserializes the _key attribute."""
174
+ state["_key"] = serialization.load_pem_private_key(state["_key"], None)
175
+ self.__dict__.update(state)
lib/python3.10/site-packages/google/auth/crypt/rsa.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 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
+
15
+ """RSA cryptography signer and verifier."""
16
+
17
+
18
+ try:
19
+ # Prefer cryptograph-based RSA implementation.
20
+ from google.auth.crypt import _cryptography_rsa
21
+
22
+ RSASigner = _cryptography_rsa.RSASigner
23
+ RSAVerifier = _cryptography_rsa.RSAVerifier
24
+ except ImportError: # pragma: NO COVER
25
+ # Fallback to pure-python RSA implementation if cryptography is
26
+ # unavailable.
27
+ from google.auth.crypt import _python_rsa
28
+
29
+ RSASigner = _python_rsa.RSASigner # type: ignore
30
+ RSAVerifier = _python_rsa.RSAVerifier # type: ignore
lib/python3.10/site-packages/google/auth/downscoped.py ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ """Downscoping with Credential Access Boundaries
16
+
17
+ This module provides the ability to downscope credentials using
18
+ `Downscoping with Credential Access Boundaries`_. This is useful to restrict the
19
+ Identity and Access Management (IAM) permissions that a short-lived credential
20
+ can use.
21
+
22
+ To downscope permissions of a source credential, a Credential Access Boundary
23
+ that specifies which resources the new credential can access, as well as
24
+ an upper bound on the permissions that are available on each resource, has to
25
+ be defined. A downscoped credential can then be instantiated using the source
26
+ credential and the Credential Access Boundary.
27
+
28
+ The common pattern of usage is to have a token broker with elevated access
29
+ generate these downscoped credentials from higher access source credentials and
30
+ pass the downscoped short-lived access tokens to a token consumer via some
31
+ secure authenticated channel for limited access to Google Cloud Storage
32
+ resources.
33
+
34
+ For example, a token broker can be set up on a server in a private network.
35
+ Various workloads (token consumers) in the same network will send authenticated
36
+ requests to that broker for downscoped tokens to access or modify specific google
37
+ cloud storage buckets.
38
+
39
+ The broker will instantiate downscoped credentials instances that can be used to
40
+ generate short lived downscoped access tokens that can be passed to the token
41
+ consumer. These downscoped access tokens can be injected by the consumer into
42
+ google.oauth2.Credentials and used to initialize a storage client instance to
43
+ access Google Cloud Storage resources with restricted access.
44
+
45
+ Note: Only Cloud Storage supports Credential Access Boundaries. Other Google
46
+ Cloud services do not support this feature.
47
+
48
+ .. _Downscoping with Credential Access Boundaries: https://cloud.google.com/iam/docs/downscoping-short-lived-credentials
49
+ """
50
+
51
+ import datetime
52
+
53
+ from google.auth import _helpers
54
+ from google.auth import credentials
55
+ from google.auth import exceptions
56
+ from google.oauth2 import sts
57
+
58
+ # The maximum number of access boundary rules a Credential Access Boundary can
59
+ # contain.
60
+ _MAX_ACCESS_BOUNDARY_RULES_COUNT = 10
61
+ # The token exchange grant_type used for exchanging credentials.
62
+ _STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
63
+ # The token exchange requested_token_type. This is always an access_token.
64
+ _STS_REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
65
+ # The STS token URL used to exchanged a short lived access token for a downscoped one.
66
+ _STS_TOKEN_URL_PATTERN = "https://sts.{}/v1/token"
67
+ # The subject token type to use when exchanging a short lived access token for a
68
+ # downscoped token.
69
+ _STS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
70
+
71
+
72
+ class CredentialAccessBoundary(object):
73
+ """Defines a Credential Access Boundary which contains a list of access boundary
74
+ rules. Each rule contains information on the resource that the rule applies to,
75
+ the upper bound of the permissions that are available on that resource and an
76
+ optional condition to further restrict permissions.
77
+ """
78
+
79
+ def __init__(self, rules=[]):
80
+ """Instantiates a Credential Access Boundary. A Credential Access Boundary
81
+ can contain up to 10 access boundary rules.
82
+
83
+ Args:
84
+ rules (Sequence[google.auth.downscoped.AccessBoundaryRule]): The list of
85
+ access boundary rules limiting the access that a downscoped credential
86
+ will have.
87
+ Raises:
88
+ InvalidType: If any of the rules are not a valid type.
89
+ InvalidValue: If the provided rules exceed the maximum allowed.
90
+ """
91
+ self.rules = rules
92
+
93
+ @property
94
+ def rules(self):
95
+ """Returns the list of access boundary rules defined on the Credential
96
+ Access Boundary.
97
+
98
+ Returns:
99
+ Tuple[google.auth.downscoped.AccessBoundaryRule, ...]: The list of access
100
+ boundary rules defined on the Credential Access Boundary. These are returned
101
+ as an immutable tuple to prevent modification.
102
+ """
103
+ return tuple(self._rules)
104
+
105
+ @rules.setter
106
+ def rules(self, value):
107
+ """Updates the current rules on the Credential Access Boundary. This will overwrite
108
+ the existing set of rules.
109
+
110
+ Args:
111
+ value (Sequence[google.auth.downscoped.AccessBoundaryRule]): The list of
112
+ access boundary rules limiting the access that a downscoped credential
113
+ will have.
114
+ Raises:
115
+ InvalidType: If any of the rules are not a valid type.
116
+ InvalidValue: If the provided rules exceed the maximum allowed.
117
+ """
118
+ if len(value) > _MAX_ACCESS_BOUNDARY_RULES_COUNT:
119
+ raise exceptions.InvalidValue(
120
+ "Credential access boundary rules can have a maximum of {} rules.".format(
121
+ _MAX_ACCESS_BOUNDARY_RULES_COUNT
122
+ )
123
+ )
124
+ for access_boundary_rule in value:
125
+ if not isinstance(access_boundary_rule, AccessBoundaryRule):
126
+ raise exceptions.InvalidType(
127
+ "List of rules provided do not contain a valid 'google.auth.downscoped.AccessBoundaryRule'."
128
+ )
129
+ # Make a copy of the original list.
130
+ self._rules = list(value)
131
+
132
+ def add_rule(self, rule):
133
+ """Adds a single access boundary rule to the existing rules.
134
+
135
+ Args:
136
+ rule (google.auth.downscoped.AccessBoundaryRule): The access boundary rule,
137
+ limiting the access that a downscoped credential will have, to be added to
138
+ the existing rules.
139
+ Raises:
140
+ InvalidType: If any of the rules are not a valid type.
141
+ InvalidValue: If the provided rules exceed the maximum allowed.
142
+ """
143
+ if len(self.rules) == _MAX_ACCESS_BOUNDARY_RULES_COUNT:
144
+ raise exceptions.InvalidValue(
145
+ "Credential access boundary rules can have a maximum of {} rules.".format(
146
+ _MAX_ACCESS_BOUNDARY_RULES_COUNT
147
+ )
148
+ )
149
+ if not isinstance(rule, AccessBoundaryRule):
150
+ raise exceptions.InvalidType(
151
+ "The provided rule does not contain a valid 'google.auth.downscoped.AccessBoundaryRule'."
152
+ )
153
+ self._rules.append(rule)
154
+
155
+ def to_json(self):
156
+ """Generates the dictionary representation of the Credential Access Boundary.
157
+ This uses the format expected by the Security Token Service API as documented in
158
+ `Defining a Credential Access Boundary`_.
159
+
160
+ .. _Defining a Credential Access Boundary:
161
+ https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary
162
+
163
+ Returns:
164
+ Mapping: Credential Access Boundary Rule represented in a dictionary object.
165
+ """
166
+ rules = []
167
+ for access_boundary_rule in self.rules:
168
+ rules.append(access_boundary_rule.to_json())
169
+
170
+ return {"accessBoundary": {"accessBoundaryRules": rules}}
171
+
172
+
173
+ class AccessBoundaryRule(object):
174
+ """Defines an access boundary rule which contains information on the resource that
175
+ the rule applies to, the upper bound of the permissions that are available on that
176
+ resource and an optional condition to further restrict permissions.
177
+ """
178
+
179
+ def __init__(
180
+ self, available_resource, available_permissions, availability_condition=None
181
+ ):
182
+ """Instantiates a single access boundary rule.
183
+
184
+ Args:
185
+ available_resource (str): The full resource name of the Cloud Storage bucket
186
+ that the rule applies to. Use the format
187
+ "//storage.googleapis.com/projects/_/buckets/bucket-name".
188
+ available_permissions (Sequence[str]): A list defining the upper bound that
189
+ the downscoped token will have on the available permissions for the
190
+ resource. Each value is the identifier for an IAM predefined role or
191
+ custom role, with the prefix "inRole:". For example:
192
+ "inRole:roles/storage.objectViewer".
193
+ Only the permissions in these roles will be available.
194
+ availability_condition (Optional[google.auth.downscoped.AvailabilityCondition]):
195
+ Optional condition that restricts the availability of permissions to
196
+ specific Cloud Storage objects.
197
+
198
+ Raises:
199
+ InvalidType: If any of the parameters are not of the expected types.
200
+ InvalidValue: If any of the parameters are not of the expected values.
201
+ """
202
+ self.available_resource = available_resource
203
+ self.available_permissions = available_permissions
204
+ self.availability_condition = availability_condition
205
+
206
+ @property
207
+ def available_resource(self):
208
+ """Returns the current available resource.
209
+
210
+ Returns:
211
+ str: The current available resource.
212
+ """
213
+ return self._available_resource
214
+
215
+ @available_resource.setter
216
+ def available_resource(self, value):
217
+ """Updates the current available resource.
218
+
219
+ Args:
220
+ value (str): The updated value of the available resource.
221
+
222
+ Raises:
223
+ google.auth.exceptions.InvalidType: If the value is not a string.
224
+ """
225
+ if not isinstance(value, str):
226
+ raise exceptions.InvalidType(
227
+ "The provided available_resource is not a string."
228
+ )
229
+ self._available_resource = value
230
+
231
+ @property
232
+ def available_permissions(self):
233
+ """Returns the current available permissions.
234
+
235
+ Returns:
236
+ Tuple[str, ...]: The current available permissions. These are returned
237
+ as an immutable tuple to prevent modification.
238
+ """
239
+ return tuple(self._available_permissions)
240
+
241
+ @available_permissions.setter
242
+ def available_permissions(self, value):
243
+ """Updates the current available permissions.
244
+
245
+ Args:
246
+ value (Sequence[str]): The updated value of the available permissions.
247
+
248
+ Raises:
249
+ InvalidType: If the value is not a list of strings.
250
+ InvalidValue: If the value is not valid.
251
+ """
252
+ for available_permission in value:
253
+ if not isinstance(available_permission, str):
254
+ raise exceptions.InvalidType(
255
+ "Provided available_permissions are not a list of strings."
256
+ )
257
+ if available_permission.find("inRole:") != 0:
258
+ raise exceptions.InvalidValue(
259
+ "available_permissions must be prefixed with 'inRole:'."
260
+ )
261
+ # Make a copy of the original list.
262
+ self._available_permissions = list(value)
263
+
264
+ @property
265
+ def availability_condition(self):
266
+ """Returns the current availability condition.
267
+
268
+ Returns:
269
+ Optional[google.auth.downscoped.AvailabilityCondition]: The current
270
+ availability condition.
271
+ """
272
+ return self._availability_condition
273
+
274
+ @availability_condition.setter
275
+ def availability_condition(self, value):
276
+ """Updates the current availability condition.
277
+
278
+ Args:
279
+ value (Optional[google.auth.downscoped.AvailabilityCondition]): The updated
280
+ value of the availability condition.
281
+
282
+ Raises:
283
+ google.auth.exceptions.InvalidType: If the value is not of type google.auth.downscoped.AvailabilityCondition
284
+ or None.
285
+ """
286
+ if not isinstance(value, AvailabilityCondition) and value is not None:
287
+ raise exceptions.InvalidType(
288
+ "The provided availability_condition is not a 'google.auth.downscoped.AvailabilityCondition' or None."
289
+ )
290
+ self._availability_condition = value
291
+
292
+ def to_json(self):
293
+ """Generates the dictionary representation of the access boundary rule.
294
+ This uses the format expected by the Security Token Service API as documented in
295
+ `Defining a Credential Access Boundary`_.
296
+
297
+ .. _Defining a Credential Access Boundary:
298
+ https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary
299
+
300
+ Returns:
301
+ Mapping: The access boundary rule represented in a dictionary object.
302
+ """
303
+ json = {
304
+ "availablePermissions": list(self.available_permissions),
305
+ "availableResource": self.available_resource,
306
+ }
307
+ if self.availability_condition:
308
+ json["availabilityCondition"] = self.availability_condition.to_json()
309
+ return json
310
+
311
+
312
+ class AvailabilityCondition(object):
313
+ """An optional condition that can be used as part of a Credential Access Boundary
314
+ to further restrict permissions."""
315
+
316
+ def __init__(self, expression, title=None, description=None):
317
+ """Instantiates an availability condition using the provided expression and
318
+ optional title or description.
319
+
320
+ Args:
321
+ expression (str): A condition expression that specifies the Cloud Storage
322
+ objects where permissions are available. For example, this expression
323
+ makes permissions available for objects whose name starts with "customer-a":
324
+ "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a')"
325
+ title (Optional[str]): An optional short string that identifies the purpose of
326
+ the condition.
327
+ description (Optional[str]): Optional details about the purpose of the condition.
328
+
329
+ Raises:
330
+ InvalidType: If any of the parameters are not of the expected types.
331
+ InvalidValue: If any of the parameters are not of the expected values.
332
+ """
333
+ self.expression = expression
334
+ self.title = title
335
+ self.description = description
336
+
337
+ @property
338
+ def expression(self):
339
+ """Returns the current condition expression.
340
+
341
+ Returns:
342
+ str: The current conditon expression.
343
+ """
344
+ return self._expression
345
+
346
+ @expression.setter
347
+ def expression(self, value):
348
+ """Updates the current condition expression.
349
+
350
+ Args:
351
+ value (str): The updated value of the condition expression.
352
+
353
+ Raises:
354
+ google.auth.exceptions.InvalidType: If the value is not of type string.
355
+ """
356
+ if not isinstance(value, str):
357
+ raise exceptions.InvalidType("The provided expression is not a string.")
358
+ self._expression = value
359
+
360
+ @property
361
+ def title(self):
362
+ """Returns the current title.
363
+
364
+ Returns:
365
+ Optional[str]: The current title.
366
+ """
367
+ return self._title
368
+
369
+ @title.setter
370
+ def title(self, value):
371
+ """Updates the current title.
372
+
373
+ Args:
374
+ value (Optional[str]): The updated value of the title.
375
+
376
+ Raises:
377
+ google.auth.exceptions.InvalidType: If the value is not of type string or None.
378
+ """
379
+ if not isinstance(value, str) and value is not None:
380
+ raise exceptions.InvalidType("The provided title is not a string or None.")
381
+ self._title = value
382
+
383
+ @property
384
+ def description(self):
385
+ """Returns the current description.
386
+
387
+ Returns:
388
+ Optional[str]: The current description.
389
+ """
390
+ return self._description
391
+
392
+ @description.setter
393
+ def description(self, value):
394
+ """Updates the current description.
395
+
396
+ Args:
397
+ value (Optional[str]): The updated value of the description.
398
+
399
+ Raises:
400
+ google.auth.exceptions.InvalidType: If the value is not of type string or None.
401
+ """
402
+ if not isinstance(value, str) and value is not None:
403
+ raise exceptions.InvalidType(
404
+ "The provided description is not a string or None."
405
+ )
406
+ self._description = value
407
+
408
+ def to_json(self):
409
+ """Generates the dictionary representation of the availability condition.
410
+ This uses the format expected by the Security Token Service API as documented in
411
+ `Defining a Credential Access Boundary`_.
412
+
413
+ .. _Defining a Credential Access Boundary:
414
+ https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary
415
+
416
+ Returns:
417
+ Mapping[str, str]: The availability condition represented in a dictionary
418
+ object.
419
+ """
420
+ json = {"expression": self.expression}
421
+ if self.title:
422
+ json["title"] = self.title
423
+ if self.description:
424
+ json["description"] = self.description
425
+ return json
426
+
427
+
428
+ class Credentials(credentials.CredentialsWithQuotaProject):
429
+ """Defines a set of Google credentials that are downscoped from an existing set
430
+ of Google OAuth2 credentials. This is useful to restrict the Identity and Access
431
+ Management (IAM) permissions that a short-lived credential can use.
432
+ The common pattern of usage is to have a token broker with elevated access
433
+ generate these downscoped credentials from higher access source credentials and
434
+ pass the downscoped short-lived access tokens to a token consumer via some
435
+ secure authenticated channel for limited access to Google Cloud Storage
436
+ resources.
437
+ """
438
+
439
+ def __init__(
440
+ self,
441
+ source_credentials,
442
+ credential_access_boundary,
443
+ quota_project_id=None,
444
+ universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
445
+ ):
446
+ """Instantiates a downscoped credentials object using the provided source
447
+ credentials and credential access boundary rules.
448
+ To downscope permissions of a source credential, a Credential Access Boundary
449
+ that specifies which resources the new credential can access, as well as an
450
+ upper bound on the permissions that are available on each resource, has to be
451
+ defined. A downscoped credential can then be instantiated using the source
452
+ credential and the Credential Access Boundary.
453
+
454
+ Args:
455
+ source_credentials (google.auth.credentials.Credentials): The source credentials
456
+ to be downscoped based on the provided Credential Access Boundary rules.
457
+ credential_access_boundary (google.auth.downscoped.CredentialAccessBoundary):
458
+ The Credential Access Boundary which contains a list of access boundary
459
+ rules. Each rule contains information on the resource that the rule applies to,
460
+ the upper bound of the permissions that are available on that resource and an
461
+ optional condition to further restrict permissions.
462
+ quota_project_id (Optional[str]): The optional quota project ID.
463
+ universe_domain (Optional[str]): The universe domain value, default is googleapis.com
464
+ Raises:
465
+ google.auth.exceptions.RefreshError: If the source credentials
466
+ return an error on token refresh.
467
+ google.auth.exceptions.OAuthError: If the STS token exchange
468
+ endpoint returned an error during downscoped token generation.
469
+ """
470
+
471
+ super(Credentials, self).__init__()
472
+ self._source_credentials = source_credentials
473
+ self._credential_access_boundary = credential_access_boundary
474
+ self._quota_project_id = quota_project_id
475
+ self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
476
+ self._sts_client = sts.Client(
477
+ _STS_TOKEN_URL_PATTERN.format(self.universe_domain)
478
+ )
479
+
480
+ @_helpers.copy_docstring(credentials.Credentials)
481
+ def refresh(self, request):
482
+ # Generate an access token from the source credentials.
483
+ self._source_credentials.refresh(request)
484
+ now = _helpers.utcnow()
485
+ # Exchange the access token for a downscoped access token.
486
+ response_data = self._sts_client.exchange_token(
487
+ request=request,
488
+ grant_type=_STS_GRANT_TYPE,
489
+ subject_token=self._source_credentials.token,
490
+ subject_token_type=_STS_SUBJECT_TOKEN_TYPE,
491
+ requested_token_type=_STS_REQUESTED_TOKEN_TYPE,
492
+ additional_options=self._credential_access_boundary.to_json(),
493
+ )
494
+ self.token = response_data.get("access_token")
495
+ # For downscoping CAB flow, the STS endpoint may not return the expiration
496
+ # field for some flows. The generated downscoped token should always have
497
+ # the same expiration time as the source credentials. When no expires_in
498
+ # field is returned in the response, we can just get the expiration time
499
+ # from the source credentials.
500
+ if response_data.get("expires_in"):
501
+ lifetime = datetime.timedelta(seconds=response_data.get("expires_in"))
502
+ self.expiry = now + lifetime
503
+ else:
504
+ self.expiry = self._source_credentials.expiry
505
+
506
+ @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
507
+ def with_quota_project(self, quota_project_id):
508
+ return self.__class__(
509
+ self._source_credentials,
510
+ self._credential_access_boundary,
511
+ quota_project_id=quota_project_id,
512
+ )
lib/python3.10/site-packages/google/auth/exceptions.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Exceptions used in the google.auth package."""
16
+
17
+
18
+ class GoogleAuthError(Exception):
19
+ """Base class for all google.auth errors."""
20
+
21
+ def __init__(self, *args, **kwargs):
22
+ super(GoogleAuthError, self).__init__(*args)
23
+ retryable = kwargs.get("retryable", False)
24
+ self._retryable = retryable
25
+
26
+ @property
27
+ def retryable(self):
28
+ return self._retryable
29
+
30
+
31
+ class TransportError(GoogleAuthError):
32
+ """Used to indicate an error occurred during an HTTP request."""
33
+
34
+
35
+ class RefreshError(GoogleAuthError):
36
+ """Used to indicate that an refreshing the credentials' access token
37
+ failed."""
38
+
39
+
40
+ class UserAccessTokenError(GoogleAuthError):
41
+ """Used to indicate ``gcloud auth print-access-token`` command failed."""
42
+
43
+
44
+ class DefaultCredentialsError(GoogleAuthError):
45
+ """Used to indicate that acquiring default credentials failed."""
46
+
47
+
48
+ class MutualTLSChannelError(GoogleAuthError):
49
+ """Used to indicate that mutual TLS channel creation is failed, or mutual
50
+ TLS channel credentials is missing or invalid."""
51
+
52
+
53
+ class ClientCertError(GoogleAuthError):
54
+ """Used to indicate that client certificate is missing or invalid."""
55
+
56
+ @property
57
+ def retryable(self):
58
+ return False
59
+
60
+
61
+ class OAuthError(GoogleAuthError):
62
+ """Used to indicate an error occurred during an OAuth related HTTP
63
+ request."""
64
+
65
+
66
+ class ReauthFailError(RefreshError):
67
+ """An exception for when reauth failed."""
68
+
69
+ def __init__(self, message=None, **kwargs):
70
+ super(ReauthFailError, self).__init__(
71
+ "Reauthentication failed. {0}".format(message), **kwargs
72
+ )
73
+
74
+
75
+ class ReauthSamlChallengeFailError(ReauthFailError):
76
+ """An exception for SAML reauth challenge failures."""
77
+
78
+
79
+ class MalformedError(DefaultCredentialsError, ValueError):
80
+ """An exception for malformed data."""
81
+
82
+
83
+ class InvalidResource(DefaultCredentialsError, ValueError):
84
+ """An exception for URL error."""
85
+
86
+
87
+ class InvalidOperation(DefaultCredentialsError, ValueError):
88
+ """An exception for invalid operation."""
89
+
90
+
91
+ class InvalidValue(DefaultCredentialsError, ValueError):
92
+ """Used to wrap general ValueError of python."""
93
+
94
+
95
+ class InvalidType(DefaultCredentialsError, TypeError):
96
+ """Used to wrap general TypeError of python."""
97
+
98
+
99
+ class OSError(DefaultCredentialsError, EnvironmentError):
100
+ """Used to wrap EnvironmentError(OSError after python3.3)."""
101
+
102
+
103
+ class TimeoutError(GoogleAuthError):
104
+ """Used to indicate a timeout error occurred during an HTTP request."""
105
+
106
+
107
+ class ResponseError(GoogleAuthError):
108
+ """Used to indicate an error occurred when reading an HTTP response."""
lib/python3.10/site-packages/google/auth/external_account.py ADDED
@@ -0,0 +1,628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ """External Account Credentials.
16
+
17
+ This module provides credentials that exchange workload identity pool external
18
+ credentials for Google access tokens. This facilitates accessing Google Cloud
19
+ Platform resources from on-prem and non-Google Cloud platforms (e.g. AWS,
20
+ Microsoft Azure, OIDC identity providers), using native credentials retrieved
21
+ from the current environment without the need to copy, save and manage
22
+ long-lived service account credentials.
23
+
24
+ Specifically, this is intended to use access tokens acquired using the GCP STS
25
+ token exchange endpoint following the `OAuth 2.0 Token Exchange`_ spec.
26
+
27
+ .. _OAuth 2.0 Token Exchange: https://tools.ietf.org/html/rfc8693
28
+ """
29
+
30
+ import abc
31
+ import copy
32
+ from dataclasses import dataclass
33
+ import datetime
34
+ import functools
35
+ import io
36
+ import json
37
+ import re
38
+
39
+ from google.auth import _helpers
40
+ from google.auth import credentials
41
+ from google.auth import exceptions
42
+ from google.auth import impersonated_credentials
43
+ from google.auth import metrics
44
+ from google.oauth2 import sts
45
+ from google.oauth2 import utils
46
+
47
+ # External account JSON type identifier.
48
+ _EXTERNAL_ACCOUNT_JSON_TYPE = "external_account"
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
+ # Cloud resource manager URL used to retrieve project information.
54
+ _CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/"
55
+ # Default Google sts token url.
56
+ _DEFAULT_TOKEN_URL = "https://sts.{universe_domain}/v1/token"
57
+
58
+
59
+ @dataclass
60
+ class SupplierContext:
61
+ """A context class that contains information about the requested third party credential that is passed
62
+ to AWS security credential and subject token suppliers.
63
+
64
+ Attributes:
65
+ subject_token_type (str): The requested subject token type based on the Oauth2.0 token exchange spec.
66
+ Expected values include::
67
+
68
+ “urn:ietf:params:oauth:token-type:jwt”
69
+ “urn:ietf:params:oauth:token-type:id-token”
70
+ “urn:ietf:params:oauth:token-type:saml2”
71
+ “urn:ietf:params:aws:token-type:aws4_request”
72
+
73
+ audience (str): The requested audience for the subject token.
74
+ """
75
+
76
+ subject_token_type: str
77
+ audience: str
78
+
79
+
80
+ class Credentials(
81
+ credentials.Scoped,
82
+ credentials.CredentialsWithQuotaProject,
83
+ credentials.CredentialsWithTokenUri,
84
+ metaclass=abc.ABCMeta,
85
+ ):
86
+ """Base class for all external account credentials.
87
+
88
+ This is used to instantiate Credentials for exchanging external account
89
+ credentials for Google access token and authorizing requests to Google APIs.
90
+ The base class implements the common logic for exchanging external account
91
+ credentials for Google access tokens.
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ audience,
97
+ subject_token_type,
98
+ token_url,
99
+ credential_source,
100
+ service_account_impersonation_url=None,
101
+ service_account_impersonation_options=None,
102
+ client_id=None,
103
+ client_secret=None,
104
+ token_info_url=None,
105
+ quota_project_id=None,
106
+ scopes=None,
107
+ default_scopes=None,
108
+ workforce_pool_user_project=None,
109
+ universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
110
+ trust_boundary=None,
111
+ ):
112
+ """Instantiates an external account credentials object.
113
+
114
+ Args:
115
+ audience (str): The STS audience field.
116
+ subject_token_type (str): The subject token type based on the Oauth2.0 token exchange spec.
117
+ Expected values include::
118
+
119
+ “urn:ietf:params:oauth:token-type:jwt”
120
+ “urn:ietf:params:oauth:token-type:id-token”
121
+ “urn:ietf:params:oauth:token-type:saml2”
122
+ “urn:ietf:params:aws:token-type:aws4_request”
123
+
124
+ token_url (str): The STS endpoint URL.
125
+ credential_source (Mapping): The credential source dictionary.
126
+ service_account_impersonation_url (Optional[str]): The optional service account
127
+ impersonation generateAccessToken URL.
128
+ client_id (Optional[str]): The optional client ID.
129
+ client_secret (Optional[str]): The optional client secret.
130
+ token_info_url (str): The optional STS endpoint URL for token introspection.
131
+ quota_project_id (Optional[str]): The optional quota project ID.
132
+ scopes (Optional[Sequence[str]]): Optional scopes to request during the
133
+ authorization grant.
134
+ default_scopes (Optional[Sequence[str]]): Default scopes passed by a
135
+ Google client library. Use 'scopes' for user-defined scopes.
136
+ workforce_pool_user_project (Optona[str]): The optional workforce pool user
137
+ project number when the credential corresponds to a workforce pool and not
138
+ a workload identity pool. The underlying principal must still have
139
+ serviceusage.services.use IAM permission to use the project for
140
+ billing/quota.
141
+ universe_domain (str): The universe domain. The default universe
142
+ domain is googleapis.com.
143
+ trust_boundary (str): String representation of trust boundary meta.
144
+ Raises:
145
+ google.auth.exceptions.RefreshError: If the generateAccessToken
146
+ endpoint returned an error.
147
+ """
148
+ super(Credentials, self).__init__()
149
+ self._audience = audience
150
+ self._subject_token_type = subject_token_type
151
+ self._universe_domain = universe_domain
152
+ self._token_url = token_url
153
+ if self._token_url == _DEFAULT_TOKEN_URL:
154
+ self._token_url = self._token_url.replace(
155
+ "{universe_domain}", self._universe_domain
156
+ )
157
+ self._token_info_url = token_info_url
158
+ self._credential_source = credential_source
159
+ self._service_account_impersonation_url = service_account_impersonation_url
160
+ self._service_account_impersonation_options = (
161
+ service_account_impersonation_options or {}
162
+ )
163
+ self._client_id = client_id
164
+ self._client_secret = client_secret
165
+ self._quota_project_id = quota_project_id
166
+ self._scopes = scopes
167
+ self._default_scopes = default_scopes
168
+ self._workforce_pool_user_project = workforce_pool_user_project
169
+ self._trust_boundary = {
170
+ "locations": [],
171
+ "encoded_locations": "0x0",
172
+ } # expose a placeholder trust boundary value.
173
+
174
+ if self._client_id:
175
+ self._client_auth = utils.ClientAuthentication(
176
+ utils.ClientAuthType.basic, self._client_id, self._client_secret
177
+ )
178
+ else:
179
+ self._client_auth = None
180
+ self._sts_client = sts.Client(self._token_url, self._client_auth)
181
+
182
+ self._metrics_options = self._create_default_metrics_options()
183
+
184
+ self._impersonated_credentials = None
185
+ self._project_id = None
186
+ self._supplier_context = SupplierContext(
187
+ self._subject_token_type, self._audience
188
+ )
189
+ self._cred_file_path = None
190
+
191
+ if not self.is_workforce_pool and self._workforce_pool_user_project:
192
+ # Workload identity pools do not support workforce pool user projects.
193
+ raise exceptions.InvalidValue(
194
+ "workforce_pool_user_project should not be set for non-workforce pool "
195
+ "credentials"
196
+ )
197
+
198
+ @property
199
+ def info(self):
200
+ """Generates the dictionary representation of the current credentials.
201
+
202
+ Returns:
203
+ Mapping: The dictionary representation of the credentials. This is the
204
+ reverse of "from_info" defined on the subclasses of this class. It is
205
+ useful for serializing the current credentials so it can deserialized
206
+ later.
207
+ """
208
+ config_info = self._constructor_args()
209
+ config_info.update(
210
+ type=_EXTERNAL_ACCOUNT_JSON_TYPE,
211
+ service_account_impersonation=config_info.pop(
212
+ "service_account_impersonation_options", None
213
+ ),
214
+ )
215
+ config_info.pop("scopes", None)
216
+ config_info.pop("default_scopes", None)
217
+ return {key: value for key, value in config_info.items() if value is not None}
218
+
219
+ def _constructor_args(self):
220
+ args = {
221
+ "audience": self._audience,
222
+ "subject_token_type": self._subject_token_type,
223
+ "token_url": self._token_url,
224
+ "token_info_url": self._token_info_url,
225
+ "service_account_impersonation_url": self._service_account_impersonation_url,
226
+ "service_account_impersonation_options": copy.deepcopy(
227
+ self._service_account_impersonation_options
228
+ )
229
+ or None,
230
+ "credential_source": copy.deepcopy(self._credential_source),
231
+ "quota_project_id": self._quota_project_id,
232
+ "client_id": self._client_id,
233
+ "client_secret": self._client_secret,
234
+ "workforce_pool_user_project": self._workforce_pool_user_project,
235
+ "scopes": self._scopes,
236
+ "default_scopes": self._default_scopes,
237
+ "universe_domain": self._universe_domain,
238
+ }
239
+ if not self.is_workforce_pool:
240
+ args.pop("workforce_pool_user_project")
241
+ return args
242
+
243
+ @property
244
+ def service_account_email(self):
245
+ """Returns the service account email if service account impersonation is used.
246
+
247
+ Returns:
248
+ Optional[str]: The service account email if impersonation is used. Otherwise
249
+ None is returned.
250
+ """
251
+ if self._service_account_impersonation_url:
252
+ # Parse email from URL. The formal looks as follows:
253
+ # https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/[email protected]:generateAccessToken
254
+ url = self._service_account_impersonation_url
255
+ start_index = url.rfind("/")
256
+ end_index = url.find(":generateAccessToken")
257
+ if start_index != -1 and end_index != -1 and start_index < end_index:
258
+ start_index = start_index + 1
259
+ return url[start_index:end_index]
260
+ return None
261
+
262
+ @property
263
+ def is_user(self):
264
+ """Returns whether the credentials represent a user (True) or workload (False).
265
+ Workloads behave similarly to service accounts. Currently workloads will use
266
+ service account impersonation but will eventually not require impersonation.
267
+ As a result, this property is more reliable than the service account email
268
+ property in determining if the credentials represent a user or workload.
269
+
270
+ Returns:
271
+ bool: True if the credentials represent a user. False if they represent a
272
+ workload.
273
+ """
274
+ # If service account impersonation is used, the credentials will always represent a
275
+ # service account.
276
+ if self._service_account_impersonation_url:
277
+ return False
278
+ return self.is_workforce_pool
279
+
280
+ @property
281
+ def is_workforce_pool(self):
282
+ """Returns whether the credentials represent a workforce pool (True) or
283
+ workload (False) based on the credentials' audience.
284
+
285
+ This will also return True for impersonated workforce pool credentials.
286
+
287
+ Returns:
288
+ bool: True if the credentials represent a workforce pool. False if they
289
+ represent a workload.
290
+ """
291
+ # Workforce pools representing users have the following audience format:
292
+ # //iam.googleapis.com/locations/$location/workforcePools/$poolId/providers/$providerId
293
+ p = re.compile(r"//iam\.googleapis\.com/locations/[^/]+/workforcePools/")
294
+ return p.match(self._audience or "") is not None
295
+
296
+ @property
297
+ def requires_scopes(self):
298
+ """Checks if the credentials requires scopes.
299
+
300
+ Returns:
301
+ bool: True if there are no scopes set otherwise False.
302
+ """
303
+ return not self._scopes and not self._default_scopes
304
+
305
+ @property
306
+ def project_number(self):
307
+ """Optional[str]: The project number corresponding to the workload identity pool."""
308
+
309
+ # STS audience pattern:
310
+ # //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...
311
+ components = self._audience.split("/")
312
+ try:
313
+ project_index = components.index("projects")
314
+ if project_index + 1 < len(components):
315
+ return components[project_index + 1] or None
316
+ except ValueError:
317
+ return None
318
+
319
+ @property
320
+ def token_info_url(self):
321
+ """Optional[str]: The STS token introspection endpoint."""
322
+
323
+ return self._token_info_url
324
+
325
+ @_helpers.copy_docstring(credentials.Credentials)
326
+ def get_cred_info(self):
327
+ if self._cred_file_path:
328
+ cred_info_json = {
329
+ "credential_source": self._cred_file_path,
330
+ "credential_type": "external account credentials",
331
+ }
332
+ if self.service_account_email:
333
+ cred_info_json["principal"] = self.service_account_email
334
+ return cred_info_json
335
+ return None
336
+
337
+ @_helpers.copy_docstring(credentials.Scoped)
338
+ def with_scopes(self, scopes, default_scopes=None):
339
+ kwargs = self._constructor_args()
340
+ kwargs.update(scopes=scopes, default_scopes=default_scopes)
341
+ scoped = self.__class__(**kwargs)
342
+ scoped._cred_file_path = self._cred_file_path
343
+ scoped._metrics_options = self._metrics_options
344
+ return scoped
345
+
346
+ @abc.abstractmethod
347
+ def retrieve_subject_token(self, request):
348
+ """Retrieves the subject token using the credential_source object.
349
+
350
+ Args:
351
+ request (google.auth.transport.Request): A callable used to make
352
+ HTTP requests.
353
+ Returns:
354
+ str: The retrieved subject token.
355
+ """
356
+ # pylint: disable=missing-raises-doc
357
+ # (pylint doesn't recognize that this is abstract)
358
+ raise NotImplementedError("retrieve_subject_token must be implemented")
359
+
360
+ def get_project_id(self, request):
361
+ """Retrieves the project ID corresponding to the workload identity or workforce pool.
362
+ For workforce pool credentials, it returns the project ID corresponding to
363
+ the workforce_pool_user_project.
364
+
365
+ When not determinable, None is returned.
366
+
367
+ This is introduced to support the current pattern of using the Auth library:
368
+
369
+ credentials, project_id = google.auth.default()
370
+
371
+ The resource may not have permission (resourcemanager.projects.get) to
372
+ call this API or the required scopes may not be selected:
373
+ https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes
374
+
375
+ Args:
376
+ request (google.auth.transport.Request): A callable used to make
377
+ HTTP requests.
378
+ Returns:
379
+ Optional[str]: The project ID corresponding to the workload identity pool
380
+ or workforce pool if determinable.
381
+ """
382
+ if self._project_id:
383
+ # If already retrieved, return the cached project ID value.
384
+ return self._project_id
385
+ scopes = self._scopes if self._scopes is not None else self._default_scopes
386
+ # Scopes are required in order to retrieve a valid access token.
387
+ project_number = self.project_number or self._workforce_pool_user_project
388
+ if project_number and scopes:
389
+ headers = {}
390
+ url = _CLOUD_RESOURCE_MANAGER + project_number
391
+ self.before_request(request, "GET", url, headers)
392
+ response = request(url=url, method="GET", headers=headers)
393
+
394
+ response_body = (
395
+ response.data.decode("utf-8")
396
+ if hasattr(response.data, "decode")
397
+ else response.data
398
+ )
399
+ response_data = json.loads(response_body)
400
+
401
+ if response.status == 200:
402
+ # Cache result as this field is immutable.
403
+ self._project_id = response_data.get("projectId")
404
+ return self._project_id
405
+
406
+ return None
407
+
408
+ @_helpers.copy_docstring(credentials.Credentials)
409
+ def refresh(self, request):
410
+ scopes = self._scopes if self._scopes is not None else self._default_scopes
411
+
412
+ # Inject client certificate into request.
413
+ if self._mtls_required():
414
+ request = functools.partial(
415
+ request, cert=self._get_mtls_cert_and_key_paths()
416
+ )
417
+
418
+ if self._should_initialize_impersonated_credentials():
419
+ self._impersonated_credentials = self._initialize_impersonated_credentials()
420
+
421
+ if self._impersonated_credentials:
422
+ self._impersonated_credentials.refresh(request)
423
+ self.token = self._impersonated_credentials.token
424
+ self.expiry = self._impersonated_credentials.expiry
425
+ else:
426
+ now = _helpers.utcnow()
427
+ additional_options = None
428
+ # Do not pass workforce_pool_user_project when client authentication
429
+ # is used. The client ID is sufficient for determining the user project.
430
+ if self._workforce_pool_user_project and not self._client_id:
431
+ additional_options = {"userProject": self._workforce_pool_user_project}
432
+ additional_headers = {
433
+ metrics.API_CLIENT_HEADER: metrics.byoid_metrics_header(
434
+ self._metrics_options
435
+ )
436
+ }
437
+ response_data = self._sts_client.exchange_token(
438
+ request=request,
439
+ grant_type=_STS_GRANT_TYPE,
440
+ subject_token=self.retrieve_subject_token(request),
441
+ subject_token_type=self._subject_token_type,
442
+ audience=self._audience,
443
+ scopes=scopes,
444
+ requested_token_type=_STS_REQUESTED_TOKEN_TYPE,
445
+ additional_options=additional_options,
446
+ additional_headers=additional_headers,
447
+ )
448
+ self.token = response_data.get("access_token")
449
+ expires_in = response_data.get("expires_in")
450
+ # Some services do not respect the OAUTH2.0 RFC and send expires_in as a
451
+ # JSON String.
452
+ if isinstance(expires_in, str):
453
+ expires_in = int(expires_in)
454
+
455
+ lifetime = datetime.timedelta(seconds=expires_in)
456
+
457
+ self.expiry = now + lifetime
458
+
459
+ def _make_copy(self):
460
+ kwargs = self._constructor_args()
461
+ new_cred = self.__class__(**kwargs)
462
+ new_cred._cred_file_path = self._cred_file_path
463
+ new_cred._metrics_options = self._metrics_options
464
+ return new_cred
465
+
466
+ @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
467
+ def with_quota_project(self, quota_project_id):
468
+ # Return copy of instance with the provided quota project ID.
469
+ cred = self._make_copy()
470
+ cred._quota_project_id = quota_project_id
471
+ return cred
472
+
473
+ @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
474
+ def with_token_uri(self, token_uri):
475
+ cred = self._make_copy()
476
+ cred._token_url = token_uri
477
+ return cred
478
+
479
+ @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
480
+ def with_universe_domain(self, universe_domain):
481
+ cred = self._make_copy()
482
+ cred._universe_domain = universe_domain
483
+ return cred
484
+
485
+ def _should_initialize_impersonated_credentials(self):
486
+ return (
487
+ self._service_account_impersonation_url is not None
488
+ and self._impersonated_credentials is None
489
+ )
490
+
491
+ def _initialize_impersonated_credentials(self):
492
+ """Generates an impersonated credentials.
493
+
494
+ For more details, see `projects.serviceAccounts.generateAccessToken`_.
495
+
496
+ .. _projects.serviceAccounts.generateAccessToken: https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken
497
+
498
+ Returns:
499
+ impersonated_credentials.Credential: The impersonated credentials
500
+ object.
501
+
502
+ Raises:
503
+ google.auth.exceptions.RefreshError: If the generateAccessToken
504
+ endpoint returned an error.
505
+ """
506
+ # Return copy of instance with no service account impersonation.
507
+ kwargs = self._constructor_args()
508
+ kwargs.update(
509
+ service_account_impersonation_url=None,
510
+ service_account_impersonation_options={},
511
+ )
512
+ source_credentials = self.__class__(**kwargs)
513
+ source_credentials._metrics_options = self._metrics_options
514
+
515
+ # Determine target_principal.
516
+ target_principal = self.service_account_email
517
+ if not target_principal:
518
+ raise exceptions.RefreshError(
519
+ "Unable to determine target principal from service account impersonation URL."
520
+ )
521
+
522
+ scopes = self._scopes if self._scopes is not None else self._default_scopes
523
+ # Initialize and return impersonated credentials.
524
+ return impersonated_credentials.Credentials(
525
+ source_credentials=source_credentials,
526
+ target_principal=target_principal,
527
+ target_scopes=scopes,
528
+ quota_project_id=self._quota_project_id,
529
+ iam_endpoint_override=self._service_account_impersonation_url,
530
+ lifetime=self._service_account_impersonation_options.get(
531
+ "token_lifetime_seconds"
532
+ ),
533
+ )
534
+
535
+ def _create_default_metrics_options(self):
536
+ metrics_options = {}
537
+ if self._service_account_impersonation_url:
538
+ metrics_options["sa-impersonation"] = "true"
539
+ else:
540
+ metrics_options["sa-impersonation"] = "false"
541
+ if self._service_account_impersonation_options.get("token_lifetime_seconds"):
542
+ metrics_options["config-lifetime"] = "true"
543
+ else:
544
+ metrics_options["config-lifetime"] = "false"
545
+
546
+ return metrics_options
547
+
548
+ def _mtls_required(self):
549
+ """Returns a boolean representing whether the current credential is configured
550
+ for mTLS and should add a certificate to the outgoing calls to the sts and service
551
+ account impersonation endpoint.
552
+
553
+ Returns:
554
+ bool: True if the credential is configured for mTLS, False if it is not.
555
+ """
556
+ return False
557
+
558
+ def _get_mtls_cert_and_key_paths(self):
559
+ """Gets the file locations for a certificate and private key file
560
+ to be used for configuring mTLS for the sts and service account
561
+ impersonation calls. Currently only expected to return a value when using
562
+ X509 workload identity federation.
563
+
564
+ Returns:
565
+ Tuple[str, str]: The cert and key file locations as strings in a tuple.
566
+
567
+ Raises:
568
+ NotImplementedError: When the current credential is not configured for
569
+ mTLS.
570
+ """
571
+ raise NotImplementedError(
572
+ "_get_mtls_cert_and_key_location must be implemented."
573
+ )
574
+
575
+ @classmethod
576
+ def from_info(cls, info, **kwargs):
577
+ """Creates a Credentials instance from parsed external account info.
578
+
579
+ Args:
580
+ info (Mapping[str, str]): The external account info in Google
581
+ format.
582
+ kwargs: Additional arguments to pass to the constructor.
583
+
584
+ Returns:
585
+ google.auth.identity_pool.Credentials: The constructed
586
+ credentials.
587
+
588
+ Raises:
589
+ InvalidValue: For invalid parameters.
590
+ """
591
+ return cls(
592
+ audience=info.get("audience"),
593
+ subject_token_type=info.get("subject_token_type"),
594
+ token_url=info.get("token_url"),
595
+ token_info_url=info.get("token_info_url"),
596
+ service_account_impersonation_url=info.get(
597
+ "service_account_impersonation_url"
598
+ ),
599
+ service_account_impersonation_options=info.get(
600
+ "service_account_impersonation"
601
+ )
602
+ or {},
603
+ client_id=info.get("client_id"),
604
+ client_secret=info.get("client_secret"),
605
+ credential_source=info.get("credential_source"),
606
+ quota_project_id=info.get("quota_project_id"),
607
+ workforce_pool_user_project=info.get("workforce_pool_user_project"),
608
+ universe_domain=info.get(
609
+ "universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN
610
+ ),
611
+ **kwargs
612
+ )
613
+
614
+ @classmethod
615
+ def from_file(cls, filename, **kwargs):
616
+ """Creates a Credentials instance from an external account json file.
617
+
618
+ Args:
619
+ filename (str): The path to the external account json file.
620
+ kwargs: Additional arguments to pass to the constructor.
621
+
622
+ Returns:
623
+ google.auth.identity_pool.Credentials: The constructed
624
+ credentials.
625
+ """
626
+ with io.open(filename, "r", encoding="utf-8") as json_file:
627
+ data = json.load(json_file)
628
+ return cls.from_info(data, **kwargs)
lib/python3.10/site-packages/google/auth/external_account_authorized_user.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+
15
+ """External Account Authorized User Credentials.
16
+ This module provides credentials based on OAuth 2.0 access and refresh tokens.
17
+ These credentials usually access resources on behalf of a user (resource
18
+ owner).
19
+
20
+ Specifically, these are sourced using external identities via Workforce Identity Federation.
21
+
22
+ Obtaining the initial access and refresh token can be done through the Google Cloud CLI.
23
+
24
+ Example credential:
25
+ {
26
+ "type": "external_account_authorized_user",
27
+ "audience": "//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID",
28
+ "refresh_token": "refreshToken",
29
+ "token_url": "https://sts.googleapis.com/v1/oauth/token",
30
+ "token_info_url": "https://sts.googleapis.com/v1/instrospect",
31
+ "client_id": "clientId",
32
+ "client_secret": "clientSecret"
33
+ }
34
+ """
35
+
36
+ import datetime
37
+ import io
38
+ import json
39
+
40
+ from google.auth import _helpers
41
+ from google.auth import credentials
42
+ from google.auth import exceptions
43
+ from google.oauth2 import sts
44
+ from google.oauth2 import utils
45
+
46
+ _EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_TYPE = "external_account_authorized_user"
47
+
48
+
49
+ class Credentials(
50
+ credentials.CredentialsWithQuotaProject,
51
+ credentials.ReadOnlyScoped,
52
+ credentials.CredentialsWithTokenUri,
53
+ ):
54
+ """Credentials for External Account Authorized Users.
55
+
56
+ This is used to instantiate Credentials for exchanging refresh tokens from
57
+ authorized users for Google access token and authorizing requests to Google
58
+ APIs.
59
+
60
+ The credentials are considered immutable. If you want to modify the
61
+ quota project, use `with_quota_project` and if you want to modify the token
62
+ uri, use `with_token_uri`.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ token=None,
68
+ expiry=None,
69
+ refresh_token=None,
70
+ audience=None,
71
+ client_id=None,
72
+ client_secret=None,
73
+ token_url=None,
74
+ token_info_url=None,
75
+ revoke_url=None,
76
+ scopes=None,
77
+ quota_project_id=None,
78
+ universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
79
+ ):
80
+ """Instantiates a external account authorized user credentials object.
81
+
82
+ Args:
83
+ token (str): The OAuth 2.0 access token. Can be None if refresh information
84
+ is provided.
85
+ expiry (datetime.datetime): The optional expiration datetime of the OAuth 2.0 access
86
+ token.
87
+ refresh_token (str): The optional OAuth 2.0 refresh token. If specified,
88
+ credentials can be refreshed.
89
+ audience (str): The optional STS audience which contains the resource name for the workforce
90
+ pool and the provider identifier in that pool.
91
+ client_id (str): The OAuth 2.0 client ID. Must be specified for refresh, can be left as
92
+ None if the token can not be refreshed.
93
+ client_secret (str): The OAuth 2.0 client secret. Must be specified for refresh, can be
94
+ left as None if the token can not be refreshed.
95
+ token_url (str): The optional STS token exchange endpoint for refresh. Must be specified for
96
+ refresh, can be left as None if the token can not be refreshed.
97
+ token_info_url (str): The optional STS endpoint URL for token introspection.
98
+ revoke_url (str): The optional STS endpoint URL for revoking tokens.
99
+ quota_project_id (str): The optional project ID used for quota and billing.
100
+ This project may be different from the project used to
101
+ create the credentials.
102
+ universe_domain (Optional[str]): The universe domain. The default value
103
+ is googleapis.com.
104
+
105
+ Returns:
106
+ google.auth.external_account_authorized_user.Credentials: The
107
+ constructed credentials.
108
+ """
109
+ super(Credentials, self).__init__()
110
+
111
+ self.token = token
112
+ self.expiry = expiry
113
+ self._audience = audience
114
+ self._refresh_token = refresh_token
115
+ self._token_url = token_url
116
+ self._token_info_url = token_info_url
117
+ self._client_id = client_id
118
+ self._client_secret = client_secret
119
+ self._revoke_url = revoke_url
120
+ self._quota_project_id = quota_project_id
121
+ self._scopes = scopes
122
+ self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
123
+ self._cred_file_path = None
124
+
125
+ if not self.valid and not self.can_refresh:
126
+ raise exceptions.InvalidOperation(
127
+ "Token should be created with fields to make it valid (`token` and "
128
+ "`expiry`), or fields to allow it to refresh (`refresh_token`, "
129
+ "`token_url`, `client_id`, `client_secret`)."
130
+ )
131
+
132
+ self._client_auth = None
133
+ if self._client_id:
134
+ self._client_auth = utils.ClientAuthentication(
135
+ utils.ClientAuthType.basic, self._client_id, self._client_secret
136
+ )
137
+ self._sts_client = sts.Client(self._token_url, self._client_auth)
138
+
139
+ @property
140
+ def info(self):
141
+ """Generates the serializable dictionary representation of the current
142
+ credentials.
143
+
144
+ Returns:
145
+ Mapping: The dictionary representation of the credentials. This is the
146
+ reverse of the "from_info" method defined in this class. It is
147
+ useful for serializing the current credentials so it can deserialized
148
+ later.
149
+ """
150
+ config_info = self.constructor_args()
151
+ config_info.update(type=_EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_TYPE)
152
+ if config_info["expiry"]:
153
+ config_info["expiry"] = config_info["expiry"].isoformat() + "Z"
154
+
155
+ return {key: value for key, value in config_info.items() if value is not None}
156
+
157
+ def constructor_args(self):
158
+ return {
159
+ "audience": self._audience,
160
+ "refresh_token": self._refresh_token,
161
+ "token_url": self._token_url,
162
+ "token_info_url": self._token_info_url,
163
+ "client_id": self._client_id,
164
+ "client_secret": self._client_secret,
165
+ "token": self.token,
166
+ "expiry": self.expiry,
167
+ "revoke_url": self._revoke_url,
168
+ "scopes": self._scopes,
169
+ "quota_project_id": self._quota_project_id,
170
+ "universe_domain": self._universe_domain,
171
+ }
172
+
173
+ @property
174
+ def scopes(self):
175
+ """Optional[str]: The OAuth 2.0 permission scopes."""
176
+ return self._scopes
177
+
178
+ @property
179
+ def requires_scopes(self):
180
+ """ False: OAuth 2.0 credentials have their scopes set when
181
+ the initial token is requested and can not be changed."""
182
+ return False
183
+
184
+ @property
185
+ def client_id(self):
186
+ """Optional[str]: The OAuth 2.0 client ID."""
187
+ return self._client_id
188
+
189
+ @property
190
+ def client_secret(self):
191
+ """Optional[str]: The OAuth 2.0 client secret."""
192
+ return self._client_secret
193
+
194
+ @property
195
+ def audience(self):
196
+ """Optional[str]: The STS audience which contains the resource name for the
197
+ workforce pool and the provider identifier in that pool."""
198
+ return self._audience
199
+
200
+ @property
201
+ def refresh_token(self):
202
+ """Optional[str]: The OAuth 2.0 refresh token."""
203
+ return self._refresh_token
204
+
205
+ @property
206
+ def token_url(self):
207
+ """Optional[str]: The STS token exchange endpoint for refresh."""
208
+ return self._token_url
209
+
210
+ @property
211
+ def token_info_url(self):
212
+ """Optional[str]: The STS endpoint for token info."""
213
+ return self._token_info_url
214
+
215
+ @property
216
+ def revoke_url(self):
217
+ """Optional[str]: The STS endpoint for token revocation."""
218
+ return self._revoke_url
219
+
220
+ @property
221
+ def is_user(self):
222
+ """ True: This credential always represents a user."""
223
+ return True
224
+
225
+ @property
226
+ def can_refresh(self):
227
+ return all(
228
+ (self._refresh_token, self._token_url, self._client_id, self._client_secret)
229
+ )
230
+
231
+ def get_project_id(self, request=None):
232
+ """Retrieves the project ID corresponding to the workload identity or workforce pool.
233
+ For workforce pool credentials, it returns the project ID corresponding to
234
+ the workforce_pool_user_project.
235
+
236
+ When not determinable, None is returned.
237
+
238
+ Args:
239
+ request (google.auth.transport.requests.Request): Request object.
240
+ Unused here, but passed from _default.default().
241
+
242
+ Return:
243
+ str: project ID is not determinable for this credential type so it returns None
244
+ """
245
+
246
+ return None
247
+
248
+ def to_json(self, strip=None):
249
+ """Utility function that creates a JSON representation of this
250
+ credential.
251
+ Args:
252
+ strip (Sequence[str]): Optional list of members to exclude from the
253
+ generated JSON.
254
+ Returns:
255
+ str: A JSON representation of this instance. When converted into
256
+ a dictionary, it can be passed to from_info()
257
+ to create a new instance.
258
+ """
259
+ strip = strip if strip else []
260
+ return json.dumps({k: v for (k, v) in self.info.items() if k not in strip})
261
+
262
+ def refresh(self, request):
263
+ """Refreshes the access token.
264
+
265
+ Args:
266
+ request (google.auth.transport.Request): The object used to make
267
+ HTTP requests.
268
+
269
+ Raises:
270
+ google.auth.exceptions.RefreshError: If the credentials could
271
+ not be refreshed.
272
+ """
273
+ if not self.can_refresh:
274
+ raise exceptions.RefreshError(
275
+ "The credentials do not contain the necessary fields need to "
276
+ "refresh the access token. You must specify refresh_token, "
277
+ "token_url, client_id, and client_secret."
278
+ )
279
+
280
+ now = _helpers.utcnow()
281
+ response_data = self._make_sts_request(request)
282
+
283
+ self.token = response_data.get("access_token")
284
+
285
+ lifetime = datetime.timedelta(seconds=response_data.get("expires_in"))
286
+ self.expiry = now + lifetime
287
+
288
+ if "refresh_token" in response_data:
289
+ self._refresh_token = response_data["refresh_token"]
290
+
291
+ def _make_sts_request(self, request):
292
+ return self._sts_client.refresh_token(request, self._refresh_token)
293
+
294
+ @_helpers.copy_docstring(credentials.Credentials)
295
+ def get_cred_info(self):
296
+ if self._cred_file_path:
297
+ return {
298
+ "credential_source": self._cred_file_path,
299
+ "credential_type": "external account authorized user credentials",
300
+ }
301
+ return None
302
+
303
+ def _make_copy(self):
304
+ kwargs = self.constructor_args()
305
+ cred = self.__class__(**kwargs)
306
+ cred._cred_file_path = self._cred_file_path
307
+ return cred
308
+
309
+ @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
310
+ def with_quota_project(self, quota_project_id):
311
+ cred = self._make_copy()
312
+ cred._quota_project_id = quota_project_id
313
+ return cred
314
+
315
+ @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
316
+ def with_token_uri(self, token_uri):
317
+ cred = self._make_copy()
318
+ cred._token_url = token_uri
319
+ return cred
320
+
321
+ @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
322
+ def with_universe_domain(self, universe_domain):
323
+ cred = self._make_copy()
324
+ cred._universe_domain = universe_domain
325
+ return cred
326
+
327
+ @classmethod
328
+ def from_info(cls, info, **kwargs):
329
+ """Creates a Credentials instance from parsed external account info.
330
+
331
+ Args:
332
+ info (Mapping[str, str]): The external account info in Google
333
+ format.
334
+ kwargs: Additional arguments to pass to the constructor.
335
+
336
+ Returns:
337
+ google.auth.external_account_authorized_user.Credentials: The
338
+ constructed credentials.
339
+
340
+ Raises:
341
+ ValueError: For invalid parameters.
342
+ """
343
+ expiry = info.get("expiry")
344
+ if expiry:
345
+ expiry = datetime.datetime.strptime(
346
+ expiry.rstrip("Z").split(".")[0], "%Y-%m-%dT%H:%M:%S"
347
+ )
348
+ return cls(
349
+ audience=info.get("audience"),
350
+ refresh_token=info.get("refresh_token"),
351
+ token_url=info.get("token_url"),
352
+ token_info_url=info.get("token_info_url"),
353
+ client_id=info.get("client_id"),
354
+ client_secret=info.get("client_secret"),
355
+ token=info.get("token"),
356
+ expiry=expiry,
357
+ revoke_url=info.get("revoke_url"),
358
+ quota_project_id=info.get("quota_project_id"),
359
+ scopes=info.get("scopes"),
360
+ universe_domain=info.get(
361
+ "universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN
362
+ ),
363
+ **kwargs
364
+ )
365
+
366
+ @classmethod
367
+ def from_file(cls, filename, **kwargs):
368
+ """Creates a Credentials instance from an external account json file.
369
+
370
+ Args:
371
+ filename (str): The path to the external account json file.
372
+ kwargs: Additional arguments to pass to the constructor.
373
+
374
+ Returns:
375
+ google.auth.external_account_authorized_user.Credentials: The
376
+ constructed credentials.
377
+ """
378
+ with io.open(filename, "r", encoding="utf-8") as json_file:
379
+ data = json.load(json_file)
380
+ return cls.from_info(data, **kwargs)
lib/python3.10/site-packages/google/auth/iam.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 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
+
15
+ """Tools for using the Google `Cloud Identity and Access Management (IAM)
16
+ API`_'s auth-related functionality.
17
+
18
+ .. _Cloud Identity and Access Management (IAM) API:
19
+ https://cloud.google.com/iam/docs/
20
+ """
21
+
22
+ import base64
23
+ import http.client as http_client
24
+ import json
25
+
26
+ from google.auth import _exponential_backoff
27
+ from google.auth import _helpers
28
+ from google.auth import credentials
29
+ from google.auth import crypt
30
+ from google.auth import exceptions
31
+
32
+ IAM_RETRY_CODES = {
33
+ http_client.INTERNAL_SERVER_ERROR,
34
+ http_client.BAD_GATEWAY,
35
+ http_client.SERVICE_UNAVAILABLE,
36
+ http_client.GATEWAY_TIMEOUT,
37
+ }
38
+
39
+ _IAM_SCOPE = ["https://www.googleapis.com/auth/iam"]
40
+
41
+ _IAM_ENDPOINT = (
42
+ "https://iamcredentials.googleapis.com/v1/projects/-"
43
+ + "/serviceAccounts/{}:generateAccessToken"
44
+ )
45
+
46
+ _IAM_SIGN_ENDPOINT = (
47
+ "https://iamcredentials.googleapis.com/v1/projects/-"
48
+ + "/serviceAccounts/{}:signBlob"
49
+ )
50
+
51
+ _IAM_SIGNJWT_ENDPOINT = (
52
+ "https://iamcredentials.googleapis.com/v1/projects/-"
53
+ + "/serviceAccounts/{}:signJwt"
54
+ )
55
+
56
+ _IAM_IDTOKEN_ENDPOINT = (
57
+ "https://iamcredentials.googleapis.com/v1/"
58
+ + "projects/-/serviceAccounts/{}:generateIdToken"
59
+ )
60
+
61
+
62
+ class Signer(crypt.Signer):
63
+ """Signs messages using the IAM `signBlob API`_.
64
+
65
+ This is useful when you need to sign bytes but do not have access to the
66
+ credential's private key file.
67
+
68
+ .. _signBlob API:
69
+ https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts
70
+ /signBlob
71
+ """
72
+
73
+ def __init__(self, request, credentials, service_account_email):
74
+ """
75
+ Args:
76
+ request (google.auth.transport.Request): The object used to make
77
+ HTTP requests.
78
+ credentials (google.auth.credentials.Credentials): The credentials
79
+ that will be used to authenticate the request to the IAM API.
80
+ The credentials must have of one the following scopes:
81
+
82
+ - https://www.googleapis.com/auth/iam
83
+ - https://www.googleapis.com/auth/cloud-platform
84
+ service_account_email (str): The service account email identifying
85
+ which service account to use to sign bytes. Often, this can
86
+ be the same as the service account email in the given
87
+ credentials.
88
+ """
89
+ self._request = request
90
+ self._credentials = credentials
91
+ self._service_account_email = service_account_email
92
+
93
+ def _make_signing_request(self, message):
94
+ """Makes a request to the API signBlob API."""
95
+ message = _helpers.to_bytes(message)
96
+
97
+ method = "POST"
98
+ url = _IAM_SIGN_ENDPOINT.replace(
99
+ credentials.DEFAULT_UNIVERSE_DOMAIN, self._credentials.universe_domain
100
+ ).format(self._service_account_email)
101
+ headers = {"Content-Type": "application/json"}
102
+ body = json.dumps(
103
+ {"payload": base64.b64encode(message).decode("utf-8")}
104
+ ).encode("utf-8")
105
+
106
+ retries = _exponential_backoff.ExponentialBackoff()
107
+ for _ in retries:
108
+ self._credentials.before_request(self._request, method, url, headers)
109
+
110
+ response = self._request(url=url, method=method, body=body, headers=headers)
111
+
112
+ if response.status in IAM_RETRY_CODES:
113
+ continue
114
+
115
+ if response.status != http_client.OK:
116
+ raise exceptions.TransportError(
117
+ "Error calling the IAM signBlob API: {}".format(response.data)
118
+ )
119
+
120
+ return json.loads(response.data.decode("utf-8"))
121
+ raise exceptions.TransportError("exhausted signBlob endpoint retries")
122
+
123
+ @property
124
+ def key_id(self):
125
+ """Optional[str]: The key ID used to identify this private key.
126
+
127
+ .. warning::
128
+ This is always ``None``. The key ID used by IAM can not
129
+ be reliably determined ahead of time.
130
+ """
131
+ return None
132
+
133
+ @_helpers.copy_docstring(crypt.Signer)
134
+ def sign(self, message):
135
+ response = self._make_signing_request(message)
136
+ return base64.b64decode(response["signedBlob"])
lib/python3.10/site-packages/google/auth/impersonated_credentials.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 Google Inc.
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
+
15
+ """Google Cloud Impersonated credentials.
16
+
17
+ This module provides authentication for applications where local credentials
18
+ impersonates a remote service account using `IAM Credentials API`_.
19
+
20
+ This class can be used to impersonate a service account as long as the original
21
+ Credential object has the "Service Account Token Creator" role on the target
22
+ service account.
23
+
24
+ .. _IAM Credentials API:
25
+ https://cloud.google.com/iam/credentials/reference/rest/
26
+ """
27
+
28
+ import base64
29
+ import copy
30
+ from datetime import datetime
31
+ import http.client as http_client
32
+ import json
33
+
34
+ from google.auth import _exponential_backoff
35
+ from google.auth import _helpers
36
+ from google.auth import credentials
37
+ from google.auth import exceptions
38
+ from google.auth import iam
39
+ from google.auth import jwt
40
+ from google.auth import metrics
41
+ from google.oauth2 import _client
42
+
43
+
44
+ _REFRESH_ERROR = "Unable to acquire impersonated credentials"
45
+
46
+ _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
47
+
48
+ _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
49
+
50
+
51
+ def _make_iam_token_request(
52
+ request,
53
+ principal,
54
+ headers,
55
+ body,
56
+ universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
57
+ iam_endpoint_override=None,
58
+ ):
59
+ """Makes a request to the Google Cloud IAM service for an access token.
60
+ Args:
61
+ request (Request): The Request object to use.
62
+ principal (str): The principal to request an access token for.
63
+ headers (Mapping[str, str]): Map of headers to transmit.
64
+ body (Mapping[str, str]): JSON Payload body for the iamcredentials
65
+ API call.
66
+ iam_endpoint_override (Optiona[str]): The full IAM endpoint override
67
+ with the target_principal embedded. This is useful when supporting
68
+ impersonation with regional endpoints.
69
+
70
+ Raises:
71
+ google.auth.exceptions.TransportError: Raised if there is an underlying
72
+ HTTP connection error
73
+ google.auth.exceptions.RefreshError: Raised if the impersonated
74
+ credentials are not available. Common reasons are
75
+ `iamcredentials.googleapis.com` is not enabled or the
76
+ `Service Account Token Creator` is not assigned
77
+ """
78
+ iam_endpoint = iam_endpoint_override or iam._IAM_ENDPOINT.replace(
79
+ credentials.DEFAULT_UNIVERSE_DOMAIN, universe_domain
80
+ ).format(principal)
81
+
82
+ body = json.dumps(body).encode("utf-8")
83
+
84
+ response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
85
+
86
+ # support both string and bytes type response.data
87
+ response_body = (
88
+ response.data.decode("utf-8")
89
+ if hasattr(response.data, "decode")
90
+ else response.data
91
+ )
92
+
93
+ if response.status != http_client.OK:
94
+ raise exceptions.RefreshError(_REFRESH_ERROR, response_body)
95
+
96
+ try:
97
+ token_response = json.loads(response_body)
98
+ token = token_response["accessToken"]
99
+ expiry = datetime.strptime(token_response["expireTime"], "%Y-%m-%dT%H:%M:%SZ")
100
+
101
+ return token, expiry
102
+
103
+ except (KeyError, ValueError) as caught_exc:
104
+ new_exc = exceptions.RefreshError(
105
+ "{}: No access token or invalid expiration in response.".format(
106
+ _REFRESH_ERROR
107
+ ),
108
+ response_body,
109
+ )
110
+ raise new_exc from caught_exc
111
+
112
+
113
+ class Credentials(
114
+ credentials.Scoped, credentials.CredentialsWithQuotaProject, credentials.Signing
115
+ ):
116
+ """This module defines impersonated credentials which are essentially
117
+ impersonated identities.
118
+
119
+ Impersonated Credentials allows credentials issued to a user or
120
+ service account to impersonate another. The target service account must
121
+ grant the originating credential principal the
122
+ `Service Account Token Creator`_ IAM role:
123
+
124
+ For more information about Token Creator IAM role and
125
+ IAMCredentials API, see
126
+ `Creating Short-Lived Service Account Credentials`_.
127
+
128
+ .. _Service Account Token Creator:
129
+ https://cloud.google.com/iam/docs/service-accounts#the_service_account_token_creator_role
130
+
131
+ .. _Creating Short-Lived Service Account Credentials:
132
+ https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
133
+
134
+ Usage:
135
+
136
+ First grant source_credentials the `Service Account Token Creator`
137
+ role on the target account to impersonate. In this example, the
138
+ service account represented by svc_account.json has the
139
+ token creator role on
140
+ `impersonated-account@_project_.iam.gserviceaccount.com`.
141
+
142
+ Enable the IAMCredentials API on the source project:
143
+ `gcloud services enable iamcredentials.googleapis.com`.
144
+
145
+ Initialize a source credential which does not have access to
146
+ list bucket::
147
+
148
+ from google.oauth2 import service_account
149
+
150
+ target_scopes = [
151
+ 'https://www.googleapis.com/auth/devstorage.read_only']
152
+
153
+ source_credentials = (
154
+ service_account.Credentials.from_service_account_file(
155
+ '/path/to/svc_account.json',
156
+ scopes=target_scopes))
157
+
158
+ Now use the source credentials to acquire credentials to impersonate
159
+ another service account::
160
+
161
+ from google.auth import impersonated_credentials
162
+
163
+ target_credentials = impersonated_credentials.Credentials(
164
+ source_credentials=source_credentials,
165
+ target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
166
+ target_scopes = target_scopes,
167
+ lifetime=500)
168
+
169
+ Resource access is granted::
170
+
171
+ client = storage.Client(credentials=target_credentials)
172
+ buckets = client.list_buckets(project='your_project')
173
+ for bucket in buckets:
174
+ print(bucket.name)
175
+ """
176
+
177
+ def __init__(
178
+ self,
179
+ source_credentials,
180
+ target_principal,
181
+ target_scopes,
182
+ delegates=None,
183
+ subject=None,
184
+ lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
185
+ quota_project_id=None,
186
+ iam_endpoint_override=None,
187
+ ):
188
+ """
189
+ Args:
190
+ source_credentials (google.auth.Credentials): The source credential
191
+ used as to acquire the impersonated credentials.
192
+ target_principal (str): The service account to impersonate.
193
+ target_scopes (Sequence[str]): Scopes to request during the
194
+ authorization grant.
195
+ delegates (Sequence[str]): The chained list of delegates required
196
+ to grant the final access_token. If set, the sequence of
197
+ identities must have "Service Account Token Creator" capability
198
+ granted to the prceeding identity. For example, if set to
199
+ [serviceAccountB, serviceAccountC], the source_credential
200
+ must have the Token Creator role on serviceAccountB.
201
+ serviceAccountB must have the Token Creator on
202
+ serviceAccountC.
203
+ Finally, C must have Token Creator on target_principal.
204
+ If left unset, source_credential must have that role on
205
+ target_principal.
206
+ lifetime (int): Number of seconds the delegated credential should
207
+ be valid for (upto 3600).
208
+ quota_project_id (Optional[str]): The project ID used for quota and billing.
209
+ This project may be different from the project used to
210
+ create the credentials.
211
+ iam_endpoint_override (Optional[str]): The full IAM endpoint override
212
+ with the target_principal embedded. This is useful when supporting
213
+ impersonation with regional endpoints.
214
+ subject (Optional[str]): sub field of a JWT. This field should only be set
215
+ if you wish to impersonate as a user. This feature is useful when
216
+ using domain wide delegation.
217
+ """
218
+
219
+ super(Credentials, self).__init__()
220
+
221
+ self._source_credentials = copy.copy(source_credentials)
222
+ # Service account source credentials must have the _IAM_SCOPE
223
+ # added to refresh correctly. User credentials cannot have
224
+ # their original scopes modified.
225
+ if isinstance(self._source_credentials, credentials.Scoped):
226
+ self._source_credentials = self._source_credentials.with_scopes(
227
+ iam._IAM_SCOPE
228
+ )
229
+ # If the source credential is service account and self signed jwt
230
+ # is needed, we need to create a jwt credential inside it
231
+ if (
232
+ hasattr(self._source_credentials, "_create_self_signed_jwt")
233
+ and self._source_credentials._always_use_jwt_access
234
+ ):
235
+ self._source_credentials._create_self_signed_jwt(None)
236
+
237
+ self._universe_domain = source_credentials.universe_domain
238
+ self._target_principal = target_principal
239
+ self._target_scopes = target_scopes
240
+ self._delegates = delegates
241
+ self._subject = subject
242
+ self._lifetime = lifetime or _DEFAULT_TOKEN_LIFETIME_SECS
243
+ self.token = None
244
+ self.expiry = _helpers.utcnow()
245
+ self._quota_project_id = quota_project_id
246
+ self._iam_endpoint_override = iam_endpoint_override
247
+ self._cred_file_path = None
248
+
249
+ def _metric_header_for_usage(self):
250
+ return metrics.CRED_TYPE_SA_IMPERSONATE
251
+
252
+ @_helpers.copy_docstring(credentials.Credentials)
253
+ def refresh(self, request):
254
+ self._update_token(request)
255
+
256
+ def _update_token(self, request):
257
+ """Updates credentials with a new access_token representing
258
+ the impersonated account.
259
+
260
+ Args:
261
+ request (google.auth.transport.requests.Request): Request object
262
+ to use for refreshing credentials.
263
+ """
264
+
265
+ # Refresh our source credentials if it is not valid.
266
+ if (
267
+ self._source_credentials.token_state == credentials.TokenState.STALE
268
+ or self._source_credentials.token_state == credentials.TokenState.INVALID
269
+ ):
270
+ self._source_credentials.refresh(request)
271
+
272
+ body = {
273
+ "delegates": self._delegates,
274
+ "scope": self._target_scopes,
275
+ "lifetime": str(self._lifetime) + "s",
276
+ }
277
+
278
+ headers = {
279
+ "Content-Type": "application/json",
280
+ metrics.API_CLIENT_HEADER: metrics.token_request_access_token_impersonate(),
281
+ }
282
+
283
+ # Apply the source credentials authentication info.
284
+ self._source_credentials.apply(headers)
285
+
286
+ # If a subject is specified a domain-wide delegation auth-flow is initiated
287
+ # to impersonate as the provided subject (user).
288
+ if self._subject:
289
+ if self.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
290
+ raise exceptions.GoogleAuthError(
291
+ "Domain-wide delegation is not supported in universes other "
292
+ + "than googleapis.com"
293
+ )
294
+
295
+ now = _helpers.utcnow()
296
+ payload = {
297
+ "iss": self._target_principal,
298
+ "scope": _helpers.scopes_to_string(self._target_scopes or ()),
299
+ "sub": self._subject,
300
+ "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
301
+ "iat": _helpers.datetime_to_secs(now),
302
+ "exp": _helpers.datetime_to_secs(now) + _DEFAULT_TOKEN_LIFETIME_SECS,
303
+ }
304
+
305
+ assertion = _sign_jwt_request(
306
+ request=request,
307
+ principal=self._target_principal,
308
+ headers=headers,
309
+ payload=payload,
310
+ delegates=self._delegates,
311
+ )
312
+
313
+ self.token, self.expiry, _ = _client.jwt_grant(
314
+ request, _GOOGLE_OAUTH2_TOKEN_ENDPOINT, assertion
315
+ )
316
+
317
+ return
318
+
319
+ self.token, self.expiry = _make_iam_token_request(
320
+ request=request,
321
+ principal=self._target_principal,
322
+ headers=headers,
323
+ body=body,
324
+ universe_domain=self.universe_domain,
325
+ iam_endpoint_override=self._iam_endpoint_override,
326
+ )
327
+
328
+ def sign_bytes(self, message):
329
+ from google.auth.transport.requests import AuthorizedSession
330
+
331
+ iam_sign_endpoint = iam._IAM_SIGN_ENDPOINT.replace(
332
+ credentials.DEFAULT_UNIVERSE_DOMAIN, self.universe_domain
333
+ ).format(self._target_principal)
334
+
335
+ body = {
336
+ "payload": base64.b64encode(message).decode("utf-8"),
337
+ "delegates": self._delegates,
338
+ }
339
+
340
+ headers = {"Content-Type": "application/json"}
341
+
342
+ authed_session = AuthorizedSession(self._source_credentials)
343
+
344
+ try:
345
+ retries = _exponential_backoff.ExponentialBackoff()
346
+ for _ in retries:
347
+ response = authed_session.post(
348
+ url=iam_sign_endpoint, headers=headers, json=body
349
+ )
350
+ if response.status_code in iam.IAM_RETRY_CODES:
351
+ continue
352
+ if response.status_code != http_client.OK:
353
+ raise exceptions.TransportError(
354
+ "Error calling sign_bytes: {}".format(response.json())
355
+ )
356
+
357
+ return base64.b64decode(response.json()["signedBlob"])
358
+ finally:
359
+ authed_session.close()
360
+ raise exceptions.TransportError("exhausted signBlob endpoint retries")
361
+
362
+ @property
363
+ def signer_email(self):
364
+ return self._target_principal
365
+
366
+ @property
367
+ def service_account_email(self):
368
+ return self._target_principal
369
+
370
+ @property
371
+ def signer(self):
372
+ return self
373
+
374
+ @property
375
+ def requires_scopes(self):
376
+ return not self._target_scopes
377
+
378
+ @_helpers.copy_docstring(credentials.Credentials)
379
+ def get_cred_info(self):
380
+ if self._cred_file_path:
381
+ return {
382
+ "credential_source": self._cred_file_path,
383
+ "credential_type": "impersonated credentials",
384
+ "principal": self._target_principal,
385
+ }
386
+ return None
387
+
388
+ def _make_copy(self):
389
+ cred = self.__class__(
390
+ self._source_credentials,
391
+ target_principal=self._target_principal,
392
+ target_scopes=self._target_scopes,
393
+ delegates=self._delegates,
394
+ lifetime=self._lifetime,
395
+ quota_project_id=self._quota_project_id,
396
+ iam_endpoint_override=self._iam_endpoint_override,
397
+ )
398
+ cred._cred_file_path = self._cred_file_path
399
+ return cred
400
+
401
+ @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
402
+ def with_quota_project(self, quota_project_id):
403
+ cred = self._make_copy()
404
+ cred._quota_project_id = quota_project_id
405
+ return cred
406
+
407
+ @_helpers.copy_docstring(credentials.Scoped)
408
+ def with_scopes(self, scopes, default_scopes=None):
409
+ cred = self._make_copy()
410
+ cred._target_scopes = scopes or default_scopes
411
+ return cred
412
+
413
+
414
+ class IDTokenCredentials(credentials.CredentialsWithQuotaProject):
415
+ """Open ID Connect ID Token-based service account credentials.
416
+
417
+ """
418
+
419
+ def __init__(
420
+ self,
421
+ target_credentials,
422
+ target_audience=None,
423
+ include_email=False,
424
+ quota_project_id=None,
425
+ ):
426
+ """
427
+ Args:
428
+ target_credentials (google.auth.Credentials): The target
429
+ credential used as to acquire the id tokens for.
430
+ target_audience (string): Audience to issue the token for.
431
+ include_email (bool): Include email in IdToken
432
+ quota_project_id (Optional[str]): The project ID used for
433
+ quota and billing.
434
+ """
435
+ super(IDTokenCredentials, self).__init__()
436
+
437
+ if not isinstance(target_credentials, Credentials):
438
+ raise exceptions.GoogleAuthError(
439
+ "Provided Credential must be " "impersonated_credentials"
440
+ )
441
+ self._target_credentials = target_credentials
442
+ self._target_audience = target_audience
443
+ self._include_email = include_email
444
+ self._quota_project_id = quota_project_id
445
+
446
+ def from_credentials(self, target_credentials, target_audience=None):
447
+ return self.__class__(
448
+ target_credentials=target_credentials,
449
+ target_audience=target_audience,
450
+ include_email=self._include_email,
451
+ quota_project_id=self._quota_project_id,
452
+ )
453
+
454
+ def with_target_audience(self, target_audience):
455
+ return self.__class__(
456
+ target_credentials=self._target_credentials,
457
+ target_audience=target_audience,
458
+ include_email=self._include_email,
459
+ quota_project_id=self._quota_project_id,
460
+ )
461
+
462
+ def with_include_email(self, include_email):
463
+ return self.__class__(
464
+ target_credentials=self._target_credentials,
465
+ target_audience=self._target_audience,
466
+ include_email=include_email,
467
+ quota_project_id=self._quota_project_id,
468
+ )
469
+
470
+ @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
471
+ def with_quota_project(self, quota_project_id):
472
+ return self.__class__(
473
+ target_credentials=self._target_credentials,
474
+ target_audience=self._target_audience,
475
+ include_email=self._include_email,
476
+ quota_project_id=quota_project_id,
477
+ )
478
+
479
+ @_helpers.copy_docstring(credentials.Credentials)
480
+ def refresh(self, request):
481
+ from google.auth.transport.requests import AuthorizedSession
482
+
483
+ iam_sign_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace(
484
+ credentials.DEFAULT_UNIVERSE_DOMAIN,
485
+ self._target_credentials.universe_domain,
486
+ ).format(self._target_credentials.signer_email)
487
+
488
+ body = {
489
+ "audience": self._target_audience,
490
+ "delegates": self._target_credentials._delegates,
491
+ "includeEmail": self._include_email,
492
+ }
493
+
494
+ headers = {
495
+ "Content-Type": "application/json",
496
+ metrics.API_CLIENT_HEADER: metrics.token_request_id_token_impersonate(),
497
+ }
498
+
499
+ authed_session = AuthorizedSession(
500
+ self._target_credentials._source_credentials, auth_request=request
501
+ )
502
+
503
+ try:
504
+ response = authed_session.post(
505
+ url=iam_sign_endpoint,
506
+ headers=headers,
507
+ data=json.dumps(body).encode("utf-8"),
508
+ )
509
+ finally:
510
+ authed_session.close()
511
+
512
+ if response.status_code != http_client.OK:
513
+ raise exceptions.RefreshError(
514
+ "Error getting ID token: {}".format(response.json())
515
+ )
516
+
517
+ id_token = response.json()["token"]
518
+ self.token = id_token
519
+ self.expiry = datetime.utcfromtimestamp(
520
+ jwt.decode(id_token, verify=False)["exp"]
521
+ )
522
+
523
+
524
+ def _sign_jwt_request(request, principal, headers, payload, delegates=[]):
525
+ """Makes a request to the Google Cloud IAM service to sign a JWT using a
526
+ service account's system-managed private key.
527
+ Args:
528
+ request (Request): The Request object to use.
529
+ principal (str): The principal to request an access token for.
530
+ headers (Mapping[str, str]): Map of headers to transmit.
531
+ payload (Mapping[str, str]): The JWT payload to sign. Must be a
532
+ serialized JSON object that contains a JWT Claims Set.
533
+ delegates (Sequence[str]): The chained list of delegates required
534
+ to grant the final access_token. If set, the sequence of
535
+ identities must have "Service Account Token Creator" capability
536
+ granted to the prceeding identity. For example, if set to
537
+ [serviceAccountB, serviceAccountC], the source_credential
538
+ must have the Token Creator role on serviceAccountB.
539
+ serviceAccountB must have the Token Creator on
540
+ serviceAccountC.
541
+ Finally, C must have Token Creator on target_principal.
542
+ If left unset, source_credential must have that role on
543
+ target_principal.
544
+
545
+ Raises:
546
+ google.auth.exceptions.TransportError: Raised if there is an underlying
547
+ HTTP connection error
548
+ google.auth.exceptions.RefreshError: Raised if the impersonated
549
+ credentials are not available. Common reasons are
550
+ `iamcredentials.googleapis.com` is not enabled or the
551
+ `Service Account Token Creator` is not assigned
552
+ """
553
+ iam_endpoint = iam._IAM_SIGNJWT_ENDPOINT.format(principal)
554
+
555
+ body = {"delegates": delegates, "payload": json.dumps(payload)}
556
+ body = json.dumps(body).encode("utf-8")
557
+
558
+ response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
559
+
560
+ # support both string and bytes type response.data
561
+ response_body = (
562
+ response.data.decode("utf-8")
563
+ if hasattr(response.data, "decode")
564
+ else response.data
565
+ )
566
+
567
+ if response.status != http_client.OK:
568
+ raise exceptions.RefreshError(_REFRESH_ERROR, response_body)
569
+
570
+ try:
571
+ jwt_response = json.loads(response_body)
572
+ signed_jwt = jwt_response["signedJwt"]
573
+ return signed_jwt
574
+
575
+ except (KeyError, ValueError) as caught_exc:
576
+ new_exc = exceptions.RefreshError(
577
+ "{}: No signed JWT in response.".format(_REFRESH_ERROR), response_body
578
+ )
579
+ raise new_exc from caught_exc
lib/python3.10/site-packages/google/auth/metrics.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+
15
+ """ We use x-goog-api-client header to report metrics. This module provides
16
+ the constants and helper methods to construct x-goog-api-client header.
17
+ """
18
+
19
+ import platform
20
+
21
+ from google.auth import version
22
+
23
+
24
+ API_CLIENT_HEADER = "x-goog-api-client"
25
+
26
+ # BYOID Specific consts
27
+ BYOID_HEADER_SECTION = "google-byoid-sdk"
28
+
29
+ # Auth request type
30
+ REQUEST_TYPE_ACCESS_TOKEN = "auth-request-type/at"
31
+ REQUEST_TYPE_ID_TOKEN = "auth-request-type/it"
32
+ REQUEST_TYPE_MDS_PING = "auth-request-type/mds"
33
+ REQUEST_TYPE_REAUTH_START = "auth-request-type/re-start"
34
+ REQUEST_TYPE_REAUTH_CONTINUE = "auth-request-type/re-cont"
35
+
36
+ # Credential type
37
+ CRED_TYPE_USER = "cred-type/u"
38
+ CRED_TYPE_SA_ASSERTION = "cred-type/sa"
39
+ CRED_TYPE_SA_JWT = "cred-type/jwt"
40
+ CRED_TYPE_SA_MDS = "cred-type/mds"
41
+ CRED_TYPE_SA_IMPERSONATE = "cred-type/imp"
42
+
43
+
44
+ # Versions
45
+ def python_and_auth_lib_version():
46
+ return "gl-python/{} auth/{}".format(platform.python_version(), version.__version__)
47
+
48
+
49
+ # Token request metric header values
50
+
51
+ # x-goog-api-client header value for access token request via metadata server.
52
+ # Example: "gl-python/3.7 auth/1.1 auth-request-type/at cred-type/mds"
53
+ def token_request_access_token_mds():
54
+ return "{} {} {}".format(
55
+ python_and_auth_lib_version(), REQUEST_TYPE_ACCESS_TOKEN, CRED_TYPE_SA_MDS
56
+ )
57
+
58
+
59
+ # x-goog-api-client header value for ID token request via metadata server.
60
+ # Example: "gl-python/3.7 auth/1.1 auth-request-type/it cred-type/mds"
61
+ def token_request_id_token_mds():
62
+ return "{} {} {}".format(
63
+ python_and_auth_lib_version(), REQUEST_TYPE_ID_TOKEN, CRED_TYPE_SA_MDS
64
+ )
65
+
66
+
67
+ # x-goog-api-client header value for impersonated credentials access token request.
68
+ # Example: "gl-python/3.7 auth/1.1 auth-request-type/at cred-type/imp"
69
+ def token_request_access_token_impersonate():
70
+ return "{} {} {}".format(
71
+ python_and_auth_lib_version(),
72
+ REQUEST_TYPE_ACCESS_TOKEN,
73
+ CRED_TYPE_SA_IMPERSONATE,
74
+ )
75
+
76
+
77
+ # x-goog-api-client header value for impersonated credentials ID token request.
78
+ # Example: "gl-python/3.7 auth/1.1 auth-request-type/it cred-type/imp"
79
+ def token_request_id_token_impersonate():
80
+ return "{} {} {}".format(
81
+ python_and_auth_lib_version(), REQUEST_TYPE_ID_TOKEN, CRED_TYPE_SA_IMPERSONATE
82
+ )
83
+
84
+
85
+ # x-goog-api-client header value for service account credentials access token
86
+ # request (assertion flow).
87
+ # Example: "gl-python/3.7 auth/1.1 auth-request-type/at cred-type/sa"
88
+ def token_request_access_token_sa_assertion():
89
+ return "{} {} {}".format(
90
+ python_and_auth_lib_version(), REQUEST_TYPE_ACCESS_TOKEN, CRED_TYPE_SA_ASSERTION
91
+ )
92
+
93
+
94
+ # x-goog-api-client header value for service account credentials ID token
95
+ # request (assertion flow).
96
+ # Example: "gl-python/3.7 auth/1.1 auth-request-type/it cred-type/sa"
97
+ def token_request_id_token_sa_assertion():
98
+ return "{} {} {}".format(
99
+ python_and_auth_lib_version(), REQUEST_TYPE_ID_TOKEN, CRED_TYPE_SA_ASSERTION
100
+ )
101
+
102
+
103
+ # x-goog-api-client header value for user credentials token request.
104
+ # Example: "gl-python/3.7 auth/1.1 cred-type/u"
105
+ def token_request_user():
106
+ return "{} {}".format(python_and_auth_lib_version(), CRED_TYPE_USER)
107
+
108
+
109
+ # Miscellenous metrics
110
+
111
+ # x-goog-api-client header value for metadata server ping.
112
+ # Example: "gl-python/3.7 auth/1.1 auth-request-type/mds"
113
+ def mds_ping():
114
+ return "{} {}".format(python_and_auth_lib_version(), REQUEST_TYPE_MDS_PING)
115
+
116
+
117
+ # x-goog-api-client header value for reauth start endpoint calls.
118
+ # Example: "gl-python/3.7 auth/1.1 auth-request-type/re-start"
119
+ def reauth_start():
120
+ return "{} {}".format(python_and_auth_lib_version(), REQUEST_TYPE_REAUTH_START)
121
+
122
+
123
+ # x-goog-api-client header value for reauth continue endpoint calls.
124
+ # Example: "gl-python/3.7 auth/1.1 cred-type/re-cont"
125
+ def reauth_continue():
126
+ return "{} {}".format(python_and_auth_lib_version(), REQUEST_TYPE_REAUTH_CONTINUE)
127
+
128
+
129
+ # x-goog-api-client header value for BYOID calls to the Security Token Service exchange token endpoint.
130
+ # Example: "gl-python/3.7 auth/1.1 google-byoid-sdk source/aws sa-impersonation/true sa-impersonation/true"
131
+ def byoid_metrics_header(metrics_options):
132
+ header = "{} {}".format(python_and_auth_lib_version(), BYOID_HEADER_SECTION)
133
+ for key, value in metrics_options.items():
134
+ header = "{} {}/{}".format(header, key, value)
135
+ return header
136
+
137
+
138
+ def add_metric_header(headers, metric_header_value):
139
+ """Add x-goog-api-client header with the given value.
140
+
141
+ Args:
142
+ headers (Mapping[str, str]): The headers to which we will add the
143
+ metric header.
144
+ metric_header_value (Optional[str]): If value is None, do nothing;
145
+ if headers already has a x-goog-api-client header, append the value
146
+ to the existing header; otherwise add a new x-goog-api-client
147
+ header with the given value.
148
+ """
149
+ if not metric_header_value:
150
+ return
151
+ if API_CLIENT_HEADER not in headers:
152
+ headers[API_CLIENT_HEADER] = metric_header_value
153
+ else:
154
+ headers[API_CLIENT_HEADER] += " " + metric_header_value
lib/python3.10/site-packages/google/auth/py.typed ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Marker file for PEP 561.
2
+ # The google-auth package uses inline types.
lib/python3.10/site-packages/google/auth/transport/__init__.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Transport - HTTP client library support.
16
+
17
+ :mod:`google.auth` is designed to work with various HTTP client libraries such
18
+ as urllib3 and requests. In order to work across these libraries with different
19
+ interfaces some abstraction is needed.
20
+
21
+ This module provides two interfaces that are implemented by transport adapters
22
+ to support HTTP libraries. :class:`Request` defines the interface expected by
23
+ :mod:`google.auth` to make requests. :class:`Response` defines the interface
24
+ for the return value of :class:`Request`.
25
+ """
26
+
27
+ import abc
28
+ import http.client as http_client
29
+
30
+ DEFAULT_RETRYABLE_STATUS_CODES = (
31
+ http_client.INTERNAL_SERVER_ERROR,
32
+ http_client.SERVICE_UNAVAILABLE,
33
+ http_client.REQUEST_TIMEOUT,
34
+ http_client.TOO_MANY_REQUESTS,
35
+ )
36
+ """Sequence[int]: HTTP status codes indicating a request can be retried.
37
+ """
38
+
39
+
40
+ DEFAULT_REFRESH_STATUS_CODES = (http_client.UNAUTHORIZED,)
41
+ """Sequence[int]: Which HTTP status code indicate that credentials should be
42
+ refreshed.
43
+ """
44
+
45
+ DEFAULT_MAX_REFRESH_ATTEMPTS = 2
46
+ """int: How many times to refresh the credentials and retry a request."""
47
+
48
+
49
+ class Response(metaclass=abc.ABCMeta):
50
+ """HTTP Response data."""
51
+
52
+ @abc.abstractproperty
53
+ def status(self):
54
+ """int: The HTTP status code."""
55
+ raise NotImplementedError("status must be implemented.")
56
+
57
+ @abc.abstractproperty
58
+ def headers(self):
59
+ """Mapping[str, str]: The HTTP response headers."""
60
+ raise NotImplementedError("headers must be implemented.")
61
+
62
+ @abc.abstractproperty
63
+ def data(self):
64
+ """bytes: The response body."""
65
+ raise NotImplementedError("data must be implemented.")
66
+
67
+
68
+ class Request(metaclass=abc.ABCMeta):
69
+ """Interface for a callable that makes HTTP requests.
70
+
71
+ Specific transport implementations should provide an implementation of
72
+ this that adapts their specific request / response API.
73
+
74
+ .. automethod:: __call__
75
+ """
76
+
77
+ @abc.abstractmethod
78
+ def __call__(
79
+ self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
80
+ ):
81
+ """Make an HTTP request.
82
+
83
+ Args:
84
+ url (str): The URI to be requested.
85
+ method (str): The HTTP method to use for the request. Defaults
86
+ to 'GET'.
87
+ body (bytes): The payload / body in HTTP request.
88
+ headers (Mapping[str, str]): Request headers.
89
+ timeout (Optional[int]): The number of seconds to wait for a
90
+ response from the server. If not specified or if None, the
91
+ transport-specific default timeout will be used.
92
+ kwargs: Additionally arguments passed on to the transport's
93
+ request method.
94
+
95
+ Returns:
96
+ Response: The HTTP response.
97
+
98
+ Raises:
99
+ google.auth.exceptions.TransportError: If any exception occurred.
100
+ """
101
+ # pylint: disable=redundant-returns-doc, missing-raises-doc
102
+ # (pylint doesn't play well with abstract docstrings.)
103
+ raise NotImplementedError("__call__ must be implemented.")
lib/python3.10/site-packages/google/auth/transport/_aiohttp_requests.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ """Transport adapter for Async HTTP (aiohttp).
16
+
17
+ NOTE: This async support is experimental and marked internal. This surface may
18
+ change in minor releases.
19
+ """
20
+
21
+ from __future__ import absolute_import
22
+
23
+ import asyncio
24
+ import functools
25
+
26
+ import aiohttp # type: ignore
27
+ import urllib3 # type: ignore
28
+
29
+ from google.auth import exceptions
30
+ from google.auth import transport
31
+ from google.auth.transport import requests
32
+
33
+ # Timeout can be re-defined depending on async requirement. Currently made 60s more than
34
+ # sync timeout.
35
+ _DEFAULT_TIMEOUT = 180 # in seconds
36
+
37
+
38
+ class _CombinedResponse(transport.Response):
39
+ """
40
+ In order to more closely resemble the `requests` interface, where a raw
41
+ and deflated content could be accessed at once, this class lazily reads the
42
+ stream in `transport.Response` so both return forms can be used.
43
+
44
+ The gzip and deflate transfer-encodings are automatically decoded for you
45
+ because the default parameter for autodecompress into the ClientSession is set
46
+ to False, and therefore we add this class to act as a wrapper for a user to be
47
+ able to access both the raw and decoded response bodies - mirroring the sync
48
+ implementation.
49
+ """
50
+
51
+ def __init__(self, response):
52
+ self._response = response
53
+ self._raw_content = None
54
+
55
+ def _is_compressed(self):
56
+ headers = self._response.headers
57
+ return "Content-Encoding" in headers and (
58
+ headers["Content-Encoding"] == "gzip"
59
+ or headers["Content-Encoding"] == "deflate"
60
+ )
61
+
62
+ @property
63
+ def status(self):
64
+ return self._response.status
65
+
66
+ @property
67
+ def headers(self):
68
+ return self._response.headers
69
+
70
+ @property
71
+ def data(self):
72
+ return self._response.content
73
+
74
+ async def raw_content(self):
75
+ if self._raw_content is None:
76
+ self._raw_content = await self._response.content.read()
77
+ return self._raw_content
78
+
79
+ async def content(self):
80
+ # Load raw_content if necessary
81
+ await self.raw_content()
82
+ if self._is_compressed():
83
+ decoder = urllib3.response.MultiDecoder(
84
+ self._response.headers["Content-Encoding"]
85
+ )
86
+ decompressed = decoder.decompress(self._raw_content)
87
+ return decompressed
88
+
89
+ return self._raw_content
90
+
91
+
92
+ class _Response(transport.Response):
93
+ """
94
+ Requests transport response adapter.
95
+
96
+ Args:
97
+ response (requests.Response): The raw Requests response.
98
+ """
99
+
100
+ def __init__(self, response):
101
+ self._response = response
102
+
103
+ @property
104
+ def status(self):
105
+ return self._response.status
106
+
107
+ @property
108
+ def headers(self):
109
+ return self._response.headers
110
+
111
+ @property
112
+ def data(self):
113
+ return self._response.content
114
+
115
+
116
+ class Request(transport.Request):
117
+ """Requests request adapter.
118
+
119
+ This class is used internally for making requests using asyncio transports
120
+ in a consistent way. If you use :class:`AuthorizedSession` you do not need
121
+ to construct or use this class directly.
122
+
123
+ This class can be useful if you want to manually refresh a
124
+ :class:`~google.auth.credentials.Credentials` instance::
125
+
126
+ import google.auth.transport.aiohttp_requests
127
+
128
+ request = google.auth.transport.aiohttp_requests.Request()
129
+
130
+ credentials.refresh(request)
131
+
132
+ Args:
133
+ session (aiohttp.ClientSession): An instance :class:`aiohttp.ClientSession` used
134
+ to make HTTP requests. If not specified, a session will be created.
135
+
136
+ .. automethod:: __call__
137
+ """
138
+
139
+ def __init__(self, session=None):
140
+ # TODO: Use auto_decompress property for aiohttp 3.7+
141
+ if session is not None and session._auto_decompress:
142
+ raise exceptions.InvalidOperation(
143
+ "Client sessions with auto_decompress=True are not supported."
144
+ )
145
+ self.session = session
146
+
147
+ async def __call__(
148
+ self,
149
+ url,
150
+ method="GET",
151
+ body=None,
152
+ headers=None,
153
+ timeout=_DEFAULT_TIMEOUT,
154
+ **kwargs,
155
+ ):
156
+ """
157
+ Make an HTTP request using aiohttp.
158
+
159
+ Args:
160
+ url (str): The URL to be requested.
161
+ method (Optional[str]):
162
+ The HTTP method to use for the request. Defaults to 'GET'.
163
+ body (Optional[bytes]):
164
+ The payload or body in HTTP request.
165
+ headers (Optional[Mapping[str, str]]):
166
+ Request headers.
167
+ timeout (Optional[int]): The number of seconds to wait for a
168
+ response from the server. If not specified or if None, the
169
+ requests default timeout will be used.
170
+ kwargs: Additional arguments passed through to the underlying
171
+ requests :meth:`requests.Session.request` method.
172
+
173
+ Returns:
174
+ google.auth.transport.Response: The HTTP response.
175
+
176
+ Raises:
177
+ google.auth.exceptions.TransportError: If any exception occurred.
178
+ """
179
+
180
+ try:
181
+ if self.session is None: # pragma: NO COVER
182
+ self.session = aiohttp.ClientSession(
183
+ auto_decompress=False
184
+ ) # pragma: NO COVER
185
+ requests._LOGGER.debug("Making request: %s %s", method, url)
186
+ response = await self.session.request(
187
+ method, url, data=body, headers=headers, timeout=timeout, **kwargs
188
+ )
189
+ return _CombinedResponse(response)
190
+
191
+ except aiohttp.ClientError as caught_exc:
192
+ new_exc = exceptions.TransportError(caught_exc)
193
+ raise new_exc from caught_exc
194
+
195
+ except asyncio.TimeoutError as caught_exc:
196
+ new_exc = exceptions.TransportError(caught_exc)
197
+ raise new_exc from caught_exc
198
+
199
+
200
+ class AuthorizedSession(aiohttp.ClientSession):
201
+ """This is an async implementation of the Authorized Session class. We utilize an
202
+ aiohttp transport instance, and the interface mirrors the google.auth.transport.requests
203
+ Authorized Session class, except for the change in the transport used in the async use case.
204
+
205
+ A Requests Session class with credentials.
206
+
207
+ This class is used to perform requests to API endpoints that require
208
+ authorization::
209
+
210
+ from google.auth.transport import aiohttp_requests
211
+
212
+ async with aiohttp_requests.AuthorizedSession(credentials) as authed_session:
213
+ response = await authed_session.request(
214
+ 'GET', 'https://www.googleapis.com/storage/v1/b')
215
+
216
+ The underlying :meth:`request` implementation handles adding the
217
+ credentials' headers to the request and refreshing credentials as needed.
218
+
219
+ Args:
220
+ credentials (google.auth._credentials_async.Credentials):
221
+ The credentials to add to the request.
222
+ refresh_status_codes (Sequence[int]): Which HTTP status codes indicate
223
+ that credentials should be refreshed and the request should be
224
+ retried.
225
+ max_refresh_attempts (int): The maximum number of times to attempt to
226
+ refresh the credentials and retry the request.
227
+ refresh_timeout (Optional[int]): The timeout value in seconds for
228
+ credential refresh HTTP requests.
229
+ auth_request (google.auth.transport.aiohttp_requests.Request):
230
+ (Optional) An instance of
231
+ :class:`~google.auth.transport.aiohttp_requests.Request` used when
232
+ refreshing credentials. If not passed,
233
+ an instance of :class:`~google.auth.transport.aiohttp_requests.Request`
234
+ is created.
235
+ kwargs: Additional arguments passed through to the underlying
236
+ ClientSession :meth:`aiohttp.ClientSession` object.
237
+ """
238
+
239
+ def __init__(
240
+ self,
241
+ credentials,
242
+ refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
243
+ max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
244
+ refresh_timeout=None,
245
+ auth_request=None,
246
+ auto_decompress=False,
247
+ **kwargs,
248
+ ):
249
+ super(AuthorizedSession, self).__init__(**kwargs)
250
+ self.credentials = credentials
251
+ self._refresh_status_codes = refresh_status_codes
252
+ self._max_refresh_attempts = max_refresh_attempts
253
+ self._refresh_timeout = refresh_timeout
254
+ self._is_mtls = False
255
+ self._auth_request = auth_request
256
+ self._auth_request_session = None
257
+ self._loop = asyncio.get_event_loop()
258
+ self._refresh_lock = asyncio.Lock()
259
+ self._auto_decompress = auto_decompress
260
+
261
+ async def request(
262
+ self,
263
+ method,
264
+ url,
265
+ data=None,
266
+ headers=None,
267
+ max_allowed_time=None,
268
+ timeout=_DEFAULT_TIMEOUT,
269
+ auto_decompress=False,
270
+ **kwargs,
271
+ ):
272
+
273
+ """Implementation of Authorized Session aiohttp request.
274
+
275
+ Args:
276
+ method (str):
277
+ The http request method used (e.g. GET, PUT, DELETE)
278
+ url (str):
279
+ The url at which the http request is sent.
280
+ data (Optional[dict]): Dictionary, list of tuples, bytes, or file-like
281
+ object to send in the body of the Request.
282
+ headers (Optional[dict]): Dictionary of HTTP Headers to send with the
283
+ Request.
284
+ timeout (Optional[Union[float, aiohttp.ClientTimeout]]):
285
+ The amount of time in seconds to wait for the server response
286
+ with each individual request. Can also be passed as an
287
+ ``aiohttp.ClientTimeout`` object.
288
+ max_allowed_time (Optional[float]):
289
+ If the method runs longer than this, a ``Timeout`` exception is
290
+ automatically raised. Unlike the ``timeout`` parameter, this
291
+ value applies to the total method execution time, even if
292
+ multiple requests are made under the hood.
293
+
294
+ Mind that it is not guaranteed that the timeout error is raised
295
+ at ``max_allowed_time``. It might take longer, for example, if
296
+ an underlying request takes a lot of time, but the request
297
+ itself does not timeout, e.g. if a large file is being
298
+ transmitted. The timout error will be raised after such
299
+ request completes.
300
+ """
301
+ # Headers come in as bytes which isn't expected behavior, the resumable
302
+ # media libraries in some cases expect a str type for the header values,
303
+ # but sometimes the operations return these in bytes types.
304
+ if headers:
305
+ for key in headers.keys():
306
+ if type(headers[key]) is bytes:
307
+ headers[key] = headers[key].decode("utf-8")
308
+
309
+ async with aiohttp.ClientSession(
310
+ auto_decompress=self._auto_decompress,
311
+ trust_env=kwargs.get("trust_env", False),
312
+ ) as self._auth_request_session:
313
+ auth_request = Request(self._auth_request_session)
314
+ self._auth_request = auth_request
315
+
316
+ # Use a kwarg for this instead of an attribute to maintain
317
+ # thread-safety.
318
+ _credential_refresh_attempt = kwargs.pop("_credential_refresh_attempt", 0)
319
+ # Make a copy of the headers. They will be modified by the credentials
320
+ # and we want to pass the original headers if we recurse.
321
+ request_headers = headers.copy() if headers is not None else {}
322
+
323
+ # Do not apply the timeout unconditionally in order to not override the
324
+ # _auth_request's default timeout.
325
+ auth_request = (
326
+ self._auth_request
327
+ if timeout is None
328
+ else functools.partial(self._auth_request, timeout=timeout)
329
+ )
330
+
331
+ remaining_time = max_allowed_time
332
+
333
+ with requests.TimeoutGuard(remaining_time, asyncio.TimeoutError) as guard:
334
+ await self.credentials.before_request(
335
+ auth_request, method, url, request_headers
336
+ )
337
+
338
+ with requests.TimeoutGuard(remaining_time, asyncio.TimeoutError) as guard:
339
+ response = await super(AuthorizedSession, self).request(
340
+ method,
341
+ url,
342
+ data=data,
343
+ headers=request_headers,
344
+ timeout=timeout,
345
+ **kwargs,
346
+ )
347
+
348
+ remaining_time = guard.remaining_timeout
349
+
350
+ if (
351
+ response.status in self._refresh_status_codes
352
+ and _credential_refresh_attempt < self._max_refresh_attempts
353
+ ):
354
+
355
+ requests._LOGGER.info(
356
+ "Refreshing credentials due to a %s response. Attempt %s/%s.",
357
+ response.status,
358
+ _credential_refresh_attempt + 1,
359
+ self._max_refresh_attempts,
360
+ )
361
+
362
+ # Do not apply the timeout unconditionally in order to not override the
363
+ # _auth_request's default timeout.
364
+ auth_request = (
365
+ self._auth_request
366
+ if timeout is None
367
+ else functools.partial(self._auth_request, timeout=timeout)
368
+ )
369
+
370
+ with requests.TimeoutGuard(
371
+ remaining_time, asyncio.TimeoutError
372
+ ) as guard:
373
+ async with self._refresh_lock:
374
+ await self._loop.run_in_executor(
375
+ None, self.credentials.refresh, auth_request
376
+ )
377
+
378
+ remaining_time = guard.remaining_timeout
379
+
380
+ return await self.request(
381
+ method,
382
+ url,
383
+ data=data,
384
+ headers=headers,
385
+ max_allowed_time=remaining_time,
386
+ timeout=timeout,
387
+ _credential_refresh_attempt=_credential_refresh_attempt + 1,
388
+ **kwargs,
389
+ )
390
+
391
+ return response
lib/python3.10/site-packages/google/auth/transport/_custom_tls_signer.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+
15
+ """
16
+ Code for configuring client side TLS to offload the signing operation to
17
+ signing libraries.
18
+ """
19
+
20
+ import ctypes
21
+ import json
22
+ import logging
23
+ import os
24
+ import sys
25
+
26
+ import cffi # type: ignore
27
+
28
+ from google.auth import exceptions
29
+
30
+ _LOGGER = logging.getLogger(__name__)
31
+
32
+ # C++ offload lib requires google-auth lib to provide the following callback:
33
+ # using SignFunc = int (*)(unsigned char *sig, size_t *sig_len,
34
+ # const unsigned char *tbs, size_t tbs_len)
35
+ # The bytes to be signed and the length are provided via `tbs` and `tbs_len`,
36
+ # the callback computes the signature, and write the signature and its length
37
+ # into `sig` and `sig_len`.
38
+ # If the signing is successful, the callback returns 1, otherwise it returns 0.
39
+ SIGN_CALLBACK_CTYPE = ctypes.CFUNCTYPE(
40
+ ctypes.c_int, # return type
41
+ ctypes.POINTER(ctypes.c_ubyte), # sig
42
+ ctypes.POINTER(ctypes.c_size_t), # sig_len
43
+ ctypes.POINTER(ctypes.c_ubyte), # tbs
44
+ ctypes.c_size_t, # tbs_len
45
+ )
46
+
47
+
48
+ # Cast SSL_CTX* to void*
49
+ def _cast_ssl_ctx_to_void_p_pyopenssl(ssl_ctx):
50
+ return ctypes.cast(int(cffi.FFI().cast("intptr_t", ssl_ctx)), ctypes.c_void_p)
51
+
52
+
53
+ # Cast SSL_CTX* to void*
54
+ def _cast_ssl_ctx_to_void_p_stdlib(context):
55
+ return ctypes.c_void_p.from_address(
56
+ id(context) + ctypes.sizeof(ctypes.c_void_p) * 2
57
+ )
58
+
59
+
60
+ # Load offload library and set up the function types.
61
+ def load_offload_lib(offload_lib_path):
62
+ _LOGGER.debug("loading offload library from %s", offload_lib_path)
63
+
64
+ # winmode parameter is only available for python 3.8+.
65
+ lib = (
66
+ ctypes.CDLL(offload_lib_path, winmode=0)
67
+ if sys.version_info >= (3, 8) and os.name == "nt"
68
+ else ctypes.CDLL(offload_lib_path)
69
+ )
70
+
71
+ # Set up types for:
72
+ # int ConfigureSslContext(SignFunc sign_func, const char *cert, SSL_CTX *ctx)
73
+ lib.ConfigureSslContext.argtypes = [
74
+ SIGN_CALLBACK_CTYPE,
75
+ ctypes.c_char_p,
76
+ ctypes.c_void_p,
77
+ ]
78
+ lib.ConfigureSslContext.restype = ctypes.c_int
79
+
80
+ return lib
81
+
82
+
83
+ # Load signer library and set up the function types.
84
+ # See: https://github.com/googleapis/enterprise-certificate-proxy/blob/main/cshared/main.go
85
+ def load_signer_lib(signer_lib_path):
86
+ _LOGGER.debug("loading signer library from %s", signer_lib_path)
87
+
88
+ # winmode parameter is only available for python 3.8+.
89
+ lib = (
90
+ ctypes.CDLL(signer_lib_path, winmode=0)
91
+ if sys.version_info >= (3, 8) and os.name == "nt"
92
+ else ctypes.CDLL(signer_lib_path)
93
+ )
94
+
95
+ # Set up types for:
96
+ # func GetCertPemForPython(configFilePath *C.char, certHolder *byte, certHolderLen int)
97
+ lib.GetCertPemForPython.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]
98
+ # Returns: certLen
99
+ lib.GetCertPemForPython.restype = ctypes.c_int
100
+
101
+ # Set up types for:
102
+ # func SignForPython(configFilePath *C.char, digest *byte, digestLen int,
103
+ # sigHolder *byte, sigHolderLen int)
104
+ lib.SignForPython.argtypes = [
105
+ ctypes.c_char_p,
106
+ ctypes.c_char_p,
107
+ ctypes.c_int,
108
+ ctypes.c_char_p,
109
+ ctypes.c_int,
110
+ ]
111
+ # Returns: the signature length
112
+ lib.SignForPython.restype = ctypes.c_int
113
+
114
+ return lib
115
+
116
+
117
+ def load_provider_lib(provider_lib_path):
118
+ _LOGGER.debug("loading provider library from %s", provider_lib_path)
119
+
120
+ # winmode parameter is only available for python 3.8+.
121
+ lib = (
122
+ ctypes.CDLL(provider_lib_path, winmode=0)
123
+ if sys.version_info >= (3, 8) and os.name == "nt"
124
+ else ctypes.CDLL(provider_lib_path)
125
+ )
126
+
127
+ lib.ECP_attach_to_ctx.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
128
+ lib.ECP_attach_to_ctx.restype = ctypes.c_int
129
+
130
+ return lib
131
+
132
+
133
+ # Computes SHA256 hash.
134
+ def _compute_sha256_digest(to_be_signed, to_be_signed_len):
135
+ from cryptography.hazmat.primitives import hashes
136
+
137
+ data = ctypes.string_at(to_be_signed, to_be_signed_len)
138
+ hash = hashes.Hash(hashes.SHA256())
139
+ hash.update(data)
140
+ return hash.finalize()
141
+
142
+
143
+ # Create the signing callback. The actual signing work is done by the
144
+ # `SignForPython` method from the signer lib.
145
+ def get_sign_callback(signer_lib, config_file_path):
146
+ def sign_callback(sig, sig_len, tbs, tbs_len):
147
+ _LOGGER.debug("calling sign callback...")
148
+
149
+ digest = _compute_sha256_digest(tbs, tbs_len)
150
+ digestArray = ctypes.c_char * len(digest)
151
+
152
+ # reserve 2000 bytes for the signature, shoud be more then enough.
153
+ # RSA signature is 256 bytes, EC signature is 70~72.
154
+ sig_holder_len = 2000
155
+ sig_holder = ctypes.create_string_buffer(sig_holder_len)
156
+
157
+ signature_len = signer_lib.SignForPython(
158
+ config_file_path.encode(), # configFilePath
159
+ digestArray.from_buffer(bytearray(digest)), # digest
160
+ len(digest), # digestLen
161
+ sig_holder, # sigHolder
162
+ sig_holder_len, # sigHolderLen
163
+ )
164
+
165
+ if signature_len == 0:
166
+ # signing failed, return 0
167
+ return 0
168
+
169
+ sig_len[0] = signature_len
170
+ bs = bytearray(sig_holder)
171
+ for i in range(signature_len):
172
+ sig[i] = bs[i]
173
+
174
+ return 1
175
+
176
+ return SIGN_CALLBACK_CTYPE(sign_callback)
177
+
178
+
179
+ # Obtain the certificate bytes by calling the `GetCertPemForPython` method from
180
+ # the signer lib. The method is called twice, the first time is to compute the
181
+ # cert length, then we create a buffer to hold the cert, and call it again to
182
+ # fill the buffer.
183
+ def get_cert(signer_lib, config_file_path):
184
+ # First call to calculate the cert length
185
+ cert_len = signer_lib.GetCertPemForPython(
186
+ config_file_path.encode(), # configFilePath
187
+ None, # certHolder
188
+ 0, # certHolderLen
189
+ )
190
+ if cert_len == 0:
191
+ raise exceptions.MutualTLSChannelError("failed to get certificate")
192
+
193
+ # Then we create an array to hold the cert, and call again to fill the cert
194
+ cert_holder = ctypes.create_string_buffer(cert_len)
195
+ signer_lib.GetCertPemForPython(
196
+ config_file_path.encode(), # configFilePath
197
+ cert_holder, # certHolder
198
+ cert_len, # certHolderLen
199
+ )
200
+ return bytes(cert_holder)
201
+
202
+
203
+ class CustomTlsSigner(object):
204
+ def __init__(self, enterprise_cert_file_path):
205
+ """
206
+ This class loads the offload and signer library, and calls APIs from
207
+ these libraries to obtain the cert and a signing callback, and attach
208
+ them to SSL context. The cert and the signing callback will be used
209
+ for client authentication in TLS handshake.
210
+
211
+ Args:
212
+ enterprise_cert_file_path (str): the path to a enterprise cert JSON
213
+ file. The file should contain the following field:
214
+
215
+ {
216
+ "libs": {
217
+ "ecp_client": "...",
218
+ "tls_offload": "..."
219
+ }
220
+ }
221
+ """
222
+ self._enterprise_cert_file_path = enterprise_cert_file_path
223
+ self._cert = None
224
+ self._sign_callback = None
225
+ self._provider_lib = None
226
+
227
+ def load_libraries(self):
228
+ with open(self._enterprise_cert_file_path, "r") as f:
229
+ enterprise_cert_json = json.load(f)
230
+ libs = enterprise_cert_json.get("libs", {})
231
+
232
+ signer_library = libs.get("ecp_client", None)
233
+ offload_library = libs.get("tls_offload", None)
234
+ provider_library = libs.get("ecp_provider", None)
235
+
236
+ # Using newer provider implementation. This is mutually exclusive to the
237
+ # offload implementation.
238
+ if provider_library:
239
+ self._provider_lib = load_provider_lib(provider_library)
240
+ return
241
+
242
+ # Using old offload implementation
243
+ if offload_library and signer_library:
244
+ self._offload_lib = load_offload_lib(offload_library)
245
+ self._signer_lib = load_signer_lib(signer_library)
246
+ self.set_up_custom_key()
247
+ return
248
+
249
+ raise exceptions.MutualTLSChannelError("enterprise cert file is invalid")
250
+
251
+ def set_up_custom_key(self):
252
+ # We need to keep a reference of the cert and sign callback so it won't
253
+ # be garbage collected, otherwise it will crash when used by signer lib.
254
+ self._cert = get_cert(self._signer_lib, self._enterprise_cert_file_path)
255
+ self._sign_callback = get_sign_callback(
256
+ self._signer_lib, self._enterprise_cert_file_path
257
+ )
258
+
259
+ def should_use_provider(self):
260
+ if self._provider_lib:
261
+ return True
262
+ return False
263
+
264
+ def attach_to_ssl_context(self, ctx):
265
+ if self.should_use_provider():
266
+ if not self._provider_lib.ECP_attach_to_ctx(
267
+ _cast_ssl_ctx_to_void_p_stdlib(ctx),
268
+ self._enterprise_cert_file_path.encode("ascii"),
269
+ ):
270
+ raise exceptions.MutualTLSChannelError(
271
+ "failed to configure ECP Provider SSL context"
272
+ )
273
+ elif self._offload_lib and self._signer_lib:
274
+ if not self._offload_lib.ConfigureSslContext(
275
+ self._sign_callback,
276
+ ctypes.c_char_p(self._cert),
277
+ _cast_ssl_ctx_to_void_p_pyopenssl(ctx._ctx._context),
278
+ ):
279
+ raise exceptions.MutualTLSChannelError(
280
+ "failed to configure ECP Offload SSL context"
281
+ )
282
+ else:
283
+ raise exceptions.MutualTLSChannelError("Invalid ECP configuration.")
lib/python3.10/site-packages/google/auth/transport/_http_client.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 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
+
15
+ """Transport adapter for http.client, for internal use only."""
16
+
17
+ import http.client as http_client
18
+ import logging
19
+ import socket
20
+ import urllib
21
+
22
+ from google.auth import exceptions
23
+ from google.auth import transport
24
+
25
+ _LOGGER = logging.getLogger(__name__)
26
+
27
+
28
+ class Response(transport.Response):
29
+ """http.client transport response adapter.
30
+
31
+ Args:
32
+ response (http.client.HTTPResponse): The raw http client response.
33
+ """
34
+
35
+ def __init__(self, response):
36
+ self._status = response.status
37
+ self._headers = {key.lower(): value for key, value in response.getheaders()}
38
+ self._data = response.read()
39
+
40
+ @property
41
+ def status(self):
42
+ return self._status
43
+
44
+ @property
45
+ def headers(self):
46
+ return self._headers
47
+
48
+ @property
49
+ def data(self):
50
+ return self._data
51
+
52
+
53
+ class Request(transport.Request):
54
+ """http.client transport request adapter."""
55
+
56
+ def __call__(
57
+ self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
58
+ ):
59
+ """Make an HTTP request using http.client.
60
+
61
+ Args:
62
+ url (str): The URI to be requested.
63
+ method (str): The HTTP method to use for the request. Defaults
64
+ to 'GET'.
65
+ body (bytes): The payload / body in HTTP request.
66
+ headers (Mapping): Request headers.
67
+ timeout (Optional(int)): The number of seconds to wait for a
68
+ response from the server. If not specified or if None, the
69
+ socket global default timeout will be used.
70
+ kwargs: Additional arguments passed throught to the underlying
71
+ :meth:`~http.client.HTTPConnection.request` method.
72
+
73
+ Returns:
74
+ Response: The HTTP response.
75
+
76
+ Raises:
77
+ google.auth.exceptions.TransportError: If any exception occurred.
78
+ """
79
+ # socket._GLOBAL_DEFAULT_TIMEOUT is the default in http.client.
80
+ if timeout is None:
81
+ timeout = socket._GLOBAL_DEFAULT_TIMEOUT
82
+
83
+ # http.client doesn't allow None as the headers argument.
84
+ if headers is None:
85
+ headers = {}
86
+
87
+ # http.client needs the host and path parts specified separately.
88
+ parts = urllib.parse.urlsplit(url)
89
+ path = urllib.parse.urlunsplit(
90
+ ("", "", parts.path, parts.query, parts.fragment)
91
+ )
92
+
93
+ if parts.scheme != "http":
94
+ raise exceptions.TransportError(
95
+ "http.client transport only supports the http scheme, {}"
96
+ "was specified".format(parts.scheme)
97
+ )
98
+
99
+ connection = http_client.HTTPConnection(parts.netloc, timeout=timeout)
100
+
101
+ try:
102
+ _LOGGER.debug("Making request: %s %s", method, url)
103
+
104
+ connection.request(method, path, body=body, headers=headers, **kwargs)
105
+ response = connection.getresponse()
106
+ return Response(response)
107
+
108
+ except (http_client.HTTPException, socket.error) as caught_exc:
109
+ new_exc = exceptions.TransportError(caught_exc)
110
+ raise new_exc from caught_exc
111
+
112
+ finally:
113
+ connection.close()
lib/python3.10/site-packages/google/auth/transport/_mtls_helper.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ """Helper functions for getting mTLS cert and key."""
16
+
17
+ import json
18
+ import logging
19
+ from os import environ, path
20
+ import re
21
+ import subprocess
22
+
23
+ from google.auth import exceptions
24
+
25
+ CONTEXT_AWARE_METADATA_PATH = "~/.secureConnect/context_aware_metadata.json"
26
+ CERTIFICATE_CONFIGURATION_DEFAULT_PATH = "~/.config/gcloud/certificate_config.json"
27
+ _CERTIFICATE_CONFIGURATION_ENV = "GOOGLE_API_CERTIFICATE_CONFIG"
28
+ _CERT_PROVIDER_COMMAND = "cert_provider_command"
29
+ _CERT_REGEX = re.compile(
30
+ b"-----BEGIN CERTIFICATE-----.+-----END CERTIFICATE-----\r?\n?", re.DOTALL
31
+ )
32
+
33
+ # support various format of key files, e.g.
34
+ # "-----BEGIN PRIVATE KEY-----...",
35
+ # "-----BEGIN EC PRIVATE KEY-----...",
36
+ # "-----BEGIN RSA PRIVATE KEY-----..."
37
+ # "-----BEGIN ENCRYPTED PRIVATE KEY-----"
38
+ _KEY_REGEX = re.compile(
39
+ b"-----BEGIN [A-Z ]*PRIVATE KEY-----.+-----END [A-Z ]*PRIVATE KEY-----\r?\n?",
40
+ re.DOTALL,
41
+ )
42
+
43
+ _LOGGER = logging.getLogger(__name__)
44
+
45
+
46
+ _PASSPHRASE_REGEX = re.compile(
47
+ b"-----BEGIN PASSPHRASE-----(.+)-----END PASSPHRASE-----", re.DOTALL
48
+ )
49
+
50
+
51
+ def _check_config_path(config_path):
52
+ """Checks for config file path. If it exists, returns the absolute path with user expansion;
53
+ otherwise returns None.
54
+
55
+ Args:
56
+ config_path (str): The config file path for either context_aware_metadata.json or certificate_config.json for example
57
+
58
+ Returns:
59
+ str: absolute path if exists and None otherwise.
60
+ """
61
+ config_path = path.expanduser(config_path)
62
+ if not path.exists(config_path):
63
+ _LOGGER.debug("%s is not found.", config_path)
64
+ return None
65
+ return config_path
66
+
67
+
68
+ def _load_json_file(path):
69
+ """Reads and loads JSON from the given path. Used to read both X509 workload certificate and
70
+ secure connect configurations.
71
+
72
+ Args:
73
+ path (str): the path to read from.
74
+
75
+ Returns:
76
+ Dict[str, str]: The JSON stored at the file.
77
+
78
+ Raises:
79
+ google.auth.exceptions.ClientCertError: If failed to parse the file as JSON.
80
+ """
81
+ try:
82
+ with open(path) as f:
83
+ json_data = json.load(f)
84
+ except ValueError as caught_exc:
85
+ new_exc = exceptions.ClientCertError(caught_exc)
86
+ raise new_exc from caught_exc
87
+
88
+ return json_data
89
+
90
+
91
+ def _get_workload_cert_and_key(certificate_config_path=None):
92
+ """Read the workload identity cert and key files specified in the certificate config provided.
93
+ If no config path is provided, check the environment variable: "GOOGLE_API_CERTIFICATE_CONFIG"
94
+ first, then the well known gcloud location: "~/.config/gcloud/certificate_config.json".
95
+
96
+ Args:
97
+ certificate_config_path (string): The certificate config path. If no path is provided,
98
+ the environment variable will be checked first, then the well known gcloud location.
99
+
100
+ Returns:
101
+ Tuple[Optional[bytes], Optional[bytes]]: client certificate bytes in PEM format and key
102
+ bytes in PEM format.
103
+
104
+ Raises:
105
+ google.auth.exceptions.ClientCertError: if problems occurs when retrieving
106
+ the certificate or key information.
107
+ """
108
+
109
+ cert_path, key_path = _get_workload_cert_and_key_paths(certificate_config_path)
110
+
111
+ if cert_path is None and key_path is None:
112
+ return None, None
113
+
114
+ return _read_cert_and_key_files(cert_path, key_path)
115
+
116
+
117
+ def _get_cert_config_path(certificate_config_path=None):
118
+ """Get the certificate configuration path based on the following order:
119
+
120
+ 1: Explicit override, if set
121
+ 2: Environment variable, if set
122
+ 3: Well-known location
123
+
124
+ Returns "None" if the selected config file does not exist.
125
+
126
+ Args:
127
+ certificate_config_path (string): The certificate config path. If provided, the well known
128
+ location and environment variable will be ignored.
129
+
130
+ Returns:
131
+ The absolute path of the certificate config file, and None if the file does not exist.
132
+ """
133
+
134
+ if certificate_config_path is None:
135
+ env_path = environ.get(_CERTIFICATE_CONFIGURATION_ENV, None)
136
+ if env_path is not None and env_path != "":
137
+ certificate_config_path = env_path
138
+ else:
139
+ certificate_config_path = CERTIFICATE_CONFIGURATION_DEFAULT_PATH
140
+
141
+ certificate_config_path = path.expanduser(certificate_config_path)
142
+ if not path.exists(certificate_config_path):
143
+ return None
144
+ return certificate_config_path
145
+
146
+
147
+ def _get_workload_cert_and_key_paths(config_path):
148
+ absolute_path = _get_cert_config_path(config_path)
149
+ if absolute_path is None:
150
+ return None, None
151
+
152
+ data = _load_json_file(absolute_path)
153
+
154
+ if "cert_configs" not in data:
155
+ raise exceptions.ClientCertError(
156
+ 'Certificate config file {} is in an invalid format, a "cert configs" object is expected'.format(
157
+ absolute_path
158
+ )
159
+ )
160
+ cert_configs = data["cert_configs"]
161
+
162
+ if "workload" not in cert_configs:
163
+ raise exceptions.ClientCertError(
164
+ 'Certificate config file {} is in an invalid format, a "workload" cert config is expected'.format(
165
+ absolute_path
166
+ )
167
+ )
168
+ workload = cert_configs["workload"]
169
+
170
+ if "cert_path" not in workload:
171
+ raise exceptions.ClientCertError(
172
+ 'Certificate config file {} is in an invalid format, a "cert_path" is expected in the workload cert config'.format(
173
+ absolute_path
174
+ )
175
+ )
176
+ cert_path = workload["cert_path"]
177
+
178
+ if "key_path" not in workload:
179
+ raise exceptions.ClientCertError(
180
+ 'Certificate config file {} is in an invalid format, a "key_path" is expected in the workload cert config'.format(
181
+ absolute_path
182
+ )
183
+ )
184
+ key_path = workload["key_path"]
185
+
186
+ return cert_path, key_path
187
+
188
+
189
+ def _read_cert_and_key_files(cert_path, key_path):
190
+ cert_data = _read_cert_file(cert_path)
191
+ key_data = _read_key_file(key_path)
192
+
193
+ return cert_data, key_data
194
+
195
+
196
+ def _read_cert_file(cert_path):
197
+ with open(cert_path, "rb") as cert_file:
198
+ cert_data = cert_file.read()
199
+
200
+ cert_match = re.findall(_CERT_REGEX, cert_data)
201
+ if len(cert_match) != 1:
202
+ raise exceptions.ClientCertError(
203
+ "Certificate file {} is in an invalid format, a single PEM formatted certificate is expected".format(
204
+ cert_path
205
+ )
206
+ )
207
+ return cert_match[0]
208
+
209
+
210
+ def _read_key_file(key_path):
211
+ with open(key_path, "rb") as key_file:
212
+ key_data = key_file.read()
213
+
214
+ key_match = re.findall(_KEY_REGEX, key_data)
215
+ if len(key_match) != 1:
216
+ raise exceptions.ClientCertError(
217
+ "Private key file {} is in an invalid format, a single PEM formatted private key is expected".format(
218
+ key_path
219
+ )
220
+ )
221
+
222
+ return key_match[0]
223
+
224
+
225
+ def _run_cert_provider_command(command, expect_encrypted_key=False):
226
+ """Run the provided command, and return client side mTLS cert, key and
227
+ passphrase.
228
+
229
+ Args:
230
+ command (List[str]): cert provider command.
231
+ expect_encrypted_key (bool): If encrypted private key is expected.
232
+
233
+ Returns:
234
+ Tuple[bytes, bytes, bytes]: client certificate bytes in PEM format, key
235
+ bytes in PEM format and passphrase bytes.
236
+
237
+ Raises:
238
+ google.auth.exceptions.ClientCertError: if problems occurs when running
239
+ the cert provider command or generating cert, key and passphrase.
240
+ """
241
+ try:
242
+ process = subprocess.Popen(
243
+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
244
+ )
245
+ stdout, stderr = process.communicate()
246
+ except OSError as caught_exc:
247
+ new_exc = exceptions.ClientCertError(caught_exc)
248
+ raise new_exc from caught_exc
249
+
250
+ # Check cert provider command execution error.
251
+ if process.returncode != 0:
252
+ raise exceptions.ClientCertError(
253
+ "Cert provider command returns non-zero status code %s" % process.returncode
254
+ )
255
+
256
+ # Extract certificate (chain), key and passphrase.
257
+ cert_match = re.findall(_CERT_REGEX, stdout)
258
+ if len(cert_match) != 1:
259
+ raise exceptions.ClientCertError("Client SSL certificate is missing or invalid")
260
+ key_match = re.findall(_KEY_REGEX, stdout)
261
+ if len(key_match) != 1:
262
+ raise exceptions.ClientCertError("Client SSL key is missing or invalid")
263
+ passphrase_match = re.findall(_PASSPHRASE_REGEX, stdout)
264
+
265
+ if expect_encrypted_key:
266
+ if len(passphrase_match) != 1:
267
+ raise exceptions.ClientCertError("Passphrase is missing or invalid")
268
+ if b"ENCRYPTED" not in key_match[0]:
269
+ raise exceptions.ClientCertError("Encrypted private key is expected")
270
+ return cert_match[0], key_match[0], passphrase_match[0].strip()
271
+
272
+ if b"ENCRYPTED" in key_match[0]:
273
+ raise exceptions.ClientCertError("Encrypted private key is not expected")
274
+ if len(passphrase_match) > 0:
275
+ raise exceptions.ClientCertError("Passphrase is not expected")
276
+ return cert_match[0], key_match[0], None
277
+
278
+
279
+ def get_client_ssl_credentials(
280
+ generate_encrypted_key=False,
281
+ context_aware_metadata_path=CONTEXT_AWARE_METADATA_PATH,
282
+ certificate_config_path=CERTIFICATE_CONFIGURATION_DEFAULT_PATH,
283
+ ):
284
+ """Returns the client side certificate, private key and passphrase.
285
+
286
+ We look for certificates and keys with the following order of priority:
287
+ 1. Certificate and key specified by certificate_config.json.
288
+ Currently, only X.509 workload certificates are supported.
289
+ 2. Certificate and key specified by context aware metadata (i.e. SecureConnect).
290
+
291
+ Args:
292
+ generate_encrypted_key (bool): If set to True, encrypted private key
293
+ and passphrase will be generated; otherwise, unencrypted private key
294
+ will be generated and passphrase will be None. This option only
295
+ affects keys obtained via context_aware_metadata.json.
296
+ context_aware_metadata_path (str): The context_aware_metadata.json file path.
297
+ certificate_config_path (str): The certificate_config.json file path.
298
+
299
+ Returns:
300
+ Tuple[bool, bytes, bytes, bytes]:
301
+ A boolean indicating if cert, key and passphrase are obtained, the
302
+ cert bytes and key bytes both in PEM format, and passphrase bytes.
303
+
304
+ Raises:
305
+ google.auth.exceptions.ClientCertError: if problems occurs when getting
306
+ the cert, key and passphrase.
307
+ """
308
+
309
+ # 1. Check for certificate config json.
310
+ cert_config_path = _check_config_path(certificate_config_path)
311
+ if cert_config_path:
312
+ # Attempt to retrieve X.509 Workload cert and key.
313
+ cert, key = _get_workload_cert_and_key(cert_config_path)
314
+ if cert and key:
315
+ return True, cert, key, None
316
+
317
+ # 2. Check for context aware metadata json
318
+ metadata_path = _check_config_path(context_aware_metadata_path)
319
+
320
+ if metadata_path:
321
+ metadata_json = _load_json_file(metadata_path)
322
+
323
+ if _CERT_PROVIDER_COMMAND not in metadata_json:
324
+ raise exceptions.ClientCertError("Cert provider command is not found")
325
+
326
+ command = metadata_json[_CERT_PROVIDER_COMMAND]
327
+
328
+ if generate_encrypted_key and "--with_passphrase" not in command:
329
+ command.append("--with_passphrase")
330
+
331
+ # Execute the command.
332
+ cert, key, passphrase = _run_cert_provider_command(
333
+ command, expect_encrypted_key=generate_encrypted_key
334
+ )
335
+ return True, cert, key, passphrase
336
+
337
+ return False, None, None, None
338
+
339
+
340
+ def get_client_cert_and_key(client_cert_callback=None):
341
+ """Returns the client side certificate and private key. The function first
342
+ tries to get certificate and key from client_cert_callback; if the callback
343
+ is None or doesn't provide certificate and key, the function tries application
344
+ default SSL credentials.
345
+
346
+ Args:
347
+ client_cert_callback (Optional[Callable[[], (bytes, bytes)]]): An
348
+ optional callback which returns client certificate bytes and private
349
+ key bytes both in PEM format.
350
+
351
+ Returns:
352
+ Tuple[bool, bytes, bytes]:
353
+ A boolean indicating if cert and key are obtained, the cert bytes
354
+ and key bytes both in PEM format.
355
+
356
+ Raises:
357
+ google.auth.exceptions.ClientCertError: if problems occurs when getting
358
+ the cert and key.
359
+ """
360
+ if client_cert_callback:
361
+ cert, key = client_cert_callback()
362
+ return True, cert, key
363
+
364
+ has_cert, cert, key, _ = get_client_ssl_credentials(generate_encrypted_key=False)
365
+ return has_cert, cert, key
366
+
367
+
368
+ def decrypt_private_key(key, passphrase):
369
+ """A helper function to decrypt the private key with the given passphrase.
370
+ google-auth library doesn't support passphrase protected private key for
371
+ mutual TLS channel. This helper function can be used to decrypt the
372
+ passphrase protected private key in order to estalish mutual TLS channel.
373
+
374
+ For example, if you have a function which produces client cert, passphrase
375
+ protected private key and passphrase, you can convert it to a client cert
376
+ callback function accepted by google-auth::
377
+
378
+ from google.auth.transport import _mtls_helper
379
+
380
+ def your_client_cert_function():
381
+ return cert, encrypted_key, passphrase
382
+
383
+ # callback accepted by google-auth for mutual TLS channel.
384
+ def client_cert_callback():
385
+ cert, encrypted_key, passphrase = your_client_cert_function()
386
+ decrypted_key = _mtls_helper.decrypt_private_key(encrypted_key,
387
+ passphrase)
388
+ return cert, decrypted_key
389
+
390
+ Args:
391
+ key (bytes): The private key bytes in PEM format.
392
+ passphrase (bytes): The passphrase bytes.
393
+
394
+ Returns:
395
+ bytes: The decrypted private key in PEM format.
396
+
397
+ Raises:
398
+ ImportError: If pyOpenSSL is not installed.
399
+ OpenSSL.crypto.Error: If there is any problem decrypting the private key.
400
+ """
401
+ from OpenSSL import crypto
402
+
403
+ # First convert encrypted_key_bytes to PKey object
404
+ pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key, passphrase=passphrase)
405
+
406
+ # Then dump the decrypted key bytes
407
+ return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)