software.amazon.awssdk.auth.credentials.AwsCredentials Java Examples

The following examples show how to use software.amazon.awssdk.auth.credentials.AwsCredentials. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EnvironmentAwsCredentialsProvider.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Override
public AwsCredentials resolveCredentials() {
    String accessKey = environment.getProperty(ACCESS_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_ACCESS_KEY_ENV_VAR, String.class, (String) null));

    String secretKey = environment.getProperty(SECRET_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_SECRET_KEY_ENV_VAR, String.class, (String) null));
    accessKey = StringUtils.trim(accessKey);
    secretKey = StringUtils.trim(secretKey);
    String sessionToken = StringUtils.trim(environment.getProperty(AWS_SESSION_TOKEN_ENV_VAR, String.class, (String) null));

    if (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey)) {
        throw SdkClientException.create(
                "Unable to load AWS credentials from environment "
                        + "(" + ACCESS_KEY_ENV_VAR + " (or " + ALTERNATE_ACCESS_KEY_ENV_VAR + ") and "
                        + SECRET_KEY_ENV_VAR + " (or " + ALTERNATE_SECRET_KEY_ENV_VAR + "))");
    }

    return sessionToken == null
            ? AwsBasicCredentials.create(accessKey, secretKey)
            : AwsSessionCredentials.create(accessKey, secretKey, sessionToken);
}
 
Example #2
Source File: AbstractAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
protected final byte[] deriveSigningKey(AwsCredentials credentials, Instant signingInstant, String region, String service) {
    String cacheKey = createSigningCacheKeyName(credentials, region, service);
    SignerKey signerKey = SIGNER_CACHE.get(cacheKey);

    if (signerKey != null && signerKey.isValidForDate(signingInstant)) {
        return signerKey.getSigningKey();
    }

    LOG.trace(() -> "Generating a new signing key as the signing key not available in the cache for the date: " +
            signingInstant.toEpochMilli());
    byte[] signingKey = newSigningKey(credentials,
            Aws4SignerUtils.formatDateStamp(signingInstant),
            region,
            service);
    SIGNER_CACHE.add(cacheKey, new SignerKey(signingInstant, signingKey));
    return signingKey;
}
 
Example #3
Source File: DefaultPollyPresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void presign_requestLevelCredentials_honored() {
    AwsCredentials requestCredentials = AwsBasicCredentials.create("akid2", "skid2");

    PollyPresigner presigner = DefaultPollyPresigner.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(credentialsProvider)
            .build();

    SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
            .overrideConfiguration(AwsRequestOverrideConfiguration.builder()
                    .credentialsProvider(StaticCredentialsProvider.create(requestCredentials)).build())
            .build();

    SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
            .synthesizeSpeechRequest(synthesizeSpeechRequest)
            .signatureDuration(Duration.ofHours(3))
            .build();

    PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);

    assertThat(presignedSynthesizeSpeechRequest.url().getQuery()).contains("X-Amz-Credential=akid2");
}
 
Example #4
Source File: SignerTestUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public static SdkHttpFullRequest signRequest(BaseAws4Signer signer,
                                             SdkHttpFullRequest request,
                                             AwsCredentials credentials,
                                             String signingName,
                                             Clock signingDateOverride,
                                             String region) {

    Aws4SignerParams signerParams = Aws4SignerParams.builder()
                                                    .awsCredentials(credentials)
                                                    .signingName(signingName)
                                                    .signingClockOverride(signingDateOverride)
                                                    .signingRegion(Region.of(region))
                                                    .build();

    return signer.sign(request, signerParams);
}
 
Example #5
Source File: SignerTestUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public static AsyncRequestBody signAsyncRequest(BaseAsyncAws4Signer signer,
                                                SdkHttpFullRequest request,
                                                AsyncRequestBody asyncRequestBody,
                                                AwsCredentials credentials,
                                                String signingName,
                                                Clock signingDateOverride,
                                                String region) {

    Aws4SignerParams signerParams = Aws4SignerParams.builder()
        .awsCredentials(credentials)
        .signingName(signingName)
        .signingClockOverride(signingDateOverride)
        .signingRegion(Region.of(region))
        .build();

    final Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signerParams);

    return signer.signAsync(request, asyncRequestBody, requestParams, signerParams);
}
 
