How to use the awsume.awsumepy.lib.exceptions function in awsume

To help you get started, we’ve selected a few awsume examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github trek10inc / awsume / awsume / awsumepy / lib / config_management.py View on Github external
raise exceptions.ConfigOperationException('Must supply value to get')
        logger.debug('Getting {}'.format(operations[1]))
        value = get_dict_parts(config, operations[1])
        safe_print(json.dumps(value))
        raise exceptions.EarlyExit()

    if operations[0].lower() == 'list':
        if len(operations) != 1:
            raise exceptions.ConfigOperationException('No operands are valid for operation "list"')
        logger.debug('Listing config')
        yaml.safe_dump(config, sys.stderr, width=1000)
        raise exceptions.EarlyExit()

    if operations[0].lower() == 'set':
        if len(operations) < 3:
            raise exceptions.ConfigOperationException('Must supply value to set {} to'.format(operations[1]))
        logger.debug('Setting {} to {}'.format(operations[1], operations[2]))
        value = get_value_from_args(operations[2:])
        config = update_dict_parts(config, operations[1], value)

    if operations[0].lower() in ['reset']:
        default_value = get_dict_parts(defaults, operations[1])
        if default_value is None:
            raise exceptions.ConfigOperationException('Key does not have a default: {}'.format(operations[1]), colorama.Fore.YELLOW)
        config = update_dict_parts(config, operations[1], default_value)
        safe_print('Reset key {} to {}'.format(operations[1], default_value), colorama.Fore.YELLOW)

    if operations[0].lower() in ['clear']:
        config, deleted = delete_dict_value_parts(config, operations[1])
        if deleted:
            safe_print('Deleted key {}'.format(operations[1]), colorama.Fore.YELLOW)
github trek10inc / awsume / awsume / autoawsume / main.py View on Github external
def refresh_profile(auto_profile):
    logger.debug('Refreshing profile {}'.format(json.dumps(auto_profile, default=str)))
    try:
        session = awsumepy.awsume(*auto_profile.get('awsumepy_command').split(' '))
        return session
    except exceptions.AwsumeException as e:
        logger.debug('There was an issue refreshing the profile, not returning a session: {}'.format(e))
        logger.debug('', exc_info=True)
        return None
github trek10inc / awsume / awsume / awsumepy / app.py View on Github external
def get_saml_credentials(self, args: argparse.Namespace, profiles: dict) -> dict:
        assertion = self.plugin_manager.hook.get_credentials_with_saml(
            config=self.config,
            arguments=args,
        )
        assertion = next((_ for _ in assertion if _), None) # pragma: no cover
        if not assertion:
            raise exceptions.SAMLAssertionNotFoundError('No assertion to use!')
        roles = saml.parse_assertion(assertion)
        if not roles:
            raise exceptions.SAMLAssertionMissingRoleError('No roles found in the saml assertion')
        role_arn = None
        principal_arn = None
        role_duration = args.role_duration or int(self.config.get('role-duration', '0'))

        if len(roles) > 1:
            if args.role_arn and args.principal_arn:
                principal_plus_role_arn = ','.join(args.role_arn, args.principal_arn)
                if self.config.get('fuzzy-match'):
                    choice = difflib.get_close_matches(principal_plus_role_arn, roles, cutoff=0)[0]
                    safe_print('Closest match: {}'.format(choice))
                else:
                    if principal_plus_role_arn not in roles:
                        raise exceptions.SAMLRoleNotFoundError(args.principal_arn, args.role_arn)
                    else:
                        choice = principal_plus_role_arn
            elif args.profile_name:
github trek10inc / awsume / awsume / awsumepy / app.py View on Github external
except exceptions.UserAuthenticationError as e:
            self.plugin_manager.hook.catch_user_authentication_error(config=self.config, arguments=args, profiles=profiles, error=e)
            raise
        except exceptions.RoleAuthenticationError as e:
            self.plugin_manager.hook.catch_role_authentication_error(config=self.config, arguments=args, profiles=profiles, error=e)
            raise
        credentials = next((_ for _ in credentials if _), {}) # pragma: no cover
        self.plugin_manager.hook.post_get_credentials(
            config=self.config,
            arguments=args,
            profiles=profiles,
            credentials=credentials,
        )
        if not credentials:
            safe_print('No credentials to awsume', colorama.Fore.RED)
            raise exceptions.NoCredentialsError()
        return credentials
