Java Code Examples for software.amazon.awssdk.auth.credentials.AwsBasicCredentials#create()

The following examples show how to use software.amazon.awssdk.auth.credentials.AwsBasicCredentials#create() . 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: S3PinotFS.java    From incubator-pinot with Apache License 2.0 7 votes vote down vote up
@Override
public void init(Configuration config) {
  Preconditions.checkArgument(!isNullOrEmpty(config.getString(REGION)));
  String region = config.getString(REGION);

  AwsCredentialsProvider awsCredentialsProvider;
  try {

    if (!isNullOrEmpty(config.getString(ACCESS_KEY)) && !isNullOrEmpty(config.getString(SECRET_KEY))) {
      String accessKey = config.getString(ACCESS_KEY);
      String secretKey = config.getString(SECRET_KEY);
      AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(accessKey, secretKey);
      awsCredentialsProvider = StaticCredentialsProvider.create(awsBasicCredentials);
    } else {
      awsCredentialsProvider =
          AwsCredentialsProviderChain.builder().addCredentialsProvider(SystemPropertyCredentialsProvider.create())
              .addCredentialsProvider(EnvironmentVariableCredentialsProvider.create()).build();
    }

    _s3Client = S3Client.builder().region(Region.of(region)).credentialsProvider(awsCredentialsProvider).build();
  } catch (S3Exception e) {
    throw new RuntimeException("Could not initialize S3PinotFS", e);
  }
}
 
Example 2
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 3
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 4
Source File: AwsS3Sender.java    From fluency with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected S3Client buildClient(S3ClientBuilder s3ClientBuilder)
{
    if (config.getEndpoint() != null) {
        try {
            URI uri = new URI(config.getEndpoint());
            s3ClientBuilder.endpointOverride(uri);
        }
        catch (URISyntaxException e) {
            throw new NonRetryableException(
                    String.format("Invalid endpoint. %s", config.getEndpoint()), e);
        }
    }

    if (config.getRegion() != null) {
        s3ClientBuilder.region(Region.of(config.getRegion()));
    }

    if (config.getAwsAccessKeyId() != null && config.getAwsSecretAccessKey() != null) {
        AwsBasicCredentials credentials =
                AwsBasicCredentials.create(config.getAwsAccessKeyId(), config.getAwsSecretAccessKey());
        s3ClientBuilder.credentialsProvider(StaticCredentialsProvider.create(credentials));
    }

    return s3ClientBuilder.build();
}
 
Example 5
Source File: S3TestHelper.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
public static S3Client createS3Client(final Integer mappedPort) {
    final AwsBasicCredentials credentials = AwsBasicCredentials.create("test", "test");
    final StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(credentials);

    return S3Client.builder()
            .credentialsProvider(credentialsProvider)
            .endpointOverride(URI.create(String.format("http://localhost:%d", mappedPort)))
            .region(Region.EU_CENTRAL_1)
            .serviceConfiguration(S3Configuration.builder()
                    .pathStyleAccessEnabled(true)
                    .build())
            .overrideConfiguration(ClientOverrideConfiguration
                    .builder()
                    .putAdvancedOption(SdkAdvancedClientOption.SIGNER, new NoOpSigner())
                    .build())
            .build();
}
 
Example 6
Source File: Aws4SignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPresigning() throws Exception {
    final String expectedAmzSignature = "bf7ae1c2f266d347e290a2aee7b126d38b8a695149d003b9fab2ed1eb6d6ebda";
    final String expectedAmzCredentials = "access/19810216/us-east-1/demo/aws4_request";
    final String expectedAmzHeader = "19810216T063000Z";
    final String expectedAmzExpires = "604800";

    AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret");
    // Test request without 'x-amz-sha256' header

    SdkHttpFullRequest request = generateBasicRequest().build();

    SdkHttpFullRequest signed = SignerTestUtils.presignRequest(signer, request, credentials, null, "demo",
                                                               signingOverrideClock, "us-east-1");
    assertEquals(expectedAmzSignature, signed.rawQueryParameters().get("X-Amz-Signature").get(0));
    assertEquals(expectedAmzCredentials, signed.rawQueryParameters().get("X-Amz-Credential").get(0));
    assertEquals(expectedAmzHeader, signed.rawQueryParameters().get("X-Amz-Date").get(0));
    assertEquals(expectedAmzExpires, signed.rawQueryParameters().get("X-Amz-Expires").get(0));
}
 
