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();
}
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;
}
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;
}
Aggregations