Example #6
Source File: SignerTestUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public static SdkHttpFullRequest presignRequest(BaseAws4Signer presigner,
                                                SdkHttpFullRequest request,
                                                AwsCredentials credentials,
                                                Instant expiration,
                                                String signingName,
                                                Clock signingDateOverride,
                                                String region) {
    Aws4PresignerParams signerParams = Aws4PresignerParams.builder()
                                                          .awsCredentials(credentials)
                                                          .expirationTime(expiration)
                                                          .signingName(signingName)
                                                          .signingClockOverride(signingDateOverride)
                                                          .signingRegion(Region.of(region))
                                                          .build();

    return presigner.presign(request, signerParams);
}
 
Example #7
Source File: V2CredentialWrapper.java    From amazon-kinesis-client with Apache License 2.0 6 votes vote down vote up
@Override
public AwsCredentials resolveCredentials() {
    AWSCredentials current = oldCredentialsProvider.getCredentials();
    if (current instanceof AWSSessionCredentials) {
        return AwsSessionCredentials.create(current.getAWSAccessKeyId(), current.getAWSSecretKey(), ((AWSSessionCredentials) current).getSessionToken());
    }
    return new AwsCredentials() {
        @Override
        public String accessKeyId() {
            return current.getAWSAccessKeyId();
        }

        @Override
        public String secretAccessKey() {
            return current.getAWSSecretKey();
        }
    };
}
 
Example #8
Source File: S3BundlePersistenceProvider.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private AwsCredentialsProvider getCredentialsProvider(final ProviderConfigurationContext configurationContext) {
    final String credentialsProviderValue = configurationContext.getProperties().get(CREDENTIALS_PROVIDER_PROP);
    if (StringUtils.isBlank(credentialsProviderValue)) {
        throw new ProviderCreationException("The property '" + CREDENTIALS_PROVIDER_PROP + "' must be provided");
    }

    CredentialProvider credentialProvider;
    try {
        credentialProvider = CredentialProvider.valueOf(credentialsProviderValue);
    } catch (Exception e) {
        throw new ProviderCreationException("The property '" + CREDENTIALS_PROVIDER_PROP + "' must be one of ["
                + CredentialProvider.STATIC + ", " + CredentialProvider.DEFAULT_CHAIN + " ]");
    }

    if (CredentialProvider.STATIC == credentialProvider) {
        final String accesKeyValue = configurationContext.getProperties().get(ACCESS_KEY_PROP);
        final String secretAccessKey = configurationContext.getProperties().get(SECRET_ACCESS_KEY_PROP);

        if (StringUtils.isBlank(accesKeyValue) || StringUtils.isBlank(secretAccessKey)) {
            throw new ProviderCreationException("The properties '" + ACCESS_KEY_PROP + "' and '" + SECRET_ACCESS_KEY_PROP
                    + "' must be provided when using " + CredentialProvider.STATIC + " credentials provider");
        }

        LOGGER.debug("Creating StaticCredentialsProvider");
        final AwsCredentials awsCredentials = AwsBasicCredentials.create(accesKeyValue, secretAccessKey);
        return StaticCredentialsProvider.create(awsCredentials);

    } else {
        LOGGER.debug("Creating DefaultCredentialsProvider");
        return DefaultCredentialsProvider.create();
    }
}
 
Example #9
Source File: AwsS3SenderTest.java    From fluency with Apache License 2.0 5 votes vote down vote up
@Test
void buildClientWithCustomizedConfig()
{
    AwsS3Sender.Config config = new AwsS3Sender.Config();
    config.setEndpoint("https://another.s3endpoi.nt");
    config.setRegion("ap-northeast-1");
    config.setAwsAccessKeyId("foo");
    config.setAwsSecretAccessKey("bar");

    S3Client s3Client = mock(S3Client.class);
    S3ClientBuilder s3ClientBuilder = mock(S3ClientBuilder.class);
    doReturn(s3Client).when(s3ClientBuilder).build();
    doAnswer(invocation -> {
        AwsCredentialsProvider provider = invocation.getArgument(0);
        AwsCredentials awsCredentials = provider.resolveCredentials();
        assertEquals("foo", awsCredentials.accessKeyId());
        assertEquals("bar", awsCredentials.secretAccessKey());
        return null;
    }).when(s3ClientBuilder).credentialsProvider(any());

    new AwsS3Sender(s3ClientBuilder, config);

    verify(s3ClientBuilder, times(1)).build();
    verify(s3ClientBuilder, times(1)).endpointOverride(eq(URI.create("https://another.s3endpoi.nt")));
    verify(s3ClientBuilder, times(1)).region(eq(Region.AP_NORTHEAST_1));
    verify(s3ClientBuilder, times(1)).credentialsProvider(any());
}
 
