Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def get_value_from_args(args):
values = args
for index, value in enumerate(args):
try:
values[index] = json.loads(value)
except json.JSONDecodeError:
logger.debug('Cannot parse input', exc_info=True)
return values[0] if len(values) == 1 else values
def validate_profile(config: dict, arguments: argparse.Namespace, profiles: dict, target_profile_name: str) -> bool:
logger.debug('Validating profile')
profile = get_profile(config, arguments, profiles, target_profile_name)
if not profile:
raise exceptions.ProfileNotFoundError(profile_name=target_profile_name)
# validate role profiles
if 'role_arn' in profile:
if profile.get('credential_process'):
raise exceptions.InvalidProfileError(target_profile_name, message='awsume does not support the credential_process profile option: {}')
if profile.get('credential_source') and profile.get('source_profile'):
raise exceptions.InvalidProfileError(target_profile_name, message='credential_source and source_profile are mutually exclusive profile options')
if not profile.get('credential_source') and not profile.get('source_profile') and not profile.get('principal_arn'):
raise exceptions.InvalidProfileError(target_profile_name, message='role profiles must contain one of credential_source or source_profile')
if profile.get('credential_source') not in VALID_CREDENTIAL_SOURCES:
raise exceptions.InvalidProfileError(target_profile_name, message='unsupported awsume credential_source profile option: {}'.format(profile.get('credential_source')))
source_profile_name = profile.get('source_profile')
if source_profile_name and not profiles.get(source_profile_name):
cache_path = str(constants.AWSUME_CACHE_DIR) + '/' + cache_file_name
if os.path.exists(cache_path):
os.chmod(cache_path, 0o600)
else:
open(cache_path, 'a').close()
os.chmod(cache_path, 0o600)
logger.debug('Cache file path: ' + cache_path)
expiration = session['Expiration'].astimezone(dateutil.tz.tzlocal())
expiration = expiration.strftime('%Y-%m-%d %H:%M:%S')
try:
json.dump({
**session,
'Expiration': expiration,
}, open(cache_path, 'w'), indent=2, default=str)
except:
logger.debug('There was an error writing to the cache file', exc_info=True)
session['Expiration'] = datetime.strptime(expiration, '%Y-%m-%d %H:%M:%S')
return session
elif len(parts) == 3:
partition = parts[0]
account_id = parts[1]
provider_name = parts[2]
else:
parser.error('--principal-arn must be a valid role arn or follow the format "::"')
if not provider_name.isnumeric() or len(provider_name) is not 12:
parser.error('--principal-arn account id must be valid numeric account id of length 12')
arguments.principal_arn = 'arn:{}:iam::{}:role/{}'.format(partition, account_id, provider_name)
if not arguments.profile_name:
if arguments.role_arn:
logger.debug('Role arn passed, target profile name will be role_arn')
arguments.target_profile_name = arguments.role_arn
else:
logger.debug('No profile name passed, target profile name will be "default"')
arguments.target_profile_name = 'default'
else:
arguments.target_profile_name = arguments.profile_name
aws_secret_access_key=source_credentials.get('SecretAccessKey'),
aws_session_token=source_credentials.get('SessionToken'),
region_name=region,
)
role_sts_client = boto_session.client('sts') # type: botostubs.STS
kwargs = { 'RoleSessionName': session_name, 'RoleArn': role_arn }
if external_id:
kwargs['ExternalId'] = external_id
if role_duration:
kwargs['DurationSeconds'] = int(role_duration)
if mfa_serial:
kwargs['SerialNumber'] = mfa_serial
kwargs['TokenCode'] = mfa_token or profile_lib.get_mfa_token()
logger.debug('Assuming role now')
role_session = role_sts_client.assume_role(**kwargs).get('Credentials')
logger.debug('Received role credentials')
role_session['Expiration'] = role_session['Expiration'].astimezone(dateutil.tz.tzlocal())
role_session['Region'] = region or boto_session.region_name
except Exception as e:
raise RoleAuthenticationError(str(e))
logger.debug('Role credentials received')
return role_session
role_duration=role_duration,
mfa_serial=mfa_serial,
mfa_token=arguments.mfa_token,
)
else:
logger.debug('MFA not needed, assuming role from with profile creds')
role_session = aws_lib.assume_role(
source_credentials,
arguments.role_arn,
session_name,
region=region,
external_id=arguments.external_id,
role_duration=role_duration,
)
else:
logger.debug('Using default role duration')
if mfa_serial:
logger.debug('MFA required')
source_session = aws_lib.get_session_token(
source_credentials,
region=profile_lib.get_region(profiles, arguments, config),
mfa_serial=mfa_serial,
mfa_token=arguments.mfa_token,
ignore_cache=arguments.force_refresh,
duration_seconds=config.get('debug', {}).get('session_token_duration'),
)
else:
logger.debug('MFA not required')
source_session = source_credentials
role_session = aws_lib.assume_role(
source_session,
arguments.role_arn,
def get_assume_role_credentials_mfa_required_large_custom_duration(config: dict, arguments: argparse.Namespace, profiles: dict, target_profile: dict, role_duration: int):
if arguments.auto_refresh and role_duration > 3600:
raise exceptions.ValidationException('Cannot use autoawsume with custom role duration of more than 1 hour')
logger.debug('Skipping the get_session_token call, temp creds cannot be used for custom role duration')
region = profile_lib.get_region(profiles, arguments, config)
mfa_serial = profile_lib.get_mfa_serial(profiles, arguments.target_profile_name)
external_id = profile_lib.get_external_id(arguments, target_profile)
source_profile = profile_lib.get_source_profile(profiles, arguments.target_profile_name)
source_session = profile_lib.profile_to_credentials(source_profile)
role_session = aws_lib.assume_role(
source_session,
target_profile.get('role_arn'),
arguments.session_name or arguments.target_profile_name,
region=region,
external_id=external_id,
role_duration=role_duration,
mfa_serial=mfa_serial,
mfa_token=arguments.mfa_token,
def get_plugin_manager(self) -> pluggy.PluginManager:
logger.debug('Creating plugin manager')
pm = pluggy.PluginManager('awsume')
pm.add_hookspecs(hookspec)
logger.debug('Loading plugins')
pm.register(default_plugins)
pm.load_setuptools_entrypoints('awsume')
return pm
def get_credentials(self, args: argparse.Namespace, profiles: dict) -> dict:
logger.debug('Getting credentials')
self.plugin_manager.hook.pre_get_credentials(
config=self.config,
arguments=args,
profiles=profiles,
)
try:
if not args.auto_refresh and args.json: # sending credentials to awsume directly
logger.debug('Pulling credentials from json parameter')
args.target_profile_name = 'json'
credentials = json.loads(args.json)
if 'Credentials' in credentials:
credentials = credentials['Credentials']
credentials = [credentials]
elif args.with_saml:
logger.debug('Pulling credentials from saml')
credentials = self.get_saml_credentials(args, profiles)
logger.debug('Session name: {}'.format(session_name))
if not arguments.source_profile:
logger.debug('Using current credentials to assume role')
role_session = aws_lib.assume_role({}, arguments.role_arn, session_name, region=region, external_id=arguments.external_id, role_duration=role_duration)
else:
logger.debug('Using the source_profile from the cli to call assume_role')
source_profile = profiles.get(arguments.source_profile)
if not source_profile:
raise exceptions.ProfileNotFoundError(profile_name=arguments.source_profile)
source_credentials = profile_lib.profile_to_credentials(source_profile)
mfa_serial = source_profile.get('mfa_serial')
if role_duration:
logger.debug('Using custom role duration')
if mfa_serial:
logger.debug('Requires MFA')
logger.debug('Using custom role duration for role that needs mfa_serial, skipping get-session-token call')
source_session = source_credentials
role_session = aws_lib.assume_role(
source_session,
arguments.role_arn,
session_name,
region=region,
external_id=arguments.external_id,
role_duration=role_duration,
mfa_serial=mfa_serial,
mfa_token=arguments.mfa_token,
)
else:
logger.debug('MFA not needed, assuming role from with profile creds')
role_session = aws_lib.assume_role(
source_credentials,
arguments.role_arn,