Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/_s3/common.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Contributors to the Ansible project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 import functools
9 import typing
10 from typing import cast
11
12 if typing.TYPE_CHECKING:
13 from typing import Any
14 from typing import Callable
15
16 try:
17 # Beware, S3 is a "special" case, it sometimes catches botocore exceptions and
18 # re-raises them as boto3 exceptions.
19 import boto3
20 import botocore
21 except ImportError:
22 pass # Handled by the calling module
23
24
25 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
26 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_httpstatus
27 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_message
28 from ansible_collections.amazon.aws.plugins.module_utils.errors import AWSErrorHandler
29 from ansible_collections.amazon.aws.plugins.module_utils.exceptions import AnsibleAWSError
30
31 IGNORE_S3_DROP_IN_EXCEPTIONS = [
32 "NotSupported",
33 "XNotImplemented",
34 "NotImplemented",
35 "501",
36 ]
37
38
39 class AnsibleS3Error(AnsibleAWSError):
40 """Base exception for S3-related errors."""
41
42 pass
43
44
45 class AnsibleS3Sigv4RequiredError(AnsibleS3Error):
46 """Exception raised when AWS Signature Version 4 is required but not used."""
47
48 pass
49
50
51 class AnsibleS3PermissionsError(AnsibleS3Error):
52 """Exception raised for S3 permission/authorization errors."""
53
54 pass
55
56
57 class AnsibleS3SupportError(AnsibleS3Error):
58 """Exception raised when an S3 operation is not supported by the cloud provider."""
59
60 pass
61
62
63 class AnsibleS3ACLSupportError(AnsibleS3SupportError):
64 """Exception raised when an S3 operation is specifically due to ACLs not being supported."""
65
66 pass
67
68
69 class AnsibleS3RegionSupportError(AnsibleS3SupportError):
70 """Exception raised when an S3 feature is not supported in the current region."""
71
72 pass
73
74
75 class S3ErrorHandler(AWSErrorHandler):
76 """
77 Error handler for S3 operations with S3-specific exception handling.
78
79 Extends AWSErrorHandler to provide custom error handling for S3-specific
80 error codes and S3-compatible services.
81 """
82
83 _CUSTOM_EXCEPTION = AnsibleS3Error
84
85 @classmethod
86 def _is_missing(cls) -> Callable:
87 """
88 Check if a boto3 exception indicates a missing/not found resource.
89
90 Returns:
91 A matcher function for boto3 error codes indicating missing resources.
92 """
93 return is_boto3_error_code(
94 [
95 "404",
96 "NoSuchTagSet",
97 "NoSuchTagSetError",
98 "ObjectLockConfigurationNotFoundError",
99 "NoSuchBucketPolicy",
100 "ServerSideEncryptionConfigurationNotFoundError",
101 "NoSuchBucket",
102 "NoSuchPublicAccessBlockConfiguration",
103 "OwnershipControlsNotFoundError",
104 "NoSuchOwnershipControls",
105 ]
106 )
107
108 @classmethod
109 def common_error_handler(cls, description: str) -> Callable:
110 """
111 Decorator for S3 operations that provides comprehensive error handling.
112
113 Catches and converts boto3 exceptions to appropriate AnsibleS3 exceptions,
114 including handling for permission errors, unsupported operations on S3-compatible
115 services, and signature version requirements.
116
117 Parameters:
118 description (str): Human-readable description of the operation for error messages.
119
120 Returns:
121 Decorated function with S3-specific error handling.
122 """
123
124 def wrapper(func: Callable) -> Callable:
125 parent_class = cast(AWSErrorHandler, super(S3ErrorHandler, cls))
126
127 @parent_class.common_error_handler(description)
128 @functools.wraps(func)
129 def handler(*args: Any, **kwargs: Any) -> Any:
130 try:
131 return func(*args, **kwargs)
132 except is_boto3_error_code(["403", "AccessDenied"]) as e:
133 # FUTURE: there's a case to be made that this moves up into AWSErrorHandler
134 # for now, we'll handle this just for S3, but wait and see if it pops up in too
135 # many other places
136 raise AnsibleS3PermissionsError(
137 message=f"Failed to {description} (permission denied)", exception=e
138 ) from e
139 except is_boto3_error_httpstatus(403) as e: # pylint: disable=duplicate-except
140 # FUTURE: there's a case to be made that this moves up into AWSErrorHandler
141 # for now, we'll handle this just for S3, but wait and see if it pops up in too
142 # many other places
143 raise AnsibleS3PermissionsError(
144 message=f"Failed to {description} (permission denied)", exception=e
145 ) from e
146 except is_boto3_error_message( # pylint: disable=duplicate-except
147 "require AWS Signature Version 4"
148 ) as e:
149 raise AnsibleS3Sigv4RequiredError(
150 message=f"Failed to {description} (not supported by cloud)", exception=e
151 ) from e
152 except is_boto3_error_code("AccessControlListNotSupported") as e: # pylint: disable=duplicate-except
153 # This error is more likely to be specifically related to the bucket
154 raise AnsibleS3ACLSupportError(
155 message=f"Failed to {description} (not supported by bucket)", exception=e
156 ) from e
157 except is_boto3_error_code(IGNORE_S3_DROP_IN_EXCEPTIONS) as e: # pylint: disable=duplicate-except
158 # Unlike most of our modules, we attempt to handle non-AWS clouds. For read-only
159 # actions we sometimes need the ability to ignore unsupported features.
160 raise AnsibleS3SupportError(
161 message=f"Failed to {description} (not supported by cloud)", exception=e
162 ) from e
163 except is_boto3_error_httpstatus(501) as e: # pylint: disable=duplicate-except
164 # Unlike most of our modules, we attempt to handle non-AWS clouds. For read-only
165 # actions we sometimes need the ability to ignore unsupported features.
166 raise AnsibleS3SupportError(
167 message=f"Failed to {description} (not supported by cloud)", exception=e
168 ) from e
169 except botocore.exceptions.EndpointConnectionError as e:
170 raise cls._CUSTOM_EXCEPTION(
171 message=f"Failed to {description} - Invalid endpoint provided", exception=e
172 ) from e
173 except boto3.exceptions.Boto3Error as e:
174 raise cls._CUSTOM_EXCEPTION(message=f"Failed to {description}", exception=e) from e
175
176 return handler
177
178 return wrapper