5
5
6
6
import argparse
7
7
import json
8
+ import logging
8
9
import os
9
10
import subprocess
10
11
import sys
11
12
from functools import partial
13
+ from pathlib import Path
12
14
from urllib .parse import quote_plus
13
15
14
16
from pymongo import MongoClient
15
17
from pymongo .errors import OperationFailure
16
18
17
- HERE = os .path .abspath (os .path .dirname (__file__ ))
19
+ HERE = Path (__file__ ).absolute ().parent
20
+ LOGGER = logging .getLogger (__name__ )
21
+ logging .basicConfig (level = logging .INFO , format = "%(levelname)-8s %(message)s" )
18
22
19
23
20
24
def join (* parts ):
21
25
return os .path .join (* parts ).replace (os .sep , "/" )
22
26
23
27
24
- sys .path .insert (0 , join (HERE , "lib" ))
28
+ sys .path .insert (0 , str (HERE / "lib" ))
25
29
from aws_assign_instance_profile import _assign_instance_policy
26
30
from aws_assume_role import _assume_role
27
31
from aws_assume_web_role import _assume_role_with_web_identity
@@ -35,7 +39,7 @@ def join(*parts):
35
39
_USE_AWS_SECRETS = False
36
40
37
41
try :
38
- with open ( join ( HERE , "aws_e2e_setup.json" )) as fid :
42
+ with ( HERE / "aws_e2e_setup.json" ). open ( ) as fid :
39
43
CONFIG = json .load (fid )
40
44
get_key = partial (_get_key , uppercase = False )
41
45
except FileNotFoundError :
@@ -51,7 +55,7 @@ def run(args, env):
51
55
52
56
def create_user (user , kwargs ):
53
57
"""Create a user and verify access."""
54
- print ("Creating user" , user )
58
+ LOGGER . info ("Creating user %s " , user )
55
59
client = MongoClient (username = "bob" , password = "pwd123" )
56
60
db = client ["$external" ]
57
61
try :
@@ -76,7 +80,7 @@ def setup_assume_role():
76
80
77
81
role_name = CONFIG [get_key ("iam_auth_assume_role_name" )]
78
82
creds = _assume_role (role_name , quiet = True )
79
- with open ( join ( HERE , "creds.json" ), "w" ) as fid :
83
+ with ( HERE / "creds.json" ). open ( "w" ) as fid :
80
84
json .dump (creds , fid )
81
85
82
86
# Create the user.
@@ -87,6 +91,11 @@ def setup_assume_role():
87
91
authmechanismproperties = f"AWS_SESSION_TOKEN:{ token } " ,
88
92
)
89
93
create_user (ASSUMED_ROLE , kwargs )
94
+ return dict (
95
+ USER = kwargs ["username" ],
96
+ PASS = kwargs ["password" ],
97
+ SESSION_TOKEN = creds ["SessionToken" ],
98
+ )
90
99
91
100
92
101
def setup_ec2 ():
@@ -95,6 +104,7 @@ def setup_ec2():
95
104
os .environ .pop ("AWS_ACCESS_KEY_ID" , None )
96
105
os .environ .pop ("AWS_SECRET_ACCESS_KEY" , None )
97
106
create_user (AWS_ACCOUNT_ARN , dict ())
107
+ return dict ()
98
108
99
109
100
110
def setup_ecs ():
@@ -138,6 +148,18 @@ def setup_ecs():
138
148
# Run the test in a container
139
149
subprocess .check_call (["/bin/sh" , "-c" , run_test_command ], env = env )
140
150
151
+ return dict ()
152
+
153
+
154
+ def setup_session_creds ():
155
+ # Set up the assume role user, and export the aws vars.
156
+ creds = setup_assume_role ()
157
+ return dict (
158
+ AWS_ACCESS_KEY_ID = creds ["USER" ],
159
+ AWS_SECRET_ACCESS_KEY = creds ["PASS" ],
160
+ AWS_SESSION_TOKEN = creds ["SESSION_TOKEN" ],
161
+ )
162
+
141
163
142
164
def setup_regular ():
143
165
# Create the user.
@@ -147,6 +169,14 @@ def setup_regular():
147
169
)
148
170
create_user (CONFIG [get_key ("iam_auth_ecs_account_arn" )], kwargs )
149
171
172
+ return dict (USER = kwargs ["username" ], PASS = kwargs ["password" ])
173
+
174
+
175
+ def setup_env_creds ():
176
+ # Set up the regular user, but export the creds as environment vars.
177
+ creds = setup_regular ()
178
+ return dict (AWS_ACCESS_KEY_ID = creds ["USER" ], AWS_SECRET_ACCESS_KEY = creds ["PASS" ])
179
+
150
180
151
181
def setup_web_identity ():
152
182
# Unassign the instance profile.
@@ -161,7 +191,7 @@ def setup_web_identity():
161
191
raise RuntimeError ("Request limit exceeded for AWS API" )
162
192
163
193
if ret != 0 :
164
- print ( "ret was" , ret )
194
+ LOGGER . debug ( "return code was %s " , ret )
165
195
raise RuntimeError (
166
196
"Failed to unassign an instance profile from the current machine"
167
197
)
@@ -186,10 +216,11 @@ def setup_web_identity():
186
216
187
217
# Assume the web role to get temp credentials.
188
218
os .environ ["AWS_WEB_IDENTITY_TOKEN_FILE" ] = token_file
189
- os .environ ["AWS_ROLE_ARN" ] = CONFIG [get_key ("iam_auth_assume_web_role_name" )]
219
+ role_arn = CONFIG [get_key ("iam_auth_assume_web_role_name" )]
220
+ os .environ ["AWS_ROLE_ARN" ] = role_arn
190
221
191
222
creds = _assume_role_with_web_identity (True )
192
- with open ( join ( HERE , "creds.json" ), "w" ) as fid :
223
+ with ( HERE / "creds.json" ). open ( "w" ) as fid :
193
224
json .dump (creds , fid )
194
225
195
226
# Create the user.
@@ -201,6 +232,34 @@ def setup_web_identity():
201
232
)
202
233
create_user (ASSUMED_WEB_ROLE , kwargs )
203
234
235
+ return dict (AWS_WEB_IDENTITY_TOKEN_FILE = token_file , AWS_ROLE_ARN = role_arn )
236
+
237
+
238
+ def handle_creds (creds : dict ):
239
+ if "USER" in creds :
240
+ USER = quote_plus (creds ["USER" ])
241
+ if "PASS" in creds :
242
+ PASS = quote_plus (creds ["PASS" ])
243
+ MONGODB_URI = f"mongodb://{ USER } :{ PASS } @localhost"
244
+ else :
245
+ MONGODB_URI = f"mongodb://{ USER } @localhost"
246
+ else :
247
+ MONGODB_URI = "mongodb://localhost"
248
+ MONGODB_URI = f"{ MONGODB_URI } /aws?authMechanism=MONGODB-AWS"
249
+ if "SESSION_TOKEN" in creds :
250
+ SESSION_TOKEN = quote_plus (creds ["SESSION_TOKEN" ])
251
+ MONGODB_URI = (
252
+ f"{ MONGODB_URI } &authMechanismProperties=AWS_SESSION_TOKEN:{ SESSION_TOKEN } "
253
+ )
254
+ with (HERE / "test-env.sh" ).open ("w" , newline = "\n " ) as fid :
255
+ fid .write ("#!/usr/bin/env bash\n \n " )
256
+ fid .write ("set +x\n " )
257
+ for key , value in creds .items ():
258
+ if key in ["USER" , "PASS" , "SESSION_TOKEN" ]:
259
+ value = quote_plus (value ) # noqa: PLW2901
260
+ fid .write (f"export { key } ={ value } \n " )
261
+ fid .write (f"export MONGODB_URI={ MONGODB_URI } \n " )
262
+
204
263
205
264
def main ():
206
265
parser = argparse .ArgumentParser (description = "MONGODB-AWS tester." )
@@ -218,11 +277,21 @@ def main():
218
277
run_regular_cmd = sub .add_parser ("regular" , help = "Regular credentials test" )
219
278
run_regular_cmd .set_defaults (func = setup_regular )
220
279
280
+ run_session_creds_cmd = sub .add_parser ("session-creds" , help = "Session credentials" )
281
+ run_session_creds_cmd .set_defaults (func = setup_session_creds )
282
+
283
+ run_env_creds_cmd = sub .add_parser ("env-creds" , help = "Environment credentials" )
284
+ run_env_creds_cmd .set_defaults (func = setup_env_creds )
285
+
221
286
run_web_identity_cmd = sub .add_parser ("web-identity" , help = "Web identity test" )
222
287
run_web_identity_cmd .set_defaults (func = setup_web_identity )
223
288
224
289
args = parser .parse_args ()
225
- args .func ()
290
+ func_name = args .func .__name__ .replace ("setup_" , "" ).replace ("_" , "-" )
291
+ LOGGER .info ("Running aws_tester.py with %s..." , func_name )
292
+ creds = args .func ()
293
+ handle_creds (creds )
294
+ LOGGER .info ("Running aws_tester.py with %s... done." , func_name )
226
295
227
296
228
297
if __name__ == "__main__" :
0 commit comments