Example 7
Source File: Aws4SignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void queryParamsWithNullValuesAreStillSignedWithTrailingEquals() throws Exception {
    final String expectedAuthorizationHeaderWithoutSha256Header =
            "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " +
            "SignedHeaders=host;x-amz-archive-description;x-amz-date, " +
            "Signature=c45a3ff1f028e83017f3812c06b4440f0b3240264258f6e18cd683b816990ba4";

    AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret");
    // Test request without 'x-amz-sha256' header
    SdkHttpFullRequest.Builder request = generateBasicRequest().putRawQueryParameter("Foo", (String) null);

    SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials,
                                                            "demo", signingOverrideClock, "us-east-1");
    assertThat(signed.firstMatchingHeader("Authorization"))
            .hasValue(expectedAuthorizationHeaderWithoutSha256Header);
}
 
Example 8
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 9
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 10
Source File: Aws4SignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * x-amzn-trace-id should not be signed as it may be mutated by proxies or load balancers.
 */
@Test
public void xAmznTraceId_NotSigned() throws Exception {
    AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid");
    SdkHttpFullRequest.Builder request = generateBasicRequest();
    request.putHeader("X-Amzn-Trace-Id", " Root=1-584b150a-708479cb060007ffbf3ee1da;Parent=36d3dbcfd150aac9;Sampled=1");

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

    assertThat(actual.firstMatchingHeader("Authorization"))
            .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " +
                      "SignedHeaders=host;x-amz-archive-description;x-amz-date, " +
                      "Signature=581d0042389009a28d461124138f1fe8eeb8daed87611d2a2b47fd3d68d81d73");
}
 
Example 11
Source File: Aws4SignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSigning() throws Exception {
    final String expectedAuthorizationHeaderWithoutSha256Header =
            "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " +
            "SignedHeaders=host;x-amz-archive-description;x-amz-date, " +
            "Signature=77fe7c02927966018667f21d1dc3dfad9057e58401cbb9ed64f1b7868288e35a";

    final String expectedAuthorizationHeaderWithSha256Header =
            "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " +
            "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-sha256, " +
            "Signature=e73e20539446307a5dc71252dbd5b97e861f1d1267456abda3ebd8d57e519951";


    AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret");
    // Test request without 'x-amz-sha256' header
    SdkHttpFullRequest.Builder request = generateBasicRequest();

    SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials,
                                                            "demo", signingOverrideClock, "us-east-1");
    assertThat(signed.firstMatchingHeader("Authorization"))
            .hasValue(expectedAuthorizationHeaderWithoutSha256Header);


    // Test request with 'x-amz-sha256' header
    request = generateBasicRequest();
    request.putHeader("x-amz-sha256", "required");

    signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1");
    assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorizationHeaderWithSha256Header);
}
 
Example 12
Source File: Aws4EventStreamSignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventStreamSigning() {
    TestVector testVector = generateTestVector();
    SdkHttpFullRequest.Builder request = testVector.httpFullRequest();
    AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret");
    SdkHttpFullRequest signedRequest =
        SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingClock(), "us-east-1");

    AsyncRequestBody transformedPublisher =
        SignerTestUtils.signAsyncRequest(signer, signedRequest, testVector.requestBodyPublisher(),
                                         credentials, "demo", signingClock(), "us-east-1");

    TestSubscriber testSubscriber = TestSubscriber.create();

    Flowable.fromPublisher(transformedPublisher)
            .flatMap(new Function<ByteBuffer, Publisher<?>>() {
                Queue<Message> messages = new LinkedList<>();
                MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message));

                @Override
                public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception {
                    decoder.feed(byteBuffer.array());
                    List<Message> messageList = new ArrayList<>();
                    while (!messages.isEmpty()) {
                        messageList.add(messages.poll());
                    }

                    return Flowable.fromIterable(messageList);
                }
            })
            .subscribe(testSubscriber);

    testSubscriber.assertNoErrors();
    testSubscriber.assertComplete();
    testSubscriber.assertValueSequence(testVector.expectedMessagePublisher().blockingIterable());
}
 
Example 13
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 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 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 16
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 17
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 18
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");
}
 
Example 19
Source File: Aws4EventStreamSignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * Test that without demand from subscriber, trailing empty frame is not delivered
 */
