File: exceptions.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (655 lines) | stat: -rw-r--r-- 18,389 bytes parent folder | download
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
from typing import TYPE_CHECKING, Any, Optional, Union

from moto.core.exceptions import RESTError

from .notifications import S3NotificationEvent

if TYPE_CHECKING:
    from moto.s3.models import FakeDeleteMarker


ERROR_WITH_BUCKET_NAME = """{% extends 'single_error' %}
{% block extra %}<BucketName>{{ bucket }}</BucketName>{% endblock %}
"""

ERROR_WITH_KEY_NAME = """{% extends 'single_error' %}
{% block extra %}<Key>{{ key }}</Key>{% endblock %}
"""

ERROR_WITH_KEY_AND_VERSION = """{% extends 'single_error' %}
{% block extra %}<Key>{{ key }}</Key><VersionId>{{ version_id }}</VersionId>{% endblock %}
"""

ERROR_WITH_METHOD_AND_RESOURCE = """{% extends 'single_error' %}
{% block extra %}{% if method %}<Method>{{ method }}</Method>{% endif %}{% if resource_type %}<ResourceType>{{ resource_type }}</ResourceType>{% endif %}{% endblock %}
"""

ERROR_WITH_ARGUMENT = """{% extends 'single_error' %}
{% block extra %}<ArgumentName>{{ name }}</ArgumentName>
<ArgumentValue>{{ value }}</ArgumentValue>{% endblock %}
"""

ERROR_WITH_UPLOADID = """{% extends 'single_error' %}
{% block extra %}<UploadId>{{ upload_id }}</UploadId>{% endblock %}
"""

ERROR_WITH_CONDITION_NAME = """{% extends 'single_error' %}
{% block extra %}<Condition>{{ condition }}</Condition>{% endblock %}
"""

ERROR_WITH_RANGE = """{% extends 'single_error' %}
{% block extra %}<ActualObjectSize>{{ actual_size }}</ActualObjectSize>
<RangeRequested>{{ range_requested }}</RangeRequested>{% endblock %}
"""

ERROR_WITH_STORAGE_CLASS = """{% extends 'single_error' %}
{% block extra %}<StorageClass>{{ storage_class }}</StorageClass>{% endblock %}
"""


class S3ClientError(RESTError):
    # S3 API uses <RequestID> as the XML tag in response messages
    request_id_tag_name = "RequestID"

    extended_templates = {
        "bucket_error": ERROR_WITH_BUCKET_NAME,
        "key_error": ERROR_WITH_KEY_NAME,
        "key_version_error": ERROR_WITH_KEY_AND_VERSION,
        "method_resource_error": ERROR_WITH_METHOD_AND_RESOURCE,
        "argument_error": ERROR_WITH_ARGUMENT,
        "error_uploadid": ERROR_WITH_UPLOADID,
        "condition_error": ERROR_WITH_CONDITION_NAME,
        "range_error": ERROR_WITH_RANGE,
        "storage_error": ERROR_WITH_STORAGE_CLASS,
    }
    env = RESTError.extended_environment(extended_templates)

    def __init__(self, *args: Any, **kwargs: Any):
        kwargs.setdefault("template", "single_error")
        super().__init__(*args, **kwargs)


class InvalidArgumentError(S3ClientError):
    code = 400

    def __init__(self, message: str, name: str, value: str, *args: Any, **kwargs: Any):
        kwargs.setdefault("template", "argument_error")
        kwargs["name"] = name
        kwargs["value"] = value
        super().__init__("InvalidArgument", message, *args, **kwargs)


class AccessForbidden(S3ClientError):
    code = 403

    def __init__(self, msg: str):
        super().__init__("AccessForbidden", msg)


class BadRequest(S3ClientError):
    code = 403

    def __init__(self, msg: str):
        super().__init__("BadRequest", msg)


class BucketError(S3ClientError):
    def __init__(self, *args: Any, **kwargs: Any):
        kwargs.setdefault("template", "bucket_error")
        super().__init__(*args, **kwargs)