Example #10
Source File: AwsAccount.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@Override
public AwsCredentials resolveCredentials() {
  // check, if account is auto-discovered
  if (this.isAutoDiscovered()) {
    // then, hand it down to the default AWS provider chain
    return DEFAULT_PROVIDER.resolveCredentials();
  }

  // otherwise, we need to specify the stored credentials
  return this;
}
 
Example #11
Source File: Aws4SignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that if passed anonymous credentials, signer will not generate a signature.
 */
@Test
public void testAnonymous() throws Exception {
    AwsCredentials credentials = AnonymousCredentialsProvider.create().resolveCredentials();
    SdkHttpFullRequest request = generateBasicRequest().build();

    SignerTestUtils.signRequest(signer, request, credentials, "demo", signingOverrideClock, "us-east-1");

    assertNull(request.headers().get("Authorization"));
}
 
Example #12
Source File: ProcessCredentialsProvider.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the process output to retrieve the credentials.
 */
private AwsCredentials credentials(JsonNode credentialsJson) {
    String accessKeyId = getText(credentialsJson, "AccessKeyId");
    String secretAccessKey = getText(credentialsJson, "SecretAccessKey");
    String sessionToken = getText(credentialsJson, "SessionToken");

    Validate.notEmpty(accessKeyId, "AccessKeyId cannot be empty.");
    Validate.notEmpty(secretAccessKey, "SecretAccessKey cannot be empty.");

    if (sessionToken != null) {
        return AwsSessionCredentials.create(accessKeyId, secretAccessKey, sessionToken);
    } else {
        return AwsBasicCredentials.create(accessKeyId, secretAccessKey);
    }
}
 
Example #13
Source File: ProcessCredentialsProvider.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * @see #builder()
 */
private ProcessCredentialsProvider(Builder builder) {
    List<String> cmd = new ArrayList<>();

    if (Platform.isWindows()) {
        cmd.add("cmd.exe");
        cmd.add("/C");
    } else {
        cmd.add("sh");
        cmd.add("-c");
    }

    String builderCommand = Validate.paramNotNull(builder.command, "command");

    cmd.add(builderCommand);

    this.command = Collections.unmodifiableList(cmd);
    this.processOutputLimit = Validate.isPositive(builder.processOutputLimit, "processOutputLimit");
    this.credentialRefreshThreshold = Validate.isPositive(builder.credentialRefreshThreshold, "expirationBuffer");

    CachedSupplier.Builder<AwsCredentials> cacheBuilder = CachedSupplier.builder(this::refreshCredentials);
    if (builder.asyncCredentialUpdateEnabled) {
        cacheBuilder.prefetchStrategy(new NonBlocking("process-credentials-provider"));
    }

    this.processCredentialCache = cacheBuilder.build();
}
 
Example #14
Source File: SystemSettingsCredentialsProvider.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public AwsCredentials resolveCredentials() {
    String accessKey = trim(loadSetting(SdkSystemSetting.AWS_ACCESS_KEY_ID).orElse(null));
    String secretKey = trim(loadSetting(SdkSystemSetting.AWS_SECRET_ACCESS_KEY).orElse(null));
    String sessionToken = trim(loadSetting(SdkSystemSetting.AWS_SESSION_TOKEN).orElse(null));

    if (StringUtils.isEmpty(accessKey)) {
        throw SdkClientException.builder()
                                .message(String.format("Unable to load credentials from system settings. Access key must be" +
                                         " specified either via environment variable (%s) or system property (%s).",
                                         SdkSystemSetting.AWS_ACCESS_KEY_ID.environmentVariable(),
                                         SdkSystemSetting.AWS_ACCESS_KEY_ID.property()))
                                .build();
    }

    if (StringUtils.isEmpty(secretKey)) {
        throw SdkClientException.builder()
                                .message(String.format("Unable to load credentials from system settings. Secret key must be" +
                                         " specified either via environment variable (%s) or system property (%s).",
                                         SdkSystemSetting.AWS_SECRET_ACCESS_KEY.environmentVariable(),
                                         SdkSystemSetting.AWS_SECRET_ACCESS_KEY.property()))
                                .build();
    }

    return sessionToken == null ? AwsBasicCredentials.create(accessKey, secretKey)
                                : AwsSessionCredentials.create(accessKey, secretKey, sessionToken);
}
 