@Test
public void testBackPressure() {
    TestVector testVector = generateTestVector();
    SdkHttpFullRequest.Builder request = testVector.httpFullRequest();
    AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret");
    SdkHttpFullRequest signedRequest =
        SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingClock(), "us-east-1");

    AsyncRequestBody transformedPublisher =
        SignerTestUtils.signAsyncRequest(signer, signedRequest, testVector.requestBodyPublisher(),
                                         credentials, "demo", signingClock(), "us-east-1");


    Subscriber<Object> subscriber = Mockito.spy(new Subscriber<Object>() {

        @Override
        public void onSubscribe(Subscription s) {
            //Only request the number of request body (excluding trailing empty frame)
            s.request(testVector.requestBody().size());
        }

        @Override
        public void onNext(Object o) {
        }

        @Override
        public void onError(Throwable t) {
            Assert.fail("onError should never been called");

        }

        @Override
        public void onComplete() {
            Assert.fail("onComplete should never been called");

        }
    });

    Flowable.fromPublisher(transformedPublisher)
            .flatMap(new Function<ByteBuffer, Publisher<?>>() {
                Queue<Message> messages = new LinkedList<>();
                MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message));

                @Override
                public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception {
                    decoder.feed(byteBuffer.array());
                    List<Message> messageList = new ArrayList<>();
                    while (!messages.isEmpty()) {
                        messageList.add(messages.poll());
                    }
                    return Flowable.fromIterable(messageList);
                }
            })
            .subscribe(subscriber);


    // The number of events equal to the size of request body (excluding trailing empty frame)
    verify(subscriber, times(testVector.requestBody().size())).onNext(any());
    // subscriber is not terminated (no onError/onComplete) since trailing empty frame is not delivered yet
    verify(subscriber, never()).onError(any());
    verify(subscriber, never()).onComplete();
}
 
Example 20
Source File: EventStreamAws4SignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that when an event stream is open from one day to the next, the signature is properly signed for the day of the
 * event.
 */
@Test
public void openStreamEventSignaturesCanRollOverBetweenDays() {
    EventStreamAws4Signer signer = EventStreamAws4Signer.create();

    Region region = Region.US_WEST_2;
    AwsCredentials credentials = AwsBasicCredentials.create("a", "s");
    String signingName = "name";
    AdjustableClock clock = new AdjustableClock();
    clock.time = Instant.parse("2020-01-01T23:59:59Z");

    SdkHttpFullRequest initialRequest = SdkHttpFullRequest.builder()
                                                          .uri(URI.create("http://localhost:8080"))
                                                          .method(SdkHttpMethod.GET)
                                                          .build();
    SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, initialRequest, credentials, signingName, clock,
                                                                   region.id());

    ByteBuffer event = new Message(Collections.emptyMap(), "foo".getBytes(UTF_8)).toByteBuffer();

    Callable<ByteBuffer> lastEvent = () -> {
        clock.time = Instant.parse("2020-01-02T00:00:00Z");
        return event;
    };

    AsyncRequestBody requestBody = AsyncRequestBody.fromPublisher(Flowable.concatArray(Flowable.just(event),
                                                                                       Flowable.fromCallable(lastEvent)));

    AsyncRequestBody signedBody = SignerTestUtils.signAsyncRequest(signer, signedRequest, requestBody, credentials,
                                                                   signingName, clock, region.id());

    List<Message> signedMessages = readMessages(signedBody);
    assertThat(signedMessages.size()).isEqualTo(3);

    Map<String, HeaderValue> firstMessageHeaders = signedMessages.get(0).getHeaders();
    assertThat(firstMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-01T23:59:59Z");
    assertThat(Base64.getEncoder().encodeToString(firstMessageHeaders.get(":chunk-signature").getByteArray()))
        .isEqualTo("EFt7ZU043r/TJE8U+1GxJXscmNxoqmIdGtUIl8wE9u0=");

    Map<String, HeaderValue> lastMessageHeaders = signedMessages.get(2).getHeaders();
    assertThat(lastMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-02T00:00:00Z");
    assertThat(Base64.getEncoder().encodeToString(lastMessageHeaders.get(":chunk-signature").getByteArray()))
        .isEqualTo("UTRGo0D7BQytiVkH1VofR/8f3uFsM4V5QR1A8grr1+M=");

}