-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
models.py
2947 lines (2539 loc) · 106 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import codecs
import copy
import datetime
import itertools
import json
import os
import string
import sys
import tempfile
import threading
import urllib.parse
from bisect import insort
from importlib import reload
from typing import Any, Dict, Iterator, List, Optional, Set, Tuple, Union
from moto.cloudwatch.models import MetricDatum
from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import (
BaseModel,
CloudFormationModel,
CloudWatchMetricProvider,
)
from moto.core.utils import (
iso_8601_datetime_without_milliseconds_s3,
rfc_1123_datetime,
unix_time,
unix_time_millis,
utcnow,
)
from moto.moto_api._internal import mock_random as random
from moto.moto_api._internal.managed_state_model import ManagedState
from moto.s3.exceptions import (
AccessDeniedByLock,
BadRequest,
BucketAlreadyExists,
BucketNeedsToBeNew,
CopyObjectMustChangeSomething,
CrossLocationLoggingProhibitted,
DaysMustNotProvidedForSelectRequest,
DaysMustProvidedExceptForSelectRequest,
EntityTooSmall,
HeadOnDeleteMarker,
InvalidBucketName,
InvalidNotificationDestination,
InvalidNotificationEvent,
InvalidObjectState,
InvalidPart,
InvalidPublicAccessBlockConfiguration,
InvalidRequest,
InvalidStorageClass,
InvalidTagError,
InvalidTargetBucketForLogging,
MalformedXML,
MissingBucket,
MissingKey,
NoSuchPublicAccessBlockConfiguration,
NoSuchUpload,
ObjectLockConfigurationNotFoundError,
)
from moto.utilities.tagging_service import TaggingService
from moto.utilities.utils import LowercaseDict, md5_hash
from ..events.notifications import send_notification as events_send_notification
from ..settings import (
S3_UPLOAD_PART_MIN_SIZE,
get_s3_default_key_buffer_size,
s3_allow_crossdomain_access,
)
from . import notifications
from .cloud_formation import cfn_to_api_encryption, is_replacement_update
from .select_object_content import parse_query
from .utils import (
ARCHIVE_STORAGE_CLASSES,
LOGGING_SERVICE_PRINCIPAL,
STORAGE_CLASS,
CaseInsensitiveDict,
_VersionedKeyStore,
compute_checksum,
)
MAX_BUCKET_NAME_LENGTH = 63
MIN_BUCKET_NAME_LENGTH = 3
UPLOAD_ID_BYTES = 43
DEFAULT_TEXT_ENCODING = sys.getdefaultencoding()
OWNER = "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a"
class FakeDeleteMarker(BaseModel):
def __init__(self, key: "FakeKey"):
self.key = key
self.name = key.name
self.last_modified = utcnow()
self._version_id = str(random.uuid4())
@property
def last_modified_ISO8601(self) -> str:
return iso_8601_datetime_without_milliseconds_s3(self.last_modified) # type: ignore
@property
def version_id(self) -> str:
return self._version_id
class FakeKey(BaseModel, ManagedState):
def __init__(
self,
name: str,
value: bytes,
account_id: str,
storage: Optional[str] = "STANDARD",
etag: Optional[str] = None,
is_versioned: bool = False,
version_id: Optional[str] = None,
max_buffer_size: Optional[int] = None,
multipart: Optional["FakeMultipart"] = None,
bucket_name: Optional[str] = None,
encryption: Optional[str] = None,
kms_key_id: Optional[str] = None,
bucket_key_enabled: Any = None,
lock_mode: Optional[str] = None,
lock_legal_status: Optional[str] = None,
lock_until: Optional[str] = None,
checksum_value: Optional[str] = None,
):
ManagedState.__init__(
self,
"s3::keyrestore",
transitions=[
(None, "IN_PROGRESS"),
("IN_PROGRESS", "RESTORED"),
],
)
self.name = name
self.account_id = account_id
self.last_modified = utcnow()
self.acl: Optional[FakeAcl] = get_canned_acl("private")
self.website_redirect_location: Optional[str] = None
self.checksum_algorithm = None
self._storage_class: Optional[str] = storage if storage else "STANDARD"
self._metadata = LowercaseDict()
self._expiry: Optional[datetime.datetime] = None
self._etag = etag
self._version_id = version_id
self._is_versioned = is_versioned
self.multipart = multipart
self.bucket_name = bucket_name
self._max_buffer_size = (
max_buffer_size if max_buffer_size else get_s3_default_key_buffer_size()
)
self._value_buffer = tempfile.SpooledTemporaryFile(self._max_buffer_size)
self.disposed = False
self.value = value # type: ignore
self.lock = threading.Lock()
self.encryption = encryption
self.kms_key_id = kms_key_id
self.bucket_key_enabled = bucket_key_enabled
self.lock_mode = lock_mode
self.lock_legal_status = lock_legal_status
self.lock_until = lock_until
self.checksum_value = checksum_value
# Default metadata values
self._metadata["Content-Type"] = "binary/octet-stream"
def safe_name(self, encoding_type: Optional[str] = None) -> str:
if encoding_type == "url":
return urllib.parse.quote(self.name)
return self.name
@property
def version_id(self) -> str:
return self._version_id or "null"
@property
def value(self) -> bytes:
with self.lock:
self._value_buffer.seek(0)
r = self._value_buffer.read()
r = copy.copy(r)
return r
@property
def arn(self) -> str:
# S3 Objects don't have an ARN, but we do need something unique when creating tags against this resource
return f"arn:aws:s3:::{self.bucket_name}/{self.name}/{self.version_id}"
@value.setter # type: ignore
def value(self, new_value: bytes) -> None:
self._value_buffer.seek(0)
self._value_buffer.truncate()
# Hack for working around moto's own unit tests; this probably won't
# actually get hit in normal use.
if isinstance(new_value, str):
new_value = new_value.encode(DEFAULT_TEXT_ENCODING)
self._value_buffer.write(new_value)
self.contentsize = len(new_value)
@property
def status(self) -> Optional[str]:
previous = self._status
new_status = super().status
if previous != "RESTORED" and new_status == "RESTORED":
s3_backend = s3_backends[self.account_id]["global"]
bucket = s3_backend.get_bucket(self.bucket_name) # type: ignore
notifications.send_event(
self.account_id,
notifications.S3NotificationEvent.OBJECT_RESTORE_COMPLETED_EVENT,
bucket,
key=self,
)
return new_status
@status.setter
def status(self, value: str) -> None:
self._status = value
def set_metadata(self, metadata: Any, replace: bool = False) -> None:
if replace:
self._metadata = {} # type: ignore
self._metadata.update(metadata)
def set_storage_class(self, storage: Optional[str]) -> None:
if storage is not None and storage not in STORAGE_CLASS:
raise InvalidStorageClass(storage=storage)
self._storage_class = storage
def set_expiry(self, expiry: Optional[datetime.datetime]) -> None:
self._expiry = expiry
def set_acl(self, acl: Optional["FakeAcl"]) -> None:
self.acl = acl
def restore(self, days: int) -> None:
self._expiry = utcnow() + datetime.timedelta(days)
s3_backend = s3_backends[self.account_id]["global"]
bucket = s3_backend.get_bucket(self.bucket_name) # type: ignore
notifications.send_event(
self.account_id,
notifications.S3NotificationEvent.OBJECT_RESTORE_POST_EVENT,
bucket,
key=self,
)
@property
def etag(self) -> str:
if self._etag is None:
value_md5 = md5_hash()
self._value_buffer.seek(0)
while True:
block = self._value_buffer.read(16 * 1024 * 1024) # read in 16MB chunks
if not block:
break
value_md5.update(block)
self._etag = value_md5.hexdigest()
return f'"{self._etag}"'
@property
def last_modified_ISO8601(self) -> str:
return iso_8601_datetime_without_milliseconds_s3(self.last_modified) # type: ignore
@property
def last_modified_RFC1123(self) -> str:
# Different datetime formats depending on how the key is obtained
# https://github.com/boto/boto/issues/466
return rfc_1123_datetime(self.last_modified)
@property
def metadata(self) -> LowercaseDict:
return self._metadata
@property
def response_dict(self) -> Dict[str, Any]: # type: ignore[misc]
res: Dict[str, Any] = {
"ETag": self.etag,
"last-modified": self.last_modified_RFC1123,
"content-length": str(self.size),
}
if self.encryption is not None:
res["x-amz-server-side-encryption"] = self.encryption
if self.encryption == "aws:kms" and self.kms_key_id is not None:
res["x-amz-server-side-encryption-aws-kms-key-id"] = self.kms_key_id
if self.encryption == "aws:kms" and self.bucket_key_enabled is not None:
res["x-amz-server-side-encryption-bucket-key-enabled"] = (
self.bucket_key_enabled
)
if self._storage_class != "STANDARD":
res["x-amz-storage-class"] = self._storage_class
if self._expiry is not None:
if self.status == "IN_PROGRESS":
header = 'ongoing-request="true"'
else:
header = f'ongoing-request="false", expiry-date="{self.expiry_date}"'
res["x-amz-restore"] = header
if self._is_versioned:
res["x-amz-version-id"] = str(self.version_id)
if self.checksum_algorithm is not None:
res["x-amz-sdk-checksum-algorithm"] = self.checksum_algorithm
if self.website_redirect_location:
res["x-amz-website-redirect-location"] = self.website_redirect_location
if self.lock_legal_status:
res["x-amz-object-lock-legal-hold"] = self.lock_legal_status
if self.lock_until:
res["x-amz-object-lock-retain-until-date"] = self.lock_until
if self.lock_mode:
res["x-amz-object-lock-mode"] = self.lock_mode
if self.lock_legal_status:
res["x-amz-object-lock-legal-hold"] = self.lock_legal_status
if self.lock_until:
res["x-amz-object-lock-retain-until-date"] = self.lock_until
if self.lock_mode:
res["x-amz-object-lock-mode"] = self.lock_mode
tags = s3_backends[self.account_id]["global"].tagger.get_tag_dict_for_resource(
self.arn
)
if tags:
res["x-amz-tagging-count"] = str(len(tags.keys()))
return res
@property
def size(self) -> int:
return self.contentsize
@property
def storage_class(self) -> Optional[str]:
return self._storage_class
@property
def expiry_date(self) -> Optional[str]:
if self._expiry is not None:
return self._expiry.strftime("%a, %d %b %Y %H:%M:%S GMT")
return None
# Keys need to be pickleable due to some implementation details of boto3.
# Since file objects aren't pickleable, we need to override the default
# behavior. The following is adapted from the Python docs:
# https://docs.python.org/3/library/pickle.html#handling-stateful-objects
def __getstate__(self) -> Dict[str, Any]:
state = self.__dict__.copy()
try:
state["value"] = self.value
except ValueError:
# Buffer is already closed, so we can't reach the data
# Only happens if the key was deleted
state["value"] = ""
del state["_value_buffer"]
del state["lock"]
return state
def __setstate__(self, state: Dict[str, Any]) -> None:
self.__dict__.update({k: v for k, v in state.items() if k != "value"})
self._value_buffer = tempfile.SpooledTemporaryFile(
max_size=self._max_buffer_size
)
self.value = state["value"] # type: ignore
self.lock = threading.Lock()
@property
def is_locked(self) -> bool:
if self.lock_legal_status == "ON":
return True
if self.lock_mode == "COMPLIANCE":
now = utcnow()
try:
until = datetime.datetime.strptime(
self.lock_until,
"%Y-%m-%dT%H:%M:%SZ", # type: ignore
)
except ValueError:
until = datetime.datetime.strptime(
self.lock_until,
"%Y-%m-%dT%H:%M:%S.%fZ", # type: ignore
)
if until > now:
return True
return False
def dispose(self, garbage: bool = False) -> None:
if garbage and not self.disposed:
import warnings
warnings.warn("S3 key was not disposed of in time", ResourceWarning)
try:
self._value_buffer.close()
if self.multipart:
self.multipart.dispose()
except: # noqa: E722 Do not use bare except
pass
self.disposed = True
def __del__(self) -> None:
self.dispose(garbage=True)
class FakeMultipart(BaseModel):
def __init__(
self,
key_name: str,
metadata: CaseInsensitiveDict, # type: ignore
account_id: str,
storage: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
acl: Optional["FakeAcl"] = None,
sse_encryption: Optional[str] = None,
kms_key_id: Optional[str] = None,
):
self.key_name = key_name
self.metadata = metadata
self.account_id = account_id
self.storage = storage
self.tags = tags
self.acl = acl
self.parts: Dict[int, FakeKey] = {}
self.partlist: List[int] = [] # ordered list of part ID's
rand_b64 = base64.b64encode(os.urandom(UPLOAD_ID_BYTES))
self.id = (
rand_b64.decode("utf-8").replace("=", "").replace("+", "").replace("/", "")
)
self.sse_encryption = sse_encryption
self.kms_key_id = kms_key_id
def complete(
self, body: Iterator[Tuple[int, str]]
) -> Tuple[bytes, str, Optional[str]]:
checksum_algo = self.metadata.get("x-amz-checksum-algorithm")
decode_hex = codecs.getdecoder("hex_codec")
total = bytearray()
md5s = bytearray()
checksum = bytearray()
last = None
count = 0
for pn, etag in body:
part = self.parts.get(pn)
part_etag = None
if part is not None:
part_etag = part.etag.replace('"', "")
etag = etag.replace('"', "")
if part is None or part_etag != etag:
raise InvalidPart()
if last is not None and last.contentsize < S3_UPLOAD_PART_MIN_SIZE:
raise EntityTooSmall()
md5s.extend(decode_hex(part_etag)[0]) # type: ignore
total.extend(part.value)
if checksum_algo:
checksum.extend(
compute_checksum(part.value, checksum_algo, encode_base64=False)
)
last = part
count += 1
if count == 0:
raise MalformedXML
full_etag = md5_hash()
full_etag.update(bytes(md5s))
if checksum_algo:
encoded_checksum = compute_checksum(checksum, checksum_algo).decode("utf-8")
else:
encoded_checksum = None
return total, f"{full_etag.hexdigest()}-{count}", encoded_checksum
def set_part(self, part_id: int, value: bytes) -> FakeKey:
if part_id < 1:
raise NoSuchUpload(upload_id=part_id)
key = FakeKey(
part_id,
value,
account_id=self.account_id,
encryption=self.sse_encryption,
kms_key_id=self.kms_key_id, # type: ignore
)
if part_id in self.parts:
# We're overwriting the current part - dispose of it first
self.parts[part_id].dispose()
self.parts[part_id] = key
if part_id not in self.partlist:
insort(self.partlist, part_id)
return key
def list_parts(self, part_number_marker: int, max_parts: int) -> Iterator[FakeKey]:
max_marker = part_number_marker + max_parts
for part_id in self.partlist[part_number_marker:max_marker]:
yield self.parts[part_id]
def dispose(self) -> None:
for part in self.parts.values():
part.dispose()
class FakeGrantee(BaseModel):
def __init__(self, grantee_id: str = "", uri: str = "", display_name: str = ""):
self.id = grantee_id
self.uri = uri
self.display_name = display_name
def __eq__(self, other: Any) -> bool:
if not isinstance(other, FakeGrantee):
return False
return (
self.id == other.id
and self.uri == other.uri
and self.display_name == other.display_name
)
@property
def type(self) -> str:
return "Group" if self.uri else "CanonicalUser"
def __repr__(self) -> str:
return f"FakeGrantee(display_name: '{self.display_name}', id: '{self.id}', uri: '{self.uri}')"
ALL_USERS_GRANTEE = FakeGrantee(uri="http://acs.amazonaws.com/groups/global/AllUsers")
AUTHENTICATED_USERS_GRANTEE = FakeGrantee(
uri="http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
)
LOG_DELIVERY_GRANTEE = FakeGrantee(uri="http://acs.amazonaws.com/groups/s3/LogDelivery")
PERMISSION_FULL_CONTROL = "FULL_CONTROL"
PERMISSION_WRITE = "WRITE"
PERMISSION_READ = "READ"
PERMISSION_WRITE_ACP = "WRITE_ACP"
PERMISSION_READ_ACP = "READ_ACP"
CAMEL_CASED_PERMISSIONS = {
"FULL_CONTROL": "FullControl",
"WRITE": "Write",
"READ": "Read",
"WRITE_ACP": "WriteAcp",
"READ_ACP": "ReadAcp",
}
class FakeGrant(BaseModel):
def __init__(self, grantees: List[FakeGrantee], permissions: List[str]):
self.grantees = grantees
self.permissions = permissions
def __repr__(self) -> str:
return f"FakeGrant(grantees: {self.grantees}, permissions: {self.permissions})"
class FakeAcl(BaseModel):
def __init__(self, grants: Optional[List[FakeGrant]] = None):
self.grants = grants or []
@property
def public_read(self) -> bool:
for grant in self.grants:
if ALL_USERS_GRANTEE in grant.grantees:
if PERMISSION_READ in grant.permissions:
return True
if PERMISSION_FULL_CONTROL in grant.permissions:
return True
return False
def __repr__(self) -> str:
return f"FakeAcl(grants: {self.grants})"
def to_config_dict(self) -> Dict[str, Any]:
"""Returns the object into the format expected by AWS Config"""
data: Dict[str, Any] = {
"grantSet": None, # Always setting this to None. Feel free to change.
"owner": {"displayName": None, "id": OWNER},
}
# Add details for each Grant:
grant_list = []
for grant in self.grants:
permissions = (
grant.permissions
if isinstance(grant.permissions, list)
else [grant.permissions] # type: ignore
)
for permission in permissions:
for grantee in grant.grantees:
if grantee.uri:
grant_list.append(
{
"grantee": grantee.uri.split(
"http://acs.amazonaws.com/groups/s3/"
)[1],
"permission": CAMEL_CASED_PERMISSIONS[permission],
}
)
else:
grant_list.append(
{
"grantee": { # type: ignore
"id": grantee.id,
"displayName": None
if not grantee.display_name
else grantee.display_name,
},
"permission": CAMEL_CASED_PERMISSIONS[permission],
}
)
if grant_list:
data["grantList"] = grant_list
return data
def get_canned_acl(acl: str) -> FakeAcl:
owner_grantee = FakeGrantee(grantee_id=OWNER)
grants = [FakeGrant([owner_grantee], [PERMISSION_FULL_CONTROL])]
if acl == "private":
pass # no other permissions
elif acl == "public-read":
grants.append(FakeGrant([ALL_USERS_GRANTEE], [PERMISSION_READ]))
elif acl == "public-read-write":
grants.append(
FakeGrant([ALL_USERS_GRANTEE], [PERMISSION_READ, PERMISSION_WRITE])
)
elif acl == "authenticated-read":
grants.append(FakeGrant([AUTHENTICATED_USERS_GRANTEE], [PERMISSION_READ]))
elif acl == "bucket-owner-read":
pass # TODO: bucket owner ACL
elif acl == "bucket-owner-full-control":
pass # TODO: bucket owner ACL
elif acl == "aws-exec-read":
pass # TODO: bucket owner, EC2 Read
elif acl == "log-delivery-write":
grants.append(
FakeGrant([LOG_DELIVERY_GRANTEE], [PERMISSION_READ_ACP, PERMISSION_WRITE])
)
else:
assert False, f"Unknown canned acl: {acl}"
return FakeAcl(grants=grants)
class LifecycleFilter(BaseModel):
def __init__(
self,
prefix: Optional[str] = None,
tag: Optional[Tuple[str, str]] = None,
and_filter: Optional["LifecycleAndFilter"] = None,
):
self.prefix = prefix
(self.tag_key, self.tag_value) = tag if tag else (None, None)
self.and_filter = and_filter
def to_config_dict(self) -> Dict[str, Any]:
if self.prefix is not None:
return {
"predicate": {"type": "LifecyclePrefixPredicate", "prefix": self.prefix}
}
elif self.tag_key:
return {
"predicate": {
"type": "LifecycleTagPredicate",
"tag": {"key": self.tag_key, "value": self.tag_value},
}
}
else:
return {
"predicate": {
"type": "LifecycleAndOperator",
"operands": self.and_filter.to_config_dict(), # type: ignore
}
}
class LifecycleAndFilter(BaseModel):
def __init__(
self, prefix: Optional[str] = None, tags: Optional[Dict[str, str]] = None
):
self.prefix = prefix
self.tags = tags or {}
def to_config_dict(self) -> List[Dict[str, Any]]:
data: List[Dict[str, Any]] = []
if self.prefix is not None:
data.append({"type": "LifecyclePrefixPredicate", "prefix": self.prefix})
for key, value in self.tags.items():
data.append(
{"type": "LifecycleTagPredicate", "tag": {"key": key, "value": value}}
)
return data
class LifecycleTransition(BaseModel):
def __init__(
self,
date: Optional[str] = None,
days: Optional[int] = None,
storage_class: Optional[str] = None,
):
self.date = date
self.days = days
self.storage_class = storage_class
def to_config_dict(self) -> Dict[str, Any]:
config: Dict[str, Any] = {}
if self.date is not None:
config["date"] = self.date
if self.days is not None:
config["days"] = self.days
if self.storage_class is not None:
config["storageClass"] = self.storage_class
return config
class LifeCycleNoncurrentVersionTransition(BaseModel):
def __init__(
self, days: int, storage_class: str, newer_versions: Optional[int] = None
):
self.newer_versions = newer_versions
self.days = days
self.storage_class = storage_class
def to_config_dict(self) -> Dict[str, Any]:
config: Dict[str, Any] = {}
if self.newer_versions is not None:
config["newerNoncurrentVersions"] = self.newer_versions
if self.days is not None:
config["noncurrentDays"] = self.days
if self.storage_class is not None:
config["storageClass"] = self.storage_class
return config
class LifecycleRule(BaseModel):
def __init__(
self,
rule_id: Optional[str] = None,
prefix: Optional[str] = None,
lc_filter: Optional[LifecycleFilter] = None,
status: Optional[str] = None,
expiration_days: Optional[str] = None,
expiration_date: Optional[str] = None,
transitions: Optional[List[LifecycleTransition]] = None,
expired_object_delete_marker: Optional[str] = None,
nve_noncurrent_days: Optional[str] = None,
noncurrent_version_transitions: Optional[
List[LifeCycleNoncurrentVersionTransition]
] = None,
aimu_days: Optional[str] = None,
):
self.id = rule_id
self.prefix = prefix
self.filter = lc_filter
self.status = status
self.expiration_days = expiration_days
self.expiration_date = expiration_date
self.transitions = transitions
self.expired_object_delete_marker = expired_object_delete_marker
self.nve_noncurrent_days = nve_noncurrent_days
self.noncurrent_version_transitions = noncurrent_version_transitions
self.aimu_days = aimu_days
def to_config_dict(self) -> Dict[str, Any]:
"""Converts the object to the AWS Config data dict.
:param kwargs:
:return:
"""
lifecycle_dict: Dict[str, Any] = {
"id": self.id,
"prefix": self.prefix,
"status": self.status,
"expirationInDays": int(self.expiration_days)
if self.expiration_days
else None,
"expiredObjectDeleteMarker": self.expired_object_delete_marker,
"noncurrentVersionExpirationInDays": -1 or int(self.nve_noncurrent_days), # type: ignore
"expirationDate": self.expiration_date,
}
if self.transitions:
lifecycle_dict["transitions"] = [
t.to_config_dict() for t in self.transitions
]
else:
lifecycle_dict["transitions"] = None
if self.noncurrent_version_transitions:
lifecycle_dict["noncurrentVersionTransitions"] = [
t.to_config_dict() for t in self.noncurrent_version_transitions
]
else:
lifecycle_dict["noncurrentVersionTransitions"] = None
if self.aimu_days:
lifecycle_dict["abortIncompleteMultipartUpload"] = {
"daysAfterInitiation": self.aimu_days
}
else:
lifecycle_dict["abortIncompleteMultipartUpload"] = None
# Format the filter:
if self.prefix is None and self.filter is None:
lifecycle_dict["filter"] = {"predicate": None}
elif self.prefix:
lifecycle_dict["filter"] = None
else:
lifecycle_dict["filter"] = self.filter.to_config_dict() # type: ignore
return lifecycle_dict
class CorsRule(BaseModel):
def __init__(
self,
allowed_methods: Any,
allowed_origins: Any,
allowed_headers: Any = None,
expose_headers: Any = None,
max_age_seconds: Any = None,
):
self.allowed_methods = (
[allowed_methods] if isinstance(allowed_methods, str) else allowed_methods
)
self.allowed_origins = (
[allowed_origins] if isinstance(allowed_origins, str) else allowed_origins
)
self.allowed_headers = (
[allowed_headers] if isinstance(allowed_headers, str) else allowed_headers
)
self.exposed_headers = (
[expose_headers] if isinstance(expose_headers, str) else expose_headers
)
self.max_age_seconds = max_age_seconds
class Notification(BaseModel):
def __init__(
self,
arn: str,
events: List[str],
filters: Optional[Dict[str, Any]] = None,
notification_id: Optional[str] = None,
):
self.id = notification_id or "".join(
random.choice(string.ascii_letters + string.digits) for _ in range(50)
)
self.arn = arn
for event_name in events:
if not notifications.S3NotificationEvent.is_event_valid(event_name):
raise InvalidNotificationEvent(event_name)
self.events = events
self.filters = filters if filters else {}
def _event_matches(self, event_name: str) -> bool:
if event_name in self.events:
return True
# s3:ObjectCreated:Put --> s3:ObjectCreated:*
wildcard = ":".join(event_name.rsplit(":")[0:2]) + ":*"
if wildcard in self.events:
return True
return False
def _key_matches(self, key_name: str) -> bool:
if "S3Key" not in self.filters:
return True
_filters = {f["Name"]: f["Value"] for f in self.filters["S3Key"]["FilterRule"]}
prefix_matches = "prefix" not in _filters or key_name.startswith(
_filters["prefix"]
)
suffix_matches = "suffix" not in _filters or key_name.endswith(
_filters["suffix"]
)
return prefix_matches and suffix_matches
def matches(self, event_name: str, key_name: str) -> bool:
if self._event_matches(event_name):
if self._key_matches(key_name):
return True
return False
def to_config_dict(self) -> Dict[str, Any]:
# Type and ARN will be filled in by NotificationConfiguration's to_config_dict:
data: Dict[str, Any] = {"events": [event for event in self.events]}
if self.filters:
data["filter"] = {
"s3KeyFilter": {
"filterRules": [
{"name": fr["Name"], "value": fr["Value"]}
for fr in self.filters["S3Key"]["FilterRule"]
]
}
}
else:
data["filter"] = None
# Not sure why this is a thing since AWS just seems to return this as filters ¯\_(ツ)_/¯
data["objectPrefixes"] = []
return data
class NotificationConfiguration(BaseModel):
def __init__(
self,
topic: Optional[List[Dict[str, Any]]] = None,
queue: Optional[List[Dict[str, Any]]] = None,
cloud_function: Optional[List[Dict[str, Any]]] = None,
event_bridge: Optional[Dict[str, Any]] = None,
):
self.topic = (
[
Notification(
t["Topic"],
t["Event"],
filters=t.get("Filter"),
notification_id=t.get("Id"),
)
for t in topic
]
if topic
else []
)
self.queue = (
[
Notification(
q["Queue"],
q["Event"],
filters=q.get("Filter"),
notification_id=q.get("Id"),
)
for q in queue
]
if queue
else []
)
self.cloud_function = (
[
Notification(
c["CloudFunction"],
c["Event"],
filters=c.get("Filter"),
notification_id=c.get("Id"),
)
for c in cloud_function
]
if cloud_function
else []
)
self.event_bridge = event_bridge
def to_config_dict(self) -> Dict[str, Any]:
data: Dict[str, Any] = {"configurations": {}}
for topic in self.topic:
topic_config = topic.to_config_dict()
topic_config["topicARN"] = topic.arn
topic_config["type"] = "TopicConfiguration"
data["configurations"][topic.id] = topic_config
for queue in self.queue:
queue_config = queue.to_config_dict()
queue_config["queueARN"] = queue.arn
queue_config["type"] = "QueueConfiguration"
data["configurations"][queue.id] = queue_config
for cloud_function in self.cloud_function:
cf_config = cloud_function.to_config_dict()
cf_config["queueARN"] = cloud_function.arn
cf_config["type"] = "LambdaConfiguration"
data["configurations"][cloud_function.id] = cf_config
if self.event_bridge is not None:
data["configurations"]["EventBridgeConfiguration"] = self.event_bridge
return data
def convert_str_to_bool(item: Any) -> bool:
"""Converts a boolean string to a boolean value"""
if isinstance(item, str):
return item.lower() == "true"
return False
class PublicAccessBlock(BaseModel):
def __init__(