Debian Codegraph @

ansible_collections/amazon/aws/plugins/plugin_utils/ssm/s3clientmanager.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 try:
7 import boto3
8 except ImportError:
9 pass
10 from typing import Any
11 from typing import Dict
12 from typing import Optional
13 from typing import Tuple
14
15
16 def generate_encryption_settings(
17 bucket_sse_mode: Optional[str], bucket_sse_kms_key_id: Optional[str]
18 ) -> Tuple[Dict, Dict]:
19 """Generate Encryption Settings"""
20 args = {}
21 headers = {}
22 if not bucket_sse_mode:
23 return args, headers
24
25 args["ServerSideEncryption"] = bucket_sse_mode
26 headers["x-amz-server-side-encryption"] = bucket_sse_mode
27 if bucket_sse_mode == "aws:kms" and bucket_sse_kms_key_id:
28 args["SSEKMSKeyId"] = bucket_sse_kms_key_id
29 headers["x-amz-server-side-encryption-aws-kms-key-id"] = bucket_sse_kms_key_id
30 return args, headers
31
32
33 class S3ClientManager:
34 def __init__(self, client: Any) -> None:
35 self._s3_client = client
36
37 @property
38 def client(self) -> Any:
39 return self._s3_client
40
41 @staticmethod
42 def _get_s3_client(
43 access_key_id: Optional[str],
44 secret_key_id: Optional[str],
45 session_token: Optional[str],
46 region_name: str,
47 profile_name: Optional[str],
48 ) -> Any:
49 if not region_name:
50 region_name = "us-east-1"
51 session_args = dict(
52 aws_access_key_id=access_key_id,
53 aws_secret_access_key=secret_key_id,
54 aws_session_token=session_token,
55 region_name=region_name,
56 )
57 if profile_name:
58 session_args["profile_name"] = profile_name
59 session = boto3.session.Session(**session_args)
60 return session.client("s3")
61
62 @staticmethod
63 def get_bucket_endpoint(
64 bucket_name: str,
65 bucket_endpoint_url: Optional[str],
66 access_key_id: Optional[str],
67 secret_key_id: Optional[str],
68 session_token: Optional[str],
69 region_name: Optional[str],
70 profile_name: Optional[str],
71 ) -> Tuple[str, str]:
72 """
73 Fetches the correct S3 endpoint and region for use with our bucket.
74 If we don't explicitly set the endpoint then some commands will use the global
75 endpoint and fail
76 (new AWS regions and new buckets in a region other than the one we're running in)
77 """
78 if not region_name:
79 region_name = "us-east-1"
80 tmp_s3_client = S3ClientManager._get_s3_client(
81 access_key_id, secret_key_id, session_token, region_name, profile_name
82 )
83
84 # Fetch the location of the bucket so we can open a client against the 'right' endpoint
85 # This /should/ always work
86 head_bucket = tmp_s3_client.head_bucket(Bucket=(bucket_name))
87 bucket_region = head_bucket.get("ResponseMetadata", {}).get("HTTPHeaders", {}).get("x-amz-bucket-region", None)
88 if bucket_region is None:
89 bucket_region = "us-east-1"
90
91 if bucket_endpoint_url:
92 return bucket_endpoint_url, bucket_region
93
94 # Create another client for the region the bucket lives in, so we can nab the endpoint URL
95 if bucket_region != region_name:
96 tmp_s3_client = S3ClientManager._get_s3_client(
97 access_key_id, secret_key_id, session_token, bucket_region, profile_name
98 )
99
100 return tmp_s3_client.meta.endpoint_url, tmp_s3_client.meta.region_name
101
102 def get_url(
103 self,
104 client_method: str,
105 bucket_name: str,
106 out_path: str,
107 http_method: str,
108 extra_args: Optional[Dict[str, Any]] = None,
109 ) -> str:
110 """Generate URL for get_object / put_object"""
111
112 params = {"Bucket": bucket_name, "Key": out_path}
113 if extra_args is not None:
114 params.update(extra_args)
115 return self._s3_client.generate_presigned_url(
116 client_method, Params=params, ExpiresIn=3600, HttpMethod=http_method
117 )
118
119 def generate_host_commands(
120 self,
121 bucket_name: str,
122 bucket_sse_mode: Optional[str],
123 bucket_sse_kms_key_id: Optional[str],
124 s3_path: str,
125 in_path: str,
126 out_path: str,
127 is_windows: bool,
128 method: str,
129 ) -> Tuple[str, Optional[Dict[str, str]]]:
130 """
131 Generate commands for the specified bucket and configurations, S3 path, input path, and output path.
132 The function generates a curl/Invoke-WebRequest command to be executed on the managed node.
133 The method 'get' means the controller node wants to retrieve content from the managed node, the corresponding
134 on the managed node is a 'put' command to updload content to the S3 bucket.
135 The method 'put' means the controller node wants to upload content to the managed node, the corresponding
136 on the managed node is a 'get' command to download content to the S3 bucket.
137
138 :param bucket_name: The name of the S3 bucket used for file transfers.
139 :param s3_path: The S3 path to the file to be sent.
140 :param in_path: Input path
141 :param out_path: Output path
142 :param method: The request method to use for the command (can be "get" or "put").
143
144 :returns: A tuple containing a shell command string and optional extra arguments for the PUT request.
145 """
146
147 command = None
148 url = None
149 put_args = None
150 if method == "get":
151 put_args, put_headers = generate_encryption_settings(bucket_sse_mode, bucket_sse_kms_key_id)
152 url = self.get_url("put_object", bucket_name, s3_path, "PUT", extra_args=put_args)
153 if is_windows:
154 put_command_headers = "; ".join([f"'{h}' = '{v}'" for h, v in put_headers.items()])
155 command = (
156 "Invoke-WebRequest -Method PUT "
157 # @{'key' = 'value'; 'key2' = 'value2'}
158 f"-Headers @{{{put_command_headers}}} "
159 f"-InFile '{in_path}' "
160 f"-Uri '{url}' "
161 f"-UseBasicParsing"
162 ) # fmt: skip
163 else:
164 # Due to https://github.com/curl/curl/issues/183 earlier
165 # versions of curl did not create the output file, when the
166 # response was empty. Although this issue was fixed in 2015,
167 # some actively maintained operating systems still use older
168 # versions of it (e.g. CentOS 7)
169 put_command_headers = " ".join([f"-H '{h}: {v}'" for h, v in put_headers.items()])
170 command = (
171 "curl --request PUT "
172 f"{put_command_headers} "
173 f"--upload-file '{in_path}' "
174 f"'{url}'"
175 ) # fmt: skip
176 elif method == "put":
177 url = self.get_url("get_object", bucket_name, s3_path, "GET")
178 if is_windows:
179 command = (
180 "Invoke-WebRequest "
181 f"'{url}' "
182 f"-OutFile '{out_path}'"
183 ) # fmt: skip
184 else:
185 command = (
186 "curl "
187 f"-o '{out_path}' "
188 f"'{url}'"
189 ";"
190 "touch "
191 f"'{out_path}'"
192 ) # fmt: skip
193
194 return command, put_args