Search in sources :

Example 1 with AllProfiles

use of com.amazonaws.auth.profile.internal.AllProfiles in project intellij-idea-plugin-connector-for-aws-lambda by satr.

the class AbstractConnectorModel method getCredentialsProvider.

protected AWSCredentialsProvider getCredentialsProvider() {
    if (isEmpty(credentialProfileName)) {
        getLogger().logDebug("Cannot get a profile for an empty name");
        return tryDefaultAwsCredentialsProviderChain();
    }
    if (!validateCredentialProfilesExist()) {
        getLogger().logError("Cannot find any credentials profiles. Please create at least one.");
        return tryDefaultAwsCredentialsProviderChain();
    }
    ProfileStaticCredentialsProvider profileCredentialsProvider = null;
    AllProfiles allBasicProfiles = loadProfilesWithProperties();
    BasicProfile profile = allBasicProfiles.getProfile(credentialProfileName);
    if (profile == null) {
        getLogger().logDebug("Last loaded profile does not exist: \"%s\".", credentialProfileName);
    } else {
        getLogger().logDebug("Select the profile \"%s\".", credentialProfileName);
        profileCredentialsProvider = tryCreateProfileCredentialsProvider(profile);
        if (profileCredentialsProvider != null) {
            String profileRegionName = profile.getRegion();
            if (!isEmpty(profileRegionName)) {
                getLogger().logDebug("Selected a region from the profile: %s", regionName);
                regionName = profileRegionName;
            }
            return profileCredentialsProvider;
        }
    }
    profileCredentialsProvider = tryGetAlternativeAwsCredentialsProvider(credentialProfileName, allBasicProfiles);
    if (profileCredentialsProvider != null) {
        return profileCredentialsProvider;
    }
    getLogger().logDebug("No profiles could be selected and used.");
    return tryDefaultAwsCredentialsProviderChain();
}
Also used : AllProfiles(com.amazonaws.auth.profile.internal.AllProfiles) BasicProfile(com.amazonaws.auth.profile.internal.BasicProfile) ProfileStaticCredentialsProvider(com.amazonaws.auth.profile.internal.ProfileStaticCredentialsProvider)

Example 2 with AllProfiles

use of com.amazonaws.auth.profile.internal.AllProfiles in project intellij-idea-plugin-connector-for-aws-lambda by satr.

the class AbstractConnectorModel method loadProfilesWithProperties.

// Load profiles from the file ".aws/credentials" with regions and other properties (if exist) from the file ".aws/config"
// Logic has been borrowed from https://github.com/aws/aws-sdk-java/issues/803#issuecomment-374043898
// The issue with not loading regions from the file ".aws/config" supposed to be fixed in Java SDK 2.0, which is in "preview" now
// Java SDK 2.0  https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/welcome.html
private static AllProfiles loadProfilesWithProperties() {
    final AllProfiles allProfiles = new AllProfiles(Stream.concat(BasicProfileConfigLoader.INSTANCE.loadProfiles(AwsProfileFileLocationProvider.DEFAULT_CONFIG_LOCATION_PROVIDER.getLocation()).getProfiles().values().stream(), BasicProfileConfigLoader.INSTANCE.loadProfiles(AwsProfileFileLocationProvider.DEFAULT_CREDENTIALS_LOCATION_PROVIDER.getLocation()).getProfiles().values().stream()).map(profile -> new BasicProfile(profile.getProfileName().replaceFirst("^profile ", ""), profile.getProperties())).collect(Collectors.toMap(profile -> profile.getProfileName(), profile -> profile, (left, right) -> {
        final Map<String, String> properties = new HashMap<>(left.getProperties());
        properties.putAll(right.getProperties());
        return new BasicProfile(left.getProfileName(), properties);
    })));
    return allProfiles;
}
Also used : AllProfiles(com.amazonaws.auth.profile.internal.AllProfiles) BasicProfile(com.amazonaws.auth.profile.internal.BasicProfile) HashMap(java.util.HashMap)