Example #15
Source File: ProfileCredentialsUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Load a set of session credentials that have been configured in this profile.
 */
private AwsCredentialsProvider sessionProfileCredentialsProvider() {
    requireProperties(ProfileProperty.AWS_ACCESS_KEY_ID,
                      ProfileProperty.AWS_SECRET_ACCESS_KEY,
                      ProfileProperty.AWS_SESSION_TOKEN);
    AwsCredentials credentials = AwsSessionCredentials.create(properties.get(ProfileProperty.AWS_ACCESS_KEY_ID),
                                                              properties.get(ProfileProperty.AWS_SECRET_ACCESS_KEY),
                                                              properties.get(ProfileProperty.AWS_SESSION_TOKEN));
    return StaticCredentialsProvider.create(credentials);
}
 
Example #16
Source File: ProfileCredentialsUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Load a basic set of credentials that have been configured in this profile.
 */
private AwsCredentialsProvider basicProfileCredentialsProvider() {
    requireProperties(ProfileProperty.AWS_ACCESS_KEY_ID,
                      ProfileProperty.AWS_SECRET_ACCESS_KEY);
    AwsCredentials credentials = AwsBasicCredentials.create(properties.get(ProfileProperty.AWS_ACCESS_KEY_ID),
                                                                 properties.get(ProfileProperty.AWS_SECRET_ACCESS_KEY));
    return StaticCredentialsProvider.create(credentials);
}
 
Example #17
Source File: AbstractAwsSigner.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the individual access key ID and secret key from the specified credentials, trimming any extra whitespace from the
 * credentials.
 *
 * <p>Returns either a {@link AwsSessionCredentials} or a {@link AwsBasicCredentials} object, depending on the input type.
 *
 * @return A new credentials object with the sanitized credentials.
 */
protected AwsCredentials sanitizeCredentials(AwsCredentials credentials) {
    String accessKeyId = StringUtils.trim(credentials.accessKeyId());
    String secretKey = StringUtils.trim(credentials.secretAccessKey());

    if (credentials instanceof AwsSessionCredentials) {
        AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials;
        return AwsSessionCredentials.create(accessKeyId,
                                            secretKey,
                                            StringUtils.trim(sessionCredentials.sessionToken()));
    }

    return AwsBasicCredentials.create(accessKeyId, secretKey);
}
 
Example #18
Source File: AbstractAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a new signing key from the given parameters and returns it.
 */
private byte[] newSigningKey(AwsCredentials credentials,
                             String dateStamp, String regionName, String serviceName) {
    byte[] kSecret = ("AWS4" + credentials.secretAccessKey())
        .getBytes(Charset.forName("UTF-8"));
    byte[] kDate = sign(dateStamp, kSecret, SigningAlgorithm.HmacSHA256);
    byte[] kRegion = sign(regionName, kDate, SigningAlgorithm.HmacSHA256);
    byte[] kService = sign(serviceName, kRegion,
                           SigningAlgorithm.HmacSHA256);
    return sign(SignerConstant.AWS4_TERMINATOR, kService, SigningAlgorithm.HmacSHA256);
}
 
Example #19
Source File: AbstractAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Includes all the signing headers as request parameters for pre-signing.
 */
private void addPreSignInformationToRequest(SdkHttpFullRequest.Builder mutableRequest,
                                            String signedHeadersString,
                                            AwsCredentials sanitizedCredentials,
                                            Aws4SignerRequestParams signerParams,
                                            long expirationInSeconds) {

    String signingCredentials = sanitizedCredentials.accessKeyId() + "/" + signerParams.getScope();

    mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_ALGORITHM, SignerConstant.AWS4_SIGNING_ALGORITHM);
    mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_DATE, signerParams.getFormattedRequestSigningDateTime());
    mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_SIGNED_HEADER, signedHeadersString);
    mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_EXPIRES, Long.toString(expirationInSeconds));
    mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_CREDENTIAL, signingCredentials);
}
 
Example #20
Source File: AbstractAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the authorization header to be included in the request.
 */