github trek10inc / awsume / awsume / awsumepy / lib / config_management.py View on Github external
def load_config() -> dict:
    if not os.path.exists(str(constants.AWSUME_DIR)):
        os.makedirs(str(constants.AWSUME_DIR))
    if not os.path.isfile(str(constants.AWSUME_CONFIG)):
        open(str(constants.AWSUME_CONFIG), 'a').close()

    options = None
    try:
        options = yaml.safe_load(open(str(constants.AWSUME_CONFIG), 'r'))
    except Exception as e:
        raise exceptions.ConfigParseException(constants.AWSUME_CONFIG, message='Cannot parse config file', error=e)
    if options is None:
        options = defaults
        write_config(options)
    return options
github trek10inc / awsume / awsume / awsumepy / lib / profile.py View on Github external
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):
            raise exceptions.ProfileNotFoundError(profile_name=source_profile_name)
        user_profile = get_source_profile(profiles, target_profile_name)
        user_profile_name = source_profile_name
github trek10inc / awsume / awsume / awsumepy / app.py View on Github external
def get_saml_credentials(self, args: argparse.Namespace, profiles: dict) -> dict:
        assertion = self.plugin_manager.hook.get_credentials_with_saml(
            config=self.config,
            arguments=args,
        )
        assertion = next((_ for _ in assertion if _), None) # pragma: no cover
        if not assertion:
            raise exceptions.SAMLAssertionNotFoundError('No assertion to use!')
        roles = saml.parse_assertion(assertion)
        if not roles:
            raise exceptions.SAMLAssertionMissingRoleError('No roles found in the saml assertion')
        role_arn = None
        principal_arn = None
        role_duration = args.role_duration or int(self.config.get('role-duration', '0'))

        if len(roles) > 1:
            if args.role_arn and args.principal_arn:
                principal_plus_role_arn = ','.join(args.role_arn, args.principal_arn)
                if self.config.get('fuzzy-match'):
                    choice = difflib.get_close_matches(principal_plus_role_arn, roles, cutoff=0)[0]
                    safe_print('Closest match: {}'.format(choice))
                else:
                    if principal_plus_role_arn not in roles:
                        raise exceptions.SAMLRoleNotFoundError(args.principal_arn, args.role_arn)
github trek10inc / awsume / awsume / awsumepy / default_plugins.py View on Github external
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,
github trek10inc / awsume / awsume / awsumepy / app.py View on Github external
roles = saml.parse_assertion(assertion)
        if not roles:
            raise exceptions.SAMLAssertionMissingRoleError('No roles found in the saml assertion')
        role_arn = None
        principal_arn = None
        role_duration = args.role_duration or int(self.config.get('role-duration', '0'))

        if len(roles) > 1:
            if args.role_arn and args.principal_arn:
                principal_plus_role_arn = ','.join(args.role_arn, args.principal_arn)
                if self.config.get('fuzzy-match'):
                    choice = difflib.get_close_matches(principal_plus_role_arn, roles, cutoff=0)[0]
                    safe_print('Closest match: {}'.format(choice))
                else:
                    if principal_plus_role_arn not in roles:
                        raise exceptions.SAMLRoleNotFoundError(args.principal_arn, args.role_arn)
                    else:
                        choice = principal_plus_role_arn
            elif args.profile_name:
                profile_role_arn = profiles.get(args.profile_name, {}).get('role_arn')
                principal_arn = profiles.get(args.profile_name, {}).get('principal_arn')
                if profile_role_arn is None or principal_arn is None:
                    raise exceptions.InvalidProfileError(args.profile_name, 'both role_arn and principal_arn are necessary for saml profiles')
                principal_plus_profile_role_arn = ','.join([principal_arn, profile_role_arn])
                if principal_plus_profile_role_arn in roles:
                    choice = principal_plus_profile_role_arn
                else:
                    raise exceptions.SAMLRoleNotFoundError(principal_arn, profile_role_arn)
                safe_print('Match: {}'.format(choice))
            else:
                for index, choice in enumerate(roles):
                    safe_print('{}) {}'.format(index, choice), color=colorama.Fore.LIGHTYELLOW_EX)