Example 3 with AllProfiles

use of com.amazonaws.auth.profile.internal.AllProfiles in project cyberduck by iterate-ch.

the class STSCredentialsConfigurator method configure.

public Credentials configure(final Host host) throws LoginFailureException, LoginCanceledException {
    final Credentials credentials = new Credentials(host.getCredentials());
    // See https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html for configuration behavior
    final Local awsDirectory = LocalFactory.get(LocalFactory.get(), ".aws");
    final Local configFile = LocalFactory.get(awsDirectory, "config");
    final Local credentialsFile = LocalFactory.get(awsDirectory, "credentials");
    // Profile can be null. The default profile from the configuration will be loaded
    final String profile = host.getCredentials().getUsername();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Look for profile name %s in %s and %s", profile, configFile, credentialsFile));
    }
    // Iterating all profiles on our own because AWSProfileCredentialsConfigurator does not support MFA tokens
    final Map<String, Map<String, String>> allProfileProperties = new HashMap<>();
    try {
        final Map<String, Map<String, String>> credentialsFileProfileProperties = new ProfilesConfigFileLoaderHelper().parseProfileProperties(credentialsFile);
        allProfileProperties.putAll(credentialsFileProfileProperties);
        final Map<String, Map<String, String>> configFileProfileProperties = new ProfilesConfigFileLoaderHelper().parseProfileProperties(configFile);
        for (Map.Entry<String, Map<String, String>> entry : configFileProfileProperties.entrySet()) {
            final String profileName = entry.getKey();
            final Map<String, String> configFileProperties = entry.getValue();
            final Map<String, String> credentialsFileProperties = allProfileProperties.get(profileName);
            // If the credentials file had properties, then merge them in
            if (credentialsFileProperties != null) {
                configFileProperties.putAll(credentialsFileProperties);
            }
            allProfileProperties.put(profileName, configFileProperties);
        }
    } catch (AccessDeniedException | IllegalArgumentException | IOException e) {
        log.warn(String.format("Failure reading %s and %s", configFile, credentialsFile), e);
        return credentials;
    }
    if (allProfileProperties.isEmpty()) {
        log.warn("Missing configuration file ~/.aws/credentials or ~/.aws/config. Skip auto configuration");
        return host.getCredentials();
    }
    // Convert the loaded property map to credential objects
    final Map<String, BasicProfile> profilesByName = new LinkedHashMap<>();
    for (Map.Entry<String, Map<String, String>> entry : allProfileProperties.entrySet()) {
        String profileName = entry.getKey();
        Map<String, String> properties = entry.getValue();
        profilesByName.put(profileName, new BasicProfile(profileName, properties));
    }
    final Map<String, BasicProfile> profiles = new AllProfiles(profilesByName).getProfiles();
    final Optional<Map.Entry<String, BasicProfile>> optional = profiles.entrySet().stream().filter(new Predicate<Map.Entry<String, BasicProfile>>() {

        @Override
        public boolean test(final Map.Entry<String, BasicProfile> entry) {
            final String profileName = entry.getKey();
            final BasicProfile basicProfile = entry.getValue();
            final String awsAccessIdKey = basicProfile.getAwsAccessIdKey();
            // Matching access key or profile name
            if (StringUtils.equals(profileName, profile) || StringUtils.equals(awsAccessIdKey, profile)) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Found matching profile %s", profile));
                }
                return true;
            }
            return false;
        }
    }).findFirst();
    if (optional.isPresent()) {
        final Map.Entry<String, BasicProfile> entry = optional.get();
        final BasicProfile basicProfile = entry.getValue();
        if (basicProfile.isRoleBasedProfile()) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Configure credentials from role based profile %s", basicProfile.getProfileName()));
            }
            if (StringUtils.isBlank(basicProfile.getRoleSourceProfile())) {
                throw new LoginFailureException(String.format("Missing source profile reference in profile %s", basicProfile.getProfileName()));
            } else if (!profiles.containsKey(basicProfile.getRoleSourceProfile())) {
                throw new LoginFailureException(String.format("Missing source profile with name %s", basicProfile.getRoleSourceProfile()));
            } else {
                final BasicProfile sourceProfile = profiles.get(basicProfile.getRoleSourceProfile());
                // If a profile defines the role_arn property then the profile is treated as an assume role profile
                final AWSSecurityTokenService service = this.getTokenService(host, host.getRegion(), sourceProfile.getAwsAccessIdKey(), sourceProfile.getAwsSecretAccessKey(), sourceProfile.getAwsSessionToken());
                final String tokenCode;
                if (basicProfile.getProperties().containsKey("mfa_serial")) {
                    tokenCode = prompt.prompt(host, LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), String.format("%s %s", LocaleFactory.localizedString("Multi-Factor Authentication", "S3"), basicProfile.getPropertyValue("mfa_serial")), new LoginOptions(host.getProtocol()).password(true).passwordPlaceholder(LocaleFactory.localizedString("MFA Authentication Code", "S3")).keychain(false)).getPassword();
                } else {
                    tokenCode = null;
                }
                final Integer durationSeconds;
                if (basicProfile.getProperties().containsKey("duration_seconds")) {
                    durationSeconds = Integer.valueOf(basicProfile.getPropertyValue("duration_seconds"));
                } else {
                    durationSeconds = null;
                }
                // Starts a new session by sending a request to the AWS Security Token Service (STS) to assume a
                // Role using the long lived AWS credentials
                final AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withExternalId(basicProfile.getRoleExternalId()).withRoleArn(basicProfile.getRoleArn()).withSerialNumber(basicProfile.getPropertyValue("mfa_serial")).withTokenCode(tokenCode).withRoleSessionName(new AsciiRandomStringService().random()).withDurationSeconds(durationSeconds);
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Request %s from %s", assumeRoleRequest, service));
                }
                try {
                    final AssumeRoleResult assumeRoleResult = service.assumeRole(assumeRoleRequest);
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Set credentials from %s", assumeRoleResult));
                    }
                    credentials.setUsername(assumeRoleResult.getCredentials().getAccessKeyId());
                    credentials.setPassword(assumeRoleResult.getCredentials().getSecretAccessKey());
                    credentials.setToken(assumeRoleResult.getCredentials().getSessionToken());
                } catch (AWSSecurityTokenServiceException e) {
                    throw new LoginFailureException(e.getErrorMessage(), e);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Configure credentials from basic profile %s", basicProfile.getProfileName()));
            }
            final Map<String, String> profileProperties = basicProfile.getProperties();
            if (profileProperties.containsKey("sso_start_url")) {
                // Read cached SSO credentials
                final CachedCredential cached = this.fetchSsoCredentials(credentials, profileProperties, awsDirectory);
                credentials.setUsername(cached.accessKey);
                credentials.setPassword(cached.secretKey);
                credentials.setToken(cached.sessionToken);
            } else if (StringUtils.isNotBlank(basicProfile.getAwsSessionToken())) {
                // No need to obtain session token if preconfigured in profile
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Set session token credentials from profile %s", profile));
                }
                credentials.setUsername(basicProfile.getAwsAccessIdKey());
                credentials.setPassword(basicProfile.getAwsSecretAccessKey());
                credentials.setToken(basicProfile.getAwsSessionToken());
            } else {
                if (host.getProtocol().isTokenConfigurable()) {
                    // Obtain session token
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Get session token from credentials in profile %s", basicProfile.getProfileName()));
                    }
                    final AWSSecurityTokenService service = this.getTokenService(host, host.getRegion(), basicProfile.getAwsAccessIdKey(), basicProfile.getAwsSecretAccessKey(), basicProfile.getAwsSessionToken());
                    final GetSessionTokenRequest sessionTokenRequest = new GetSessionTokenRequest();
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Request %s from %s", sessionTokenRequest, service));
                    }
                    try {
                        final GetSessionTokenResult sessionTokenResult = service.getSessionToken(sessionTokenRequest);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format("Set credentials from %s", sessionTokenResult));
                        }
                        credentials.setUsername(sessionTokenResult.getCredentials().getAccessKeyId());
                        credentials.setPassword(sessionTokenResult.getCredentials().getSecretAccessKey());
                        credentials.setToken(sessionTokenResult.getCredentials().getSessionToken());
                    } catch (AWSSecurityTokenServiceException e) {
                        throw new LoginFailureException(e.getErrorMessage(), e);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Set static credentials from profile %s", basicProfile.getProfileName()));
                    }
                    credentials.setUsername(basicProfile.getAwsAccessIdKey());
                    credentials.setPassword(basicProfile.getAwsSecretAccessKey());
                }
            }
        }
    }
    return credentials;
}
Also used : AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest) AccessDeniedException(ch.cyberduck.core.exception.AccessDeniedException) AllProfiles(com.amazonaws.auth.profile.internal.AllProfiles) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap) Predicate(java.util.function.Predicate) LoginOptions(ch.cyberduck.core.LoginOptions) AWSSecurityTokenServiceException(com.amazonaws.services.securitytoken.model.AWSSecurityTokenServiceException) BasicProfile(com.amazonaws.auth.profile.internal.BasicProfile) AsciiRandomStringService(ch.cyberduck.core.AsciiRandomStringService) GetSessionTokenResult(com.amazonaws.services.securitytoken.model.GetSessionTokenResult) Local(ch.cyberduck.core.Local) IOException(java.io.IOException) AssumeRoleResult(com.amazonaws.services.securitytoken.model.AssumeRoleResult) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) GetSessionTokenRequest(com.amazonaws.services.securitytoken.model.GetSessionTokenRequest) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AWSSecurityTokenService(com.amazonaws.services.securitytoken.AWSSecurityTokenService) AWSCredentials(com.amazonaws.auth.AWSCredentials) AWSSessionCredentials(com.amazonaws.auth.AWSSessionCredentials) Credentials(ch.cyberduck.core.Credentials)