private String buildAuthorizationHeader(byte[] signature,
                                        AwsCredentials credentials,
                                        Aws4SignerRequestParams signerParams,
                                        String signedHeadersString) {

    String signingCredentials = credentials.accessKeyId() + "/" + signerParams.getScope();
    String credential = "Credential=" + signingCredentials;
    String signerHeaders = "SignedHeaders=" + signedHeadersString;
    String signatureHeader = "Signature=" + BinaryUtils.toHex(signature);

    return SignerConstant.AWS4_SIGNING_ALGORITHM + " " + credential + ", " + signerHeaders + ", " + signatureHeader;
}
 
Example #21
Source File: S3ClientConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public AwsCredentialsProvider awsCredentialsProvider(S3ClientConfigurarionProperties s3props) {

    if (StringUtils.isBlank(s3props.getAccessKeyId())) {
        // Return default provider
        return DefaultCredentialsProvider.create();
    } 
    else {
        // Return custom credentials provider
        return () -> {
            AwsCredentials creds = AwsBasicCredentials.create(s3props.getAccessKeyId(), s3props.getSecretAccessKey());
            return creds;
        };
    }
}
 
Example #22
Source File: AbstractAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Step 3 of the AWS Signature version 4 calculation. It involves deriving
 * the signing key and computing the signature. Refer to
 * http://docs.aws.amazon
 * .com/general/latest/gr/sigv4-calculate-signature.html
 */
protected final byte[] deriveSigningKey(AwsCredentials credentials, Aws4SignerRequestParams signerRequestParams) {
    return deriveSigningKey(credentials,
            Instant.ofEpochMilli(signerRequestParams.getRequestSigningDateTimeMilli()),
            signerRequestParams.getRegionName(),
            signerRequestParams.getServiceSigningName());
}
 
Example #23
Source File: AbstractAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
protected SdkHttpFullRequest.Builder doPresign(SdkHttpFullRequest request,
                                               Aws4SignerRequestParams requestParams,
                                               U signingParams) {

    SdkHttpFullRequest.Builder mutableRequest = request.toBuilder();

    long expirationInSeconds = getSignatureDurationInSeconds(requestParams, signingParams);
    addHostHeader(mutableRequest);

    AwsCredentials sanitizedCredentials = sanitizeCredentials(signingParams.awsCredentials());
    if (sanitizedCredentials instanceof AwsSessionCredentials) {
        // For SigV4 pre-signing URL, we need to add "X-Amz-Security-Token"
        // as a query string parameter, before constructing the canonical
        // request.
        mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_SECURITY_TOKEN,
                                            ((AwsSessionCredentials) sanitizedCredentials).sessionToken());
    }

    // Add the important parameters for v4 signing
    Map<String, List<String>> canonicalizedHeaders = canonicalizeSigningHeaders(mutableRequest.headers());
    String signedHeadersString = getSignedHeadersString(canonicalizedHeaders);

    addPreSignInformationToRequest(mutableRequest, signedHeadersString, sanitizedCredentials,
                                   requestParams, expirationInSeconds);

    String contentSha256 = calculateContentHashPresign(mutableRequest, signingParams);

    String canonicalRequest = createCanonicalRequest(mutableRequest, canonicalizedHeaders, signedHeadersString,
                                                     contentSha256, signingParams.doubleUrlEncode());

    String stringToSign = createStringToSign(canonicalRequest, requestParams);

    byte[] signingKey = deriveSigningKey(sanitizedCredentials, requestParams);

    byte[] signature = computeSignature(stringToSign, signingKey);

    mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_SIGNATURE, BinaryUtils.toHex(signature));

    return mutableRequest;
}
 
