codecraftai-restclient-base 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.
File without changes
@@ -0,0 +1,122 @@
1
+
2
+ """
3
+ .. module:: aspectsrest
4
+ :platform: Darwin, Linux, Unix, Windows
5
+ :synopsis: aspectsrest module.
6
+
7
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
8
+ """
9
+
10
+
11
+ __author__ = "Myron Walker"
12
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
13
+ __credits__ = []
14
+
15
+
16
+ from typing import Optional, Tuple
17
+
18
+ import logging
19
+
20
+ from enum import IntEnum
21
+
22
+ from requests import Session
23
+
24
+ from ccai.aspects.aspects import Aspects as AspectsBase
25
+
26
+ class ActionPattern(IntEnum):
27
+ """
28
+ An action pattern to use when using aspects to change the behavior of an API.
29
+ """
30
+ SINGLE_CALL = 0
31
+ SINGLE_CONNECTED_CALL = 1
32
+ DO_UNTIL_SUCCESS = 2
33
+ DO_WHILE_SUCCESS = 3
34
+ DO_UNTIL_CONNECTION_FAILURE = 4
35
+
36
+
37
+ class LoggingPattern:
38
+ """
39
+ A logging pattern to use when logging commands.
40
+ """
41
+ ALL_RESULTS = 0
42
+ FAILURE_ONLY = 1
43
+ SUCCESS_ONLY = 2
44
+
45
+
46
+ DEFAULT_COMPLETION_TIMEOUT = 600
47
+ DEFAULT_COMPLETION_INTERVAL = 10
48
+
49
+ DEFAULT_CONNECTION_TIMEOUT = 16
50
+ DEFAULT_CONNECTION_INTERVAL = 2
51
+ DEFAULT_ALLOWED_CONNECTION_EXCEPTIONS: Tuple[BaseException, ...] = ()
52
+
53
+ DEFAULT_INACTIVITY_TIMEOUT = 600
54
+ DEFAULT_INACTIVITY_INTERVAL = .5
55
+
56
+ DEFAULT_MONITOR_DELAY = 30
57
+
58
+ DEFAULT_RETRY_LOGGING_INTERVAL = 5
59
+
60
+ DEFAULT_LOGGING_PATTERN = LoggingPattern.ALL_RESULTS
61
+
62
+ DEFAULT_MUST_CONNECT = False
63
+
64
+ DEFAULT_ALLOWED_ERROR_CODES: Tuple[int, ...] = ()
65
+
66
+
67
+ class AspectsRest(AspectsBase):
68
+ """
69
+ Aspects container specialized for REST operations.
70
+ """
71
+ def __init__(self, *, action_pattern: ActionPattern = ActionPattern.SINGLE_CALL,
72
+ completion_timeout: float = DEFAULT_COMPLETION_TIMEOUT,
73
+ completion_interval: float = DEFAULT_COMPLETION_INTERVAL,
74
+ connection_timeout: float = DEFAULT_CONNECTION_TIMEOUT,
75
+ inactivity_timeout: float = DEFAULT_INACTIVITY_TIMEOUT,
76
+ monitor_delay: float = DEFAULT_MONITOR_DELAY,
77
+ logging_pattern: LoggingPattern = DEFAULT_LOGGING_PATTERN,
78
+ retry_logging_interval: int = DEFAULT_RETRY_LOGGING_INTERVAL,
79
+ allowed_error_codes: Tuple[int, ...] = DEFAULT_ALLOWED_ERROR_CODES,
80
+ allowed_connection_exceptions: Tuple[BaseException, ...] = DEFAULT_ALLOWED_CONNECTION_EXCEPTIONS,
81
+ must_connect: bool = DEFAULT_MUST_CONNECT,
82
+ logger: Optional[logging.Logger]=None,
83
+ session: Optional[Session] = None):
84
+ """
85
+ Initialize a set of REST call aspects.
86
+
87
+ :param action_pattern: Default action pattern for calls.
88
+ :param completion_timeout: Time in seconds to wait for completion.
89
+ :param completion_interval: Polling interval when waiting.
90
+ :param connection_timeout: Timeout for establishing connections.
91
+ :param inactivity_timeout: Timeout for inactivity in seconds.
92
+ :param monitor_delay: Delay before monitoring begins.
93
+ :param logging_pattern: Pattern used for call logging.
94
+ :param retry_logging_interval: Interval for retry log messages.
95
+ :param allowed_error_codes: HTTP status codes considered success.
96
+ :param allowed_connection_exceptions: Exceptions allowed during connect.
97
+ :param must_connect: Whether a connection must be established.
98
+ :param logger: Logger to use for messages.
99
+ :param session: Requests session to reuse.
100
+ """
101
+ object.__setattr__(self, "__frozen__", False)
102
+
103
+ super().__init__(completion_interval=completion_interval, completion_timeout=completion_timeout,
104
+ connection_timeout=connection_timeout)
105
+
106
+ self.action_pattern=action_pattern
107
+ self.inactivity_timeout=inactivity_timeout
108
+ self.monitor_delay=monitor_delay
109
+ self.logging_pattern=logging_pattern
110
+ self.retry_logging_interval=retry_logging_interval
111
+ self.allowed_error_codes=tuple(allowed_error_codes)
112
+ self.allowed_connection_exceptions=tuple(allowed_connection_exceptions)
113
+ self.must_connect=must_connect
114
+ self.logger=logger
115
+ self.session = session
116
+
117
+ self.freeze()
118
+ return
119
+
120
+
121
+
122
+ DEFAULT_REST_ASPECTS = AspectsRest()
@@ -0,0 +1,364 @@
1
+ """
2
+ .. module:: awssigv4
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: AWS Signature Version 4 request signing, in pure Python.
5
+
6
+ SigV4 is the request-signing scheme used by AWS and by every
7
+ S3-compatible object store that follows it — DigitalOcean Spaces, Linode
8
+ Object Storage, Backblaze B2's S3 endpoint, MinIO. It needs nothing but
9
+ ``hmac`` and ``hashlib`` from the standard library: the signature is a
10
+ chain of HMAC-SHA256 derivations over a canonicalised form of the
11
+ request.
12
+
13
+ This lives in ``restclient-base`` rather than in one provider's client
14
+ because several providers need exactly the same algorithm, and a copy per
15
+ provider would be a copy of the subtle parts too.
16
+
17
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
18
+ """
19
+
20
+ __author__ = "Myron Walker"
21
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
22
+ __credits__ = []
23
+
24
+
25
+ import datetime
26
+ import hashlib
27
+ import hmac
28
+ import urllib.parse
29
+
30
+ from typing import Dict, Mapping, Optional, Tuple
31
+
32
+
33
+ ALGORITHM = "AWS4-HMAC-SHA256"
34
+
35
+ TERMINATOR = "aws4_request"
36
+
37
+ # The SHA-256 of the empty string, which is the payload hash for every
38
+ # bodiless request. Precomputed because it appears on nearly every call.
39
+ EMPTY_PAYLOAD_SHA256 = (
40
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
41
+ )
42
+
43
+ # S3 accepts this literal in place of a real body hash, telling the service
44
+ # the payload is not signed. Useful for streaming uploads where the body
45
+ # cannot be hashed up front.
46
+ UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"
47
+
48
+
49
+ def _sha256_hex(data: bytes) -> str:
50
+ """
51
+ Return the lowercase hex SHA-256 of some bytes.
52
+
53
+ :param data: The bytes to hash.
54
+
55
+ :returns: The hex digest.
56
+ """
57
+ rtnval = hashlib.sha256(data).hexdigest()
58
+ return rtnval
59
+
60
+
61
+ def _hmac_sha256(key: bytes, message: str) -> bytes:
62
+ """
63
+ Return the raw HMAC-SHA256 of a message under a key.
64
+
65
+ :param key: The HMAC key.
66
+ :param message: The message, encoded as UTF-8.
67
+
68
+ :returns: The raw digest bytes.
69
+ """
70
+ rtnval = hmac.new(key, message.encode("utf-8"), hashlib.sha256).digest()
71
+ return rtnval
72
+
73
+
74
+ def uri_encode(value: str, *, encode_slash: bool = True) -> str:
75
+ """
76
+ Percent-encode a string the way SigV4 canonicalisation requires.
77
+
78
+ The unreserved set is ``A-Z a-z 0-9 - _ . ~``; everything else is
79
+ percent-encoded with uppercase hex. Path segments keep ``/``
80
+ unencoded, which is why ``encode_slash`` exists — encoding it in a
81
+ canonical URI would change the resource being addressed.
82
+
83
+ :param value: The string to encode.
84
+ :param encode_slash: Whether ``/`` is encoded.
85
+
86
+ :returns: The encoded string.
87
+ """
88
+ safe = "-_.~"
89
+ if encode_slash is False:
90
+ safe = safe + "/"
91
+
92
+ rtnval = urllib.parse.quote(value, safe=safe)
93
+ return rtnval
94
+
95
+
96
+ def canonical_uri(path: str) -> str:
97
+ """
98
+ Build the canonical URI for a request path.
99
+
100
+ :param path: The request path, e.g. ``/my-bucket/key name``.
101
+
102
+ :returns: The canonical URI; ``/`` when the path is empty.
103
+ """
104
+ if path is None or len(path) == 0:
105
+ rtnval = "/"
106
+ return rtnval
107
+
108
+ rtnval = uri_encode(path, encode_slash=False)
109
+ return rtnval
110
+
111
+
112
+ def canonical_query_string(params: Optional[Mapping[str, object]]) -> str:
113
+ """
114
+ Build the canonical query string.
115
+
116
+ Parameters are sorted by encoded name, then by encoded value, and a
117
+ parameter with no value still carries its ``=``.
118
+
119
+ :param params: The query parameters, or None.
120
+
121
+ :returns: The canonical query string, empty when there are none.
122
+ """
123
+ if params is None or len(params) == 0:
124
+ rtnval = ""
125
+ return rtnval
126
+
127
+ pairs = []
128
+ for name, value in params.items():
129
+ encoded_name = uri_encode(str(name))
130
+ if value is None:
131
+ encoded_value = ""
132
+ else:
133
+ encoded_value = uri_encode(str(value))
134
+ pairs.append((encoded_name, encoded_value))
135
+
136
+ pairs.sort()
137
+
138
+ rtnval = "&".join(
139
+ ["{}={}".format(name, value) for name, value in pairs])
140
+ return rtnval
141
+
142
+
143
+ def canonical_headers(headers: Mapping[str, str]) -> Tuple[str, str]:
144
+ """
145
+ Build the canonical headers block and the signed-header list.
146
+
147
+ Header names are lowercased, values have surrounding whitespace
148
+ trimmed and internal runs collapsed, and the whole set is sorted by
149
+ name.
150
+
151
+ :param headers: The headers to sign.
152
+
153
+ :returns: A ``(canonical_headers, signed_headers)`` pair.
154
+ """
155
+ normalized: Dict[str, str] = {}
156
+ for name, value in headers.items():
157
+ lowered = name.lower().strip()
158
+ collapsed = " ".join(str(value).split())
159
+ normalized[lowered] = collapsed
160
+
161
+ names = sorted(normalized.keys())
162
+
163
+ canonical = "".join(
164
+ ["{}:{}\n".format(name, normalized[name]) for name in names])
165
+ signed = ";".join(names)
166
+
167
+ rtnval = (canonical, signed)
168
+ return rtnval
169
+
170
+
171
+ def credential_scope(*, datestamp: str, region: str, service: str) -> str:
172
+ """
173
+ Build the credential scope a signature is bound to.
174
+
175
+ :param datestamp: The ``YYYYMMDD`` date.
176
+ :param region: The region name.
177
+ :param service: The service name, e.g. ``s3``.
178
+
179
+ :returns: The scope string.
180
+ """
181
+ rtnval = "{}/{}/{}/{}".format(datestamp, region, service, TERMINATOR)
182
+ return rtnval
183
+
184
+
185
+ def signing_key(*, secret_key: str, datestamp: str, region: str,
186
+ service: str) -> bytes:
187
+ """
188
+ Derive the signing key for a date, region and service.
189
+
190
+ The key is a chain of HMACs starting from the secret, which is what
191
+ makes a leaked signature useless outside its scope: it is valid only
192
+ for that one day, region and service.
193
+
194
+ :param secret_key: The secret access key.
195
+ :param datestamp: The ``YYYYMMDD`` date.
196
+ :param region: The region name.
197
+ :param service: The service name.
198
+
199
+ :returns: The derived signing key.
200
+ """
201
+ initial = ("AWS4" + secret_key).encode("utf-8")
202
+ date_key = _hmac_sha256(initial, datestamp)
203
+ region_key = _hmac_sha256(date_key, region)
204
+ service_key = _hmac_sha256(region_key, service)
205
+ rtnval = _hmac_sha256(service_key, TERMINATOR)
206
+ return rtnval
207
+
208
+
209
+ class SigV4Signer:
210
+ """
211
+ Signs requests with AWS Signature Version 4.
212
+
213
+ :ivar access_key: The access key id.
214
+ :ivar region: The region the signature is scoped to.
215
+ :ivar service: The service the signature is scoped to.
216
+ """
217
+
218
+ def __init__(self, *, access_key: str, secret_key: str, region: str,
219
+ service: str,
220
+ session_token: Optional[str] = None) -> None:
221
+ """
222
+ Construct a SigV4Signer.
223
+
224
+ :param access_key: The access key id.
225
+ :param secret_key: The secret access key.
226
+ :param region: The region name, e.g. ``us-east-1`` or ``nyc3``.
227
+ :param service: The service name, e.g. ``s3``.
228
+ :param session_token: Optional session token, for temporary
229
+ credentials.
230
+ """
231
+ self._access_key: str = access_key
232
+ self._secret_key: str = secret_key
233
+ self._region: str = region
234
+ self._service: str = service
235
+ self._session_token: Optional[str] = session_token
236
+ return
237
+
238
+ @property
239
+ def access_key(self) -> str:
240
+ """
241
+ Return the access key id.
242
+
243
+ :returns: The access key id.
244
+ """
245
+ rtnval = self._access_key
246
+ return rtnval
247
+
248
+ @property
249
+ def region(self) -> str:
250
+ """
251
+ Return the region the signature is scoped to.
252
+
253
+ :returns: The region name.
254
+ """
255
+ rtnval = self._region
256
+ return rtnval
257
+
258
+ @property
259
+ def service(self) -> str:
260
+ """
261
+ Return the service the signature is scoped to.
262
+
263
+ :returns: The service name.
264
+ """
265
+ rtnval = self._service
266
+ return rtnval
267
+
268
+ def sign(self, *, method: str, url: str,
269
+ params: Optional[Mapping[str, object]] = None,
270
+ headers: Optional[Mapping[str, str]] = None,
271
+ body: Optional[bytes] = None,
272
+ payload_hash: Optional[str] = None,
273
+ timestamp: Optional[datetime.datetime] = None
274
+ ) -> Dict[str, str]:
275
+ """
276
+ Compute the headers that authenticate one request.
277
+
278
+ The returned mapping is the COMPLETE set of headers to send: the
279
+ caller's own headers plus ``Host``, ``x-amz-date``,
280
+ ``x-amz-content-sha256``, ``Authorization`` and, when temporary
281
+ credentials are in use, ``x-amz-security-token``. Returning the
282
+ full set rather than just ``Authorization`` matters because the
283
+ signature covers those added headers — sending a different set
284
+ than was signed fails.
285
+
286
+ :param method: The HTTP method.
287
+ :param url: The absolute request URL.
288
+ :param params: The query parameters, which must match what is
289
+ actually sent.
290
+ :param headers: Any caller headers to include in the signature.
291
+ :param body: The request body, used to compute the payload hash.
292
+ :param payload_hash: An explicit payload hash, overriding
293
+ ``body`` — pass :data:`UNSIGNED_PAYLOAD` for a streamed body.
294
+ :param timestamp: The signing time; defaults to now in UTC.
295
+ Injectable so signatures are reproducible in tests.
296
+
297
+ :returns: The headers to send.
298
+ """
299
+ moment = timestamp
300
+ if moment is None:
301
+ moment = datetime.datetime.now(datetime.timezone.utc)
302
+
303
+ amz_date = moment.strftime("%Y%m%dT%H%M%SZ")
304
+ datestamp = moment.strftime("%Y%m%d")
305
+
306
+ parsed = urllib.parse.urlsplit(url)
307
+ host = parsed.netloc
308
+
309
+ effective_hash = payload_hash
310
+ if effective_hash is None:
311
+ payload = body
312
+ if payload is None:
313
+ effective_hash = EMPTY_PAYLOAD_SHA256
314
+ else:
315
+ effective_hash = _sha256_hex(payload)
316
+
317
+ to_sign: Dict[str, str] = {}
318
+ if headers is not None:
319
+ for name, value in headers.items():
320
+ to_sign[name] = value
321
+
322
+ to_sign["host"] = host
323
+ to_sign["x-amz-date"] = amz_date
324
+ to_sign["x-amz-content-sha256"] = effective_hash
325
+ if self._session_token is not None:
326
+ to_sign["x-amz-security-token"] = self._session_token
327
+
328
+ canonical, signed_headers = canonical_headers(to_sign)
329
+
330
+ canonical_request = "\n".join([
331
+ method.upper(),
332
+ canonical_uri(parsed.path),
333
+ canonical_query_string(params),
334
+ canonical,
335
+ signed_headers,
336
+ effective_hash,
337
+ ])
338
+
339
+ scope = credential_scope(datestamp=datestamp, region=self._region,
340
+ service=self._service)
341
+
342
+ string_to_sign = "\n".join([
343
+ ALGORITHM,
344
+ amz_date,
345
+ scope,
346
+ _sha256_hex(canonical_request.encode("utf-8")),
347
+ ])
348
+
349
+ derived = signing_key(secret_key=self._secret_key,
350
+ datestamp=datestamp, region=self._region,
351
+ service=self._service)
352
+
353
+ signature = hmac.new(derived, string_to_sign.encode("utf-8"),
354
+ hashlib.sha256).hexdigest()
355
+
356
+ authorization = (
357
+ "{} Credential={}/{}, SignedHeaders={}, Signature={}".format(
358
+ ALGORITHM, self._access_key, scope, signed_headers,
359
+ signature)
360
+ )
361
+
362
+ rtnval = dict(to_sign)
363
+ rtnval["Authorization"] = authorization
364
+ return rtnval