class BucketAlreadyExists(BucketError):
    code = 409

    def __init__(self, *args: Any, **kwargs: Any):
        kwargs.setdefault("template", "bucket_error")
        super().__init__(
            "BucketAlreadyExists",
            (
                "The requested bucket name is not available. The bucket "
                "namespace is shared by all users of the system. Please "
                "select a different name and try again"
            ),
            *args,
            **kwargs,
        )


class MissingBucket(BucketError):
    code = 404

    def __init__(self, bucket: str):
        super().__init__(
            "NoSuchBucket", "The specified bucket does not exist", bucket=bucket
        )


class MissingKey(S3ClientError):
    code = 404

    def __init__(self, **kwargs: Any):
        kwargs.setdefault("template", "key_error")
        super().__init__("NoSuchKey", "The specified key does not exist.", **kwargs)


class MissingVersion(S3ClientError):
    code = 404

    def __init__(self, **kwargs: Any) -> None:
        kwargs.setdefault("template", "key_version_error")
        super().__init__(
            "NoSuchVersion", "The specified version does not exist.", **kwargs
        )


class MissingInventoryConfig(S3ClientError):
    code = 404

    def __init__(self) -> None:
        super().__init__(
            "NoSuchInventoryConfig",
            "The specified inventory configuration does not exist.",
        )


class InvalidVersion(S3ClientError):
    code = 400

    def __init__(self, version_id: str, *args: Any, **kwargs: Any):
        kwargs.setdefault("template", "argument_error")
        kwargs["name"] = "versionId"
        kwargs["value"] = version_id
        super().__init__(
            "InvalidArgument", "Invalid version id specified", *args, **kwargs
        )


class ObjectNotInActiveTierError(S3ClientError):
    code = 403

    def __init__(self, key_name: Any):
        super().__init__(
            "ObjectNotInActiveTierError",
            "The source object of the COPY operation is not in the active tier and is only stored in Amazon Glacier.",
            Key=key_name,
        )


class InvalidPartOrder(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidPartOrder",
            "The list of parts was not in ascending order. The parts list must be specified in order by part number.",
        )


class InvalidPart(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidPart",
            "One or more of the specified parts could not be found. The part might not have been uploaded, or the specified entity tag might not have matched the part's entity tag.",
        )


class EntityTooSmall(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "EntityTooSmall",
            "Your proposed upload is smaller than the minimum allowed object size.",
        )


class InvalidRequest(S3ClientError):
    code = 400

    def __init__(self, method: str):
        super().__init__(
            "InvalidRequest",
            f"Found unsupported HTTP method in CORS config. Unsupported method is {method}",
        )


class IllegalLocationConstraintException(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "IllegalLocationConstraintException",
            "The unspecified location constraint is incompatible for the region specific endpoint this request was sent to.",
        )


class IncompatibleLocationConstraintException(S3ClientError):
    code = 400

    def __init__(self, location: str) -> None:
        super().__init__(
            "IllegalLocationConstraintException",
            f"The {location} location constraint is incompatible for the region specific endpoint this request was sent to.",
        )


class InvalidLocationConstraintException(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidLocationConstraint",
            "The specified location-constraint is not valid",
        )


class MalformedXML(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "MalformedXML",
            "The XML you provided was not well-formed or did not validate against our published schema",
        )


class MalformedACLError(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "MalformedACLError",
            "The XML you provided was not well-formed or did not validate against our published schema",
        )


class InvalidTargetBucketForLogging(S3ClientError):
    code = 400

    def __init__(self, msg: str):
        super().__init__("InvalidTargetBucketForLogging", msg)


class CrossLocationLoggingProhibitted(S3ClientError):
    code = 403

    def __init__(self) -> None:
        super().__init__(
            "CrossLocationLoggingProhibitted", "Cross S3 location logging not allowed."
        )


