pycraftbox-aws 4.0.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,5 @@
1
+ """AWS session, role, pagination and S3 utilities."""
2
+
3
+ from .helper import AwsHelper, Role, SessionDescriptor
4
+
5
+ __all__ = ["AwsHelper", "Role", "SessionDescriptor"]
@@ -0,0 +1,504 @@
1
+ from dataclasses import dataclass
2
+ import logging
3
+ from typing import Any, Callable, Dict, Generator, List, Tuple, Union, Optional
4
+ from datetime import datetime
5
+ import boto3
6
+ import jmespath
7
+ from botocore.credentials import Credentials
8
+ from pathlib import PurePosixPath, Path
9
+ from collections import namedtuple
10
+ from boto3 import Session
11
+ import re
12
+
13
+ ROLE_TO_ASSUME_FMT = "arn:aws:iam::{!s}:role/{!s}"
14
+
15
+ # There is no type in boto so just define here some alias for the type used
16
+ StsClient = Any
17
+ S3Client = Any
18
+
19
+
20
+ """: A tuple with:
21
+ - The last session obtained
22
+ - The STS cli from the last session
23
+ - The credentials used in this session
24
+ - The account id of the last session.
25
+ """
26
+
27
+
28
+ @dataclass
29
+ class SessionDescriptor:
30
+ session: Session
31
+ sts_cli: StsClient
32
+ credentials: Credentials
33
+ account_id: str
34
+
35
+
36
+ class Role(object):
37
+ """Describe a role to assume."""
38
+
39
+ def __init__(
40
+ self,
41
+ *,
42
+ role_name: str,
43
+ account_id: str = "",
44
+ profile_name: str = "",
45
+ session_name: str = "",
46
+ ):
47
+ """Create the role to assume
48
+
49
+ Args:
50
+ role_name (str): The role name
51
+ account_id (str, optional): Account id
52
+ profile_name (str, optional): a profile to use to assume the role
53
+ session_name (str, optional): a session name for the assume role.
54
+ """
55
+ self.account_id: str = account_id
56
+ self.role_name: str = role_name
57
+ self.profile_name: str = profile_name
58
+ self.session_name: str = session_name
59
+
60
+
61
+ class AwsHelper(object):
62
+ """Helper class to deal with boto3 operations"""
63
+
64
+ logger = logging.getLogger(__name__)
65
+
66
+ @classmethod
67
+ def get_session(
68
+ cls,
69
+ *,
70
+ aws_session: Optional[boto3.Session] = None,
71
+ aws_session_name: str = "",
72
+ aws_region: str = "eu-west-1",
73
+ aws_profile: Optional[str] = None,
74
+ aws_access_key_id: Optional[str] = None,
75
+ aws_secret_access_key: Optional[str] = None,
76
+ aws_session_token: Optional[str] = None,
77
+ roles_to_assume: List[Role] = [],
78
+ sessionDuration: int = 3600,
79
+ verify: str | bool = True,
80
+ ) -> SessionDescriptor:
81
+ """
82
+ get a boto session.
83
+
84
+ The Session is initiated from the provided credentials and if roles are provided then performs a sequence
85
+ of assume roles on each role in the list of Roles in the order they are provided.
86
+
87
+ If a session is provided we will return it if no roles are requested (strange request) otherwise it will
88
+ be used to make the first assume role of the sequence.
89
+
90
+ To acquire the first role we use a session obtained in the following order:
91
+ - The session given as parameter if there is one.
92
+ - A session obtained with the profile of the first role if there is such a role and if it has a profile
93
+ - A session obtained with one of the credentials given as parameter chosen in the following order:
94
+ - First we use the aws_profile parameter if it is not None
95
+ - If there is no profile we use the credentials provided as parameters (aws_access_key_id,aws_secret_access_key and aws_session_token)
96
+ if they are not None
97
+ - then try to use the aws credentials variables AWS_ACCESS_KEY_ID and
98
+ AWS_SECRET_ACCESS_KEY if they are found
99
+ - then use the default Session with the hope that we are running on a AWS resource that has a
100
+ role authorized to make the further actions. Or with the hope that the credentials are found in
101
+ the environment variable or that a default profile exists.
102
+
103
+ For any subsequent role we will use the current STS credentials to obtain the next role unless a profile
104
+ is given in the role. In this case the given profile will be used.
105
+
106
+ If for any role there is no account id provided then the assume role will be done on the account of the
107
+ previously obtained session or the given session for the first round if one is provided.
108
+
109
+ Args:
110
+ aws_session (Session): an existing boto3 session
111
+ aws_session_name (str) : a string that will be used to create the session name for each assume role
112
+ aws_region (str) : the aws region when to perform the actions
113
+ aws_profile (str) : an aws profile to use as first credentials.
114
+ aws_access_key_id (str) : an access key to use as first credentials.
115
+ aws_secret_access_key (str) : an secret key to use as first credentials.
116
+ aws_session_token (str) : an token to use as first credentials.
117
+ role_to_assume (List[ROle]) : the list of role to assume.
118
+ sessionDuration : see DurationSeconds of boto3 sts.assume_role
119
+
120
+ Returns:
121
+ A SessionDescriptor
122
+ """
123
+ # init the creds for the first session.
124
+ cur_creds = Credentials(
125
+ access_key=aws_access_key_id, # type: ignore
126
+ secret_key=aws_secret_access_key, # type: ignore
127
+ token=aws_session_token,
128
+ )
129
+
130
+ # variables for the loop, res will contain the value to return.
131
+ role_pos = 0
132
+ last_role_pos = len(roles_to_assume) - 1
133
+ res = None
134
+ while True:
135
+ # if we will need to assume a next role and a profile is given for it then we will use it to assume the requested role.
136
+ if role_pos <= last_role_pos and roles_to_assume[role_pos].profile_name:
137
+ aws_profile = roles_to_assume[0].profile_name
138
+
139
+ # get the session (if one session is provided (attribute aws_session not null) we will get it back along with account_id and the its associated credentials)
140
+ session_desc = cls.get_session_from_creds(
141
+ aws_session=aws_session,
142
+ aws_region=aws_region,
143
+ aws_profile=aws_profile,
144
+ aws_access_key_id=cur_creds.access_key,
145
+ aws_secret_access_key=cur_creds.secret_key,
146
+ aws_session_token=cur_creds.token,
147
+ verify=verify,
148
+ )
149
+
150
+ # if we reach the last role or there was no role then that's enough for us.
151
+ if role_pos > last_role_pos:
152
+ res = session_desc
153
+ break
154
+
155
+ # otherwise we are going to assume the next role.
156
+ else:
157
+ cur_role = roles_to_assume[role_pos]
158
+
159
+ # if there is an account Id in the role we will use it for the assume role
160
+ # otherwise we use the current account ID
161
+ if cur_role.account_id:
162
+ next_account_id = cur_role.account_id
163
+ else:
164
+ next_account_id = session_desc.account_id
165
+
166
+ # get a session name
167
+ if cur_role.session_name:
168
+ next_session_name = cur_role.session_name
169
+ else:
170
+ next_session_name = f"{aws_session_name}.{role_pos}"
171
+
172
+ # build role arn and call sts assume_role
173
+ role_arn = ROLE_TO_ASSUME_FMT.format(next_account_id, cur_role.role_name)
174
+ cls.logger.info(
175
+ f"going to assuming role {role_arn} on account {next_account_id}"
176
+ )
177
+ sts_creds = session_desc.sts_cli.assume_role(
178
+ RoleArn=role_arn,
179
+ RoleSessionName=next_session_name,
180
+ DurationSeconds=sessionDuration,
181
+ )
182
+
183
+ # get current credentials that will be used to create the next session.
184
+ cur_creds = Credentials(
185
+ access_key=sts_creds["Credentials"]["AccessKeyId"],
186
+ secret_key=sts_creds["Credentials"]["SecretAccessKey"],
187
+ token=sts_creds["Credentials"]["SessionToken"],
188
+ )
189
+
190
+ # for next call we get rid of this profile , if we find another one in one of the next role we will use
191
+ # this new one.
192
+ # idem for the aws_session parameter
193
+ aws_profile = ""
194
+ aws_session = None
195
+
196
+ # and we increment the role position
197
+ role_pos += 1
198
+
199
+ return res
200
+
201
+ @classmethod
202
+ def get_session_from_creds(
203
+ cls,
204
+ *,
205
+ aws_region: str = "eu-west-1",
206
+ aws_session: Optional[boto3.Session] = None,
207
+ aws_profile: Optional[str] = None,
208
+ aws_access_key_id: Optional[str] = None,
209
+ aws_secret_access_key: Optional[str] = None,
210
+ aws_session_token: Optional[str] = None,
211
+ verify: str | bool = True,
212
+ ) -> SessionDescriptor:
213
+ """
214
+ Try to get a session by using the provided credentials in this order:
215
+ - The session given as parameter if there is one (not very useful for direct use)
216
+ - A session obtained with the profile provided
217
+ - If there is no profile we use the credentials provided as parameters (aws_access_key_id,aws_secret_access_key and aws_session_token)
218
+ if they are not None
219
+ - A session obtained with the aws credentials variables AWS_ACCESS_KEY_ID and
220
+ AWS_SECRET_ACCESS_KEY if they are found
221
+ - A default Session with the hope that we are running on a AWS resource that has a
222
+ role authorized to make the further actions. Or with the hope that the credentials are found in
223
+ the environment variable or that a default profile exists.
224
+
225
+ Args:
226
+ aws_session (Session): an existing boto3 session
227
+ aws_region (str) : the aws region when to perform the actions
228
+ aws_profile (str) : an aws profile to use as first credentials.
229
+ aws_access_key_id (str) : an access key to use as first credentials.
230
+ aws_secret_access_key (str) : an secret key to use as first credentials.
231
+ aws_session_token (str) : an token to use as first credentials.
232
+
233
+ Returns:
234
+ A SessionDescriptor
235
+ """
236
+ cur_session = None
237
+
238
+ # First use the given session if there is one
239
+ if aws_session:
240
+ cls.logger.info(f"getting aws session existing session ...")
241
+ cur_session = aws_session
242
+
243
+ elif aws_profile:
244
+ # if there is a profile get a session from it.
245
+ cls.logger.info(f"getting aws session from profile: {aws_profile} ...")
246
+ cur_session = boto3.Session(region_name=aws_region, profile_name=aws_profile)
247
+
248
+ elif aws_access_key_id is not None and aws_secret_access_key is not None:
249
+ # then use the aws credentials variables if we have them.
250
+ cls.logger.info("getting aws session from credentials ...")
251
+ session_pars = {
252
+ "region_name": aws_region,
253
+ "aws_access_key_id": aws_access_key_id,
254
+ "aws_secret_access_key": aws_secret_access_key,
255
+ }
256
+ if aws_session_token is not None:
257
+ session_pars["aws_session_token"] = aws_session_token
258
+ cur_session = boto3.Session(**session_pars) # type: ignore
259
+
260
+ else:
261
+ # last just call Session() with the hope that environment contains the security creds.
262
+ cur_session = boto3.Session(region_name=aws_region)
263
+
264
+ # extract credentials from the session.
265
+ session_creds = cur_session.get_credentials()
266
+
267
+ sts_cli = cur_session.client("sts", verify=verify)
268
+ caller = sts_cli.get_caller_identity()
269
+ account_id = caller["Account"]
270
+
271
+ return SessionDescriptor(
272
+ cur_session, sts_cli, session_creds, account_id # type: ignore
273
+ )
274
+
275
+ @classmethod
276
+ def resp_scanner(
277
+ cls,
278
+ *,
279
+ requestor: Callable,
280
+ args: Dict[str, Any] = {},
281
+ selector: Optional[Union[str, jmespath.parser.ParsedResult]] = None,
282
+ request_token: Optional[str] = None,
283
+ response_token: Optional[str] = None,
284
+ split: bool = False,
285
+ ) -> Generator[Any, None, None]:
286
+ """
287
+ Create a generator to iterate among the items returned by a boto3 call. Can be used in replacement of paginator or
288
+ when there is no supported paginator for an operation.
289
+
290
+ if the operation potentially paginates the results (refer to the API documentation to know that) then the response token
291
+ and request token must be provided, they are two string that represent the attribute to read or write in the HTTP response
292
+ or request header:
293
+ - Note that for some of the requests these two parameters are identical. But for some of them
294
+ there are different (see list_objects_v2).
295
+ - The response token is the continuation token name that we need to look at in the API response.
296
+ - The request token is the continuation token name that we need to put in the next request when we
297
+ got a continuation token in the current response.
298
+
299
+ The page size can by passed in args otherwise the boto3 default one will be in used (usually 100)
300
+
301
+ The selector is a jmespath expression used to select the part of the json response that will be returned, if none
302
+ is provided then we return the whole response.
303
+
304
+ if split is true and there is a selector, then the values selected by the selector will be yield one by one as
305
+ they are returned by calling __iter__() on the part of the response returned when applying the selector.
306
+
307
+ Be careful: this is useful if the selector returns the sequence you are
308
+ interesting in, otherwise the result can be unpredictable.
309
+
310
+ Example:
311
+ iter = self.resp_scanner(
312
+ requestor=self.ec2_cli.describe_instances,
313
+ request_token='NextToken',
314
+ response_token='NextToken',
315
+ split=True,
316
+ selector=jmespath.compile('Reservations[].Instances[][]'),
317
+ args = {
318
+ 'Filters':[
319
+ {
320
+ 'Name' : 'instance-state-name',
321
+ 'Values': ['running']
322
+ }
323
+ ]
324
+ }
325
+ )
326
+
327
+ Args:
328
+ requestor (Callable): the method on a boto3cli to call
329
+ args (Dict[str, Any]) : the parameters to splat in the call of requestor
330
+ selector (jmespath.parser.ParsedResult) : a jmespath compiled expression
331
+ request_token (str) : the continuation token name to put in the next request when we find a response token
332
+ response_token (str) : the continuation token name to look at in the response
333
+ split (bool) : when there is a selector indicates that we need to iterate over the selected part of the response.
334
+
335
+ Returns:
336
+ A generator
337
+ """
338
+ # marker is the continuation token value.
339
+ marker = None
340
+
341
+ json_selector = None
342
+ if selector:
343
+ if isinstance(selector, str):
344
+ json_selector = jmespath.compile(selector)
345
+ else:
346
+ json_selector = selector
347
+
348
+ while True:
349
+ # we copy the passed parameters because we can alter them on some round.
350
+ # (I think that it is not necessary, but keep it because usually things are here for a reason even if we don't remember why)
351
+ cur_args = args.copy()
352
+ if marker is not None:
353
+ cur_args[request_token] = marker # type: ignore
354
+ resp = res = requestor(**cur_args)
355
+ if json_selector is not None:
356
+ res = json_selector.search(resp)
357
+ if res is None:
358
+ yield None
359
+ elif not split:
360
+ yield res
361
+ else:
362
+ for item in res:
363
+ yield item
364
+ if (
365
+ response_token is not None
366
+ and response_token in resp
367
+ and len(resp[response_token]) > 0
368
+ ):
369
+ marker = resp[response_token]
370
+ else:
371
+ break
372
+
373
+ @classmethod
374
+ def format_date_parts(cls, target_date: datetime) -> Tuple[str, str, str]:
375
+ year_str = "{0:00d}".format(target_date.year)
376
+ month_str = "{0:00d}".format(target_date.month)
377
+ day_str = "{0:00d}".format(target_date.day)
378
+
379
+ return (year_str, month_str, day_str)
380
+
381
+ @classmethod
382
+ def download_s3obj_to_string(
383
+ cls, *, s3_cli: S3Client, bucket: str, s3_key: str | PurePosixPath
384
+ ) -> str:
385
+ """Download the given s3 object from the source bucket and return its content in a string.
386
+
387
+ Args:
388
+ s3_cli(S3Client): the s3 cli
389
+ prefix: the prefix where the file is located
390
+ file_name: the name of the file.
391
+
392
+ Returns:
393
+ the content of the file as a utf-8 string
394
+ """
395
+ # get_object params that will be splatted.
396
+ download_args = {"Bucket": bucket, "Key": str(PurePosixPath(s3_key))}
397
+ # uploading the file.
398
+ response = s3_cli.get_object(**download_args)
399
+
400
+ status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
401
+
402
+ if status != 200:
403
+ raise Exception("Failed to download S3 key {key}: Status = {status}")
404
+
405
+ cls.logger.info(f"Successful downloaded S3 file {s3_key}: Status - {status}")
406
+ body = response.get("Body")
407
+ content = body.read().decode("utf-8")
408
+ return content
409
+
410
+ @classmethod
411
+ def upload_string_to_s3(
412
+ cls, *, content: str, s3_cli: S3Client, bucket: str, s3_key: str | PurePosixPath
413
+ ) -> None:
414
+ """Upload a buffer to S3."""
415
+ try:
416
+ # put_object() params that will be splatted.
417
+ upload_args = {
418
+ "Bucket": bucket,
419
+ "Key": str(PurePosixPath(s3_key)),
420
+ "Body": bytes(content, "utf-8"),
421
+ }
422
+ # uploading the file.
423
+ cls.logger.info(f"sending key {s3_key} to bucket {bucket}")
424
+ s3_cli.put_object(**upload_args)
425
+ except Exception as e:
426
+ cls.logger.error(e)
427
+ raise e
428
+
429
+ @classmethod
430
+ def _apply_pattern(
431
+ cls, pattern: str | None, items: Generator[Any, None, None]
432
+ ) -> Generator[Any, None, None]:
433
+ regex = None
434
+ if pattern is not None:
435
+ regex = re.compile(pattern)
436
+
437
+ for item in items:
438
+ if regex is not None:
439
+ if regex.match(item):
440
+ yield item
441
+ else:
442
+ yield item
443
+
444
+ @classmethod
445
+ def _normalize_prefix(cls, prefix: Union[str, PurePosixPath, None]) -> str | None:
446
+ if prefix is None:
447
+ return None
448
+
449
+ pp = PurePosixPath(prefix)
450
+ return f"{str(pp)}/"
451
+
452
+ @classmethod
453
+ def list_s3_prefixes(
454
+ cls,
455
+ *,
456
+ s3_cli: S3Client,
457
+ bucket: str,
458
+ parent_prefix: Union[str, PurePosixPath, None] = None,
459
+ pattern: Optional[str] = None,
460
+ ) -> Generator[PurePosixPath, None, None]:
461
+ params: dict[str, Any] = {"Bucket": bucket, "Delimiter": "/"}
462
+
463
+ if parent_prefix:
464
+ params["Prefix"] = cls._normalize_prefix(parent_prefix)
465
+
466
+ resp_iter = AwsHelper.resp_scanner(
467
+ requestor=s3_cli.list_objects_v2,
468
+ request_token="ContinuationToken",
469
+ response_token="NextContinuationToken",
470
+ split=True,
471
+ selector=jmespath.compile("CommonPrefixes[*].Prefix"),
472
+ args=params,
473
+ )
474
+
475
+ for item in cls._apply_pattern(pattern, resp_iter):
476
+ yield PurePosixPath(item)
477
+
478
+ @classmethod
479
+ def list_s3_obj(
480
+ cls,
481
+ *,
482
+ s3_cli: S3Client,
483
+ bucket: str,
484
+ parent_prefix: Union[str, PurePosixPath, None] = None,
485
+ pattern: Optional[str] = None,
486
+ ) -> Generator[PurePosixPath, None, None]:
487
+ params: dict[str, Any] = {"Bucket": bucket, "Delimiter": "/"}
488
+
489
+ if parent_prefix:
490
+ params["Prefix"] = cls._normalize_prefix(parent_prefix)
491
+
492
+ obj_selector = jmespath.compile("Contents[*].Key")
493
+
494
+ resp_iter = AwsHelper.resp_scanner(
495
+ requestor=s3_cli.list_objects_v2,
496
+ request_token="ContinuationToken",
497
+ response_token="NextContinuationToken",
498
+ selector=obj_selector,
499
+ split=True,
500
+ args=params,
501
+ )
502
+
503
+ for item in cls._apply_pattern(pattern, resp_iter):
504
+ yield PurePosixPath(item)
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.5
2
+ Name: pycraftbox-aws
3
+ Version: 4.0.0
4
+ Summary: AWS session, role and S3 utilities for pycraftbox
5
+ Project-URL: Homepage, https://gitlab.com/erch/pycraftbox
6
+ Project-URL: Repository, https://gitlab.com/erch/pycraftbox
7
+ Project-URL: Issues, https://gitlab.com/erch/pycraftbox/-/issues
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: boto3>=1.43.42
10
+ Requires-Dist: jmespath>=1.1.0
@@ -0,0 +1,5 @@
1
+ pycraftbox/aws/__init__.py,sha256=oGLjBfH9YsFJQq_SHEbWVmrcjWxtE0dztKHge-E0AAk,164
2
+ pycraftbox/aws/helper.py,sha256=-nug-ZZqWfwYTZMXMVc21zFim3YNjsLQPDHe_ozWml0,20499
3
+ pycraftbox_aws-4.0.0.dist-info/METADATA,sha256=GyRrYzYGkUpCXZU4oiCNzFA5mopwpZAiM_S27Sdoi90,385
4
+ pycraftbox_aws-4.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ pycraftbox_aws-4.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any