Aggregations

AllProfiles (com.amazonaws.auth.profile.internal.AllProfiles)3 BasicProfile (com.amazonaws.auth.profile.internal.BasicProfile)3 HashMap (java.util.HashMap)2 AsciiRandomStringService (ch.cyberduck.core.AsciiRandomStringService)1 Credentials (ch.cyberduck.core.Credentials)1 Local (ch.cyberduck.core.Local)1 LoginOptions (ch.cyberduck.core.LoginOptions)1 AccessDeniedException (ch.cyberduck.core.exception.AccessDeniedException)1 LoginFailureException (ch.cyberduck.core.exception.LoginFailureException)1 AWSCredentials (com.amazonaws.auth.AWSCredentials)1 AWSSessionCredentials (com.amazonaws.auth.AWSSessionCredentials)1 ProfileStaticCredentialsProvider (com.amazonaws.auth.profile.internal.ProfileStaticCredentialsProvider)1 AWSSecurityTokenService (com.amazonaws.services.securitytoken.AWSSecurityTokenService)1 AWSSecurityTokenServiceException (com.amazonaws.services.securitytoken.model.AWSSecurityTokenServiceException)1 AssumeRoleRequest (com.amazonaws.services.securitytoken.model.AssumeRoleRequest)1 AssumeRoleResult (com.amazonaws.services.securitytoken.model.AssumeRoleResult)1 GetSessionTokenRequest (com.amazonaws.services.securitytoken.model.GetSessionTokenRequest)1 GetSessionTokenResult (com.amazonaws.services.securitytoken.model.GetSessionTokenResult)1 IOException (java.io.IOException)1 LinkedHashMap (java.util.LinkedHashMap)1