aws-sdk-java: aws-cli role assumption profiles are incompatible with SDK

The CLI userguide instructs you to add delegated profiles to the file ~/.aws/config. However, profiles added here are incompatible with the SDK.

JavaDoc in com.amazonaws.profile.path.AwsProfileFileLocationProvider makes it clear that only one config file will be loaded (~/.aws/credentials or ~/.aws/config).

The confusion may be that CLI profiles that use keys are defined in ~/.aws/credentials but profiles that use source_profile should be placed in ~/.aws/config. More details in the CLI configuration section.

The workaround for this problem is to define the role assumption profile in ~/.aws/credentials without the profile prefix. However, there are other tools that do not expected delegated profiles in this file, so this solution is imperfect.

~/.aws/credentials

[stage]
role_arn = arn:aws:iam:: 123456789012:role/delegated-admin
source_profile = default

It would be very helpful if the Java SDK allowed role assumption profiles to be defined using the documented CLI format.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 63
  • Comments: 30 (7 by maintainers)

Commits related to this issue

Most upvoted comments

It’s unfortunately a very difficult issue to fix while maintaining backwards-compatibility … the behavior that the reasonable person would expect is also at odds with the CLI’s implementation

Appreciate those points, but don’t think either have any bearing on whether this is a bug or not.

Here’s my hacky workaround, which avoids having to hack the credentials files themselves (not really feasible across a lot of clients), and supports switching roles, which I couldn’t get to work even with duplicate profiles.

public AWSCredentialsProvider getDefaultCredentials() {

    final String profileName = AwsProfileNameLoader.INSTANCE.loadProfileName();
    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);
                    })));

    final BasicProfile profile = Optional.ofNullable(allProfiles.getProfile(profileName))
            .orElseThrow(() -> new RuntimeException(String.format("Profile '%s' not found in %s", 
                    profileName, allProfiles.getProfiles().keySet())));
    if (profile.isRoleBasedProfile()) {
        return new ProfileAssumeRoleCredentialsProvider(STSProfileCredentialsServiceLoader.getInstance(), allProfiles, profile);
    } else {
        return new ProfileStaticCredentialsProvider(profile);
    }
}

Example of both problems

~/.aws/credentials:

[default]
aws_access_key_id = xxx
aws_secret_access_key = xxx

[dev]
role_arn = arn:aws:iam::12345:role/dev
source_profile = default

[sandbox]
role_arn = arn:aws:iam::67890:role/admin
source_profile = default

~/.aws/config:

[default]
region = us-east-1

[dev]
region = us-east-1
source_profile = default

[profile dev]
region = us-east-1
role_arn = arn:aws:iam::12345:role/dev
source_profile = default

[sandbox]
region = us-east-1
role_arn = arn:aws:iam::67890:role/admin
source_profile = default

[profile sandbox]
region = us-east-1
source_profile = default

Preferred solution

~/.aws/credentials:

[default]
aws_access_key_id = xxx
aws_secret_access_key = xxx

~/.aws/config:

[default]
region = us-east-1

[dev]
region = us-east-1
role_arn = arn:aws:iam::12345:role/dev
source_profile = default

[sandbox]
region = us-east-1
role_arn = arn:aws:iam::67890:role/admin
source_profile = default

We’re baffled as to why this is labelled a feature rather than a bug - the Java SDK is clearly incompatible with the config + credentials formats supported and documented by https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html .

@jtheuer Because of this issue, the Java SDK team worked with the other AWS SDKs back in 2017 to write up a (long) profile file standard on which all SDKs can align going forward. That standard was written to (with a few exceptions) directly implement the CLI behavior. That standard was followed for the Java SDK 2.x, so it’s quite compatible with the CLI.

If you’re willing to add the Java SDK 2.x to your classpath (software.amazon.awssdk:auth), the following adapter should give you CLI-compatible behavior in 1.11.x:

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;

package com.example;

public class CliCompatibleCredentialsProvider implements AWSCredentialsProvider {
    private final ProfileCredentialsProvider delegate;

    public CliCompatibleCredentialsProvider() {
        this.delegate = ProfileCredentialsProvider.create();
    }

    public CliCompatibleCredentialsProvider(String profileName) {
        this.delegate = ProfileCredentialsProvider.create("my-profile-name");
    }

    @Override
    public AWSCredentials getCredentials() {
        AwsCredentials credentials = delegate.resolveCredentials();

        if (credentials instanceof AwsSessionCredentials) {
            AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials;
            return new BasicSessionCredentials(sessionCredentials.accessKeyId(),
                                               sessionCredentials.secretAccessKey(),
                                               sessionCredentials.sessionToken());
        }

        return new BasicAWSCredentials(credentials.accessKeyId(), credentials.secretAccessKey());
    }

    @Override
    public void refresh() {
        throw new UnsupportedOperationException();
    }
}