Example #24
Source File: AbstractAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
protected SdkHttpFullRequest.Builder doSign(SdkHttpFullRequest request,
                                            Aws4SignerRequestParams requestParams,
                                            T signingParams) {

    SdkHttpFullRequest.Builder mutableRequest = request.toBuilder();
    AwsCredentials sanitizedCredentials = sanitizeCredentials(signingParams.awsCredentials());
    if (sanitizedCredentials instanceof AwsSessionCredentials) {
        addSessionCredentials(mutableRequest, (AwsSessionCredentials) sanitizedCredentials);
    }

    addHostHeader(mutableRequest);
    addDateHeader(mutableRequest, requestParams.getFormattedRequestSigningDateTime());

    String contentSha256 = calculateContentHash(mutableRequest, signingParams);
    mutableRequest.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)
                  .filter(h -> h.equals("required"))
                  .ifPresent(h -> mutableRequest.putHeader(SignerConstant.X_AMZ_CONTENT_SHA256, contentSha256));

    Map<String, List<String>> canonicalHeaders = canonicalizeSigningHeaders(mutableRequest.headers());
    String signedHeadersString = getSignedHeadersString(canonicalHeaders);

    String canonicalRequest = createCanonicalRequest(mutableRequest,
                                                     canonicalHeaders,
                                                     signedHeadersString,
                                                     contentSha256,
                                                     signingParams.doubleUrlEncode());

    String stringToSign = createStringToSign(canonicalRequest, requestParams);

    byte[] signingKey = deriveSigningKey(sanitizedCredentials, requestParams);

    byte[] signature = computeSignature(stringToSign, signingKey);

    mutableRequest.putHeader(SignerConstant.AUTHORIZATION,
                             buildAuthorizationHeader(signature, sanitizedCredentials, requestParams, signedHeadersString));

    processRequestPayload(mutableRequest, signature, signingKey, requestParams, signingParams);

    return mutableRequest;
}
 
Example #25
Source File: AssumeRoleIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void profileCredentialsProviderCanAssumeRoles() throws InterruptedException {
    String ASSUME_ROLE_PROFILE =
        "[source]\n"
        + "aws_access_key_id = " + userCredentials.accessKeyId() + "\n"
        + "aws_secret_access_key = " + userCredentials.secretAccessKey() + "\n"
        + "\n"
        + "[test]\n"
        + "region = us-west-1\n"
        + "source_profile = source\n"
        + "role_arn = " + ROLE_ARN;

    ProfileFile profiles = ProfileFile.builder()
                                      .content(new StringInputStream(ASSUME_ROLE_PROFILE))
                                      .type(ProfileFile.Type.CREDENTIALS)
                                      .build();
    Optional<Profile> profile = profiles.profile("test");
    AwsCredentialsProvider awsCredentialsProvider =
        new ProfileCredentialsUtils(profile.get(), profiles::profile).credentialsProvider().get();


    // Try to assume the role until the eventual consistency catches up.
    AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials)
                                          .ignoringException(StsException.class)
                                          .orFail();

    assertThat(awsCredentials.accessKeyId()).isNotBlank();
    assertThat(awsCredentials.secretAccessKey()).isNotBlank();
    ((SdkAutoCloseable) awsCredentialsProvider).close();
}
 
Example #26
Source File: AssumeRoleIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void profileCredentialProviderCanAssumeRolesWithEnvironmentCredentialSource() throws InterruptedException {
    EnvironmentVariableHelper.run(helper -> {
        helper.set("AWS_ACCESS_KEY_ID", userCredentials.accessKeyId());
        helper.set("AWS_SECRET_ACCESS_KEY", userCredentials.secretAccessKey());

        String ASSUME_ROLE_PROFILE =
            "[test]\n"
            + "region = us-west-1\n"
            + "credential_source = Environment\n"
            + "role_arn = " + ROLE_ARN;

        ProfileFile profiles = ProfileFile.builder()
                                          .content(new StringInputStream(ASSUME_ROLE_PROFILE))
                                          .type(ProfileFile.Type.CREDENTIALS)
                                          .build();
        Optional<Profile> profile = profiles.profile("test");
        AwsCredentialsProvider awsCredentialsProvider =
            new ProfileCredentialsUtils(profile.get(), profiles::profile).credentialsProvider().get();


        // Try to assume the role until the eventual consistency catches up.
        AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials)
                                              .ignoringException(StsException.class)
                                              .orFail();

        assertThat(awsCredentials.accessKeyId()).isNotBlank();
        assertThat(awsCredentials.secretAccessKey()).isNotBlank();
        ((SdkAutoCloseable) awsCredentialsProvider).close();
    });
}
 
