55
66import argparse
77import json
8+ import logging
89import os
910import subprocess
1011import sys
1112from functools import partial
13+ from pathlib import Path
1214from urllib .parse import quote_plus
1315
1416from pymongo import MongoClient
1517from pymongo .errors import OperationFailure
1618
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" )
1822
1923
2024def join (* parts ):
2125 return os .path .join (* parts ).replace (os .sep , "/" )
2226
2327
24- sys .path .insert (0 , join (HERE , "lib" ))
28+ sys .path .insert (0 , str (HERE / "lib" ))
2529from aws_assign_instance_profile import _assign_instance_policy
2630from aws_assume_role import _assume_role
2731from aws_assume_web_role import _assume_role_with_web_identity
@@ -35,7 +39,7 @@ def join(*parts):
3539_USE_AWS_SECRETS = False
3640
3741try :
38- with open ( join ( HERE , "aws_e2e_setup.json" )) as fid :
42+ with ( HERE / "aws_e2e_setup.json" ). open ( ) as fid :
3943 CONFIG = json .load (fid )
4044 get_key = partial (_get_key , uppercase = False )
4145except FileNotFoundError :
@@ -51,7 +55,7 @@ def run(args, env):
5155
5256def create_user (user , kwargs ):
5357 """Create a user and verify access."""
54- print ("Creating user" , user )
58+ LOGGER . info ("Creating user %s " , user )
5559 client = MongoClient (username = "bob" , password = "pwd123" )
5660 db = client ["$external" ]
5761 try :
@@ -76,7 +80,7 @@ def setup_assume_role():
7680
7781 role_name = CONFIG [get_key ("iam_auth_assume_role_name" )]
7882 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 :
8084 json .dump (creds , fid )
8185
8286 # Create the user.
@@ -87,6 +91,11 @@ def setup_assume_role():
8791 authmechanismproperties = f"AWS_SESSION_TOKEN:{ token } " ,
8892 )
8993 create_user (ASSUMED_ROLE , kwargs )
94+ return dict (
95+ USER = kwargs ["username" ],
96+ PASS = kwargs ["password" ],
97+ SESSION_TOKEN = creds ["SessionToken" ],
98+ )
9099
91100
92101def setup_ec2 ():
@@ -95,6 +104,7 @@ def setup_ec2():
95104 os .environ .pop ("AWS_ACCESS_KEY_ID" , None )
96105 os .environ .pop ("AWS_SECRET_ACCESS_KEY" , None )
97106 create_user (AWS_ACCOUNT_ARN , dict ())
107+ return dict ()
98108
99109
100110def setup_ecs ():
@@ -138,6 +148,8 @@ def setup_ecs():
138148 # Run the test in a container
139149 subprocess .check_call (["/bin/sh" , "-c" , run_test_command ], env = env )
140150
151+ return dict ()
152+
141153
142154def setup_regular ():
143155 # Create the user.
@@ -147,6 +159,8 @@ def setup_regular():
147159 )
148160 create_user (CONFIG [get_key ("iam_auth_ecs_account_arn" )], kwargs )
149161
162+ return dict (USER = kwargs ["username" ], PASS = kwargs ["password" ])
163+
150164
151165def setup_web_identity ():
152166 # Unassign the instance profile.
@@ -161,7 +175,7 @@ def setup_web_identity():
161175 raise RuntimeError ("Request limit exceeded for AWS API" )
162176
163177 if ret != 0 :
164- print ( "ret was" , ret )
178+ LOGGER . debug ( "return code was %s " , ret )
165179 raise RuntimeError (
166180 "Failed to unassign an instance profile from the current machine"
167181 )
@@ -186,10 +200,11 @@ def setup_web_identity():
186200
187201 # Assume the web role to get temp credentials.
188202 os .environ ["AWS_WEB_IDENTITY_TOKEN_FILE" ] = token_file
189- os .environ ["AWS_ROLE_ARN" ] = CONFIG [get_key ("iam_auth_assume_web_role_name" )]
203+ role_arn = CONFIG [get_key ("iam_auth_assume_web_role_name" )]
204+ os .environ ["AWS_ROLE_ARN" ] = role_arn
190205
191206 creds = _assume_role_with_web_identity (True )
192- with open ( join ( HERE , "creds.json" ), "w" ) as fid :
207+ with ( HERE / "creds.json" ). open ( "w" ) as fid :
193208 json .dump (creds , fid )
194209
195210 # Create the user.
@@ -201,12 +216,37 @@ def setup_web_identity():
201216 )
202217 create_user (ASSUMED_WEB_ROLE , kwargs )
203218
219+ return dict (AWS_WEB_IDENTITY_TOKEN_FILE = token_file , AWS_ROLE_ARN = role_arn )
220+
221+
222+ def handle_creds (creds : dict ):
223+ if "USER" in creds :
224+ USER = quote_plus (creds .pop ("USER" ))
225+ PASS = quote_plus (creds .pop ("PASS" ))
226+ MONGODB_URI = f"mongodb://{ USER } :{ PASS } @localhost"
227+ else :
228+ MONGODB_URI = "mongodb://localhost"
229+ MONGODB_URI = f"{ MONGODB_URI } /aws?authMechanism=MONGODB-AWS"
230+ if "SESSION_TOKEN" in creds :
231+ SESSION_TOKEN = quote_plus (creds .pop ("SESSION_TOKEN" ))
232+ MONGODB_URI = (
233+ f"{ MONGODB_URI } &authMechanismProperties=AWS_SESSION_TOKEN:{ SESSION_TOKEN } "
234+ )
235+ with (HERE / "test-env.sh" ).open ("w" , newline = "\n " ) as fid :
236+ fid .write ("#!/usr/bin/env bash\n \n " )
237+ fid .write ("set +x\n " )
238+ for key , value in creds .items ():
239+ fid .write (f"export { key } ={ value } \n " )
240+ fid .write (f"export MONGODB_URI={ MONGODB_URI } \n " )
241+
204242
205243def main ():
206244 parser = argparse .ArgumentParser (description = "MONGODB-AWS tester." )
207245 sub = parser .add_subparsers (title = "Tester subcommands" , help = "sub-command help" )
208246
209- run_assume_role_cmd = sub .add_parser ("assume-role" , help = "Assume role test" )
247+ run_assume_role_cmd = sub .add_parser (
248+ "assume-role" , aliases = ["session-creds" ], help = "Assume role test"
249+ )
210250 run_assume_role_cmd .set_defaults (func = setup_assume_role )
211251
212252 run_ec2_cmd = sub .add_parser ("ec2" , help = "EC2 test" )
@@ -215,14 +255,20 @@ def main():
215255 run_ecs_cmd = sub .add_parser ("ecs" , help = "ECS test" )
216256 run_ecs_cmd .set_defaults (func = setup_ecs )
217257
218- run_regular_cmd = sub .add_parser ("regular" , help = "Regular credentials test" )
258+ run_regular_cmd = sub .add_parser (
259+ "regular" , aliases = ["env-creds" ], help = "Regular credentials test"
260+ )
219261 run_regular_cmd .set_defaults (func = setup_regular )
220262
221263 run_web_identity_cmd = sub .add_parser ("web-identity" , help = "Web identity test" )
222264 run_web_identity_cmd .set_defaults (func = setup_web_identity )
223265
224266 args = parser .parse_args ()
225- args .func ()
267+ func_name = args .func .__name__ .replace ("setup_" , "" )
268+ LOGGER .info ("Running aws_tester.py with %s..." , func_name )
269+ creds = args .func ()
270+ handle_creds (creds )
271+ LOGGER .info ("Running aws_tester.py with %s... done." , func_name )
226272
227273
228274if __name__ == "__main__" :
0 commit comments