We’d ideally like to implement the CLI-compatible standard natively in 1.11.x of the SDK, but because of resource limitations are focusing our efforts on getting 2.x up to feature parity with 1.11.x.

Can we get the v2 behaviour hidden behind a flag? As mentioned above, AWS_SDK_LOAD_CONFIG=true worked for aws-sdk-go, I think it would be backward compatible and it would most definitely be a welcome change.

I have a lot of code depending on SDKv1, and a rewrite to v2 will most likely never happen, so being able to have the SDK ‘just work’ by setting an env variable would be great.

Any plans to align the behavior of the AWS SDK with the other SDKs? I wonder why you share the same config file with other SDKs but use it differently. This is really confusing for me as a user.

This behaviour is quite annoying.

@zhangzhx did you ever talk this one over with the other SDK/CLI contributors? To me this is more of a bug than a feature, here’s why:

The only thing should go into the credentials file is the aws_access_key_id and the aws_secret_access_key for the source profiles, basically anything that should be kept secret. The config file should contain any other non-sensitive configuration such as the region, role_arn, source_profile, output etc. That way one can share config files and never modify the credentials except when rotating key material. I can also add new roles trivially by simply modifying the config. This is how the CLI works and is the better of the two behaviours.

The fact that the CLI has a different naming scheme for the profile heading is a separate issue. @uriahcarpenter said that duplicating the profiles in the config file is a workaround but it does not solve the real issue of how the credentials are found.

Today’s release should hopefully help with some of these issues. The 1.x SDK will now fall back to “profile X” if there is no “X” profile defined and the SDK is configured to look for profile X. There is no longer a warning if a “profile X” exists in the file.

Hi!

Other SDKs seem to swap between the behaviours depending on the environment variable AWS_SDK_LOAD_CONFIG=true. I wouldn’t even mind if there is a java version of that environment variable so people can opt in.

I think everybody would be happy with that. And I would not consider that a breaking change if you need to opt in via an environment variable.

For anyone who needs a Scala version of @adrian-baker’s snippet:

class AssumeRoleCredentialsProvider extends AWSCredentialsProvider {

  private lazy val delegate: ProfileAssumeRoleCredentialsProvider = {
    val profiles = Seq(
      AwsProfileFileLocationProvider.DEFAULT_CONFIG_LOCATION_PROVIDER,
      AwsProfileFileLocationProvider.DEFAULT_CREDENTIALS_LOCATION_PROVIDER
    )
      .map(_.getLocation)
      .map(BasicProfileConfigLoader.INSTANCE.loadProfiles)
      .flatMap(_.getProfiles.values.asScala)
      .map(profile => new BasicProfile(profile.getProfileName.stripPrefix("profile "), profile.getProperties))
      .groupBy(_.getProfileName)
      .mapValues { profiles =>
        new BasicProfile(
          profiles.head.getProfileName,
          profiles.flatMap(_.getProperties.asScala.toSeq).toMap.asJava
        )
      }

    val profileName = AwsProfileNameLoader.INSTANCE.loadProfileName
    val profile = profiles.getOrElse(profileName, throw new RuntimeException(
      s"Profile $profileName' not found in ${profiles.keys}"
    ))
    new ProfileAssumeRoleCredentialsProvider(
      STSProfileCredentialsServiceLoader.getInstance,
      new AllProfiles(profiles.asJava),
      profile
    )
  }

  override def getCredentials: AWSCredentials = delegate.getCredentials
  override def refresh(): Unit = delegate.refresh()
}

Nice workaround!

Whether or not it’s considered a bug, I can’t see a way to fix it in a backwards-compatible way, because customers could be intentionally or unintentionally relying on this behavior. It’s been around for a long time.

This is a particularly egregious deviation from the CLI’s behavior, but there are others that we’d want to fix as part of any solution we’d come up with.

A higher-work, higher-accuracy workaround would be to back-port the 2.0 profile implementation to 1.11 and make it opt-in, which would be my suggestion for how to fix this.

Note a minor niggle with the code above – while expecting users to drop profile makes it more consistent with the CLI it will cause any region = XXX setting in the [profile xxx] to be ignored.

If you want region to be respected remove the .map(...) line and pass profile xxx (or go all the way and replace the region provider).

Great workaround though – TY.

Hey guys, is there any progress with this ticket?

We are using Boto3 SDK + Assuming Roles + Athena. Everything works fine up to the moment when we are trying to connect to Athena (we are creating SQL Alchemy engine). Our AWS CLI is configured to use both ~/.aws/config and ~/.aws/credentials.

I think the problem could be related to Athena using jdbc and as a result it falls back Java AWS SDK and Python being a wrapper around. As a result we can reach all AWS resources but Athena. With Athena it either doesn’t assume roles and as a result it tries to locate KMS key under wrong account or if I pass environment variable: AWS_PROFILE={profile} - it fails with an error: Unable to load AWS credentials from any provider in the chain

@declankeyesbevan

Thank you.