codecraftai-restclient-google 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,378 @@
1
+ """
2
+ .. module:: googletokenprovider
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Access-token acquisition for the Google Cloud APIs.
5
+
6
+ Two credential kinds are supported:
7
+
8
+ * a service-account key, which self-signs a JWT asserting who it is and
9
+ what scopes it wants, then exchanges that assertion for an access token
10
+ at Google's OAuth2 endpoint;
11
+ * workload identity, which asks the instance metadata service for a token
12
+ the platform issues to the machine itself.
13
+
14
+ The JWT is signed RS256, which is the one place in this fleet's clients
15
+ that needs real asymmetric cryptography — hence the ``cryptography``
16
+ dependency here and nowhere else in the REST clients except the Oracle
17
+ one.
18
+
19
+ Tokens are cached until shortly before they expire. The early refresh
20
+ matters: a token that passes the expiry check and then expires in flight
21
+ fails the request it was fetched for, mid-apply.
22
+
23
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
24
+ """
25
+
26
+ __author__ = "Myron Walker"
27
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
28
+ __credits__ = []
29
+
30
+
31
+ import base64
32
+ import json
33
+ import os
34
+ import time
35
+
36
+ from typing import Any, Dict, List, Optional
37
+
38
+ import requests
39
+
40
+ from ccai.restclient.google.googleapierror import GoogleAuthError
41
+
42
+
43
+ GOOGLE_TOKEN_URI = "https://oauth2.googleapis.com/token"
44
+
45
+ JWT_BEARER_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer"
46
+
47
+ # The metadata server is a link-local address that only answers requests
48
+ # carrying the Metadata-Flavor header.
49
+ METADATA_TOKEN_URL = (
50
+ "http://metadata.google.internal/computeMetadata/v1/"
51
+ "instance/service-accounts/default/token"
52
+ )
53
+
54
+ CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
55
+
56
+ # A self-signed assertion is short-lived by design; Google caps it at an hour.
57
+ ASSERTION_LIFETIME_SECONDS = 3600
58
+
59
+ DEFAULT_TIMEOUT_SECONDS = 30.0
60
+
61
+ EXPIRY_SKEW_SECONDS = 300.0
62
+
63
+
64
+ def base64url(data: bytes) -> str:
65
+ """
66
+ Base64url-encode without padding, as JWT requires.
67
+
68
+ :param data: The bytes to encode.
69
+
70
+ :returns: The encoded string.
71
+ """
72
+ rtnval = base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
73
+ return rtnval
74
+
75
+
76
+ class GoogleTokenProvider:
77
+ """
78
+ Acquires and caches Google Cloud access tokens.
79
+ """
80
+
81
+ def __init__(self, *, client_email: Optional[str] = None,
82
+ private_key: Optional[str] = None,
83
+ private_key_id: Optional[str] = None,
84
+ token_uri: str = GOOGLE_TOKEN_URI,
85
+ scopes: Optional[List[str]] = None,
86
+ use_metadata_server: bool = False,
87
+ metadata_url: str = METADATA_TOKEN_URL,
88
+ session: Optional[Any] = None,
89
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS) -> None:
90
+ """
91
+ Construct a GoogleTokenProvider.
92
+
93
+ :param client_email: The service account's address, which becomes
94
+ the assertion's issuer.
95
+ :param private_key: The service account's PEM private key.
96
+ :param private_key_id: The key id, carried in the JWT header so
97
+ Google can select the right public key.
98
+ :param token_uri: The OAuth2 token endpoint, which is also the
99
+ assertion's audience.
100
+ :param scopes: The scopes to request.
101
+ :param use_metadata_server: Ask the metadata server instead of
102
+ signing an assertion.
103
+ :param metadata_url: The metadata token URL.
104
+ :param session: Optional pre-built ``requests.Session`` — the test
105
+ seam.
106
+ :param timeout_seconds: The per-request timeout.
107
+
108
+ :raises: :class:`GoogleAuthError` when the supplied material
109
+ cannot identify a caller.
110
+ """
111
+ self._client_email = client_email
112
+ self._private_key = private_key
113
+ self._private_key_id = private_key_id
114
+ self._token_uri = token_uri
115
+ self._use_metadata_server = use_metadata_server
116
+ self._metadata_url = metadata_url
117
+ self._timeout_seconds = timeout_seconds
118
+
119
+ if scopes is not None and len(scopes) > 0:
120
+ self._scopes = list(scopes)
121
+ else:
122
+ self._scopes = [CLOUD_PLATFORM_SCOPE]
123
+
124
+ self._token: Optional[str] = None
125
+ self._expires_at: float = 0.0
126
+
127
+ if use_metadata_server is False:
128
+ missing = []
129
+ if client_email is None or len(client_email) == 0:
130
+ missing.append("client_email")
131
+ if private_key is None or len(private_key) == 0:
132
+ missing.append("private_key")
133
+ if len(missing) > 0:
134
+ err_msg_lines = [
135
+ "A service-account token needs the full key material."
136
+ ]
137
+ err_msg_lines.append("MISSING: {}".format(", ".join(missing)))
138
+ err_msg_lines.append(
139
+ "Pass use_metadata_server=True to use workload identity "
140
+ "instead.")
141
+ err_msg = os.linesep.join(err_msg_lines)
142
+ raise GoogleAuthError(err_msg)
143
+
144
+ if session is not None:
145
+ self._session = session
146
+ else:
147
+ self._session = requests.Session()
148
+ return
149
+
150
+ @property
151
+ def client_email(self) -> Optional[str]:
152
+ """
153
+ Return the service account address.
154
+
155
+ :returns: The address, or None under workload identity.
156
+ """
157
+ rtnval = self._client_email
158
+ return rtnval
159
+
160
+ @property
161
+ def scopes(self) -> List[str]:
162
+ """
163
+ Return the requested scopes.
164
+
165
+ :returns: The scopes.
166
+ """
167
+ rtnval = list(self._scopes)
168
+ return rtnval
169
+
170
+ def build_assertion(self, *, issued_at: int) -> str:
171
+ """
172
+ Build and sign the JWT assertion.
173
+
174
+ :param issued_at: The issue time, as a UNIX timestamp. Passed in
175
+ rather than read here so the assertion is reproducible in
176
+ tests.
177
+
178
+ :returns: The signed JWT.
179
+
180
+ :raises: :class:`GoogleAuthError` when the key cannot be loaded.
181
+ """
182
+ header: Dict[str, Any] = {"alg": "RS256", "typ": "JWT"}
183
+ if self._private_key_id is not None:
184
+ header["kid"] = self._private_key_id
185
+
186
+ claims: Dict[str, Any] = {
187
+ "iss": self._client_email,
188
+ "scope": " ".join(self._scopes),
189
+ "aud": self._token_uri,
190
+ "iat": issued_at,
191
+ "exp": issued_at + ASSERTION_LIFETIME_SECONDS,
192
+ }
193
+
194
+ segments = [
195
+ base64url(json.dumps(header, separators=(",", ":")).encode(
196
+ "utf-8")),
197
+ base64url(json.dumps(claims, separators=(",", ":")).encode(
198
+ "utf-8")),
199
+ ]
200
+ signing_input = ".".join(segments).encode("ascii")
201
+
202
+ signature = self._sign(payload=signing_input)
203
+
204
+ rtnval = "{}.{}".format(".".join(segments), base64url(signature))
205
+ return rtnval
206
+
207
+ def _sign(self, *, payload: bytes) -> bytes:
208
+ """
209
+ Sign the assertion with the service account's RSA key.
210
+
211
+ :param payload: The signing input.
212
+
213
+ :returns: The raw signature.
214
+
215
+ :raises: :class:`GoogleAuthError` when the key cannot be loaded
216
+ or is not an RSA key.
217
+ """
218
+ from cryptography.hazmat.primitives import hashes, serialization
219
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
220
+
221
+ key_text = self._private_key
222
+ if key_text is None:
223
+ err_msg = "No private key is available to sign the assertion."
224
+ raise GoogleAuthError(err_msg)
225
+
226
+ # Service-account JSON stores the PEM with literal \n sequences when
227
+ # it has been round-tripped through an environment variable.
228
+ material = key_text.replace("\\n", "\n").encode("utf-8")
229
+
230
+ try:
231
+ private_key = serialization.load_pem_private_key(material,
232
+ password=None)
233
+ except Exception as xcpt:
234
+ err_msg_lines = [
235
+ "The service-account private key could not be loaded."
236
+ ]
237
+ err_msg_lines.append("CAUSE: {}".format(xcpt))
238
+ err_msg = os.linesep.join(err_msg_lines)
239
+ raise GoogleAuthError(err_msg) from None
240
+
241
+ if isinstance(private_key, rsa.RSAPrivateKey) is False:
242
+ err_msg_lines = [
243
+ "The service-account key must be an RSA key; Google signs "
244
+ "assertions RS256."
245
+ ]
246
+ err_msg_lines.append("ACTUAL: {}".format(
247
+ type(private_key).__name__))
248
+ err_msg = os.linesep.join(err_msg_lines)
249
+ raise GoogleAuthError(err_msg)
250
+
251
+ rtnval = private_key.sign(payload, padding.PKCS1v15(),
252
+ hashes.SHA256())
253
+ return rtnval
254
+
255
+ def token(self, *, now: Optional[float] = None) -> str:
256
+ """
257
+ Return a valid access token, fetching one when needed.
258
+
259
+ :param now: Optional current time, for tests.
260
+
261
+ :returns: The bearer token.
262
+ """
263
+ moment = now
264
+ if moment is None:
265
+ moment = time.time()
266
+
267
+ if self._token is not None and moment < self._expires_at:
268
+ rtnval = self._token
269
+ return rtnval
270
+
271
+ if self._use_metadata_server is True:
272
+ payload = self._fetch_metadata_token()
273
+ else:
274
+ payload = self._fetch_assertion_token(issued_at=int(moment))
275
+
276
+ token = payload.get("access_token", None)
277
+ if token is None or len(str(token)) == 0:
278
+ err_msg = "The token response carried no access_token."
279
+ raise GoogleAuthError(err_msg)
280
+
281
+ expires_in = payload.get("expires_in", 3600)
282
+ try:
283
+ lifetime = float(expires_in)
284
+ except (TypeError, ValueError):
285
+ lifetime = 3600.0
286
+
287
+ usable = lifetime - EXPIRY_SKEW_SECONDS
288
+ if usable <= 0:
289
+ usable = lifetime / 2.0
290
+
291
+ self._token = str(token)
292
+ self._expires_at = moment + usable
293
+
294
+ rtnval = self._token
295
+ return rtnval
296
+
297
+ def _fetch_assertion_token(self, *, issued_at: int) -> Dict[str, Any]:
298
+ """
299
+ Exchange a signed assertion for an access token.
300
+
301
+ :param issued_at: The assertion issue time.
302
+
303
+ :returns: The decoded token response.
304
+ """
305
+ assertion = self.build_assertion(issued_at=issued_at)
306
+
307
+ form = {"grant_type": JWT_BEARER_GRANT, "assertion": assertion}
308
+
309
+ response = self._session.request(
310
+ "POST", self._token_uri, data=form,
311
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
312
+ timeout=self._timeout_seconds)
313
+
314
+ rtnval = self._decode(response=response, what="service account")
315
+ return rtnval
316
+
317
+ def _fetch_metadata_token(self) -> Dict[str, Any]:
318
+ """
319
+ Ask the metadata server for an access token.
320
+
321
+ :returns: The decoded token response.
322
+ """
323
+ response = self._session.request(
324
+ "GET", self._metadata_url,
325
+ headers={"Metadata-Flavor": "Google"},
326
+ timeout=self._timeout_seconds)
327
+
328
+ rtnval = self._decode(response=response, what="workload identity")
329
+ return rtnval
330
+
331
+ def _decode(self, *, response: Any, what: str) -> Dict[str, Any]:
332
+ """
333
+ Validate and decode a token response.
334
+
335
+ :param response: The HTTP response.
336
+ :param what: Which credential kind was used, for the message.
337
+
338
+ :returns: The decoded body.
339
+
340
+ :raises: :class:`GoogleAuthError` on failure.
341
+ """
342
+ status = getattr(response, "status_code", 0)
343
+ text = getattr(response, "text", "")
344
+
345
+ if status < 200 or status >= 300:
346
+ description = text
347
+ try:
348
+ decoded = response.json()
349
+ if isinstance(decoded, dict) is True:
350
+ described = decoded.get("error_description", None)
351
+ if described is None:
352
+ described = decoded.get("error", None)
353
+ if described is not None:
354
+ description = str(described)
355
+ except Exception:
356
+ description = text
357
+
358
+ err_msg_lines = [
359
+ "Could not obtain a Google access token ({}).".format(what)
360
+ ]
361
+ err_msg_lines.append("STATUS: {}".format(status))
362
+ err_msg_lines.append("DETAIL: {}".format(description))
363
+ err_msg = os.linesep.join(err_msg_lines)
364
+ raise GoogleAuthError(err_msg, status=status, body=text)
365
+
366
+ try:
367
+ decoded = response.json()
368
+ except Exception:
369
+ err_msg = "The Google token response was not JSON."
370
+ raise GoogleAuthError(err_msg, status=status,
371
+ body=text) from None
372
+
373
+ if isinstance(decoded, dict) is False:
374
+ err_msg = "The Google token response was not an object."
375
+ raise GoogleAuthError(err_msg, status=status, body=text)
376
+
377
+ rtnval = decoded
378
+ return rtnval
@@ -0,0 +1,170 @@
1
+ """
2
+ .. module:: googletransport
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: :class:`GoogleTransport` — the shared authenticated transport.
5
+
6
+ Every Google Cloud API this package speaks is JSON over HTTPS with a
7
+ bearer token, so one transport serves Compute, Storage, DNS and TPU.
8
+
9
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
10
+ """
11
+
12
+ __author__ = "Myron Walker"
13
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
14
+ __credits__ = []
15
+
16
+
17
+ import json
18
+ import os
19
+
20
+ from typing import Any, Dict, Optional
21
+
22
+ import requests
23
+
24
+ from ccai.restclient.google.googleapierror import GoogleApiError, NotFound
25
+ from ccai.restclient.google.googleobject import ProtoObject, wrap_value
26
+
27
+
28
+ DEFAULT_TIMEOUT_SECONDS = 60.0
29
+
30
+
31
+ class GoogleTransport:
32
+ """
33
+ Authenticated JSON transport for the Google Cloud APIs.
34
+ """
35
+
36
+ def __init__(self, *, token_provider: Any,
37
+ session: Optional[Any] = None,
38
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS) -> None:
39
+ """
40
+ Construct a GoogleTransport.
41
+
42
+ :param token_provider: Supplies bearer tokens.
43
+ :param session: Optional pre-built ``requests.Session`` — the test
44
+ seam.
45
+ :param timeout_seconds: The default per-request timeout.
46
+ """
47
+ self._token_provider = token_provider
48
+ self._timeout_seconds = timeout_seconds
49
+
50
+ if session is not None:
51
+ self._session = session
52
+ else:
53
+ self._session = requests.Session()
54
+ return
55
+
56
+ def request(self, *, method: str, url: str,
57
+ params: Optional[Dict[str, Any]] = None,
58
+ body: Optional[Dict[str, Any]] = None,
59
+ timeout_seconds: Optional[float] = None) -> ProtoObject:
60
+ """
61
+ Perform one authenticated request.
62
+
63
+ :param method: The HTTP method.
64
+ :param url: The absolute URL.
65
+ :param params: Optional query parameters; ``None`` values are
66
+ dropped.
67
+ :param body: Optional JSON request body.
68
+ :param timeout_seconds: Optional per-request timeout override.
69
+
70
+ :returns: The decoded response, empty when there is no body.
71
+
72
+ :raises: :class:`NotFound` on 404, otherwise
73
+ :class:`GoogleApiError` on a non-success status.
74
+ """
75
+ query: Dict[str, Any] = {}
76
+ if params is not None:
77
+ for key, value in params.items():
78
+ if value is not None:
79
+ query[key] = value
80
+
81
+ headers: Dict[str, str] = {
82
+ "Authorization": "Bearer {}".format(self._token_provider.token()),
83
+ "Accept": "application/json",
84
+ }
85
+
86
+ payload = None
87
+ if body is not None:
88
+ payload = json.dumps(body)
89
+ headers["Content-Type"] = "application/json"
90
+
91
+ timeout = timeout_seconds
92
+ if timeout is None:
93
+ timeout = self._timeout_seconds
94
+
95
+ response = self._session.request(method, url, params=query,
96
+ data=payload, headers=headers,
97
+ timeout=timeout)
98
+
99
+ status = getattr(response, "status_code", 0)
100
+
101
+ if status < 200 or status >= 300:
102
+ text = getattr(response, "text", "")
103
+ reason = self._extract_reason(response=response,
104
+ fallback=getattr(response,
105
+ "reason", ""))
106
+ err_msg_lines = ["The Google Cloud API request failed."]
107
+ err_msg_lines.append("METHOD: {}".format(method))
108
+ err_msg_lines.append("URL: {}".format(url))
109
+ err_msg_lines.append("STATUS: {}".format(status))
110
+ err_msg_lines.append("REASON: {}".format(reason))
111
+ err_msg = os.linesep.join(err_msg_lines)
112
+
113
+ if status == 404:
114
+ raise NotFound(err_msg, status=status, reason=reason,
115
+ body=text)
116
+
117
+ raise GoogleApiError(err_msg, status=status, reason=reason,
118
+ body=text)
119
+
120
+ text = getattr(response, "text", "")
121
+ if text is None or len(text.strip()) == 0:
122
+ rtnval = ProtoObject()
123
+ return rtnval
124
+
125
+ try:
126
+ decoded = response.json()
127
+ except Exception:
128
+ rtnval = ProtoObject()
129
+ return rtnval
130
+
131
+ wrapped = wrap_value(decoded)
132
+ if isinstance(wrapped, ProtoObject) is True:
133
+ rtnval = wrapped
134
+ return rtnval
135
+
136
+ rtnval = ProtoObject({"items": wrapped})
137
+ return rtnval
138
+
139
+ def _extract_reason(self, *, response: Any, fallback: str) -> str:
140
+ """
141
+ Pull the message out of a Google error body.
142
+
143
+ Failures arrive as ``{"error": {"code": ..., "message": ...}}``,
144
+ which is far more useful than the HTTP phrase.
145
+
146
+ :param response: The failed response.
147
+ :param fallback: The reason to use when the body is unhelpful.
148
+
149
+ :returns: The extracted reason.
150
+ """
151
+ try:
152
+ decoded = response.json()
153
+ except Exception:
154
+ rtnval = fallback
155
+ return rtnval
156
+
157
+ if isinstance(decoded, dict) is False:
158
+ rtnval = fallback
159
+ return rtnval
160
+
161
+ error = decoded.get("error", None)
162
+ if isinstance(error, dict) is True:
163
+ rtnval = str(error.get("message", fallback))
164
+ return rtnval
165
+ if error is not None:
166
+ rtnval = str(error)
167
+ return rtnval
168
+
169
+ rtnval = fallback
170
+ return rtnval