class InvalidMaxPartArgument(S3ClientError):
    code = 400

    def __init__(self, arg: str, min_val: int, max_val: int):
        error = f"Argument {arg} must be an integer between {min_val} and {max_val}"
        super().__init__("InvalidArgument", error)


class InvalidMaxPartNumberArgument(InvalidArgumentError):
    code = 400

    def __init__(self, value: int):
        error = "Part number must be an integer between 1 and 10000, inclusive"
        super().__init__(message=error, name="partNumber", value=value)  # type: ignore


class NotAnIntegerException(InvalidArgumentError):
    code = 400

    def __init__(self, name: str, value: int):
        error = f"Provided {name} not an integer or within integer range"
        super().__init__(message=error, name=name, value=value)  # type: ignore


class InvalidNotificationARN(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__("InvalidArgument", "The ARN is not well formed")


class InvalidNotificationDestination(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidArgument",
            "The notification destination service region is not valid for the bucket location constraint",
        )


class InvalidNotificationEvent(S3ClientError):
    code = 400

    def __init__(self, event_name: str) -> None:
        super().__init__(
            "InvalidArgument",
            (
                f"The event '{event_name}' is not supported for notifications. "
                f"Supported events are as follows: {S3NotificationEvent.events()}"
            ),
        )


class InvalidStorageClass(S3ClientError):
    code = 400

    def __init__(self, storage: Optional[str]):
        super().__init__(
            "InvalidStorageClass",
            "The storage class you specified is not valid",
            storage=storage,
        )


class InvalidBucketName(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__("InvalidBucketName", "The specified bucket is not valid.")


class DuplicateTagKeys(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__("InvalidTag", "Cannot provide multiple Tags with the same key")


class S3AccessDeniedError(S3ClientError):
    code = 403

    def __init__(self) -> None:
        super().__init__("AccessDenied", "Access Denied")


class BucketAccessDeniedError(BucketError):
    code = 403

    def __init__(self, bucket: str):
        super().__init__("AccessDenied", "Access Denied", bucket=bucket)


class S3InvalidTokenError(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidToken", "The provided token is malformed or otherwise invalid."
        )


class S3AclAndGrantError(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidRequest",
            "Specifying both Canned ACLs and Header Grants is not allowed",
        )


class BucketInvalidTokenError(BucketError):
    code = 400

    def __init__(self, bucket: str):
        super().__init__(
            "InvalidToken",
            "The provided token is malformed or otherwise invalid.",
            bucket=bucket,
        )


class S3InvalidAccessKeyIdError(S3ClientError):
    code = 403

    def __init__(self) -> None:
        super().__init__(
            "InvalidAccessKeyId",
            "The AWS Access Key Id you provided does not exist in our records.",
        )


class BucketInvalidAccessKeyIdError(S3ClientError):
    code = 403

    def __init__(self, bucket: str):
        super().__init__(
            "InvalidAccessKeyId",
            "The AWS Access Key Id you provided does not exist in our records.",
            bucket=bucket,
        )


class S3SignatureDoesNotMatchError(S3ClientError):
    code = 403

    def __init__(self) -> None:
        super().__init__(
            "SignatureDoesNotMatch",
            "The request signature we calculated does not match the signature you provided. Check your key and signing method.",
        )


class BucketSignatureDoesNotMatchError(S3ClientError):
    code = 403

    def __init__(self, bucket: str):
        super().__init__(
            "SignatureDoesNotMatch",
            "The request signature we calculated does not match the signature you provided. Check your key and signing method.",
            bucket=bucket,
        )


class NoSuchPublicAccessBlockConfiguration(S3ClientError):
    code = 404

    def __init__(self) -> None:
        super().__init__(
            "NoSuchPublicAccessBlockConfiguration",
            "The public access block configuration was not found",
        )


class InvalidPublicAccessBlockConfiguration(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidRequest",
            "Must specify at least one configuration.",
        )


class WrongPublicAccessBlockAccountIdError(S3ClientError):
    code = 403

    def __init__(self) -> None:
        super().__init__("AccessDenied", "Access Denied")


class NoSystemTags(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidTag", "System tags cannot be added/updated by requester"
        )


class NoSuchUpload(S3ClientError):
    code = 404

    def __init__(self, upload_id: Union[int, str], *args: Any, **kwargs: Any):
        kwargs.setdefault("template", "error_uploadid")
        kwargs["upload_id"] = upload_id
        super().__init__(
            "NoSuchUpload",
            "The specified upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed.",
            *args,
            **kwargs,
        )


class PreconditionFailed(S3ClientError):
    code = 412

    def __init__(self, failed_condition: str, **kwargs: Any):
        kwargs.setdefault("template", "condition_error")
        super().__init__(
            "PreconditionFailed",
            "At least one of the pre-conditions you specified did not hold",
            condition=failed_condition,
            **kwargs,
        )


class InvalidRange(S3ClientError):
    code = 416

    def __init__(self, range_requested: str, actual_size: str, **kwargs: Any):
        kwargs.setdefault("template", "range_error")
        super().__init__(
            "InvalidRange",
            "The requested range is not satisfiable",
            range_requested=range_requested,
            actual_size=actual_size,
            **kwargs,
        )


class RangeNotSatisfiable(S3ClientError):
    code = 416

    def __init__(self) -> None:
        super().__init__(RangeNotSatisfiable.code, "Requested Range Not Satisfiable")


class InvalidContinuationToken(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidArgument", "The continuation token provided is incorrect"
        )


class InvalidBucketState(S3ClientError):
    code = 400

    def __init__(self, msg: str):
        super().__init__("InvalidBucketState", msg)


class InvalidObjectState(BucketError):
    code = 403

    def __init__(self, storage_class: Optional[str], **kwargs: Any):
        kwargs.setdefault("template", "storage_error")
        super().__init__(
            error_type="InvalidObjectState",
            message="The operation is not valid for the object's storage class",
            storage_class=storage_class,
            **kwargs,
        )


class LockNotEnabled(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__("InvalidRequest", "Bucket is missing ObjectLockConfiguration")


class MissingRequestBody(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__("MissingRequestBodyError", "Request Body is empty")


class AccessDeniedByLock(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__("AccessDenied", "Access Denied")


class MissingUploadObjectWithObjectLockHeaders(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "MissingUploadObjectWithObjectLockHeaders",
            "Content-MD5 or x-amz-sdk-checksum-algorithm header required to upload an object with a retention period configured using Object Lock",
        )


class BucketNeedsToBeNew(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__("InvalidBucket", "Bucket needs to be empty")


class CopyObjectMustChangeSomething(S3ClientError):
    code = 400

    def __init__(self) -> None:
        super().__init__(
            "InvalidRequest",
            "This copy request is illegal because it is trying to copy an object to itself without changing the object's metadata, storage class, website redirect location or encryption attributes.",
        )


class InvalidFilterRuleName(InvalidArgumentError):
    code = 400

    def __init__(self, value: str):
        super().__init__(
            "filter rule name must be either prefix or suffix",
            "FilterRule.Name",
            value,
        )


class InvalidTagError(S3ClientError):
    code = 400

    def __init__(self, value: str):
        super().__init__("InvalidTag", value)


class ObjectLockConfigurationNotFoundError(S3ClientError):
    code = 404

    def __init__(self) -> None:
        super().__init__(
            "ObjectLockConfigurationNotFoundError",
            "Object Lock configuration does not exist for this bucket",
        )


class HeadOnDeleteMarker(Exception):
    """Marker to indicate that we've called `head_object()` on a FakeDeleteMarker"""

    def __init__(self, marker: "FakeDeleteMarker"):
        self.marker = marker


class MethodNotAllowed(S3ClientError):
    code = 405

    def __init__(self, **kwargs: Any):
        kwargs.setdefault("template", "method_resource_error")
        super().__init__(
            "MethodNotAllowed",
            "The specified method is not allowed against this resource.",
            **kwargs,
        )