Example #27
Source File: AssumeRoleIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void profileCredentialProviderWithEnvironmentCredentialSourceAndSystemProperties() throws InterruptedException {
    System.setProperty("aws.accessKeyId", userCredentials.accessKeyId());
    System.setProperty("aws.secretAccessKey", userCredentials.secretAccessKey());

    EnvironmentVariableHelper.run(helper -> {
        helper.remove("AWS_ACCESS_KEY_ID");
        helper.remove("AWS_SECRET_ACCESS_KEY");

        String ASSUME_ROLE_PROFILE =
            "[test]\n"
            + "region = us-west-1\n"
            + "credential_source = Environment\n"
            + "role_arn = " + ROLE_ARN;

        ProfileFile profiles = ProfileFile.builder()
                                          .content(new StringInputStream(ASSUME_ROLE_PROFILE))
                                          .type(ProfileFile.Type.CREDENTIALS)
                                          .build();
        Optional<Profile> profile = profiles.profile("test");
        AwsCredentialsProvider awsCredentialsProvider =
            new ProfileCredentialsUtils(profile.get(), profiles::profile).credentialsProvider().get();


        // Try to assume the role until the eventual consistency catches up.
        AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials)
                                              .ignoringException(StsException.class)
                                              .orFail();

        assertThat(awsCredentials.accessKeyId()).isNotBlank();
        assertThat(awsCredentials.secretAccessKey()).isNotBlank();
        ((SdkAutoCloseable) awsCredentialsProvider).close();
    });

    System.clearProperty("aws.accessKeyId");
    System.clearProperty("aws.secretAccessKey");
}
 
Example #28
Source File: DefaultPollyPresigner.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private ExecutionAttributes createExecutionAttributes(PresignRequest presignRequest, PollyRequest requestToPresign) {
    Instant signatureExpiration = Instant.now().plus(presignRequest.signatureDuration());
    AwsCredentials credentials = resolveCredentialsProvider(requestToPresign).resolveCredentials();
    Validate.validState(credentials != null, "Credential providers must never return null.");

    return new ExecutionAttributes()
            .putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, credentials)
            .putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, SIGNING_NAME)
            .putAttribute(AwsExecutionAttribute.AWS_REGION, region())
            .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, region())
            .putAttribute(SdkInternalExecutionAttribute.IS_FULL_DUPLEX, false)
            .putAttribute(SdkExecutionAttribute.CLIENT_TYPE, ClientType.SYNC)
            .putAttribute(SdkExecutionAttribute.SERVICE_NAME, SERVICE_NAME)
            .putAttribute(PRESIGNER_EXPIRATION, signatureExpiration);
}
 
Example #29
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void putObject_CredentialsCanBeOverriddenAtTheRequestLevel() {
    AwsCredentials clientCredentials = AwsBasicCredentials.create("a", "a");
    AwsCredentials requestCredentials = AwsBasicCredentials.create("b", "b");

    S3Presigner presigner = presignerBuilder().credentialsProvider(() -> clientCredentials).build();


    AwsRequestOverrideConfiguration overrideConfiguration =
        AwsRequestOverrideConfiguration.builder()
                                       .credentialsProvider(() -> requestCredentials)
                                       .build();

    PresignedPutObjectRequest presignedWithClientCredentials =
        presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                         .putObjectRequest(go -> go.bucket("foo34343434")
                                                                   .key("bar")));

    PresignedPutObjectRequest presignedWithRequestCredentials =
        presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                         .putObjectRequest(go -> go.bucket("foo34343434")
                                                                   .key("bar")
                                                                   .overrideConfiguration(overrideConfiguration)));

    System.out.println(presignedWithClientCredentials.url());

    assertThat(presignedWithClientCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0))
        .startsWith("a");
    assertThat(presignedWithRequestCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0))
        .startsWith("b");
}
 
Example #30
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void getObject_CredentialsCanBeOverriddenAtTheRequestLevel() {
    AwsCredentials clientCredentials = AwsBasicCredentials.create("a", "a");
    AwsCredentials requestCredentials = AwsBasicCredentials.create("b", "b");

    S3Presigner presigner = presignerBuilder().credentialsProvider(() -> clientCredentials).build();


    AwsRequestOverrideConfiguration overrideConfiguration =
        AwsRequestOverrideConfiguration.builder()
                                       .credentialsProvider(() -> requestCredentials)
                                       .build();

    PresignedGetObjectRequest presignedWithClientCredentials =
        presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                         .getObjectRequest(go -> go.bucket("foo34343434")
                                                                   .key("bar")));

    PresignedGetObjectRequest presignedWithRequestCredentials =
        presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                         .getObjectRequest(go -> go.bucket("foo34343434")
                                                                   .key("bar")
                                                                   .overrideConfiguration(overrideConfiguration)));

    System.out.println(presignedWithClientCredentials.url());

    assertThat(presignedWithClientCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0))
        .startsWith("a");
    assertThat(presignedWithRequestCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0))
        .startsWith("b");
}