index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/SignerKeyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import org.junit.jupiter.api.Test;
public class SignerKeyTest {
@Test
public void isValidForDate_dayBefore_false() {
Instant signerDate = Instant.parse("2020-03-03T23:59:59Z");
SignerKey key = new SignerKey(signerDate, new byte[0]);
Instant dayBefore = Instant.parse("2020-03-02T23:59:59Z");
assertThat(key.isValidForDate(dayBefore)).isFalse();
}
@Test
public void isValidForDate_sameDay_true() {
Instant signerDate = Instant.parse("2020-03-03T23:59:59Z");
SignerKey key = new SignerKey(signerDate, new byte[0]);
Instant sameDay = Instant.parse("2020-03-03T01:02:03Z");
assertThat(key.isValidForDate(sameDay)).isTrue();
}
@Test
public void isValidForDate_dayAfter_false() {
Instant signerDate = Instant.parse("2020-03-03T23:59:59Z");
SignerKey key = new SignerKey(signerDate, new byte[0]);
Instant dayAfter = Instant.parse("2020-03-04T00:00:00Z");
assertThat(key.isValidForDate(dayAfter)).isFalse();
}
}
| 1,400 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/FifoCacheTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FifoCacheTest {
@Test
public void test() {
FifoCache<String> cache = new FifoCache<String>(3);
assertTrue(cache.size() == 0);
cache.add("k1", "v1");
assertTrue(cache.size() == 1);
cache.add("k1", "v11");
assertTrue(cache.size() == 1);
cache.add("k2", "v2");
assertTrue(cache.size() == 2);
cache.add("k3", "v3");
assertTrue(cache.size() == 3);
assertEquals("v11", cache.get("k1"));
assertEquals("v2", cache.get("k2"));
assertEquals("v3", cache.get("k3"));
cache.add("k4", "v4");
assertTrue(cache.size() == 3);
assertNull(cache.get("k1"));
}
@Test(expected = IllegalArgumentException.class)
public void testZeroSize() {
new FifoCache<Object>(0);
}
@Test(expected = IllegalArgumentException.class)
public void testIllegalArgument() {
new FifoCache<Object>(-1);
}
@Test
public void testSingleEntry() {
FifoCache<String> cache = new FifoCache<String>(1);
assertTrue(cache.size() == 0);
cache.add("k1", "v1");
assertTrue(cache.size() == 1);
cache.add("k1", "v11");
assertTrue(cache.size() == 1);
assertEquals("v11", cache.get("k1"));
cache.add("k2", "v2");
assertTrue(cache.size() == 1);
assertEquals("v2", cache.get("k2"));
assertNull(cache.get("k1"));
cache.add("k3", "v3");
assertTrue(cache.size() == 1);
assertEquals("v3", cache.get("k3"));
assertNull(cache.get("k2"));
}
}
| 1,401 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/DefaultCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.utils.StringInputStream;
class DefaultCredentialsProviderTest {
@Test
void resolveCredentials_ProfileCredentialsProviderWithProfileFile_returnsCredentials() {
DefaultCredentialsProvider provider = DefaultCredentialsProvider
.builder()
.profileFile(credentialFile("test", "access", "secret"))
.profileName("test")
.build();
assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> {
assertThat(awsCredentials.accessKeyId()).isEqualTo("access");
assertThat(awsCredentials.secretAccessKey()).isEqualTo("secret");
});
}
@Test
void resolveCredentials_ProfileCredentialsProviderWithProfileFileSupplier_resolvesCredentialsPerCall() {
List<ProfileFile> profileFileList = Arrays.asList(credentialFile("test", "access", "secret"),
credentialFile("test", "modified", "update"));
ProfileFileSupplier profileFileSupplier = supply(profileFileList);
DefaultCredentialsProvider provider = DefaultCredentialsProvider
.builder()
.profileFile(profileFileSupplier)
.profileName("test")
.build();
assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> {
assertThat(awsCredentials.accessKeyId()).isEqualTo("access");
assertThat(awsCredentials.secretAccessKey()).isEqualTo("secret");
});
assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> {
assertThat(awsCredentials.accessKeyId()).isEqualTo("modified");
assertThat(awsCredentials.secretAccessKey()).isEqualTo("update");
});
}
@Test
void resolveCredentials_ProfileCredentialsProviderWithProfileFileSupplier_returnsCredentials() {
ProfileFile profileFile = credentialFile("test", "access", "secret");
ProfileFileSupplier profileFileSupplier = ProfileFileSupplier.fixedProfileFile(profileFile);
DefaultCredentialsProvider provider = DefaultCredentialsProvider
.builder()
.profileFile(profileFileSupplier)
.profileName("test")
.build();
assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> {
assertThat(awsCredentials.accessKeyId()).isEqualTo("access");
assertThat(awsCredentials.secretAccessKey()).isEqualTo("secret");
});
}
@Test
void resolveCredentials_ProfileCredentialsProviderWithSupplierProfileFile_returnsCredentials() {
Supplier<ProfileFile> supplier = () -> credentialFile("test", "access", "secret");
DefaultCredentialsProvider provider = DefaultCredentialsProvider
.builder()
.profileFile(supplier)
.profileName("test")
.build();
assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> {
assertThat(awsCredentials.accessKeyId()).isEqualTo("access");
assertThat(awsCredentials.secretAccessKey()).isEqualTo("secret");
});
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private ProfileFile credentialFile(String name, String accessKeyId, String secretAccessKey) {
String contents = String.format("[%s]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
name, accessKeyId, secretAccessKey);
return credentialFile(contents);
}
private static ProfileFileSupplier supply(Iterable<ProfileFile> iterable) {
return iterable.iterator()::next;
}
}
| 1,402 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/EC2MetadataServiceMock.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static software.amazon.awssdk.core.SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import org.apache.commons.io.IOUtils;
import software.amazon.awssdk.auth.signer.internal.SignerTestUtils;
import software.amazon.awssdk.utils.StringUtils;
/**
* Mock server for imitating the Amazon EC2 Instance Metadata Service. Tests can
* use this class to start up a server on a localhost port, and control what
* response the server will send when a connection is made.
*/
//TODO: this should really be replaced by WireMock
public class EC2MetadataServiceMock {
private static final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: ";
private static final String OUTPUT_END_OF_HEADERS = "\r\n\r\n";
private final String securityCredentialsResource;
private EC2MockMetadataServiceListenerThread hosmMockServerThread;
public EC2MetadataServiceMock(String securityCredentialsResource) {
this.securityCredentialsResource = securityCredentialsResource;
}
/**
* Sets the name of the file that should be sent back as the response from
* this mock server. The files are loaded from the software/amazon/awssdk/auth
* directory of the tst folder, and no file extension should be specified.
*
* @param responseFileName The name of the file that should be sent back as the response
* from this mock server.
*/
public void setResponseFileName(String responseFileName) {
hosmMockServerThread.setResponseFileName(responseFileName);
}
/**
* Accepts a newline delimited list of security credential names that the
* mock metadata service should advertise as available.
*
* @param securityCredentialNames A newline delimited list of security credentials that the
* metadata service will advertise as available.
*/
public void setAvailableSecurityCredentials(String securityCredentialNames) {
hosmMockServerThread.setAvailableSecurityCredentials(securityCredentialNames);
}
public void start() throws IOException {
hosmMockServerThread = new EC2MockMetadataServiceListenerThread(startServerSocket(), securityCredentialsResource);
hosmMockServerThread.start();
}
public void stop() {
hosmMockServerThread.stopServer();
}
private ServerSocket startServerSocket() {
try {
ServerSocket serverSocket = new ServerSocket(0);
System.setProperty(AWS_EC2_METADATA_SERVICE_ENDPOINT.property(),
"http://localhost:" + serverSocket.getLocalPort());
System.out.println("Started mock metadata service at: " +
System.getProperty(AWS_EC2_METADATA_SERVICE_ENDPOINT.property()));
return serverSocket;
} catch (IOException ioe) {
throw new RuntimeException("Unable to start mock EC2 metadata server", ioe);
}
}
/**
* Thread subclass that listens for connections on an opened server socket
* and response with a predefined response file.
*/
private static class EC2MockMetadataServiceListenerThread extends Thread {
private static final String TOKEN_RESOURCE_PATH = "/latest/api/token";
private ServerSocket serverSocket;
private final String credentialsResource;
private String responseFileName;
private String securityCredentialNames;
public EC2MockMetadataServiceListenerThread(ServerSocket serverSocket, String credentialsResource) {
this.serverSocket = serverSocket;
this.credentialsResource = credentialsResource;
}
public void setResponseFileName(String responseFileName) {
this.responseFileName = responseFileName;
}
public void setAvailableSecurityCredentials(String securityCredentialNames) {
this.securityCredentialNames = securityCredentialNames;
}
@Override
public void run() {
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
} catch (IOException e) {
// Just exit if the socket gets shut down while we're waiting
return;
}
try (OutputStream outputStream = socket.getOutputStream()) {
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String requestLine = reader.readLine();
String[] strings = requestLine.split(" ");
String resourcePath = strings[1];
String httpResponse = null;
if (resourcePath.equals(credentialsResource)) {
httpResponse = formHttpResponse(securityCredentialNames);
outputStream.write(httpResponse.getBytes());
} else if (resourcePath.startsWith(credentialsResource)) {
String responseFilePath = "/software/amazon/awssdk/core/auth/" + responseFileName + ".json";
System.out.println("Serving: " + responseFilePath);
List<String> dataFromFile;
StringBuilder credentialsString;
try (InputStream responseFileInputStream = this.getClass().getResourceAsStream(responseFilePath)) {
dataFromFile = IOUtils.readLines(responseFileInputStream);
}
credentialsString = new StringBuilder();
for (String line : dataFromFile) {
credentialsString.append(line);
}
httpResponse = formHttpResponse(credentialsString
.toString());
outputStream.write(httpResponse.getBytes());
} else if (TOKEN_RESOURCE_PATH.equals(resourcePath)) {
httpResponse = "HTTP/1.1 404 Not Found\r\n" +
"Content-Length: 0\r\n" +
"\r\n";
outputStream.write(httpResponse.getBytes());
}
else {
throw new RuntimeException("Unknown resource requested: " + resourcePath);
}
} catch (IOException e) {
throw new RuntimeException("Unable to respond to request", e);
} finally {
try {
socket.close();
} catch (Exception e) {
// Ignored or expected.
}
}
}
}
private String formHttpResponse(String content) {
return OUTPUT_HEADERS + content.length()
+ OUTPUT_END_OF_HEADERS
+ content;
}
public void stopServer() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Unable to stop server", e);
}
}
}
}
}
| 1,403 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/CredentialsEndpointRetryParametersTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.util.ResourcesEndpointRetryParameters;
/**
* Unit tests for {@link ResourcesEndpointRetryParameters}.
*/
public class CredentialsEndpointRetryParametersTest {
@Test
public void defaultParams() {
ResourcesEndpointRetryParameters params = ResourcesEndpointRetryParameters.builder().build();
assertNull(params.getStatusCode());
assertNull(params.getException());
}
@Test
public void defaultParams_withStatusCode() {
Integer statusCode = new Integer(400);
ResourcesEndpointRetryParameters params = ResourcesEndpointRetryParameters.builder()
.withStatusCode(statusCode)
.build();
assertEquals(statusCode, params.getStatusCode());
assertNull(params.getException());
}
@Test
public void defaultParams_withStatusCodeAndException() {
Integer statusCode = new Integer(500);
ResourcesEndpointRetryParameters params = ResourcesEndpointRetryParameters.builder()
.withStatusCode(statusCode)
.withException(new IOException())
.build();
assertEquals(statusCode, params.getStatusCode());
assertTrue(params.getException() instanceof IOException);
}
}
| 1,404 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/NoopTestRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkRequest;
public class NoopTestRequest extends SdkRequest {
private NoopTestRequest() {
}
@Override
public Optional<? extends RequestOverrideConfiguration> overrideConfiguration() {
return Optional.empty();
}
@Override
public Builder toBuilder() {
return new BuilderImpl();
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public List<SdkField<?>> sdkFields() {
return Collections.emptyList();
}
public interface Builder extends SdkRequest.Builder {
@Override
NoopTestRequest build();
}
private static class BuilderImpl implements SdkRequest.Builder, Builder {
@Override
public RequestOverrideConfiguration overrideConfiguration() {
return null;
}
@Override
public NoopTestRequest build() {
return new NoopTestRequest();
}
}
}
| 1,405 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ContainerCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.core.SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.util.SdkUserAgent;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
/**
* Tests for the {@link ContainerCredentialsProviderTest}.
*/
public class ContainerCredentialsProviderTest {
@ClassRule
public static WireMockRule mockServer = new WireMockRule(0);
/** Environment variable name for the AWS ECS Container credentials path. */
private static final String CREDENTIALS_PATH = "/dummy/credentials/path";
private static final String ACCESS_KEY_ID = "ACCESS_KEY_ID";
private static final String SECRET_ACCESS_KEY = "SECRET_ACCESS_KEY";
private static final String TOKEN = "TOKEN_TOKEN_TOKEN";
private ContainerCredentialsProvider credentialsProvider;
private static EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
@Before
public void setup() {
credentialsProvider = ContainerCredentialsProvider.builder()
.endpoint("http://localhost:" + mockServer.port())
.build();
helper.set(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, CREDENTIALS_PATH);
}
@AfterClass
public static void tearDown() {
helper.reset();
}
/**
* Tests that when "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" is not set, throws exception.
*/
@Test(expected = SdkClientException.class)
public void testEnvVariableNotSet() {
helper.remove(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI);
ContainerCredentialsProvider.builder()
.build()
.resolveCredentials();
}
/**
* Tests that the getCredentials returns a value when it receives a valid 200 response from endpoint.
*/
@Test
public void testGetCredentialsReturnsValidResponseFromEcsEndpoint() {
stubForSuccessResponse();
AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials();
assertThat(credentials).isNotNull();
assertThat(credentials.accessKeyId()).isEqualTo(ACCESS_KEY_ID);
assertThat(credentials.secretAccessKey()).isEqualTo(SECRET_ACCESS_KEY);
assertThat(credentials.sessionToken()).isEqualTo(TOKEN);
}
/**
* Tests that the getCredentials won't leak credentials data if the response from ECS is corrupted.
*/
@Test
public void getCredentialsWithCorruptResponseDoesNotIncludeCredentialsInExceptionMessage() {
stubForCorruptedSuccessResponse();
assertThatThrownBy(credentialsProvider::resolveCredentials).satisfies(t -> {
String stackTrace = ExceptionUtils.getStackTrace(t);
assertThat(stackTrace).doesNotContain("ACCESS_KEY_ID");
assertThat(stackTrace).doesNotContain("SECRET_ACCESS_KEY");
assertThat(stackTrace).doesNotContain("TOKEN_TOKEN_TOKEN");
});
}
private void stubForSuccessResponse() {
stubFor200Response(getSuccessfulBody());
}
private void stubForCorruptedSuccessResponse() {
String body = getSuccessfulBody();
stubFor200Response(body.substring(0, body.length() - 2));
}
private void stubFor200Response(String body) {
stubFor(get(urlPathEqualTo(CREDENTIALS_PATH))
.withHeader("User-Agent", equalTo(SdkUserAgent.create().userAgent()))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withHeader("charset", "utf-8")
.withBody(body)));
}
private String getSuccessfulBody() {
return "{\"AccessKeyId\":\"ACCESS_KEY_ID\"," +
"\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," +
"\"Token\":\"TOKEN_TOKEN_TOKEN\"," +
"\"Expiration\":\"3000-05-03T04:55:54Z\"}";
}
/**
* Dummy CredentialsPathProvider that overrides the endpoint and connects to the WireMock server.
*/
private static class TestCredentialsEndpointProvider implements ResourcesEndpointProvider {
private final String host;
public TestCredentialsEndpointProvider(String host) {
this.host = host;
}
@Override
public URI endpoint() {
return invokeSafely(() -> new URI(host + CREDENTIALS_PATH));
}
}
}
| 1,406 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/HttpCredentialsLoaderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader;
import software.amazon.awssdk.auth.credentials.internal.StaticResourcesEndpointProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.util.SdkUserAgent;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.IoUtils;
public class HttpCredentialsLoaderTest {
@ClassRule
public static WireMockRule mockServer = new WireMockRule(0);
/** One minute (in milliseconds) */
private static final long ONE_MINUTE = 1000L * 60;
/** Environment variable name for the AWS ECS Container credentials path. */
private static final String CREDENTIALS_PATH = "/dummy/credentials/path";
private static String successResponse;
private static String successResponseWithInvalidBody;
@BeforeClass
public static void setup() throws IOException {
try (InputStream successInputStream = HttpCredentialsLoaderTest.class.getResourceAsStream
("/resources/wiremock/successResponse.json");
InputStream responseWithInvalidBodyInputStream = HttpCredentialsLoaderTest.class.getResourceAsStream
("/resources/wiremock/successResponseWithInvalidBody.json")) {
successResponse = IoUtils.toUtf8String(successInputStream);
successResponseWithInvalidBody = IoUtils.toUtf8String(responseWithInvalidBodyInputStream);
}
}
/**
* Test that loadCredentials returns proper credentials when response from client is in proper Json format.
*/
@Test
public void testLoadCredentialsParsesJsonResponseProperly() {
stubForSuccessResponseWithCustomBody(successResponse);
HttpCredentialsLoader credentialsProvider = HttpCredentialsLoader.create();
AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.loadCredentials(testEndpointProvider())
.getAwsCredentials();
assertThat(credentials.accessKeyId()).isEqualTo("ACCESS_KEY_ID");
assertThat(credentials.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY");
assertThat(credentials.sessionToken()).isEqualTo("TOKEN_TOKEN_TOKEN");
}
/**
* Test that when credentials are null and response from client does not have access key/secret key,
* throws RuntimeException.
*/
@Test
public void testLoadCredentialsThrowsAceWhenClientResponseDontHaveKeys() {
// Stub for success response but without keys in the response body
stubForSuccessResponseWithCustomBody(successResponseWithInvalidBody);
HttpCredentialsLoader credentialsProvider = HttpCredentialsLoader.create();
assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> credentialsProvider.loadCredentials(testEndpointProvider()))
.withMessage("Failed to load credentials from metadata service.");
}
/**
* Tests how the credentials provider behaves when the
* server is not running.
*/
@Test
public void testNoMetadataService() throws Exception {
stubForErrorResponse();
HttpCredentialsLoader credentialsProvider = HttpCredentialsLoader.create();
// When there are no credentials, the provider should throw an exception if we can't connect
assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> credentialsProvider.loadCredentials(testEndpointProvider()));
// When there are valid credentials (but need to be refreshed) and the endpoint returns 404 status,
// the provider should throw an exception.
stubForSuccessResonseWithCustomExpirationDate(new Date(System.currentTimeMillis() + ONE_MINUTE * 4));
credentialsProvider.loadCredentials(testEndpointProvider()); // loads the credentials that will be expired soon
stubForErrorResponse(); // Behaves as if server is unavailable.
assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> credentialsProvider.loadCredentials(testEndpointProvider()));
}
private void stubForSuccessResponseWithCustomBody(String body) {
stubFor(
get(urlPathEqualTo(CREDENTIALS_PATH))
.withHeader("User-Agent", equalTo(SdkUserAgent.create().userAgent()))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withHeader("charset", "utf-8")
.withBody(body)));
}
private void stubForSuccessResonseWithCustomExpirationDate(Date expiration) {
stubForSuccessResponseWithCustomBody("{\"AccessKeyId\":\"ACCESS_KEY_ID\",\"SecretAccessKey\":\"SECRET_ACCESS_KEY\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(expiration.toInstant())
+ "\"}");
}
private void stubForErrorResponse() {
stubFor(
get(urlPathEqualTo(CREDENTIALS_PATH))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "application/json")
.withHeader("charset", "utf-8")
.withBody("{\"code\":\"404 Not Found\",\"message\":\"DetailedErrorMessage\"}")));
}
private ResourcesEndpointProvider testEndpointProvider() {
return new StaticResourcesEndpointProvider(URI.create("http://localhost:" + mockServer.port() + CREDENTIALS_PATH),
null);
}
}
| 1,407 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ContainerCredentialsRetryPolicyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.internal.ContainerCredentialsRetryPolicy;
import software.amazon.awssdk.regions.util.ResourcesEndpointRetryParameters;
public class ContainerCredentialsRetryPolicyTest {
private static ContainerCredentialsRetryPolicy retryPolicy;
@BeforeAll
public static void setup() {
retryPolicy = new ContainerCredentialsRetryPolicy();
}
@Test
public void shouldRetry_ReturnsTrue_For5xxStatusCode() {
assertTrue(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder().withStatusCode(501).build()));
}
@Test
public void shouldRetry_ReturnsFalse_ForNon5xxStatusCode() {
assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder().withStatusCode(404).build()));
assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder().withStatusCode(300).build()));
assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder().withStatusCode(202).build()));
}
@Test
public void shouldRetry_ReturnsTrue_ForIoException() {
assertTrue(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder()
.withException(new IOException()).build()));
}
@Test
public void shouldRetry_ReturnsFalse_ForNonIoException() {
assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder()
.withException(new RuntimeException()).build()));
assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder()
.withException(new Exception()).build()));
}
@Test
public void shouldRetry_ReturnsFalse_WhenMaxRetriesExceeded() {
assertFalse(retryPolicy.shouldRetry(5, ResourcesEndpointRetryParameters.builder().withStatusCode(501).build()));
}
}
| 1,408 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ProfileCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Supplier;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.StringInputStream;
/**
* Verify functionality of {@link ProfileCredentialsProvider}.
*/
public class ProfileCredentialsProviderTest {
private static FileSystem jimfs;
private static Path testDirectory;
@BeforeAll
public static void setup() {
jimfs = Jimfs.newFileSystem();
testDirectory = jimfs.getPath("test");
}
@AfterAll
public static void tearDown() {
try {
jimfs.close();
} catch (IOException e) {
// no-op
}
}
@Test
void missingCredentialsFileThrowsExceptionInResolveCredentials() {
ProfileCredentialsProvider provider =
new ProfileCredentialsProvider.BuilderImpl()
.defaultProfileFileLoader(() -> { throw new IllegalStateException(); })
.build();
assertThatThrownBy(provider::resolveCredentials).isInstanceOf(IllegalStateException.class);
}
@Test
void missingProfileFileThrowsExceptionInResolveCredentials() {
ProfileCredentialsProvider provider =
new ProfileCredentialsProvider.BuilderImpl()
.defaultProfileFileLoader(() -> ProfileFile.builder()
.content(new StringInputStream(""))
.type(ProfileFile.Type.CONFIGURATION)
.build())
.build();
assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class);
}
@Test
void missingProfileThrowsExceptionInResolveCredentials() {
ProfileFile file = profileFile("[default]\n"
+ "aws_access_key_id = defaultAccessKey\n"
+ "aws_secret_access_key = defaultSecretAccessKey");
ProfileCredentialsProvider provider =
ProfileCredentialsProvider.builder().profileFile(file).profileName("foo").build();
assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class);
}
@Test
void profileWithoutCredentialsThrowsExceptionInResolveCredentials() {
ProfileFile file = profileFile("[default]");
ProfileCredentialsProvider provider =
ProfileCredentialsProvider.builder().profileFile(file).profileName("default").build();
assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class);
}
@Test
void presentProfileReturnsCredentials() {
ProfileFile file = profileFile("[default]\n"
+ "aws_access_key_id = defaultAccessKey\n"
+ "aws_secret_access_key = defaultSecretAccessKey");
ProfileCredentialsProvider provider =
ProfileCredentialsProvider.builder().profileFile(file).profileName("default").build();
assertThat(provider.resolveCredentials()).satisfies(credentials -> {
assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey");
assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey");
});
}
@Test
void profileWithWebIdentityToken() {
String token = "/User/home/test";
ProfileFile file = profileFile("[default]\n"
+ "aws_access_key_id = defaultAccessKey\n"
+ "aws_secret_access_key = defaultSecretAccessKey\n"
+ "web_identity_token_file = " + token);
assertThat(file.profile("default").get().property(ProfileProperty.WEB_IDENTITY_TOKEN_FILE).get()).isEqualTo(token);
}
@Test
void resolveCredentials_missingProfileFileCausesExceptionInMethod_throwsException() {
ProfileCredentialsProvider.BuilderImpl builder = new ProfileCredentialsProvider.BuilderImpl();
builder.defaultProfileFileLoader(() -> ProfileFile.builder()
.content(new StringInputStream(""))
.type(ProfileFile.Type.CONFIGURATION)
.build());
ProfileCredentialsProvider provider = builder.build();
assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class);
}
@Test
void resolveCredentials_missingProfile_throwsException() {
ProfileFile file = profileFile("[default]\n"
+ "aws_access_key_id = defaultAccessKey\n"
+ "aws_secret_access_key = defaultSecretAccessKey");
try (ProfileCredentialsProvider provider =
ProfileCredentialsProvider.builder()
.profileFile(() -> file)
.profileName("foo")
.build()) {
assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class);
}
}
@Test
void resolveCredentials_profileWithoutCredentials_throwsException() {
ProfileFile file = profileFile("[default]");
ProfileCredentialsProvider provider =
ProfileCredentialsProvider.builder()
.profileFile(() -> file)
.profileName("default")
.build();
assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class);
}
@Test
void resolveCredentials_presentProfile_returnsCredentials() {
ProfileFile file = profileFile("[default]\n"
+ "aws_access_key_id = defaultAccessKey\n"
+ "aws_secret_access_key = defaultSecretAccessKey");
ProfileCredentialsProvider provider =
ProfileCredentialsProvider.builder()
.profileFile(() -> file)
.profileName("default")
.build();
assertThat(provider.resolveCredentials()).satisfies(credentials -> {
assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey");
assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey");
});
}
@Test
void resolveCredentials_presentProfileFileSupplier_returnsCredentials() {
Path path = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileCredentialsProvider provider =
ProfileCredentialsProvider.builder()
.profileFile(ProfileFileSupplier.reloadWhenModified(path, ProfileFile.Type.CREDENTIALS))
.profileName("default")
.build();
assertThat(provider.resolveCredentials()).satisfies(credentials -> {
assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey");
assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey");
});
}
@Test
void resolveCredentials_presentSupplierProfileFile_returnsCredentials() {
Supplier<ProfileFile> supplier = () -> profileFile("[default]\naws_access_key_id = defaultAccessKey\n"
+ "aws_secret_access_key = defaultSecretAccessKey\n");
ProfileCredentialsProvider provider =
ProfileCredentialsProvider.builder()
.profileFile(supplier)
.profileName("default")
.build();
assertThat(provider.resolveCredentials()).satisfies(credentials -> {
assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey");
assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey");
});
}
@Test
void create_noProfileName_returnsProfileCredentialsProviderToResolveWithDefaults() {
ProfileCredentialsProvider provider = ProfileCredentialsProvider.create();
String toString = provider.toString();
assertThat(toString).satisfies(s -> assertThat(s).contains("profileName=default"));
}
@Test
void create_givenProfileName_returnsProfileCredentialsProviderToResolveForGivenName() {
ProfileCredentialsProvider provider = ProfileCredentialsProvider.create("override");
String toString = provider.toString();
assertThat(toString).satisfies(s -> assertThat(s).contains("profileName=override"));
}
@Test
void toString_anyProfileCredentialsProviderAfterResolvingCredentialsFileDoesExists_returnsProfileFile() {
ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl()
.defaultProfileFileLoader(() -> profileFile("[default]\naws_access_key_id = not-set\n"
+ "aws_secret_access_key = not-set\n"))
.build();
provider.resolveCredentials();
String toString = provider.toString();
assertThat(toString).satisfies(s -> {
assertThat(s).contains("profileName=default");
assertThat(s).contains("profileFile=");
});
}
@Test
void toString_anyProfileCredentialsProviderAfterResolvingCredentialsFileDoesNotExist_throwsException() {
ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl()
.defaultProfileFileLoader(() -> ProfileFile.builder()
.content(new StringInputStream(""))
.type(ProfileFile.Type.CONFIGURATION)
.build())
.build();
assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class);
}
@Test
void toString_anyProfileCredentialsProviderBeforeResolvingCredentials_doesNotReturnProfileFile() {
ProfileCredentialsProvider provider =
new ProfileCredentialsProvider.BuilderImpl()
.defaultProfileFileLoader(() -> ProfileFile.builder()
.content(new StringInputStream(""))
.type(ProfileFile.Type.CONFIGURATION)
.build())
.build();
String toString = provider.toString();
assertThat(toString).satisfies(s -> {
assertThat(s).contains("profileName");
assertThat(s).doesNotContain("profileFile");
});
}
@Test
void toBuilder_fromCredentialsProvider_returnsBuilderCapableOfProducingSimilarProvider() {
ProfileCredentialsProvider provider1 = ProfileCredentialsProvider.create("override");
ProfileCredentialsProvider provider2 = provider1.toBuilder().build();
String provider1ToString = provider1.toString();
String provider2ToString = provider2.toString();
assertThat(provider1ToString).isEqualTo(provider2ToString);
}
private ProfileFile profileFile(String string) {
return ProfileFile.builder().content(new StringInputStream(string)).type(ProfileFile.Type.CONFIGURATION).build();
}
private Path generateTestFile(String contents, String filename) {
try {
Files.createDirectories(testDirectory);
return Files.write(testDirectory.resolve(filename), contents.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Path generateTestCredentialsFile(String accessKeyId, String secretAccessKey) {
String contents = String.format("[default]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
accessKeyId, secretAccessKey);
return generateTestFile(contents, "credentials.txt");
}
}
| 1,409 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/CredentialUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
public class CredentialUtilsTest {
@Test
public void isAnonymous_AwsCredentials_true() {
assertThat(CredentialUtils.isAnonymous(AwsBasicCredentials.ANONYMOUS_CREDENTIALS)).isTrue();
}
@Test
public void isAnonymous_AwsCredentials_false() {
assertThat(CredentialUtils.isAnonymous(AwsBasicCredentials.create("akid", "skid"))).isFalse();
}
@Test
public void isAnonymous_AwsCredentialsIdentity_true() {
assertThat(CredentialUtils.isAnonymous((AwsCredentialsIdentity) AwsBasicCredentials.ANONYMOUS_CREDENTIALS)).isTrue();
}
@Test
public void isAnonymous_AwsCredentialsIdentity_false() {
assertThat(CredentialUtils.isAnonymous(AwsCredentialsIdentity.create("akid", "skid"))).isFalse();
}
@Test
public void toCredentials_null_returnsNull() {
assertThat(CredentialUtils.toCredentials(null)).isNull();
}
@Test
public void toCredentials_AwsSessionCredentials_doesNotCreateNewObject() {
AwsSessionCredentialsIdentity input = AwsSessionCredentials.create("ak", "sk", "session");
AwsCredentials output = CredentialUtils.toCredentials(input);
assertThat(output).isSameAs(input);
}
@Test
public void toCredentials_AwsSessionCredentialsIdentity_returnsAwsSessionCredentials() {
AwsCredentials awsCredentials = CredentialUtils.toCredentials(AwsSessionCredentialsIdentity.create(
"akid", "skid", "session"));
assertThat(awsCredentials).isInstanceOf(AwsSessionCredentials.class);
AwsSessionCredentials awsSessionCredentials = (AwsSessionCredentials) awsCredentials;
assertThat(awsSessionCredentials.accessKeyId()).isEqualTo("akid");
assertThat(awsSessionCredentials.secretAccessKey()).isEqualTo("skid");
assertThat(awsSessionCredentials.sessionToken()).isEqualTo("session");
}
@Test
public void toCredentials_AwsCredentials_returnsAsIs() {
AwsCredentialsIdentity input = AwsBasicCredentials.create("ak", "sk");
AwsCredentials output = CredentialUtils.toCredentials(input);
assertThat(output).isSameAs(input);
}
@Test
public void toCredentials_AwsCredentialsIdentity_returnsAwsCredentials() {
AwsCredentials awsCredentials = CredentialUtils.toCredentials(AwsCredentialsIdentity.create("akid", "skid"));
assertThat(awsCredentials.accessKeyId()).isEqualTo("akid");
assertThat(awsCredentials.secretAccessKey()).isEqualTo("skid");
}
@Test
public void toCredentials_Anonymous_returnsAnonymous() {
AwsCredentials awsCredentials = CredentialUtils.toCredentials(new AwsCredentialsIdentity() {
@Override
public String accessKeyId() {
return null;
}
@Override
public String secretAccessKey() {
return null;
}
});
assertThat(awsCredentials.accessKeyId()).isNull();
assertThat(awsCredentials.secretAccessKey()).isNull();
}
@Test
public void toCredentialsProvider_null_returnsNull() {
assertThat(CredentialUtils.toCredentialsProvider(null)).isNull();
}
@Test
public void toCredentialsProvider_AwsCredentialsProvider_returnsAsIs() {
IdentityProvider<AwsCredentialsIdentity> input =
StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"));
AwsCredentialsProvider output = CredentialUtils.toCredentialsProvider(input);
assertThat(output).isSameAs(input);
}
@Test
public void toCredentialsProvider_IdentityProvider_converts() {
AwsCredentialsProvider credentialsProvider = CredentialUtils.toCredentialsProvider(
StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")));
AwsCredentials credentials = credentialsProvider.resolveCredentials();
assertThat(credentials.accessKeyId()).isEqualTo("akid");
assertThat(credentials.secretAccessKey()).isEqualTo("skid");
}
}
| 1,410 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/InstanceProfileCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.matching.RequestPattern;
import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.util.SdkUserAgent;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringInputStream;
public class InstanceProfileCredentialsProviderTest {
private static final String TOKEN_RESOURCE_PATH = "/latest/api/token";
private static final String CREDENTIALS_RESOURCE_PATH = "/latest/meta-data/iam/security-credentials/";
private static final String STUB_CREDENTIALS = "{\"AccessKeyId\":\"ACCESS_KEY_ID\",\"SecretAccessKey\":\"SECRET_ACCESS_KEY\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now().plus(Duration.ofDays(1)))
+ "\"}";
private static final String TOKEN_HEADER = "x-aws-ec2-metadata-token";
private static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Rule
public WireMockRule mockMetadataEndpoint = new WireMockRule();
@Before
public void methodSetup() {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + mockMetadataEndpoint.port());
}
@AfterClass
public static void teardown() {
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property());
}
@Test
public void resolveCredentials_metadataLookupDisabled_throws() {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true");
thrown.expect(SdkClientException.class);
thrown.expectMessage("IMDS credentials have been disabled");
try {
InstanceProfileCredentialsProvider.builder().build().resolveCredentials();
} finally {
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property());
}
}
@Test
public void resolveCredentials_requestsIncludeUserAgent() {
String stubToken = "some-token";
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken)));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
String userAgentHeader = "User-Agent";
String userAgent = SdkUserAgent.create().userAgent();
WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent)));
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent)));
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent)));
}
@Test
public void resolveCredentials_queriesTokenResource() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
}
@Test
public void resolveCredentials_queriesTokenResource_includedInCredentialsRequests() {
String stubToken = "some-token";
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken)));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(TOKEN_HEADER, equalTo(stubToken)));
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(TOKEN_HEADER, equalTo(stubToken)));
}
@Test
public void resolveCredentials_queriesTokenResource_403Error_fallbackToInsecure() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)));
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")));
}
@Test
public void resolveCredentials_queriesTokenResource_404Error_fallbackToInsecure() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(404).withBody("oops")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)));
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")));
}
@Test
public void resolveCredentials_queriesTokenResource_405Error_fallbackToInsecure() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)));
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")));
}
@Test
public void resolveCredentials_queriesTokenResource_400Error_throws() {
thrown.expect(SdkClientException.class);
thrown.expectMessage("Failed to load credentials from IMDS");
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("oops")));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
}
@Test
public void resolveCredentials_queriesTokenResource_socketTimeout_fallbackToInsecure() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token").withFixedDelay(Integer.MAX_VALUE)));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)));
WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")));
}
@Test
public void resolveCredentials_endpointSettingEmpty_throws() {
thrown.expect(SdkClientException.class);
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "");
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
}
@Test
public void resolveCredentials_endpointSettingHostNotExists_throws() {
thrown.expect(SdkClientException.class);
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "some-host-that-does-not-exist");
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();
provider.resolveCredentials();
}
@Test
public void resolveCredentials_customProfileFileAndName_usesCorrectEndpoint() {
WireMockServer mockMetadataEndpoint_2 = new WireMockServer(WireMockConfiguration.options().dynamicPort());
mockMetadataEndpoint_2.start();
try {
String stubToken = "some-token";
mockMetadataEndpoint_2.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken)));
mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
String mockServer2Endpoint = "http://localhost:" + mockMetadataEndpoint_2.port();
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder()
.endpoint(mockServer2Endpoint)
.build();
provider.resolveCredentials();
String userAgentHeader = "User-Agent";
String userAgent = SdkUserAgent.create().userAgent();
mockMetadataEndpoint_2.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent)));
mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent)));
mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent)));
// all requests should have gone to the second server, and none to the other one
mockMetadataEndpoint.verify(0, RequestPatternBuilder.allRequests());
} finally {
mockMetadataEndpoint_2.stop();
}
}
@Test
public void resolveCredentials_customProfileFileSupplierAndNameSettingEndpointOverride_usesCorrectEndpointFromSupplier() {
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property());
WireMockServer mockMetadataEndpoint_2 = new WireMockServer(WireMockConfiguration.options().dynamicPort());
mockMetadataEndpoint_2.start();
try {
String stubToken = "some-token";
mockMetadataEndpoint_2.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken)));
mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
String mockServer2Endpoint = "http://localhost:" + mockMetadataEndpoint_2.port();
ProfileFile config = configFile("profile test",
Pair.of(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT, mockServer2Endpoint));
List<ProfileFile> profileFileList = Arrays.asList(credentialFile("test", "key1", "secret1"),
credentialFile("test", "key2", "secret2"),
credentialFile("test", "key3", "secret3"));
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider
.builder()
.profileFile(ProfileFileSupplier.aggregate(supply(profileFileList), () -> config))
.profileName("test")
.build();
AwsCredentials awsCredentials1 = provider.resolveCredentials();
assertThat(awsCredentials1).isNotNull();
String userAgentHeader = "User-Agent";
String userAgent = SdkUserAgent.create().userAgent();
mockMetadataEndpoint_2.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent)));
mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent)));
mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent)));
// all requests should have gone to the second server, and none to the other one
mockMetadataEndpoint.verify(0, RequestPatternBuilder.allRequests());
} finally {
mockMetadataEndpoint_2.stop();
}
}
@Test
public void resolveCredentials_customSupplierProfileFileAndNameSettingEndpointOverride_usesCorrectEndpointFromSupplier() {
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property());
WireMockServer mockMetadataEndpoint_2 = new WireMockServer(WireMockConfiguration.options().dynamicPort());
mockMetadataEndpoint_2.start();
try {
String stubToken = "some-token";
mockMetadataEndpoint_2.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken)));
mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));
String mockServer2Endpoint = "http://localhost:" + mockMetadataEndpoint_2.port();
ProfileFile config = configFile("profile test",
Pair.of(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT, mockServer2Endpoint));
Supplier<ProfileFile> supplier = () -> config;
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider
.builder()
.profileFile(supplier)
.profileName("test")
.build();
AwsCredentials awsCredentials1 = provider.resolveCredentials();
assertThat(awsCredentials1).isNotNull();
String userAgentHeader = "User-Agent";
String userAgent = SdkUserAgent.create().userAgent();
mockMetadataEndpoint_2.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent)));
mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent)));
mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent)));
// all requests should have gone to the second server, and none to the other one
mockMetadataEndpoint.verify(0, RequestPatternBuilder.allRequests());
} finally {
mockMetadataEndpoint_2.stop();
}
}
@Test
public void resolveCredentials_doesNotFailIfImdsReturnsExpiredCredentials() {
String credentialsResponse =
"{"
+ "\"AccessKeyId\":\"ACCESS_KEY_ID\","
+ "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now().minus(Duration.ofHours(1))) + '"'
+ "}";
stubCredentialsResponse(aResponse().withBody(credentialsResponse));
AwsCredentials credentials = InstanceProfileCredentialsProvider.builder().build().resolveCredentials();
assertThat(credentials.accessKeyId()).isEqualTo("ACCESS_KEY_ID");
assertThat(credentials.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY");
}
@Test
public void resolveCredentials_onlyCallsImdsOnceEvenWithExpiredCredentials() {
String credentialsResponse =
"{"
+ "\"AccessKeyId\":\"ACCESS_KEY_ID\","
+ "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now().minus(Duration.ofHours(1))) + '"'
+ "}";
stubCredentialsResponse(aResponse().withBody(credentialsResponse));
AwsCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.builder().build();
credentialsProvider.resolveCredentials();
int requestCountAfterOneRefresh = mockMetadataEndpoint.countRequestsMatching(RequestPattern.everything()).getCount();
credentialsProvider.resolveCredentials();
credentialsProvider.resolveCredentials();
int requestCountAfterThreeRefreshes = mockMetadataEndpoint.countRequestsMatching(RequestPattern.everything()).getCount();
assertThat(requestCountAfterThreeRefreshes).isEqualTo(requestCountAfterOneRefresh);
}
@Test
public void resolveCredentials_failsIfImdsReturns500OnFirstCall() {
String errorMessage = "XXXXX";
String credentialsResponse =
"{"
+ "\"code\": \"InternalServiceException\","
+ "\"message\": \"" + errorMessage + "\""
+ "}";
stubCredentialsResponse(aResponse().withStatus(500)
.withBody(credentialsResponse));
assertThatThrownBy(InstanceProfileCredentialsProvider.builder().build()::resolveCredentials)
.isInstanceOf(SdkClientException.class)
.hasRootCauseMessage(errorMessage);
}
@Test
public void resolveCredentials_usesCacheIfImdsFailsOnSecondCall() {
AdjustableClock clock = new AdjustableClock();
AwsCredentialsProvider credentialsProvider = credentialsProviderWithClock(clock);
String successfulCredentialsResponse =
"{"
+ "\"AccessKeyId\":\"ACCESS_KEY_ID\","
+ "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now()) + '"'
+ "}";
// Set the time to the past, so that the cache expiration time is still is in the past, and then prime the cache
clock.time = Instant.now().minus(24, HOURS);
stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse));
AwsCredentials credentialsBefore = credentialsProvider.resolveCredentials();
// Travel to the present time take down IMDS, so we can see if we use the cached credentials
clock.time = Instant.now();
stubCredentialsResponse(aResponse().withStatus(500));
AwsCredentials credentialsAfter = credentialsProvider.resolveCredentials();
assertThat(credentialsBefore).isEqualTo(credentialsAfter);
}
@Test
public void resolveCredentials_callsImdsIfCredentialsWithin5MinutesOfExpiration() {
AdjustableClock clock = new AdjustableClock();
AwsCredentialsProvider credentialsProvider = credentialsProviderWithClock(clock);
Instant now = Instant.now();
String successfulCredentialsResponse1 =
"{"
+ "\"AccessKeyId\":\"ACCESS_KEY_ID\","
+ "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(now) + '"'
+ "}";
String successfulCredentialsResponse2 =
"{"
+ "\"AccessKeyId\":\"ACCESS_KEY_ID\","
+ "\"SecretAccessKey\":\"SECRET_ACCESS_KEY2\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(now.plus(6, HOURS)) + '"'
+ "}";
// Set the time to the past and call IMDS to prime the cache
clock.time = now.minus(24, HOURS);
stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse1));
AwsCredentials credentials24HoursAgo = credentialsProvider.resolveCredentials();
// Set the time to 10 minutes before expiration, and fail to call IMDS
clock.time = now.minus(10, MINUTES);
stubCredentialsResponse(aResponse().withStatus(500));
AwsCredentials credentials10MinutesAgo = credentialsProvider.resolveCredentials();
// Set the time to 10 seconds before expiration, and verify that we still call IMDS to try to get credentials in at the
// last moment before expiration
clock.time = now.minus(10, SECONDS);
stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse2));
AwsCredentials credentials10SecondsAgo = credentialsProvider.resolveCredentials();
assertThat(credentials24HoursAgo).isEqualTo(credentials10MinutesAgo);
assertThat(credentials24HoursAgo.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY");
assertThat(credentials10SecondsAgo.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY2");
}
@Test
public void imdsCallFrequencyIsLimited() {
// Requires running the test multiple times to account for refresh jitter
for (int i = 0; i < 10; i++) {
AdjustableClock clock = new AdjustableClock();
AwsCredentialsProvider credentialsProvider = credentialsProviderWithClock(clock);
Instant now = Instant.now();
String successfulCredentialsResponse1 =
"{"
+ "\"AccessKeyId\":\"ACCESS_KEY_ID\","
+ "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(now) + '"'
+ "}";
String successfulCredentialsResponse2 =
"{"
+ "\"AccessKeyId\":\"ACCESS_KEY_ID2\","
+ "\"SecretAccessKey\":\"SECRET_ACCESS_KEY2\","
+ "\"Expiration\":\"" + DateUtils.formatIso8601Date(now.plus(6, HOURS)) + '"'
+ "}";
// Set the time to 5 minutes before expiration and call IMDS
clock.time = now.minus(5, MINUTES);
stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse1));
AwsCredentials credentials5MinutesAgo = credentialsProvider.resolveCredentials();
// Set the time to 2 seconds before expiration, and verify that do not call IMDS because it hasn't been 5 minutes yet
clock.time = now.minus(2, SECONDS);
stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse2));
AwsCredentials credentials2SecondsAgo = credentialsProvider.resolveCredentials();
assertThat(credentials2SecondsAgo).isEqualTo(credentials5MinutesAgo);
assertThat(credentials5MinutesAgo.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY");
}
}
private AwsCredentialsProvider credentialsProviderWithClock(Clock clock) {
InstanceProfileCredentialsProvider.BuilderImpl builder =
(InstanceProfileCredentialsProvider.BuilderImpl) InstanceProfileCredentialsProvider.builder();
builder.clock(clock);
return builder.build();
}
private void stubCredentialsResponse(ResponseDefinitionBuilder responseDefinitionBuilder) {
mockMetadataEndpoint.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH))
.willReturn(aResponse().withBody("some-token")));
mockMetadataEndpoint.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))
.willReturn(aResponse().withBody("some-profile")));
mockMetadataEndpoint.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))
.willReturn(responseDefinitionBuilder));
}
private static class AdjustableClock extends Clock {
private Instant time;
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
throw new UnsupportedOperationException();
}
@Override
public Instant instant() {
return time;
}
}
private static ProfileFileSupplier supply(Iterable<ProfileFile> iterable) {
return iterable.iterator()::next;
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private ProfileFile configFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CONFIGURATION)
.build();
}
private ProfileFile credentialFile(String name, String accessKeyId, String secretAccessKey) {
String contents = String.format("[%s]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
name, accessKeyId, secretAccessKey);
return credentialFile(contents);
}
private ProfileFile configFile(String name, Pair<?, ?>... pairs) {
String values = Arrays.stream(pairs)
.map(pair -> String.format("%s=%s", pair.left(), pair.right()))
.collect(Collectors.joining(System.lineSeparator()));
String contents = String.format("[%s]\n%s", name, values);
return configFile(contents);
}
}
| 1,411 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ContainerCredentialsEndpointProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static software.amazon.awssdk.core.SdkSystemSetting.AWS_CONTAINER_AUTHORIZATION_TOKEN;
import static software.amazon.awssdk.core.SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI;
import static software.amazon.awssdk.core.SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI;
import java.io.IOException;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.util.SdkUserAgent;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
public class ContainerCredentialsEndpointProviderTest {
private static final EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
private static final ContainerCredentialsProvider.ContainerCredentialsEndpointProvider sut =
new ContainerCredentialsProvider.ContainerCredentialsEndpointProvider(null);
@Before
public void clearContainerVariablesIncaseWereRunningTestsOnEC2() {
helper.remove(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI);
}
@After
public void restoreOriginal() {
helper.reset();
}
@Test
public void takesUriFromOverride() throws IOException {
String hostname = "http://localhost:8080";
String path = "/endpoint";
helper.set(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, path);
assertThat(new ContainerCredentialsProvider.ContainerCredentialsEndpointProvider(hostname).endpoint().toString(),
equalTo(hostname + path));
}
@Test
public void takesUriFromTheEnvironmentVariable() throws IOException {
String fullUri = "http://localhost:8080/endpoint";
helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri);
assertThat(sut.endpoint().toString(), equalTo(fullUri));
}
@Test
public void theLoopbackAddressIsAlsoAcceptable() throws IOException {
String fullUri = "http://127.0.0.1:9851/endpoint";
helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri);
assertThat(sut.endpoint().toString(), equalTo(fullUri));
}
@Test
public void theLoopbackIpv6AddressIsAlsoAcceptable() throws IOException {
String fullUri = "http://[::1]:9851/endpoint";
helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri);
assertThat(sut.endpoint().toString(), equalTo(fullUri));
}
@Test
public void anyHttpsAddressIsAlsoAcceptable() throws IOException {
String fullUri = "https://192.168.10.120:9851/endpoint";
helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri);
assertThat(sut.endpoint().toString(), equalTo(fullUri));
}
@Test
public void anyHttpsIpv6AddressIsAlsoAcceptable() throws IOException {
String fullUri = "https://[::FFFF:152.16.24.123]/endpoint";
helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri);
assertThat(sut.endpoint().toString(), equalTo(fullUri));
}
@Test(expected = SdkClientException.class)
public void nonLoopbackAddressIsNotAcceptable() throws IOException {
String fullUri = "http://192.168.10.120:9851/endpoint";
helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri);
assertThat(sut.endpoint().toString(), equalTo(fullUri));
}
@Test(expected = SdkClientException.class)
public void nonLoopbackIpv6AddressIsNotAcceptable() throws IOException {
String fullUri = "http://[::FFFF:152.16.24.123]/endpoint";
helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri);
assertThat(sut.endpoint().toString(), equalTo(fullUri));
}
@Test(expected = SdkClientException.class)
public void onlyLocalHostAddressesAreValid() throws IOException {
helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), "http://google.com/endpoint");
sut.endpoint();
}
@Test
public void authorizationHeaderIsPresentIfEnvironmentVariableSet() {
helper.set(AWS_CONTAINER_AUTHORIZATION_TOKEN.environmentVariable(), "hello authorized world!");
Map<String, String> headers = sut.headers();
assertThat(headers.size(), equalTo(2));
assertThat(headers, hasEntry("Authorization", "hello authorized world!"));
assertThat(headers, hasEntry("User-Agent", SdkUserAgent.create().userAgent()));
}
}
| 1,412 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/AwsCredentialsProviderChainTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays;
import org.junit.Test;
import org.junit.jupiter.api.function.Executable;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.StringInputStream;
public class AwsCredentialsProviderChainTest {
/**
* Tests that, by default, the chain remembers which provider was able to
* provide credentials, and only calls that provider for any additional
* calls to getCredentials.
*/
@Test
public void resolveCredentials_reuseEnabled_reusesLastProvider() throws Exception {
MockCredentialsProvider provider1 = new MockCredentialsProvider("Failed!");
MockCredentialsProvider provider2 = new MockCredentialsProvider();
AwsCredentialsProviderChain chain = AwsCredentialsProviderChain.builder()
.credentialsProviders(provider1, provider2)
.build();
assertEquals(0, provider1.getCredentialsCallCount);
assertEquals(0, provider2.getCredentialsCallCount);
chain.resolveCredentials();
assertEquals(1, provider1.getCredentialsCallCount);
assertEquals(1, provider2.getCredentialsCallCount);
chain.resolveCredentials();
assertEquals(1, provider1.getCredentialsCallCount);
assertEquals(2, provider2.getCredentialsCallCount);
chain.resolveCredentials();
assertEquals(1, provider1.getCredentialsCallCount);
assertEquals(3, provider2.getCredentialsCallCount);
}
/**
* Tests that, when provider caching is disabled, the chain will always try
* all providers in the chain, starting with the first, until it finds a
* provider that can return credentials.
*/
@Test
public void resolveCredentials_reuseDisabled_alwaysGoesThroughChain() throws Exception {
MockCredentialsProvider provider1 = new MockCredentialsProvider("Failed!");
MockCredentialsProvider provider2 = new MockCredentialsProvider();
AwsCredentialsProviderChain chain = AwsCredentialsProviderChain.builder()
.credentialsProviders(provider1, provider2)
.reuseLastProviderEnabled(false)
.build();
assertEquals(0, provider1.getCredentialsCallCount);
assertEquals(0, provider2.getCredentialsCallCount);
chain.resolveCredentials();
assertEquals(1, provider1.getCredentialsCallCount);
assertEquals(1, provider2.getCredentialsCallCount);
chain.resolveCredentials();
assertEquals(2, provider1.getCredentialsCallCount);
assertEquals(2, provider2.getCredentialsCallCount);
}
@Test
public void resolveCredentials_missingProfile_usesNextProvider() {
ProfileCredentialsProvider provider =
new ProfileCredentialsProvider.BuilderImpl()
.defaultProfileFileLoader(() -> ProfileFile.builder()
.content(new StringInputStream(""))
.type(ProfileFile.Type.CONFIGURATION)
.build())
.build();
MockCredentialsProvider provider2 = new MockCredentialsProvider();
AwsCredentialsProviderChain chain = AwsCredentialsProviderChain.builder().credentialsProviders(provider, provider2).build();
chain.resolveCredentials();
assertEquals(1, provider2.getCredentialsCallCount);
}
/**
* Tests that resolveCredentials throws an thrown if all providers in the
* chain fail to provide credentials.
*/
@Test
public void resolveCredentials_allProvidersFail_throwsExceptionWithMessageFromAllProviders() {
MockCredentialsProvider provider1 = new MockCredentialsProvider("Failed!");
MockCredentialsProvider provider2 = new MockCredentialsProvider("Bad!");
AwsCredentialsProviderChain chain = AwsCredentialsProviderChain.builder()
.credentialsProviders(provider1, provider2)
.build();
SdkClientException e = assertThrows(SdkClientException.class, () -> chain.resolveCredentials());
assertThat(e.getMessage()).contains(provider1.exceptionMessage);
assertThat(e.getMessage()).contains(provider2.exceptionMessage);
}
@Test
public void resolveCredentials_emptyChain_throwsException() {
assertThrowsIllegalArgument(() -> AwsCredentialsProviderChain.of());
assertThrowsIllegalArgument(() -> AwsCredentialsProviderChain
.builder()
.credentialsProviders()
.build());
assertThrowsIllegalArgument(() -> AwsCredentialsProviderChain
.builder()
.credentialsProviders(Arrays.asList())
.build());
}
private void assertThrowsIllegalArgument(Executable executable) {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, executable);
assertThat(e.getMessage()).contains("No credential providers were specified.");
}
/**
* Tests that the chain is setup correctly with the overloaded methods that accept the AwsCredentialsProvider type.
*/
@Test
public void createMethods_withOldCredentialsType_work() {
AwsCredentialsProvider provider = StaticCredentialsProvider.create(AwsBasicCredentials.create(
"accessKey", "secretKey"));
assertChainResolvesCorrectly(AwsCredentialsProviderChain.of(provider));
assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().credentialsProviders(provider).build());
assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().credentialsProviders(Arrays.asList(provider)).build());
assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().addCredentialsProvider(provider).build());
}
/**
* Tests that the chain is setup correctly with the overloaded methods that accept the IdentityProvider type.
*/
@Test
public void createMethods_withNewCredentialsType_work() {
IdentityProvider<AwsCredentialsIdentity> provider = StaticCredentialsProvider.create(AwsBasicCredentials.create(
"accessKey", "secretKey"));
assertChainResolvesCorrectly(AwsCredentialsProviderChain.of(provider));
assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().credentialsProviders(provider).build());
assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().credentialsIdentityProviders(Arrays.asList(provider)).build());
assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().addCredentialsProvider(provider).build());
}
private static void assertChainResolvesCorrectly(AwsCredentialsProviderChain chain) {
AwsCredentials credentials = chain.resolveCredentials();
assertThat(credentials.accessKeyId()).isEqualTo("accessKey");
assertThat(credentials.secretAccessKey()).isEqualTo("secretKey");
}
private static final class MockCredentialsProvider implements AwsCredentialsProvider {
private final StaticCredentialsProvider staticCredentialsProvider;
private final String exceptionMessage;
int getCredentialsCallCount = 0;
private MockCredentialsProvider() {
this(null);
}
private MockCredentialsProvider(String exceptionMessage) {
staticCredentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("accessKey", "secretKey"));
this.exceptionMessage = exceptionMessage;
}
@Override
public AwsCredentials resolveCredentials() {
getCredentialsCallCount++;
if (exceptionMessage != null) {
throw new RuntimeException(exceptionMessage);
} else {
return staticCredentialsProvider.resolveCredentials();
}
}
}
}
| 1,413 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ProcessCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.time.Instant;
import org.assertj.core.api.Assertions;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Platform;
public class ProcessCredentialsProviderTest {
private static final String PROCESS_RESOURCE_PATH = "/resources/process/";
private static final String RANDOM_SESSION_TOKEN = "RANDOM_TOKEN";
private static String scriptLocation;
private static String errorScriptLocation;
@BeforeClass
public static void setup() {
scriptLocation = copyHappyCaseProcessCredentialsScript();
errorScriptLocation = copyErrorCaseProcessCredentialsScript();
}
@AfterClass
public static void teardown() {
if (scriptLocation != null && !new File(scriptLocation).delete()) {
throw new IllegalStateException("Failed to delete file: " + scriptLocation);
}
if (errorScriptLocation != null && !new File(errorScriptLocation).delete()) {
throw new IllegalStateException("Failed to delete file: " + errorScriptLocation);
}
}
@Test
public void staticCredentialsCanBeLoaded() {
AwsCredentials credentials =
ProcessCredentialsProvider.builder()
.command(scriptLocation + " accessKeyId secretAccessKey")
.build()
.resolveCredentials();
Assert.assertFalse(credentials instanceof AwsSessionCredentials);
Assert.assertEquals("accessKeyId", credentials.accessKeyId());
Assert.assertEquals("secretAccessKey", credentials.secretAccessKey());
}
@Test
public void sessionCredentialsCanBeLoaded() {
ProcessCredentialsProvider credentialsProvider =
ProcessCredentialsProvider.builder()
.command(scriptLocation + " accessKeyId secretAccessKey sessionToken " +
DateUtils.formatIso8601Date(Instant.now()))
.credentialRefreshThreshold(Duration.ofSeconds(1))
.build();
AwsCredentials credentials = credentialsProvider.resolveCredentials();
Assert.assertTrue(credentials instanceof AwsSessionCredentials);
AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials;
Assert.assertEquals("accessKeyId", sessionCredentials.accessKeyId());
Assert.assertEquals("secretAccessKey", sessionCredentials.secretAccessKey());
assertNotNull(sessionCredentials.sessionToken());
}
@Test
public void resultsAreCached() {
ProcessCredentialsProvider credentialsProvider =
ProcessCredentialsProvider.builder()
.command(scriptLocation + " accessKeyId secretAccessKey sessionToken " +
DateUtils.formatIso8601Date(Instant.now().plusSeconds(20)))
.build();
AwsCredentials request1 = credentialsProvider.resolveCredentials();
AwsCredentials request2 = credentialsProvider.resolveCredentials();
Assert.assertEquals(request1, request2);
}
@Test
public void expirationBufferOverrideIsApplied() {
ProcessCredentialsProvider credentialsProvider =
ProcessCredentialsProvider.builder()
.command(String.format("%s accessKeyId secretAccessKey %s %s",
scriptLocation,
RANDOM_SESSION_TOKEN,
DateUtils.formatIso8601Date(Instant.now().plusSeconds(20))))
.credentialRefreshThreshold(Duration.ofSeconds(20))
.build();
AwsCredentials request1 = credentialsProvider.resolveCredentials();
AwsCredentials request2 = credentialsProvider.resolveCredentials();
Assert.assertNotEquals(request1, request2);
}
@Test
public void processFailed_shouldContainErrorMessage() {
ProcessCredentialsProvider credentialsProvider =
ProcessCredentialsProvider.builder()
.command(errorScriptLocation)
.credentialRefreshThreshold(Duration.ofSeconds(20))
.build();
assertThatThrownBy(credentialsProvider::resolveCredentials)
.satisfies(throwable -> assertThat(throwable.getCause())
.hasMessageContaining("(125) with error message: Some error case"));
}
@Test
public void lackOfExpirationIsCachedForever() {
ProcessCredentialsProvider credentialsProvider =
ProcessCredentialsProvider.builder()
.command(scriptLocation + " accessKeyId secretAccessKey sessionToken")
.credentialRefreshThreshold(Duration.ofSeconds(20))
.build();
AwsCredentials request1 = credentialsProvider.resolveCredentials();
AwsCredentials request2 = credentialsProvider.resolveCredentials();
Assert.assertEquals(request1, request2);
}
@Test(expected = IllegalStateException.class)
public void processOutputLimitIsEnforced() {
ProcessCredentialsProvider.builder()
.command(scriptLocation + " accessKeyId secretAccessKey")
.processOutputLimit(1)
.build()
.resolveCredentials();
}
@Test
public void processOutputLimitDefaultPassesLargeInput() {
String LONG_SESSION_TOKEN = "lYzvmByqdS1E69QQVEavDDHabQ2GuYKYABKRA4xLbAXpdnFtV030UH4" +
"bQoZWCDcfADFvBwBm3ixEFTYMjn5XQozpFV2QAsWHirCVcEJ5DC60KPCNBcDi4KLNJfbsp3r6kKTOmYOeqhEyiC4emDX33X2ppZsa5" +
"1iwr6ShIZPOUPmuR4WDglmWubgO2q5tZv48xA5idkcHEmtGdoL343sY24q4gMh21eeBnF6ikjZdfvZ0Mn86UQ8r05AD346rSwM5bFs" +
"t019ZkJIjLHD3HoKJ44EndRvSvQClXfJCmmQDH5INiXdFLLNm0dzT3ynbVIW5x1YYBWptyts4NUSy2eJ3dTPjYICpQVCkbuNVA7PqR" +
"ctUyE8lU7uvnrIVnx9xTgl34J6D9VJKHQkPuGvbtN6w4CVtXoPAQcE8tlkKyOQmIeqEahhaqLW15t692SI6hwBW0b8DxCQawX5ukt4" +
"f5gZoRFz3u8qHMSnm5oEnTgv7C5AAs0V680YvelFMNYvSoSbDnoThxfTIG9msj7WBh7iNa7mI8TXmvOegQtDWR011ZOo8dR3jnhWNH" +
"nSW4CRB7iSC5DMZ2y56dYS28XGBl01LYXF5ZTJJfLwQEhbRWSTdXIBJq07E0YxRu0SaLokA4uknOoicwXnD7LMCld4hFjuypYgWBuk" +
"3pC09CPA0MJjQNTTAvxGqDTqSWoXWDZRIMUWyGyz3FCkpPUjv4mIpVYt2bGl6cHsMBzVnpL6yXMCw2mNqJx8Rvi4gQaHH6LzvHbVKR" +
"w4kE53703DNOc8cA9Zc0efJa4NHOFxc4XmMOtjGW7vbWPp0CTVCJLG94ddSFJrimpamPM59bs12x2ih51EpOFR5ITIxJnd79HEkYDU" +
"xRIOuPIe4VpM01RnFN4g3ChDqmjQ03wQY9I8Mvh59u3MujggQfwAhCc84MAz0jVukoMfhAAhMNUPLuwRj0qpqr6B3DdKZ4KDFWF2Ga" +
"Iu1sEFlKvPdfF1uefbTj6YdjUciWu1UBH47VbIcTbvbwmUiu2javB21kOenyDoelK5GUM4u0uPeXIOOhtZsJb8kz88h1joWkaKr2fc" +
"jrIS08FM47Y4Z2Mi4zfwyN54L";
ProcessCredentialsProvider credentialsProvider = ProcessCredentialsProvider.builder()
.command(scriptLocation + " accessKeyId secretAccessKey " + LONG_SESSION_TOKEN)
.build();
AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials();
Assertions.assertThat(sessionCredentials.accessKeyId()).isEqualTo("accessKeyId");
Assertions.assertThat(sessionCredentials.sessionToken()).isNotNull();
}
@Test
public void closeDoesNotRaise() {
ProcessCredentialsProvider credentialsProvider =
ProcessCredentialsProvider.builder()
.command(scriptLocation + " accessKeyId secretAccessKey sessionToken")
.build();
credentialsProvider.resolveCredentials();
credentialsProvider.close();
}
public static String copyHappyCaseProcessCredentialsScript() {
String scriptClasspathFilename = Platform.isWindows() ? "windows-credentials-script.bat"
: "linux-credentials-script.sh";
return copyProcessCredentialsScript(scriptClasspathFilename);
}
public static String copyErrorCaseProcessCredentialsScript() {
String scriptClasspathFilename = Platform.isWindows() ? "windows-credentials-error-script.bat"
: "linux-credentials-error-script.sh";
return copyProcessCredentialsScript(scriptClasspathFilename);
}
public static String copyProcessCredentialsScript(String scriptClasspathFilename) {
String scriptClasspathLocation = PROCESS_RESOURCE_PATH + scriptClasspathFilename;
InputStream scriptInputStream = null;
OutputStream scriptOutputStream = null;
try {
scriptInputStream = ProcessCredentialsProviderTest.class.getResourceAsStream(scriptClasspathLocation);
File scriptFileOnDisk = File.createTempFile("ProcessCredentialsProviderTest", scriptClasspathFilename);
scriptFileOnDisk.deleteOnExit();
if (!scriptFileOnDisk.setExecutable(true)) {
throw new IllegalStateException("Could not make " + scriptFileOnDisk + " executable.");
}
scriptOutputStream = new FileOutputStream(scriptFileOnDisk);
IoUtils.copy(scriptInputStream, scriptOutputStream);
return scriptFileOnDisk.getAbsolutePath();
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
IoUtils.closeQuietly(scriptInputStream, null);
IoUtils.closeQuietly(scriptOutputStream, null);
}
}
} | 1,414 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/StaticCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StaticCredentialsProviderTest {
@Test
public void getAwsCredentials_ReturnsSameCredentials() throws Exception {
final AwsCredentials credentials = new AwsBasicCredentials("akid", "skid");
final AwsCredentials actualCredentials =
StaticCredentialsProvider.create(credentials).resolveCredentials();
assertEquals(credentials, actualCredentials);
}
@Test
public void getSessionAwsCredentials_ReturnsSameCredentials() throws Exception {
final AwsSessionCredentials credentials = AwsSessionCredentials.create("akid", "skid", "token");
final AwsCredentials actualCredentials = StaticCredentialsProvider.create(credentials).resolveCredentials();
assertEquals(credentials, actualCredentials);
}
@Test(expected = RuntimeException.class)
public void nullCredentials_ThrowsIllegalArgumentException() {
StaticCredentialsProvider.create(null);
}
}
| 1,415 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/EndpointModeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.auth.credentials.internal.Ec2MetadataConfigProvider.EndpointMode.IPV4;
import static software.amazon.awssdk.auth.credentials.internal.Ec2MetadataConfigProvider.EndpointMode.IPV6;
import org.junit.jupiter.api.Test;
public class EndpointModeTest {
@Test
public void fromString_caseInsensitive() {
assertThat(Ec2MetadataConfigProvider.EndpointMode.fromValue("iPv6")).isEqualTo(IPV6);
assertThat(Ec2MetadataConfigProvider.EndpointMode.fromValue("iPv4")).isEqualTo(IPV4);
}
@Test
public void fromString_unknownValue_throws() {
assertThatThrownBy(() -> Ec2MetadataConfigProvider.EndpointMode.fromValue("unknown"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fromString_nullValue_returnsNull() {
assertThat(Ec2MetadataConfigProvider.EndpointMode.fromValue(null)).isNull();
}
}
| 1,416 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/AwsSessionCredentialsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
public class AwsSessionCredentialsTest {
private static final String ACCESS_KEY_ID = "accessKeyId";
private static final String SECRET_ACCESS_KEY = "secretAccessKey";
private static final String SESSION_TOKEN = "sessionToken";
public void equalsHashcode() {
EqualsVerifier.forClass(AwsSessionCredentials.class)
.verify();
}
@Test
public void emptyBuilder_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsSessionCredentials.builder().build());
}
@Test
public void builderMissingSessionToken_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsSessionCredentials.builder()
.accessKeyId(ACCESS_KEY_ID)
.secretAccessKey(SECRET_ACCESS_KEY)
.build());
}
@Test
public void builderMissingAccessKeyId_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsSessionCredentials.builder()
.secretAccessKey(SECRET_ACCESS_KEY)
.sessionToken(SESSION_TOKEN)
.build());
}
@Test
public void create_isSuccessful() {
AwsSessionCredentials identity = AwsSessionCredentials.create(ACCESS_KEY_ID,
SECRET_ACCESS_KEY,
SESSION_TOKEN);
assertEquals(ACCESS_KEY_ID, identity.accessKeyId());
assertEquals(SECRET_ACCESS_KEY, identity.secretAccessKey());
assertEquals(SESSION_TOKEN, identity.sessionToken());
}
@Test
public void build_isSuccessful() {
AwsSessionCredentials identity = AwsSessionCredentials.builder()
.accessKeyId(ACCESS_KEY_ID)
.secretAccessKey(SECRET_ACCESS_KEY)
.sessionToken(SESSION_TOKEN)
.build();
assertEquals(ACCESS_KEY_ID, identity.accessKeyId());
assertEquals(SECRET_ACCESS_KEY, identity.secretAccessKey());
assertEquals(SESSION_TOKEN, identity.sessionToken());
}
}
| 1,417 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/Ec2MetadataConfigProviderEndpointModeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.function.Supplier;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
@RunWith(Parameterized.class)
public class Ec2MetadataConfigProviderEndpointModeTest {
private static final String TEST_PROFILES_PATH_PREFIX = "/software/amazon/awssdk/auth/credentials/internal/ec2metadataconfigprovider/";
private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
private static final String CUSTOM_PROFILE = "myprofile";
@Parameterized.Parameter
public TestCase testCase;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object> testCases() {
return Arrays.asList(
new TestCase().expectedEndpointMode(null).expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4),
new TestCase().envEndpointMode("ipv4").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4),
new TestCase().envEndpointMode("IPv4").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4),
new TestCase().envEndpointMode("ipv6").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
new TestCase().envEndpointMode("IPv6").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
new TestCase().envEndpointMode("Ipv99").expectedException(IllegalArgumentException.class),
new TestCase().systemPropertyEndpointMode("ipv4").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4),
new TestCase().systemPropertyEndpointMode("IPv4").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4),
new TestCase().systemPropertyEndpointMode("ipv6").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
new TestCase().systemPropertyEndpointMode("IPv6").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
new TestCase().systemPropertyEndpointMode("Ipv99").expectedException(IllegalArgumentException.class),
new TestCase().sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_ipv6")
.expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
new TestCase().sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_invalidValue")
.expectedException(IllegalArgumentException.class),
// System property takes highest precedence
new TestCase().systemPropertyEndpointMode("ipv6").envEndpointMode("ipv4")
.expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
new TestCase().systemPropertyEndpointMode("ipv6").sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_ipv4")
.expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
// env var has higher precedence than shared config
new TestCase().envEndpointMode("ipv6").sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_ipv4")
.expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
// Test custom profile supplier and custom profile name
new TestCase().sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_ipv6_custom_profile")
.customProfileName(CUSTOM_PROFILE).expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6),
new TestCase().customProfileFile(Ec2MetadataConfigProviderEndpointModeTest::customProfileFile)
.customProfileName(CUSTOM_PROFILE).expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6)
);
}
@Before
public void setup() {
ENVIRONMENT_VARIABLE_HELPER.reset();
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property());
if (testCase.envEndpointMode != null) {
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.environmentVariable(),
testCase.envEndpointMode);
}
if (testCase.systemPropertyEndpointMode != null) {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property(),
testCase.systemPropertyEndpointMode);
}
if (testCase.sharedConfigFile != null) {
ENVIRONMENT_VARIABLE_HELPER.set(ProfileFileSystemSetting.AWS_CONFIG_FILE.environmentVariable(),
getTestFilePath(testCase.sharedConfigFile));
}
if (testCase.expectedException != null) {
thrown.expect(testCase.expectedException);
}
}
@After
public void teardown() {
ENVIRONMENT_VARIABLE_HELPER.reset();
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property());
}
@Test
public void resolvesCorrectEndpointMode() {
Ec2MetadataConfigProvider configProvider = Ec2MetadataConfigProvider.builder()
.profileFile(testCase.customProfileFile)
.profileName(testCase.customProfileName)
.build();
assertThat(configProvider.getEndpointMode()).isEqualTo(testCase.expectedEndpointMode);
}
private static String getTestFilePath(String testFile) {
return Ec2MetadataConfigProviderEndpointModeTest.class.getResource(testFile).getFile();
}
private static ProfileFile customProfileFile() {
String content = "[profile myprofile]\n" +
"ec2_metadata_service_endpoint_mode=ipv6\n";
return ProfileFile.builder()
.type(ProfileFile.Type.CONFIGURATION)
.content(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)))
.build();
}
private static class TestCase {
private String envEndpointMode;
private String systemPropertyEndpointMode;
private String sharedConfigFile;
private Supplier<ProfileFile> customProfileFile;
private String customProfileName;
private Ec2MetadataConfigProvider.EndpointMode expectedEndpointMode;
private Class<? extends Throwable> expectedException;
public TestCase envEndpointMode(String envEndpointMode) {
this.envEndpointMode = envEndpointMode;
return this;
}
public TestCase systemPropertyEndpointMode(String systemPropertyEndpointMode) {
this.systemPropertyEndpointMode = systemPropertyEndpointMode;
return this;
}
public TestCase sharedConfigFile(String sharedConfigFile) {
this.sharedConfigFile = sharedConfigFile;
return this;
}
public TestCase customProfileFile(Supplier<ProfileFile> customProfileFile) {
this.customProfileFile = customProfileFile;
return this;
}
private TestCase customProfileName(String customProfileName) {
this.customProfileName = customProfileName;
return this;
}
public TestCase expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode expectedEndpointMode) {
this.expectedEndpointMode = expectedEndpointMode;
return this;
}
public TestCase expectedException(Class<? extends Throwable> expectedException) {
this.expectedException = expectedException;
return this;
}
@Override
public String toString() {
return "TestCase{" +
"envEndpointMode='" + envEndpointMode + '\'' +
", systemPropertyEndpointMode='" + systemPropertyEndpointMode + '\'' +
", sharedConfigFile='" + sharedConfigFile + '\'' +
", customProfileFile=" + customProfileFile +
", customProfileName='" + customProfileName + '\'' +
", expectedEndpointMode=" + expectedEndpointMode +
", expectedException=" + expectedException +
'}';
}
}
}
| 1,418 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/Ec2MetadataConfigProviderEndpointOverrideTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
@RunWith(Parameterized.class)
public class Ec2MetadataConfigProviderEndpointOverrideTest {
private static final String TEST_PROFILES_PATH_PREFIX = "/software/amazon/awssdk/auth/credentials/internal/ec2metadataconfigprovider/";
private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
@Parameterized.Parameter
public TestCase testCase;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object> testCases() {
return Arrays.<Object>asList(
new TestCase().expectedEndpointOverride(null),
new TestCase().envEndpointOverride("my-custom-imds").expectedEndpointOverride("my-custom-imds"),
new TestCase().systemPropertyEndpointOverride("my-custom-imds").expectedEndpointOverride("my-custom-imds"),
new TestCase().sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_override")
.expectedEndpointOverride("my-custom-imds-profile"),
// System property takes highest precedence
new TestCase().systemPropertyEndpointOverride("my-systemprop-endpoint").envEndpointOverride("my-env-endpoint")
.expectedEndpointOverride("my-systemprop-endpoint"),
new TestCase().systemPropertyEndpointOverride("my-systemprop-endpoint").sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_override")
.expectedEndpointOverride("my-systemprop-endpoint"),
//
// env var has higher precedence than shared config
new TestCase().envEndpointOverride("my-env-endpoint").sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_override")
.expectedEndpointOverride("my-env-endpoint")
);
}
@Before
public void setup() {
ENVIRONMENT_VARIABLE_HELPER.reset();
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property());
if (testCase.envEndpointOverride != null) {
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.environmentVariable(),
testCase.envEndpointOverride);
}
if (testCase.systemPropertyEndpointOverride != null) {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(),
testCase.systemPropertyEndpointOverride);
}
if (testCase.sharedConfigFile != null) {
ENVIRONMENT_VARIABLE_HELPER.set(ProfileFileSystemSetting.AWS_CONFIG_FILE.environmentVariable(),
getTestFilePath(testCase.sharedConfigFile));
}
if (testCase.expectedException != null) {
thrown.expect(testCase.expectedException);
}
}
@After
public void teardown() {
ENVIRONMENT_VARIABLE_HELPER.reset();
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property());
}
@Test
public void resolvesCorrectEndpointOverride() {
String endpointOverride = Ec2MetadataConfigProvider.builder().build().getEndpointOverride();
assertThat(endpointOverride).isEqualTo(testCase.expectedEndpointOverride);
}
private static String getTestFilePath(String testFile) {
return Ec2MetadataConfigProviderEndpointOverrideTest.class.getResource(testFile).getFile();
}
private static class TestCase {
private String envEndpointOverride;
private String systemPropertyEndpointOverride;
private String sharedConfigFile;
private String expectedEndpointOverride;
private Class<? extends Throwable> expectedException;
public TestCase envEndpointOverride(String envEndpointOverride) {
this.envEndpointOverride = envEndpointOverride;
return this;
}
public TestCase systemPropertyEndpointOverride(String systemPropertyEndpointOverride) {
this.systemPropertyEndpointOverride = systemPropertyEndpointOverride;
return this;
}
public TestCase sharedConfigFile(String sharedConfigFile) {
this.sharedConfigFile = sharedConfigFile;
return this;
}
public TestCase expectedEndpointOverride(String expectedEndpointOverride) {
this.expectedEndpointOverride = expectedEndpointOverride;
return this;
}
public TestCase expectedException(Class<? extends Throwable> expectedException) {
this.expectedException = expectedException;
return this;
}
@Override
public String toString() {
return "TestCase{" +
"envEndpointOverride='" + envEndpointOverride + '\'' +
", systemPropertyEndpointOverride='" + systemPropertyEndpointOverride + '\'' +
", sharedConfigFile='" + sharedConfigFile + '\'' +
", expectedEndpointOverride='" + expectedEndpointOverride + '\'' +
", expectedException=" + expectedException +
'}';
}
}
}
| 1,419 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/LazyAwsCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.utils.SdkAutoCloseable;
public class LazyAwsCredentialsProviderTest {
@SuppressWarnings("unchecked")
private Supplier<AwsCredentialsProvider> credentialsConstructor = Mockito.mock(Supplier.class);
private AwsCredentialsProvider credentials = Mockito.mock(AwsCredentialsProvider.class);
@BeforeEach
public void reset() {
Mockito.reset(credentials, credentialsConstructor);
Mockito.when(credentialsConstructor.get()).thenReturn(credentials);
}
@Test
public void creationDoesntInvokeSupplier() {
LazyAwsCredentialsProvider.create(credentialsConstructor);
Mockito.verifyNoMoreInteractions(credentialsConstructor);
}
@Test
public void resolveCredentialsInvokesSupplierExactlyOnce() {
LazyAwsCredentialsProvider credentialsProvider = LazyAwsCredentialsProvider.create(credentialsConstructor);
credentialsProvider.resolveCredentials();
credentialsProvider.resolveCredentials();
Mockito.verify(credentialsConstructor, Mockito.times(1)).get();
Mockito.verify(credentials, Mockito.times(2)).resolveCredentials();
}
@Test
public void delegatesClosesInitializerAndValue() {
CloseableSupplier initializer = Mockito.mock(CloseableSupplier.class);
CloseableCredentialsProvider value = Mockito.mock(CloseableCredentialsProvider.class);
Mockito.when(initializer.get()).thenReturn(value);
LazyAwsCredentialsProvider.create(initializer).close();
Mockito.verify(initializer).close();
Mockito.verify(value).close();
}
@Test
public void delegatesClosesInitializerEvenIfGetFails() {
CloseableSupplier initializer = Mockito.mock(CloseableSupplier.class);
Mockito.when(initializer.get()).thenThrow(new RuntimeException());
LazyAwsCredentialsProvider.create(initializer).close();
Mockito.verify(initializer).close();
}
private interface CloseableSupplier extends Supplier<AwsCredentialsProvider>, SdkAutoCloseable {}
private interface CloseableCredentialsProvider extends SdkAutoCloseable, AwsCredentialsProvider {}
}
| 1,420 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/Ec2MetadataConfigProviderEndpointResolutionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.core.SdkSystemSetting;
@RunWith(Parameterized.class)
public class Ec2MetadataConfigProviderEndpointResolutionTest {
private static final String EC2_METADATA_SERVICE_URL_IPV4 = "http://169.254.169.254";
private static final String EC2_METADATA_SERVICE_URL_IPV6 = "http://[fd00:ec2::254]";
private static final String ENDPOINT_OVERRIDE = "http://my-custom-endpoint";
@Parameterized.Parameter
public TestCase testCase;
@Parameterized.Parameters
public static Iterable<Object> testCases() {
return Arrays.asList(
new TestCase().expectedEndpoint(EC2_METADATA_SERVICE_URL_IPV4),
new TestCase().endpointMode("ipv6").expectedEndpoint(EC2_METADATA_SERVICE_URL_IPV6),
new TestCase().endpointMode("ipv4").expectedEndpoint(EC2_METADATA_SERVICE_URL_IPV4),
new TestCase().endpointOverride(ENDPOINT_OVERRIDE).expectedEndpoint(ENDPOINT_OVERRIDE),
new TestCase().endpointMode("ipv4").endpointOverride(ENDPOINT_OVERRIDE).expectedEndpoint(ENDPOINT_OVERRIDE),
new TestCase().endpointMode("ipv6").endpointOverride(ENDPOINT_OVERRIDE).expectedEndpoint(ENDPOINT_OVERRIDE),
new TestCase().endpointMode("ipv99").endpointOverride(ENDPOINT_OVERRIDE).expectedEndpoint(ENDPOINT_OVERRIDE)
);
}
@Before
public void setup() {
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property());
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property());
if (testCase.endpointMode != null) {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property(), testCase.endpointMode);
}
if (testCase.endpointOverride != null) {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), testCase.endpointOverride);
}
}
@Test
public void resolvesCorrectEndpoint() {
assertThat(Ec2MetadataConfigProvider.builder().build().getEndpoint()).isEqualTo(testCase.expectedEndpoint);
}
private static class TestCase {
private String endpointMode;
private String endpointOverride;
private String expectedEndpoint;
public TestCase endpointMode(String endpointMode) {
this.endpointMode = endpointMode;
return this;
}
public TestCase endpointOverride(String endpointOverride) {
this.endpointOverride = endpointOverride;
return this;
}
public TestCase expectedEndpoint(String expectedEndpoint) {
this.expectedEndpoint = expectedEndpoint;
return this;
}
}
} | 1,421 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/ProfileCredentialsUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.ProcessCredentialsProviderTest;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.StringInputStream;
public class ProfileCredentialsUtilsTest {
private static String scriptLocation;
@BeforeAll
public static void setup() {
scriptLocation = ProcessCredentialsProviderTest.copyHappyCaseProcessCredentialsScript();
}
@AfterAll
public static void teardown() {
if (scriptLocation != null && !new File(scriptLocation).delete()) {
throw new IllegalStateException("Failed to delete file: " + scriptLocation);
}
}
@Test
public void roleProfileCanInheritFromAnotherFile() {
String sourceProperties =
"aws_access_key_id=defaultAccessKey\n" +
"aws_secret_access_key=defaultSecretAccessKey";
String childProperties =
"source_profile=source\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole";
String configSource = "[profile source]\n" + sourceProperties;
String credentialsSource = "[source]\n" + sourceProperties;
String configChild = "[profile child]\n" + childProperties;
String credentialsChild = "[child]\n" + childProperties;
ProfileFile sourceProfile = aggregateFileProfiles(configSource, credentialsChild);
ProfileFile configProfile = aggregateFileProfiles(configChild, credentialsSource);
Consumer<ProfileFile> profileValidator = profileFile ->
assertThatThrownBy(new ProfileCredentialsUtils(profileFile, profileFile.profiles().get("child"),
profileFile::profile)::credentialsProvider)
.hasMessageContaining("the 'sts' service module must be on the class path");
assertThat(sourceProfile).satisfies(profileValidator);
assertThat(configProfile).satisfies(profileValidator);
}
@Test
public void roleProfileWithMissingSourceThrowsException() {
ProfileFile profileFile = configFile("[profile test]\n" +
"source_profile=source\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole");
assertThatThrownBy(new ProfileCredentialsUtils(profileFile, profileFile.profile("test")
.get(), profileFile::profile)::credentialsProvider)
.hasMessageContaining("source profile has no credentials configured.");
}
@Test
public void roleProfileWithSourceThatHasNoCredentialsThrowsExceptionWhenLoadingCredentials() {
ProfileFile profiles = configFile("[profile source]\n" +
"[profile test]\n" +
"source_profile=source\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole");
assertThat(profiles.profile("test")).hasValueSatisfying(profile -> {
ProfileCredentialsUtils profileCredentialsUtils = new ProfileCredentialsUtils(profiles, profile, profiles::profile);
assertThatThrownBy(profileCredentialsUtils::credentialsProvider)
.hasMessageContaining("source profile has no credentials configured");
});
}
@Test
public void profileFileWithRegionLoadsCorrectly() {
assertThat(allTypesProfile().profile("profile-with-region")).hasValueSatisfying(profile -> {
assertThat(profile.property(ProfileProperty.REGION)).hasValue("us-east-1");
});
}
@Test
public void profileFileWithStaticCredentialsLoadsCorrectly() {
ProfileFile profileFile = allTypesProfile();
assertThat(profileFile.profile("default")).hasValueSatisfying(profile -> {
assertThat(profile.name()).isEqualTo("default");
assertThat(profile.property(ProfileProperty.AWS_ACCESS_KEY_ID)).hasValue("defaultAccessKey");
assertThat(profile.toString()).contains("default");
assertThat(profile.property(ProfileProperty.REGION)).isNotPresent();
assertThat(new ProfileCredentialsUtils(profileFile, profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> {
assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> {
assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey");
assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey");
});
});
});
}
@Test
public void profileFileWithSessionCredentialsLoadsCorrectly() {
ProfileFile profileFile = allTypesProfile();
assertThat(profileFile.profile("profile-with-session-token")).hasValueSatisfying(profile -> {
assertThat(profile.property(ProfileProperty.REGION)).isNotPresent();
assertThat(new ProfileCredentialsUtils(profileFile, profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> {
assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> {
assertThat(credentials).isInstanceOf(AwsSessionCredentials.class);
assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey");
assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey");
assertThat(((AwsSessionCredentials) credentials).sessionToken()).isEqualTo("awsSessionToken");
});
});
});
}
@Test
public void profileFileWithProcessCredentialsLoadsCorrectly() {
ProfileFile profileFile = allTypesProfile();
assertThat(profileFile.profile("profile-credential-process")).hasValueSatisfying(profile -> {
assertThat(profile.property(ProfileProperty.REGION)).isNotPresent();
assertThat(new ProfileCredentialsUtils(profileFile, profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> {
assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> {
assertThat(credentials).isInstanceOf(AwsBasicCredentials.class);
assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey");
assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey");
});
});
});
}
@Test
public void profileFileWithAssumeRoleThrowsExceptionWhenRetrievingCredentialsProvider() {
ProfileFile profileFile = allTypesProfile();
assertThat(profileFile.profile("profile-with-assume-role")).hasValueSatisfying(profile -> {
assertThat(profile.property(ProfileProperty.REGION)).isNotPresent();
ProfileCredentialsUtils profileCredentialsUtils = new ProfileCredentialsUtils(profileFile, profile, profileFile::profile);
assertThatThrownBy(profileCredentialsUtils::credentialsProvider).isInstanceOf(IllegalStateException.class);
});
}
@Test
public void profileFileWithCredentialSourceThrowsExceptionWhenRetrievingCredentialsProvider() {
ProfileFile profileFile = allTypesProfile();
List<String> profiles = Arrays.asList(
"profile-with-container-credential-source",
"profile-with-instance-credential-source",
"profile-with-environment-credential-source"
);
profiles.forEach(profileName -> {
assertThat(profileFile.profile(profileName)).hasValueSatisfying(profile -> {
assertThat(profile.property(ProfileProperty.REGION)).isNotPresent();
ProfileCredentialsUtils profileCredentialsUtils = new ProfileCredentialsUtils(profileFile, profile, profileFile::profile);
assertThatThrownBy(profileCredentialsUtils::credentialsProvider).isInstanceOf(IllegalStateException.class);
});
});
}
@Test
public void profileFileWithCircularDependencyThrowsExceptionWhenResolvingCredentials() {
ProfileFile configFile = configFile("[profile source]\n" +
"aws_access_key_id=defaultAccessKey\n" +
"aws_secret_access_key=defaultSecretAccessKey\n" +
"\n" +
"[profile test]\n" +
"source_profile=test3\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole\n" +
"\n" +
"[profile test2]\n" +
"source_profile=test\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole2\n" +
"\n" +
"[profile test3]\n" +
"source_profile=test2\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole3");
assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile, configFile.profile("test").get(), configFile::profile)
.credentialsProvider())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Invalid profile file: Circular relationship detected with profiles");
}
private static Stream<Arguments> roleProfileWithIncompleteSsoRoleNameSSOCredentialsProperties() {
return Stream.of(
// No sso_region
Arguments.of(configFile("[profile test]\n" +
"sso_account_id=accountId\n" +
"sso_role_name=roleName\n" +
"sso_start_url=https//d-abc123.awsapps.com/start"),
"Profile property 'sso_region' was not configured for 'test'"),
// No sso_account_id
Arguments.of(configFile("[profile test]\n" +
"sso_region=region\n" +
"sso_role_name=roleName\n" +
"sso_start_url=https//d-abc123.awsapps.com/start"),
"Profile property 'sso_account_id' was not configured for 'test'"),
// No sso_start_url
Arguments.of(configFile("[profile test]\n" +
"sso_account_id=accountId\n" +
"sso_region=region\n" +
"sso_role_name=roleName\n" +
"sso_region=region"),
"Profile property 'sso_start_url' was not configured for 'test'"),
// No sso_role_name
Arguments.of(configFile("[profile test]\n" +
"sso_account_id=accountId\n" +
"sso_region=region\n" +
"sso_start_url=https//d-abc123.awsapps.com/start"),
"Profile property 'sso_role_name' was not configured for 'test'"),
// sso_session with No sso_account_id
Arguments.of(configFile("[profile test]\n" +
"sso_session=session\n" +
"sso_role_name=roleName"),
"Profile property 'sso_account_id' was not configured for 'test'"),
// sso_session with No sso_role_name
Arguments.of(configFile("[profile test]\n" +
"sso_session=session\n" +
"sso_account_id=accountId\n" +
"sso_start_url=https//d-abc123.awsapps.com/start"),
"Profile property 'sso_role_name' was not configured for 'test'"),
Arguments.of(configFile("[profile test]\n" +
"sso_session=session"),
"Profile property 'sso_account_id' was not configured for 'test'")
);
}
@ParameterizedTest
@MethodSource("roleProfileWithIncompleteSsoRoleNameSSOCredentialsProperties")
void validateCheckSumValues(ProfileFile profiles, String expectedValue) {
assertThat(profiles.profile("test")).hasValueSatisfying(profile -> {
ProfileCredentialsUtils profileCredentialsUtils = new ProfileCredentialsUtils(profiles, profile, profiles::profile);
assertThatThrownBy(profileCredentialsUtils::credentialsProvider)
.hasMessageContaining(expectedValue);
});
}
@Test
public void profileWithBothCredentialSourceAndSourceProfileThrowsException() {
ProfileFile configFile = configFile("[profile test]\n" +
"source_profile=source\n" +
"credential_source=Environment\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole3\n" +
"\n" +
"[profile source]\n" +
"aws_access_key_id=defaultAccessKey\n" +
"aws_secret_access_key=defaultSecretAccessKey");
assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile, configFile.profile("test").get(), configFile::profile)
.credentialsProvider())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Invalid profile file: profile has both source_profile and credential_source.");
}
@Test
public void profileWithInvalidCredentialSourceThrowsException() {
ProfileFile configFile = configFile("[profile test]\n" +
"credential_source=foobar\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole3");
assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile, configFile.profile("test").get(), configFile::profile)
.credentialsProvider())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("foobar is not a valid credential_source");
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private ProfileFile aggregateFileProfiles(String configFile, String credentialFile) {
return ProfileFile.aggregator()
.addFile(credentialFile(credentialFile))
.addFile(configFile(configFile))
.build();
}
private ProfileFile allTypesProfile() {
return configFile("[default]\n" +
"aws_access_key_id = defaultAccessKey\n" +
"aws_secret_access_key = defaultSecretAccessKey\n" +
"\n" +
"[profile profile-with-session-token]\n" +
"aws_access_key_id = defaultAccessKey\n" +
"aws_secret_access_key = defaultSecretAccessKey\n" +
"aws_session_token = awsSessionToken\n" +
"\n" +
"[profile profile-with-region]\n" +
"region = us-east-1\n" +
"\n" +
"[profile profile-with-assume-role]\n" +
"source_profile=default\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole\n" +
"\n" +
"[profile profile-credential-process]\n" +
"credential_process=" + scriptLocation +" defaultAccessKey defaultSecretAccessKey\n" +
"\n" +
"[profile profile-with-container-credential-source]\n" +
"credential_source=ecscontainer\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole\n" +
"\n" +
"[profile profile-with-instance-credential-source]\n" +
"credential_source=ec2instancemetadata\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole\n" +
"\n" +
"[profile profile-with-environment-credential-source]\n" +
"credential_source=environment\n" +
"role_arn=arn:aws:iam::123456789012:role/testRole\n");
}
private static ProfileFile configFile(String configFile) {
return ProfileFile.builder()
.content(new StringInputStream(configFile))
.type(ProfileFile.Type.CONFIGURATION)
.build();
}
}
| 1,422 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/it/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/it/java/software/amazon/awssdk/auth/credentials/InstanceProfileCredentialsProviderIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
/**
* Unit tests for the InstanceProfileCredentialsProvider.
*/
public class InstanceProfileCredentialsProviderIntegrationTest {
private EC2MetadataServiceMock mockServer;
/** Starts up the mock EC2 Instance Metadata Service. */
@Before
public void setUp() throws Exception {
mockServer = new EC2MetadataServiceMock("/latest/meta-data/iam/security-credentials/");
mockServer.start();
}
/** Shuts down the mock EC2 Instance Metadata Service. */
@After
public void tearDown() throws Exception {
mockServer.stop();
Thread.sleep(1000);
}
/** Tests that we correctly handle the metadata service returning credentials. */
@Test
public void testSessionCredentials() throws Exception {
mockServer.setResponseFileName("sessionResponse");
mockServer.setAvailableSecurityCredentials("aws-dr-tools-test");
InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.create();
AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials();
assertEquals("ACCESS_KEY_ID", credentials.accessKeyId());
assertEquals("SECRET_ACCESS_KEY", credentials.secretAccessKey());
assertEquals("TOKEN_TOKEN_TOKEN", credentials.sessionToken());
}
/**
* Tests that we correctly handle the metadata service returning credentials
* when multiple instance profiles are available.
*/
@Test
public void testSessionCredentials_MultipleInstanceProfiles() throws Exception {
mockServer.setResponseFileName("sessionResponse");
mockServer.setAvailableSecurityCredentials("test-credentials");
AwsSessionCredentials credentials;
try (InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.create()) {
credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials();
}
assertEquals("ACCESS_KEY_ID", credentials.accessKeyId());
assertEquals("SECRET_ACCESS_KEY", credentials.secretAccessKey());
assertEquals("TOKEN_TOKEN_TOKEN", credentials.sessionToken());
}
/**
* Tests that we correctly handle when no instance profiles are available
* through the metadata service.
*/
@Test
public void testNoInstanceProfiles() throws Exception {
mockServer.setResponseFileName("sessionResponse");
mockServer.setAvailableSecurityCredentials("");
try (InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.create()) {
try {
credentialsProvider.resolveCredentials();
fail("Expected an SdkClientException, but wasn't thrown");
} catch (SdkClientException ace) {
assertNotNull(ace.getMessage());
}
}
}
@Test(expected = SdkClientException.class)
public void ec2MetadataDisabled_shouldReturnNull() {
mockServer.setResponseFileName("sessionResponse");
mockServer.setAvailableSecurityCredentials("test-credentials");
try (InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.create()) {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true");
credentialsProvider.resolveCredentials();
} finally {
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property());
}
}
}
| 1,423 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/signer/SdkTokenExecutionAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.signer;
import static software.amazon.awssdk.utils.CompletableFutureUtils.joinLikeSync;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.core.SelectedAuthScheme;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.http.auth.scheme.BearerAuthScheme;
import software.amazon.awssdk.http.auth.signer.BearerHttpSigner;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption;
import software.amazon.awssdk.identity.spi.Identity;
/**
* SdkToken authorizing attributes attached to the execution.
*
* @deprecated Signer execution attributes have been deprecated in favor of signer properties, set on the auth scheme's signer
* options.
*/
@Deprecated
@SdkProtectedApi
public final class SdkTokenExecutionAttribute {
/**
* The token to sign requests using token authorization instead of AWS Credentials.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it.
*/
@Deprecated
public static final ExecutionAttribute<SdkToken> SDK_TOKEN =
ExecutionAttribute.derivedBuilder("SdkToken",
SdkToken.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(SdkTokenExecutionAttribute::sdkTokenReadMapping)
.writeMapping(SdkTokenExecutionAttribute::sdkTokenWriteMapping)
.build();
private SdkTokenExecutionAttribute() {
}
private static SdkToken sdkTokenReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
Identity identity = joinLikeSync(authScheme.identity());
if (!(identity instanceof SdkToken)) {
return null;
}
return (SdkToken) identity;
}
private static <T extends Identity> SelectedAuthScheme<?> sdkTokenWriteMapping(SelectedAuthScheme<T> authScheme,
SdkToken token) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the token so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the credentials.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(token),
BearerHttpSigner.create(),
AuthSchemeOption.builder()
.schemeId(BearerAuthScheme.SCHEME_ID)
.build());
}
return new SelectedAuthScheme<>(CompletableFuture.completedFuture((T) token),
authScheme.signer(),
authScheme.authSchemeOption());
}
}
| 1,424 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/signer/aws/BearerTokenSigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.signer.aws;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.SignerConstant;
import software.amazon.awssdk.auth.signer.params.TokenSignerParams;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.signer.SdkTokenExecutionAttribute;
import software.amazon.awssdk.core.CredentialType;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* A {@link Signer} that will sign a request with Bearer token authorization.
*/
@SdkPublicApi
public final class BearerTokenSigner implements Signer {
private static final String BEARER_LABEL = "Bearer";
public static BearerTokenSigner create() {
return new BearerTokenSigner();
}
@Override
public CredentialType credentialType() {
return CredentialType.TOKEN;
}
/**
* Signs the request by adding an 'Authorization' header containing the string value of the token
* in accordance with RFC 6750, section 2.1.
*
* @param request The request to sign
* @param signerParams Contains the attributes required for signing the request
*
* @return The signed request.
*/
public SdkHttpFullRequest sign(SdkHttpFullRequest request, TokenSignerParams signerParams) {
return doSign(request, signerParams);
}
/**
* Signs the request by adding an 'Authorization' header containing the string value of the token
* in accordance with RFC 6750, section 2.1.
*
* @param request The request to sign
* @param executionAttributes Contains the execution attributes required for signing the request
*
* @return The signed request.
*/
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
SdkToken token = executionAttributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN);
return doSign(request, TokenSignerParams.builder().token(token).build());
}
private SdkHttpFullRequest doSign(SdkHttpFullRequest request, TokenSignerParams signerParams) {
return request.toBuilder()
.putHeader(SignerConstant.AUTHORIZATION, buildAuthorizationHeader(signerParams.token()))
.build();
}
private String buildAuthorizationHeader(SdkToken token) {
return String.format("%s %s", BEARER_LABEL, token.token());
}
}
| 1,425 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/internal/ProfileTokenProviderLoader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.internal;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.token.credentials.ChildProfileTokenProviderFactory;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.internal.util.ClassLoaderHelper;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.profiles.internal.ProfileSection;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.Validate;
/**
* Utility class to load SSO Token Providers.
*/
@SdkInternalApi
public final class ProfileTokenProviderLoader {
private static final String SSO_OIDC_TOKEN_PROVIDER_FACTORY =
"software.amazon.awssdk.services.ssooidc.SsoOidcProfileTokenProviderFactory";
private final Supplier<ProfileFile> profileFileSupplier;
private final String profileName;
private volatile ProfileFile currentProfileFile;
private volatile SdkTokenProvider currentTokenProvider;
private final Lazy<ChildProfileTokenProviderFactory> factory;
public ProfileTokenProviderLoader(Supplier<ProfileFile> profileFile, String profileName) {
this.profileFileSupplier = Validate.paramNotNull(profileFile, "profileFile");
this.profileName = Validate.paramNotNull(profileName, "profileName");
this.factory = new Lazy<>(this::ssoTokenProviderFactory);
}
/**
* Retrieve the token provider for which this profile has been configured, if available.
*/
public Optional<SdkTokenProvider> tokenProvider() {
return Optional.ofNullable(ssoProfileCredentialsProvider());
}
/**
* Create the SSO credentials provider based on the related profile properties.
*/
private SdkTokenProvider ssoProfileCredentialsProvider() {
return () -> ssoProfileCredentialsProvider(profileFileSupplier, profileName).resolveToken();
}
private SdkTokenProvider ssoProfileCredentialsProvider(ProfileFile profileFile, Profile profile) {
String profileSsoSectionName = profileSsoSectionName(profile);
Profile ssoProfile = ssoProfile(profileFile, profileSsoSectionName);
validateRequiredProperties(ssoProfile, ProfileProperty.SSO_REGION, ProfileProperty.SSO_START_URL);
return factory.getValue().create(profileFile, profile);
}
private SdkTokenProvider ssoProfileCredentialsProvider(Supplier<ProfileFile> profileFile, String profileName) {
ProfileFile profileFileInstance = profileFile.get();
if (!Objects.equals(profileFileInstance, currentProfileFile)) {
synchronized (this) {
if (!Objects.equals(profileFileInstance, currentProfileFile)) {
Profile profileInstance = resolveProfile(profileFileInstance, profileName);
currentProfileFile = profileFileInstance;
currentTokenProvider = ssoProfileCredentialsProvider(profileFileInstance, profileInstance);
}
}
}
return currentTokenProvider;
}
private Profile resolveProfile(ProfileFile profileFile, String profileName) {
return profileFile.profile(profileName)
.orElseThrow(() -> {
String errorMessage = String.format("Profile file contained no information for profile '%s': %s",
profileName, profileFile);
return SdkClientException.builder().message(errorMessage).build();
});
}
private String profileSsoSectionName(Profile profile) {
return Optional.ofNullable(profile)
.flatMap(p -> p.property(ProfileSection.SSO_SESSION.getPropertyKeyName()))
.orElseThrow(() -> new IllegalArgumentException(
"Profile " + profileName + " does not have sso_session property"));
}
private Profile ssoProfile(ProfileFile profileFile, String profileSsoSectionName) {
return profileFile.getSection(ProfileSection.SSO_SESSION.getSectionTitle(), profileSsoSectionName)
.orElseThrow(() -> new IllegalArgumentException(
"Sso-session section not found with sso-session title " + profileSsoSectionName));
}
/**
* Require that the provided properties are configured in this profile.
*/
private void validateRequiredProperties(Profile ssoProfile, String... requiredProperties) {
Arrays.stream(requiredProperties)
.forEach(p -> Validate.isTrue(ssoProfile.properties().containsKey(p),
"Property '%s' was not configured for profile '%s'.",
p, profileName));
}
/**
* Load the factory that can be used to create the SSO token provider, assuming it is on the classpath.
*/
private ChildProfileTokenProviderFactory ssoTokenProviderFactory() {
try {
Class<?> ssoOidcTokenProviderFactory = ClassLoaderHelper.loadClass(SSO_OIDC_TOKEN_PROVIDER_FACTORY,
getClass());
return (ChildProfileTokenProviderFactory) ssoOidcTokenProviderFactory.getConstructor().newInstance();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("To use SSO OIDC related properties in the '" + profileName + "' profile, "
+ "the 'ssooidc' service module must be on the class path.", e);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create the '%s" + profileName + "' token provider factory.", e);
}
}
}
| 1,426 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/internal/LazyTokenProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.internal;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
/**
* A wrapper for {@link SdkTokenProvider} that defers creation of the underlying provider until the first time the
* {@link SdkTokenProvider#resolveToken()} method is invoked.
*/
@SdkInternalApi
public class LazyTokenProvider implements SdkTokenProvider, SdkAutoCloseable {
private final Lazy<SdkTokenProvider> delegate;
public LazyTokenProvider(Supplier<SdkTokenProvider> delegateConstructor) {
this.delegate = new Lazy<>(delegateConstructor);
}
public static LazyTokenProvider create(Supplier<SdkTokenProvider> delegateConstructor) {
return new LazyTokenProvider(delegateConstructor);
}
@Override
public SdkToken resolveToken() {
return delegate.getValue().resolveToken();
}
@Override
public void close() {
IoUtils.closeIfCloseable(delegate, null);
}
@Override
public String toString() {
return ToString.builder("LazyTokenProvider")
.add("delegate", delegate)
.build();
}
}
| 1,427 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/SdkTokenProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.credentials;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
import software.amazon.awssdk.identity.spi.TokenIdentity;
/**
* Interface for loading {@link SdkToken} that are used for authentication.
*
*/
@FunctionalInterface
@SdkPublicApi
public interface SdkTokenProvider extends IdentityProvider<TokenIdentity> {
/**
* Returns an {@link SdkToken} that can be used to authorize a request. Each implementation of SdkTokenProvider
* can choose its own strategy for loading token. For example, an implementation might load token from an existing
* key management system, or load new token when token is refreshed.
*
*
* @return AwsToken which the caller can use to authorize an AWS request using token authorization for a request.
*/
SdkToken resolveToken();
@Override
default Class<TokenIdentity> identityType() {
return TokenIdentity.class;
}
@Override
default CompletableFuture<TokenIdentity> resolveIdentity(ResolveIdentityRequest request) {
return CompletableFuture.completedFuture(resolveToken());
}
}
| 1,428 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/SdkTokenProviderFactoryProperties.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.Validate;
@SdkProtectedApi
public class SdkTokenProviderFactoryProperties {
private final String startUrl;
private final String region;
private SdkTokenProviderFactoryProperties(BuilderImpl builder) {
Validate.paramNotNull(builder.startUrl, "startUrl");
Validate.paramNotNull(builder.region, "region");
this.startUrl = builder.startUrl;
this.region = builder.region;
}
public String startUrl() {
return startUrl;
}
public String region() {
return region;
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder startUrl(String startUrl);
Builder region(String region);
SdkTokenProviderFactoryProperties build();
}
private static class BuilderImpl implements Builder {
private String startUrl;
private String region;
@Override
public Builder startUrl(String startUrl) {
this.startUrl = startUrl;
return this;
}
@Override
public Builder region(String region) {
this.region = region;
return this;
}
@Override
public SdkTokenProviderFactoryProperties build() {
return new SdkTokenProviderFactoryProperties(this);
}
}
}
| 1,429 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/ChildProfileTokenProviderFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
/**
* A factory for {@link SdkTokenProvider} that are derived from properties as defined in he given profile.
*
* Currently, this is used to allow a {@link Profile} configured with start_url and sso_region to configure a token
* provider via the 'software.amazon.awssdk.services.ssooidc.internal.SsooidcTokenProviderFactory', assuming ssooidc is on the
* classpath.
*/
@FunctionalInterface
@SdkProtectedApi
public interface ChildProfileTokenProviderFactory {
/**
* Create a token provider for the provided profile.
*
* @param profileFile The ProfileFile from which the Profile was derived.
* @param profile The profile that should be used to load the configuration necessary to create the token provider.
* @return The token provider with the properties derived from the source profile.
*/
SdkTokenProvider create(ProfileFile profileFile, Profile profile);
}
| 1,430 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/StaticTokenProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkTokenProvider} that returns a set implementation of {@link SdkToken}.
*/
@SdkPublicApi
public final class StaticTokenProvider implements SdkTokenProvider {
private final SdkToken token;
private StaticTokenProvider(SdkToken token) {
this.token = Validate.notNull(token, "Token must not be null.");
}
/**
* Create a token provider that always returns the provided static token.
*/
public static StaticTokenProvider create(SdkToken token) {
return new StaticTokenProvider(token);
}
@Override
public SdkToken resolveToken() {
return token;
}
@Override
public String toString() {
return ToString.builder("StaticTokenProvider")
.add("token", token)
.build();
}
}
| 1,431 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/ProfileTokenProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.credentials;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.token.internal.ProfileTokenProviderLoader;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
/**
* Token provider based on AWS configuration profiles. This loads token providers that require {@link ProfileFile} configuration,
* allowing the user to share settings between different tools like the AWS SDK for Java and the AWS CLI.
*
* <p>See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html</p>
*
* @see ProfileFile
*/
@SdkPublicApi
public final class ProfileTokenProvider implements SdkTokenProvider, SdkAutoCloseable {
private final SdkTokenProvider tokenProvider;
private final RuntimeException loadException;
private final String profileName;
/**
* @see #builder()
*/
private ProfileTokenProvider(BuilderImpl builder) {
SdkTokenProvider sdkTokenProvider = null;
RuntimeException thrownException = null;
Supplier<ProfileFile> selectedProfileFile = null;
String selectedProfileName = null;
try {
selectedProfileName = Optional.ofNullable(builder.profileName)
.orElseGet(ProfileFileSystemSetting.AWS_PROFILE::getStringValueOrThrow);
// Load the profiles file
selectedProfileFile = Optional.ofNullable(builder.profileFile)
.orElse(builder.defaultProfileFileLoader);
// Load the profile and token provider
sdkTokenProvider = createTokenProvider(selectedProfileFile, selectedProfileName);
} catch (RuntimeException e) {
// If we couldn't load the provider for some reason, save an exception describing why.
thrownException = e;
}
if (thrownException != null) {
this.loadException = thrownException;
this.tokenProvider = null;
this.profileName = null;
} else {
this.loadException = null;
this.tokenProvider = sdkTokenProvider;
this.profileName = selectedProfileName;
}
}
/**
* Create a {@link ProfileTokenProvider} using the {@link ProfileFile#defaultProfileFile()} and default profile name.
* Use {@link #builder()} for defining a custom {@link ProfileTokenProvider}.
*/
public static ProfileTokenProvider create() {
return builder().build();
}
/**
* Create a {@link ProfileTokenProvider} using the given profile name and {@link ProfileFile#defaultProfileFile()}. Use
* {@link #builder()} for defining a custom {@link ProfileTokenProvider}.
*
* @param profileName the name of the profile to use from the {@link ProfileFile#defaultProfileFile()}
*/
public static ProfileTokenProvider create(String profileName) {
return builder().profileName(profileName).build();
}
/**
* Get a builder for creating a custom {@link ProfileTokenProvider}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
public SdkToken resolveToken() {
if (loadException != null) {
throw loadException;
}
return tokenProvider.resolveToken();
}
@Override
public String toString() {
return ToString.builder("ProfileTokenProvider")
.add("profileName", profileName)
.build();
}
@Override
public void close() {
// The delegate provider may be closeable. In this case, we should clean it up when this token provider is closed.
IoUtils.closeIfCloseable(tokenProvider, null);
}
private SdkTokenProvider createTokenProvider(Supplier<ProfileFile> profileFile, String profileName) {
return new ProfileTokenProviderLoader(profileFile, profileName)
.tokenProvider()
.orElseThrow(() -> {
String errorMessage = String.format("Profile file contained no information for " +
"profile '%s'", profileName);
return SdkClientException.builder().message(errorMessage).build();
});
}
/**
* A builder for creating a custom {@link ProfileTokenProvider}.
*/
public interface Builder {
/**
* Define the profile file that should be used by this token provider. By default, the
* {@link ProfileFile#defaultProfileFile()} is used.
*/
Builder profileFile(Supplier<ProfileFile> profileFile);
/**
* Define the name of the profile that should be used by this token provider. By default, the value in
* {@link ProfileFileSystemSetting#AWS_PROFILE} is used.
*/
Builder profileName(String profileName);
/**
* Create a {@link ProfileTokenProvider} using the configuration applied to this builder.
*/
ProfileTokenProvider build();
}
static final class BuilderImpl implements Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
private Supplier<ProfileFile> defaultProfileFileLoader = ProfileFile::defaultProfileFile;
BuilderImpl() {
}
@Override
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public void setProfileFile(Supplier<ProfileFile> profileFile) {
profileFile(profileFile);
}
@Override
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public void setProfileName(String profileName) {
profileName(profileName);
}
@Override
public ProfileTokenProvider build() {
return new ProfileTokenProvider(this);
}
/**
* Override the default configuration file to be used when the customer does not explicitly set
* profileName(profileName);
* {@link #profileFile(Supplier<ProfileFile>)}. Use of this method is only useful for testing the default behavior.
*/
@SdkTestInternalApi
Builder defaultProfileFileLoader(Supplier<ProfileFile> defaultProfileFileLoader) {
this.defaultProfileFileLoader = defaultProfileFileLoader;
return this;
}
}
}
| 1,432 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/SdkTokenProviderChain.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.credentials;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.TokenUtils;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.TokenIdentity;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An {@link SdkTokenProvider} implementation that chains together multiple token providers.
*
* <p>When a caller first requests token from this provider, it calls all the providers in the chain, in the original order
* specified, until one can provide a token, and then returns that token. If all of the token providers in the
* chain have been called, and none of them can provide token, then this class will throw an exception indicated that no
* token is available.</p>
*
* <p>By default, this class will remember the first token provider in the chain that was able to provide tokens, and
* will continue to use that provider when token is requested in the future, instead of traversing the chain each time.
* This behavior can be controlled through the {@link Builder#reuseLastProviderEnabled(Boolean)} method.</p>
*
* <p>This chain implements {@link AutoCloseable}. When closed, it will call the {@link AutoCloseable#close()} on any token
* providers in the chain that need to be closed.</p>
*/
@SdkPublicApi
public final class SdkTokenProviderChain implements SdkTokenProvider, SdkAutoCloseable {
private static final Logger log = Logger.loggerFor(SdkTokenProviderChain.class);
private final List<IdentityProvider<? extends TokenIdentity>> sdkTokenProviders;
private final boolean reuseLastProviderEnabled;
private volatile IdentityProvider<? extends TokenIdentity> lastUsedProvider;
/**
* @see #builder()
*/
private SdkTokenProviderChain(BuilderImpl builder) {
Validate.notEmpty(builder.tokenProviders, "No token providers were specified.");
this.reuseLastProviderEnabled = builder.reuseLastProviderEnabled;
this.sdkTokenProviders = Collections.unmodifiableList(builder.tokenProviders);
}
/**
* Get a new builder for creating a {@link SdkTokenProviderChain}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create a token provider chain with default configuration that checks the given token providers.
* @param sdkTokenProviders The token providers that should be checked for token, in the order they should
* be checked.
* @return A token provider chain that checks the provided token providers in order.
*/
public static SdkTokenProviderChain of(SdkTokenProvider... sdkTokenProviders) {
return builder().tokenProviders(sdkTokenProviders).build();
}
/**
* Create a token provider chain with default configuration that checks the given token providers.
* @param sdkTokenProviders The token providers that should be checked for token, in the order they should
* be checked.
* @return A token provider chain that checks the provided token providers in order.
*/
public static SdkTokenProviderChain of(IdentityProvider<? extends TokenIdentity>... sdkTokenProviders) {
return builder().tokenProviders(sdkTokenProviders).build();
}
@Override
public SdkToken resolveToken() {
if (reuseLastProviderEnabled && lastUsedProvider != null) {
TokenIdentity tokenIdentity = CompletableFutureUtils.joinLikeSync(lastUsedProvider.resolveIdentity());
return TokenUtils.toSdkToken(tokenIdentity);
}
List<String> exceptionMessages = null;
for (IdentityProvider<? extends TokenIdentity> provider : sdkTokenProviders) {
try {
TokenIdentity token = CompletableFutureUtils.joinLikeSync(provider.resolveIdentity());
log.debug(() -> "Loading token from " + provider);
lastUsedProvider = provider;
return TokenUtils.toSdkToken(token);
} catch (RuntimeException e) {
// Ignore any exceptions and move onto the next provider
String message = provider + ": " + e.getMessage();
log.debug(() -> "Unable to load token from " + message , e);
if (exceptionMessages == null) {
exceptionMessages = new ArrayList<>();
}
exceptionMessages.add(message);
}
}
throw SdkClientException.builder()
.message("Unable to load token from any of the providers in the chain " +
this + " : " + exceptionMessages)
.build();
}
@Override
public void close() {
sdkTokenProviders.forEach(c -> IoUtils.closeIfCloseable(c, null));
}
@Override
public String toString() {
return ToString.builder("SdkTokenProviderChain")
.add("tokenProviders", sdkTokenProviders)
.build();
}
/**
* A builder for a {@link SdkTokenProviderChain} that allows controlling its behavior.
*/
public interface Builder {
/**
* Controls whether the chain should reuse the last successful token provider in the chain. Reusing the last
* successful token provider will typically return token faster than searching through the chain.
*
* <p>
* By default, this is enabled
*/
Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled);
/**
* Configure the token providers that should be checked for token, in the order they should be checked.
*/
Builder tokenProviders(Collection<? extends SdkTokenProvider> tokenProviders);
/**
* Configure the token providers that should be checked for token, in the order they should be checked.
*/
Builder tokenIdentityProviders(Collection<? extends IdentityProvider<? extends TokenIdentity>> tokenProviders);
/**
* Configure the token providers that should be checked for token, in the order they should be checked.
*/
default Builder tokenProviders(SdkTokenProvider... tokenProviders) {
return tokenProviders((IdentityProvider<? extends TokenIdentity>[]) tokenProviders);
}
/**
* Configure the token providers that should be checked for token, in the order they should be checked.
*/
default Builder tokenProviders(IdentityProvider<? extends TokenIdentity>... tokenProviders) {
throw new UnsupportedOperationException();
}
/**
* Add a token provider to the chain, after the token providers that have already been configured.
*/
default Builder addTokenProvider(SdkTokenProvider tokenProvider) {
return addTokenProvider((IdentityProvider<? extends TokenIdentity>) tokenProvider);
}
/**
* Add a token provider to the chain, after the token providers that have already been configured.
*/
default Builder addTokenProvider(IdentityProvider<? extends TokenIdentity> tokenProvider) {
throw new UnsupportedOperationException();
}
SdkTokenProviderChain build();
}
private static final class BuilderImpl implements Builder {
private Boolean reuseLastProviderEnabled = true;
private List<IdentityProvider<? extends TokenIdentity>> tokenProviders = new ArrayList<>();
private BuilderImpl() {
}
@Override
public Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
this.reuseLastProviderEnabled = reuseLastProviderEnabled;
return this;
}
public void setReuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
reuseLastProviderEnabled(reuseLastProviderEnabled);
}
@Override
public Builder tokenProviders(Collection<? extends SdkTokenProvider> tokenProviders) {
this.tokenProviders = new ArrayList<>(tokenProviders);
return this;
}
public void setTokenProviders(Collection<? extends SdkTokenProvider> tokenProviders) {
tokenProviders(tokenProviders);
}
@Override
public Builder tokenIdentityProviders(Collection<? extends IdentityProvider<? extends TokenIdentity>> tokenProviders) {
this.tokenProviders = new ArrayList<>(tokenProviders);
return this;
}
public void setTokenIdentityProviders(Collection<? extends IdentityProvider<? extends TokenIdentity>> tokenProviders) {
tokenIdentityProviders(tokenProviders);
}
public Builder tokenProviders(IdentityProvider<? extends TokenIdentity>... tokenProvider) {
return tokenIdentityProviders(Arrays.asList(tokenProvider));
}
@Override
public Builder addTokenProvider(IdentityProvider<? extends TokenIdentity> tokenProvider) {
this.tokenProviders.add(tokenProvider);
return this;
}
@Override
public SdkTokenProviderChain build() {
return new SdkTokenProviderChain(this);
}
}
}
| 1,433 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/SdkToken.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.TokenIdentity;
/**
* Provides token which is used to securely authorize requests to services that use token based auth, e.g., OAuth.
*
* <p>For more details on OAuth tokens, see:
* <a href="https://oauth.net/2/access-tokens">
* https://oauth.net/2/access-tokens</a></p>
*
* @see SdkTokenProvider
*/
@SdkPublicApi
public interface SdkToken extends TokenIdentity {
}
| 1,434 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/aws/DefaultAwsTokenProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.token.credentials.aws;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.token.credentials.ProfileTokenProvider;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProviderChain;
import software.amazon.awssdk.auth.token.internal.LazyTokenProvider;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
/**
* A token provider chain that looks for providers in this order:
* <ol>
* <li>A profile based provider that can initialize token providers based on profile configurations</li>
* </ol>
*
* @see ProfileTokenProvider
*/
@SdkPublicApi
public final class DefaultAwsTokenProvider implements SdkTokenProvider, SdkAutoCloseable {
private static final DefaultAwsTokenProvider DEFAULT_TOKEN_PROVIDER = new DefaultAwsTokenProvider(builder());
private final LazyTokenProvider providerChain;
private DefaultAwsTokenProvider(Builder builder) {
this.providerChain = createChain(builder);
}
public static DefaultAwsTokenProvider create() {
return DEFAULT_TOKEN_PROVIDER;
}
/**
* Create the default token provider chain using the configuration in the provided builder.
*/
private static LazyTokenProvider createChain(Builder builder) {
return LazyTokenProvider.create(
() -> SdkTokenProviderChain.of(ProfileTokenProvider.builder()
.profileFile(builder.profileFile)
.profileName(builder.profileName)
.build()));
}
/**
* Get a builder for defining a {@link DefaultAwsTokenProvider} with custom configuration.
*/
public static Builder builder() {
return new Builder();
}
@Override
public SdkToken resolveToken() {
return providerChain.resolveToken();
}
@Override
public void close() {
providerChain.close();
}
@Override
public String toString() {
return ToString.builder("DefaultAwsTokenProvider")
.add("providerChain", providerChain)
.build();
}
/**
* Configuration that defines the {@link DefaultAwsTokenProvider}'s behavior.
*/
public static final class Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
/**
* Created with {@link #builder()}.
*/
private Builder() {
}
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
/**
* Create a {@link DefaultAwsTokenProvider} using the configuration defined in this builder.
*/
public DefaultAwsTokenProvider build() {
return new DefaultAwsTokenProvider(this);
}
}
}
| 1,435 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/AwsSignerExecutionAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer;
import static software.amazon.awssdk.utils.CompletableFutureUtils.joinLikeSync;
import java.time.Clock;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.SelectedAuthScheme;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner;
import software.amazon.awssdk.http.auth.aws.signer.RegionSet;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest;
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
import software.amazon.awssdk.http.auth.spi.signer.SignRequest;
import software.amazon.awssdk.http.auth.spi.signer.SignedRequest;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.Identity;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.RegionScope;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* AWS-specific signing attributes attached to the execution. This information is available to {@link ExecutionInterceptor}s and
* {@link Signer}s.
*
* @deprecated Signer execution attributes have been deprecated in favor of signer properties, set on the auth scheme's signer
* option.
*/
@Deprecated
@SdkProtectedApi
public final class AwsSignerExecutionAttribute extends SdkExecutionAttribute {
/**
* The key under which the request credentials are set.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the credential provider via the {@code SdkRequest}'s
* {@code overrideConfiguration.credentialsProvider}. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<AwsCredentials> AWS_CREDENTIALS =
ExecutionAttribute.derivedBuilder("AwsCredentials",
AwsCredentials.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::awsCredentialsReadMapping)
.writeMapping(AwsSignerExecutionAttribute::awsCredentialsWriteMapping)
.build();
/**
* The AWS {@link Region} that is used for signing a request. This is not always same as the region configured on the client
* for global services like IAM.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the signing region via the {@code AuthSchemeProvider} that
* is configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Region> SIGNING_REGION =
ExecutionAttribute.derivedBuilder("SigningRegion",
Region.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signingRegionReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signingRegionWriteMapping)
.build();
/**
* The AWS {@link Region} that is used for signing a request. This is not always same as the region configured on the client
* for global services like IAM.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the signing region scope via the {@code AuthSchemeProvider}
* that is configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<RegionScope> SIGNING_REGION_SCOPE =
ExecutionAttribute.derivedBuilder("SigningRegionScope",
RegionScope.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signingRegionScopeReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signingRegionScopeWriteMapping)
.build();
/**
* The signing name of the service to be using in SigV4 signing
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the signing region name via the {@code AuthSchemeProvider}
* that is configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<String> SERVICE_SIGNING_NAME =
ExecutionAttribute.derivedBuilder("ServiceSigningName",
String.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::serviceSigningNameReadMapping)
.writeMapping(AwsSignerExecutionAttribute::serviceSigningNameWriteMapping)
.build();
/**
* The key to specify whether to use double url encoding during signing.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the double-url-encode setting via the {@code
* AuthSchemeProvider} that is configured on the SDK client builder. If you're using it to call the SDK's signers, you
* should migrate to a subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Boolean> SIGNER_DOUBLE_URL_ENCODE =
ExecutionAttribute.derivedBuilder("DoubleUrlEncode",
Boolean.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signerDoubleUrlEncodeReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signerDoubleUrlEncodeWriteMapping)
.build();
/**
* The key to specify whether to normalize the resource path during signing.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the normalize-path setting via the {@code
* AuthSchemeProvider} that is configured on the SDK client builder. If you're using it to call the SDK's signers, you
* should migrate to a subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Boolean> SIGNER_NORMALIZE_PATH =
ExecutionAttribute.derivedBuilder("NormalizePath",
Boolean.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signerNormalizePathReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signerNormalizePathWriteMapping)
.build();
/**
* An override clock to use during signing.
* @see Aws4SignerParams.Builder#signingClockOverride(Clock)
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the clock setting via the {@code
* AuthSchemeProvider} that is configured on the SDK client builder. If you're using it to call the SDK's signers, you
* should migrate to a subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Clock> SIGNING_CLOCK =
ExecutionAttribute.derivedBuilder("Clock",
Clock.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signingClockReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signingClockWriteMapping)
.build();
/**
* The key to specify the expiration time when pre-signing aws requests.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the expiration via the {@code AuthSchemeProvider} that is
* configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a subtype of
* {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Instant> PRESIGNER_EXPIRATION = new ExecutionAttribute("PresignerExpiration");
private AwsSignerExecutionAttribute() {
}
private static AwsCredentials awsCredentialsReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
Identity identity = joinLikeSync(authScheme.identity());
if (!(identity instanceof AwsCredentialsIdentity)) {
return null;
}
return CredentialUtils.toCredentials((AwsCredentialsIdentity) identity);
}
private static <T extends Identity> SelectedAuthScheme<?> awsCredentialsWriteMapping(SelectedAuthScheme<T> authScheme,
AwsCredentials awsCredentials) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the credentials so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the credentials.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(awsCredentials),
AwsV4HttpSigner.create(),
AuthSchemeOption.builder()
.schemeId(AwsV4AuthScheme.SCHEME_ID)
.build());
}
return new SelectedAuthScheme<>(CompletableFuture.completedFuture((T) awsCredentials),
authScheme.signer(),
authScheme.authSchemeOption());
}
private static Region signingRegionReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
String regionName = authScheme.authSchemeOption().signerProperty(AwsV4HttpSigner.REGION_NAME);
if (regionName == null) {
return null;
}
return Region.of(regionName);
}
private static <T extends Identity> SelectedAuthScheme<?> signingRegionWriteMapping(SelectedAuthScheme<T> authScheme,
Region region) {
String regionString = region == null ? null : region.id();
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the region so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the region.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4HttpSigner.REGION_NAME,
regionString)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption().copy(o -> o.putSignerProperty(AwsV4HttpSigner.REGION_NAME,
regionString)));
}
private static RegionScope signingRegionScopeReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
RegionSet regionSet = authScheme.authSchemeOption().signerProperty(AwsV4aHttpSigner.REGION_SET);
if (regionSet == null || regionSet.asString().isEmpty()) {
return null;
}
return RegionScope.create(regionSet.asString());
}
private static <T extends Identity> SelectedAuthScheme<?> signingRegionScopeWriteMapping(SelectedAuthScheme<T> authScheme,
RegionScope regionScope) {
RegionSet regionSet = regionScope != null ? RegionSet.create(regionScope.id()) : null;
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the region scope so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the region scope.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4aHttpSigner.REGION_SET, regionSet)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption().copy(o -> o.putSignerProperty(AwsV4aHttpSigner.REGION_SET,
regionSet)));
}
private static String serviceSigningNameReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
return authScheme.authSchemeOption().signerProperty(AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME);
}
private static <T extends Identity> SelectedAuthScheme<?> serviceSigningNameWriteMapping(SelectedAuthScheme<T> authScheme,
String signingName) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the signing name so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the signing name.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME,
signingName)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME,
signingName)));
}
private static Boolean signerDoubleUrlEncodeReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
AuthSchemeOption authOption = authScheme.authSchemeOption();
return authOption.signerProperty(AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE);
}
private static <T extends Identity> SelectedAuthScheme<?> signerDoubleUrlEncodeWriteMapping(SelectedAuthScheme<T> authScheme,
Boolean doubleUrlEncode) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting double-url-encode so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than double-url-encode.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE,
doubleUrlEncode)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE,
doubleUrlEncode)));
}
private static Boolean signerNormalizePathReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
AuthSchemeOption authOption = authScheme.authSchemeOption();
return authOption.signerProperty(AwsV4FamilyHttpSigner.NORMALIZE_PATH);
}
private static <T extends Identity> SelectedAuthScheme<?> signerNormalizePathWriteMapping(SelectedAuthScheme<T> authScheme,
Boolean normalizePath) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting normalize-path so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than normalize-path.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.NORMALIZE_PATH,
normalizePath)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.NORMALIZE_PATH,
normalizePath)));
}
private static Clock signingClockReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
return authScheme.authSchemeOption().signerProperty(HttpSigner.SIGNING_CLOCK);
}
private static <T extends Identity> SelectedAuthScheme<?> signingClockWriteMapping(SelectedAuthScheme<T> authScheme,
Clock clock) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting signing clock so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the signing clock.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(HttpSigner.SIGNING_CLOCK, clock)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(HttpSigner.SIGNING_CLOCK, clock)));
}
private static class UnsetIdentity implements Identity {
}
private static class UnsetHttpSigner implements HttpSigner<UnsetIdentity> {
@Override
public SignedRequest sign(SignRequest<? extends UnsetIdentity> request) {
throw new IllegalStateException("A signer was not configured.");
}
@Override
public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends UnsetIdentity> request) {
return CompletableFutureUtils.failedFuture(new IllegalStateException("A signer was not configured."));
}
}
}
| 1,436 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/S3SignerExecutionAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SelectedAuthScheme;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest;
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
import software.amazon.awssdk.http.auth.spi.signer.SignRequest;
import software.amazon.awssdk.http.auth.spi.signer.SignedRequest;
import software.amazon.awssdk.identity.spi.Identity;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* S3-specific signing attributes attached to the execution.
*
* @deprecated Signer execution attributes have been deprecated in favor of signer properties, set on the auth scheme's signer
* option.
*/
@SdkProtectedApi
@Deprecated
public final class S3SignerExecutionAttribute extends SdkExecutionAttribute {
/**
* The key to specify whether to enable chunked encoding or not
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the chunk encoding setting via the {@code AuthSchemeProvider}
* that is configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Boolean> ENABLE_CHUNKED_ENCODING =
ExecutionAttribute.derivedBuilder("ChunkedEncoding",
Boolean.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(S3SignerExecutionAttribute::enableChunkedEncodingReadMapping)
.writeMapping(S3SignerExecutionAttribute::enableChunkedEncodingWriteMapping)
.build();
/**
* The key to specify whether to enable payload signing or not
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the payload signing setting via the {@code
* AuthSchemeProvider} that is configured on the SDK client builder. If you're using it to call the SDK's signers, you
* should migrate to a subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Boolean> ENABLE_PAYLOAD_SIGNING =
ExecutionAttribute.derivedBuilder("PayloadSigning",
Boolean.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(S3SignerExecutionAttribute::enablePayloadSigningReadMapping)
.writeMapping(S3SignerExecutionAttribute::enablePayloadSigningWriteMapping)
.build();
private S3SignerExecutionAttribute() {
}
private static Boolean enableChunkedEncodingReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
AuthSchemeOption authOption = authScheme.authSchemeOption();
return authOption.signerProperty(AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED);
}
private static <T extends Identity> SelectedAuthScheme<?> enableChunkedEncodingWriteMapping(SelectedAuthScheme<T> authScheme,
Boolean enableChunkedEncoding) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting chunked-encoding so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than chunked-encoding.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED,
enableChunkedEncoding)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED,
enableChunkedEncoding)));
}
private static Boolean enablePayloadSigningReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
return authScheme.authSchemeOption().signerProperty(AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED);
}
private static <T extends Identity> SelectedAuthScheme<?> enablePayloadSigningWriteMapping(SelectedAuthScheme<T> authScheme,
Boolean payloadSigningEnabled) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're configuring payload signing so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the payload signing setting.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED,
payloadSigningEnabled)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED,
payloadSigningEnabled))
);
}
private static class UnsetIdentity implements Identity {
}
private static class UnsetHttpSigner implements HttpSigner<UnsetIdentity> {
@Override
public SignedRequest sign(SignRequest<? extends UnsetIdentity> request) {
throw new IllegalStateException("A signer was not configured.");
}
@Override
public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends UnsetIdentity> request) {
return CompletableFutureUtils.failedFuture(new IllegalStateException("A signer was not configured."));
}
}
}
| 1,437 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/SignerLoader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.internal.util.ClassLoaderHelper;
import software.amazon.awssdk.core.signer.Signer;
/**
* Utility class for instantiating signers only if they're available on the class path.
*/
@SdkProtectedApi
public final class SignerLoader {
private static final Map<String, Signer> SIGNERS = new ConcurrentHashMap<>();
private SignerLoader() {
}
public static Signer getSigV4aSigner() {
return get("software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner");
}
public static Signer getS3SigV4aSigner() {
return get("software.amazon.awssdk.authcrt.signer.AwsCrtS3V4aSigner");
}
private static Signer get(String fqcn) {
return SIGNERS.computeIfAbsent(fqcn, SignerLoader::initializeV4aSigner);
}
private static Signer initializeV4aSigner(String fqcn) {
try {
Class<?> signerClass = ClassLoaderHelper.loadClass(fqcn, false, (Class) null);
Method m = signerClass.getDeclaredMethod("create");
Object o = m.invoke(null);
return (Signer) o;
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the " + fqcn + " class."
+ " To invoke a request that requires a SigV4a signer, such as region independent " +
"signing, the 'auth-crt' core module must be on the class path. ", e);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create " + fqcn, e);
}
}
}
| 1,438 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/AwsS3V4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.AbstractAwsS3V4Signer;
/**
* AWS4 signer implementation for AWS S3
*/
@SdkPublicApi
public final class AwsS3V4Signer extends AbstractAwsS3V4Signer {
private AwsS3V4Signer() {
}
public static AwsS3V4Signer create() {
return new AwsS3V4Signer();
}
}
| 1,439 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/EventStreamAws4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.signer.internal.BaseEventStreamAsyncAws4Signer;
@SdkProtectedApi
public final class EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer {
private EventStreamAws4Signer() {
}
public static EventStreamAws4Signer create() {
return new EventStreamAws4Signer();
}
}
| 1,440 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/Aws4UnsignedPayloadSigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer;
import static software.amazon.awssdk.auth.signer.internal.SignerConstant.X_AMZ_CONTENT_SHA256;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.BaseAws4Signer;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Exactly the same as {@link Aws4Signer} except if the request is being sent
* over HTTPS, then it returns the string <code>UNSIGNED-PAYLOAD</code> as the
* content SHA-256 so services that support it can avoid needing to calculate
* the value when authorizing the request.
* <p>
* Payloads are still signed for requests over HTTP to preserve the request
* integrity over a non-secure transport.
*/
@SdkPublicApi
public final class Aws4UnsignedPayloadSigner extends BaseAws4Signer {
public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
private Aws4UnsignedPayloadSigner() {
}
public static Aws4UnsignedPayloadSigner create() {
return new Aws4UnsignedPayloadSigner();
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
request = addContentSha256Header(request);
return super.sign(request, executionAttributes);
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams) {
request = addContentSha256Header(request);
return super.sign(request, signingParams);
}
@Override
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, Aws4SignerParams signerParams,
SdkChecksum contentFlexibleChecksum) {
if ("https".equals(mutableRequest.protocol())) {
return UNSIGNED_PAYLOAD;
}
return super.calculateContentHash(mutableRequest, signerParams, contentFlexibleChecksum);
}
private SdkHttpFullRequest addContentSha256Header(SdkHttpFullRequest request) {
return request.toBuilder().putHeader(X_AMZ_CONTENT_SHA256, "required").build();
}
}
| 1,441 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/AsyncAws4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.internal.Aws4SignerRequestParams;
import software.amazon.awssdk.auth.signer.internal.BaseAws4Signer;
import software.amazon.awssdk.auth.signer.internal.ContentChecksum;
import software.amazon.awssdk.auth.signer.internal.DigestComputingSubscriber;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.AsyncSigner;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* AWS Signature Version 4 signer that can include contents of an asynchronous request body into the signature
* calculation.
*/
@SdkPublicApi
public final class AsyncAws4Signer extends BaseAws4Signer implements AsyncSigner {
@Override
public CompletableFuture<SdkHttpFullRequest> sign(SdkHttpFullRequest request,
AsyncRequestBody requestBody,
ExecutionAttributes executionAttributes) {
Aws4SignerParams signingParams = extractSignerParams(Aws4SignerParams.builder(), executionAttributes).build();
return signWithBody(request, requestBody, signingParams);
}
public CompletableFuture<SdkHttpFullRequest> signWithBody(SdkHttpFullRequest request,
AsyncRequestBody requestBody,
Aws4SignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return CompletableFuture.completedFuture(request);
}
SdkChecksum sdkChecksum = createSdkChecksumFromParams(signingParams);
DigestComputingSubscriber bodyDigester = sdkChecksum != null
? DigestComputingSubscriber.forSha256(sdkChecksum)
: DigestComputingSubscriber.forSha256();
requestBody.subscribe(bodyDigester);
CompletableFuture<byte[]> digestBytes = bodyDigester.digestBytes();
CompletableFuture<SdkHttpFullRequest> signedReqFuture = digestBytes.thenApply(bodyHash -> {
String digestHex = BinaryUtils.toHex(bodyHash);
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
SdkHttpFullRequest.Builder builder = doSign(request, requestParams, signingParams,
new ContentChecksum(digestHex, sdkChecksum));
return builder.build();
});
return CompletableFutureUtils.forwardExceptionTo(signedReqFuture, digestBytes);
}
private SdkChecksum createSdkChecksumFromParams(Aws4SignerParams signingParams) {
if (signingParams.checksumParams() != null) {
return SdkChecksum.forAlgorithm(signingParams.checksumParams().algorithm());
}
return null;
}
public static AsyncAws4Signer create() {
return new AsyncAws4Signer();
}
}
| 1,442 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/Aws4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.BaseAws4Signer;
/**
* Signer implementation that signs requests with the AWS4 signing protocol.
*/
@SdkPublicApi
public final class Aws4Signer extends BaseAws4Signer {
private Aws4Signer() {
}
public static Aws4Signer create() {
return new Aws4Signer();
}
}
| 1,443 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/SigningAlgorithm.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
@SdkInternalApi
public enum SigningAlgorithm {
HmacSHA256;
private final ThreadLocal<Mac> macReference;
SigningAlgorithm() {
String algorithmName = this.toString();
macReference = new MacThreadLocal(algorithmName);
}
/**
* Returns the thread local reference for the crypto algorithm
*/
public Mac getMac() {
return macReference.get();
}
private static class MacThreadLocal extends ThreadLocal<Mac> {
private final String algorithmName;
MacThreadLocal(String algorithmName) {
this.algorithmName = algorithmName;
}
@Override
protected Mac initialValue() {
try {
return Mac.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
throw SdkClientException.builder()
.message("Unable to fetch Mac instance for Algorithm "
+ algorithmName + e.getMessage())
.cause(e)
.build();
}
}
}
}
| 1,444 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/BoundedLinkedHashMap.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.util.LinkedHashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* A bounded linked hash map that would remove the eldest entry when the map
* size exceeds a configurable maximum.
*/
@SdkInternalApi
final class BoundedLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private final int maxSize;
BoundedLinkedHashMap(int maxSize) {
this.maxSize = maxSize;
}
/**
* {@inheritDoc}
*
* Returns true if the size of this map exceeds the maximum.
*/
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxSize;
}
/**
* Returns the maximum size of this map beyond which the eldest entry
* will get removed.
*/
int getMaxSize() {
return maxSize;
}
}
| 1,445 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/Aws4SignerRequestParams.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.time.Clock;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.regions.Region;
/**
* Parameters that are used for computing a AWS 4 signature for a request.
*/
@SdkInternalApi
public final class Aws4SignerRequestParams {
private final Clock signingClock;
private final long requestSigningDateTimeMilli;
/**
* The scope of the signature.
*/
private final String scope;
/**
* The AWS region to be used for computing the signature.
*/
private final String regionName;
/**
* The name of the AWS service.
*/
private final String serviceSigningName;
/**
* UTC formatted version of the signing time stamp.
*/
private final String formattedRequestSigningDateTime;
/**
* UTC Formatted Signing date with time stamp stripped.
*/
private final String formattedRequestSigningDate;
/**
* Generates an instance of AWS4signerRequestParams that holds the
* parameters used for computing a AWS 4 signature for a request based on
* the given {@link Aws4SignerParams} for that request.
*/
public Aws4SignerRequestParams(Aws4SignerParams signerParams) {
this.signingClock = resolveSigningClock(signerParams);
this.requestSigningDateTimeMilli = this.signingClock.millis();
this.formattedRequestSigningDate = Aws4SignerUtils.formatDateStamp(requestSigningDateTimeMilli);
this.serviceSigningName = signerParams.signingName();
this.regionName = getRegion(signerParams.signingRegion());
this.scope = generateScope(formattedRequestSigningDate, this.serviceSigningName, regionName);
this.formattedRequestSigningDateTime = Aws4SignerUtils.formatTimestamp(requestSigningDateTimeMilli);
}
/**
* @return The clock to use for signing additional data i.e. events or chunks.
*/
public Clock getSigningClock() {
return signingClock;
}
/**
* Returns the scope of the request signing.
*/
public String getScope() {
return scope;
}
/**
* Returns the formatted date and time of the request signing date in UTC
* zone.
*/
public String getFormattedRequestSigningDateTime() {
return formattedRequestSigningDateTime;
}
/**
* Returns the request signing date time in millis for which the request
* signature needs to be computed.
*/
public long getRequestSigningDateTimeMilli() {
return requestSigningDateTimeMilli;
}
/**
* Returns the AWS region name to be used while computing the signature.
*/
public String getRegionName() {
return regionName;
}
/**
* Returns the AWS Service name to be used while computing the signature.
*/
public String getServiceSigningName() {
return serviceSigningName;
}
/**
* Returns the formatted date in UTC zone of the signing date for the
* request.
*/
public String getFormattedRequestSigningDate() {
return formattedRequestSigningDate;
}
/**
* Returns the signing algorithm used for computing the signature.
*/
public String getSigningAlgorithm() {
return SignerConstant.AWS4_SIGNING_ALGORITHM;
}
private Clock resolveSigningClock(Aws4SignerParams signerParams) {
if (signerParams.signingClockOverride().isPresent()) {
return signerParams.signingClockOverride().get();
}
Clock baseClock = Clock.systemUTC();
return signerParams.timeOffset()
.map(offset -> Clock.offset(baseClock, Duration.ofSeconds(-offset)))
.orElse(baseClock);
}
private String getRegion(Region region) {
return region != null ? region.id() : null;
}
/**
* Returns the scope to be used for the signing.
*/
private String generateScope(String dateStamp, String serviceName, String regionName) {
return dateStamp + "/" + regionName + "/" + serviceName + "/" + SignerConstant.AWS4_TERMINATOR;
}
}
| 1,446 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import static software.amazon.awssdk.auth.signer.Aws4UnsignedPayloadSigner.UNSIGNED_PAYLOAD;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS;
import static software.amazon.awssdk.utils.StringUtils.lowerCase;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.auth.signer.params.SignerChecksumParams;
import software.amazon.awssdk.core.checksums.ChecksumSpecs;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.util.HttpChecksumUtils;
import software.amazon.awssdk.core.signer.Presigner;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
/**
* Abstract base class for the AWS SigV4 signer implementations.
* @param <T> Type of the signing params class that is used for signing the request
* @param <U> Type of the signing params class that is used for pre signing the request
*/
@SdkInternalApi
public abstract class AbstractAws4Signer<T extends Aws4SignerParams, U extends Aws4PresignerParams>
extends AbstractAwsSigner implements Presigner {
public static final String EMPTY_STRING_SHA256_HEX = BinaryUtils.toHex(hash(""));
private static final Logger LOG = Logger.loggerFor(Aws4Signer.class);
private static final int SIGNER_CACHE_MAX_SIZE = 300;
private static final FifoCache<SignerKey> SIGNER_CACHE =
new FifoCache<>(SIGNER_CACHE_MAX_SIZE);
private static final List<String> LIST_OF_HEADERS_TO_IGNORE_IN_LOWER_CASE =
Arrays.asList("connection", "x-amzn-trace-id", "user-agent", "expect");
protected SdkHttpFullRequest.Builder doSign(SdkHttpFullRequest request,
Aws4SignerRequestParams requestParams,
T signingParams) {
SdkHttpFullRequest.Builder mutableRequest = request.toBuilder();
SdkChecksum sdkChecksum = createSdkChecksumFromParams(signingParams, request);
String contentHash = calculateContentHash(mutableRequest, signingParams, sdkChecksum);
return doSign(mutableRequest.build(), requestParams, signingParams,
new ContentChecksum(contentHash, sdkChecksum));
}
protected SdkHttpFullRequest.Builder doSign(SdkHttpFullRequest request,
Aws4SignerRequestParams requestParams,
T signingParams,
ContentChecksum contentChecksum) {
SdkHttpFullRequest.Builder mutableRequest = request.toBuilder();
AwsCredentials sanitizedCredentials = sanitizeCredentials(signingParams.awsCredentials());
if (sanitizedCredentials instanceof AwsSessionCredentials) {
addSessionCredentials(mutableRequest, (AwsSessionCredentials) sanitizedCredentials);
}
addHostHeader(mutableRequest);
addDateHeader(mutableRequest, requestParams.getFormattedRequestSigningDateTime());
mutableRequest.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)
.filter(h -> h.equals("required"))
.ifPresent(h -> mutableRequest.putHeader(
SignerConstant.X_AMZ_CONTENT_SHA256, contentChecksum.contentHash()));
putChecksumHeader(signingParams.checksumParams(), contentChecksum.contentFlexibleChecksum(),
mutableRequest, contentChecksum.contentHash());
CanonicalRequest canonicalRequest = createCanonicalRequest(request,
mutableRequest,
contentChecksum.contentHash(),
signingParams.doubleUrlEncode(),
signingParams.normalizePath());
String canonicalRequestString = canonicalRequest.string();
String stringToSign = createStringToSign(canonicalRequestString, requestParams);
byte[] signingKey = deriveSigningKey(sanitizedCredentials, requestParams);
byte[] signature = computeSignature(stringToSign, signingKey);
mutableRequest.putHeader(SignerConstant.AUTHORIZATION,
buildAuthorizationHeader(signature, sanitizedCredentials, requestParams, canonicalRequest));
processRequestPayload(mutableRequest, signature, signingKey, requestParams, signingParams,
contentChecksum.contentFlexibleChecksum());
return mutableRequest;
}
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
String contentSha256 = calculateContentHashPresign(mutableRequest, signingParams);
CanonicalRequest canonicalRequest = createCanonicalRequest(request,
mutableRequest,
contentSha256,
signingParams.doubleUrlEncode(),
signingParams.normalizePath());
addPreSignInformationToRequest(mutableRequest, canonicalRequest, sanitizedCredentials,
requestParams, expirationInSeconds);
String string = canonicalRequest.string();
String stringToSign = createStringToSign(string, requestParams);
byte[] signingKey = deriveSigningKey(sanitizedCredentials, requestParams);
byte[] signature = computeSignature(stringToSign, signingKey);
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_SIGNATURE, BinaryUtils.toHex(signature));
return mutableRequest;
}
@Override
protected void addSessionCredentials(SdkHttpFullRequest.Builder mutableRequest,
AwsSessionCredentials credentials) {
mutableRequest.putHeader(SignerConstant.X_AMZ_SECURITY_TOKEN, credentials.sessionToken());
}
/**
* Calculate the hash of the request's payload. Subclass could override this
* method to provide different values for "x-amz-content-sha256" header or
* do any other necessary set-ups on the request headers. (e.g. aws-chunked
* uses a pre-defined header value, and needs to change some headers
* relating to content-encoding and content-length.)
*/
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, T signerParams) {
return calculateContentHash(mutableRequest, signerParams, null);
}
/**
* This method overloads calculateContentHash with contentFlexibleChecksum.
* The contentFlexibleChecksum is computed at the same time while hash is calculated for Content.
*/
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, T signerParams,
SdkChecksum contentFlexibleChecksum) {
InputStream payloadStream = getBinaryRequestPayloadStream(mutableRequest.contentStreamProvider());
return BinaryUtils.toHex(hash(payloadStream, contentFlexibleChecksum));
}
protected abstract void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
T signerParams);
protected abstract void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
T signerParams,
SdkChecksum sdkChecksum);
protected abstract String calculateContentHashPresign(SdkHttpFullRequest.Builder mutableRequest, U signerParams);
/**
* 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());
}
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;
}
/**
* Step 1 of the AWS Signature version 4 calculation. Refer to
* http://docs.aws
* .amazon.com/general/latest/gr/sigv4-create-canonical-request.html to
* generate the canonical request.
*/
private CanonicalRequest createCanonicalRequest(SdkHttpFullRequest request,
SdkHttpFullRequest.Builder requestBuilder,
String contentSha256,
boolean doubleUrlEncode,
boolean normalizePath) {
return new CanonicalRequest(request, requestBuilder, contentSha256, doubleUrlEncode, normalizePath);
}
/**
* Step 2 of the AWS Signature version 4 calculation. Refer to
* http://docs.aws
* .amazon.com/general/latest/gr/sigv4-create-string-to-sign.html.
*/
private String createStringToSign(String canonicalRequest,
Aws4SignerRequestParams requestParams) {
LOG.debug(() -> "AWS4 Canonical Request: " + canonicalRequest);
String requestHash = BinaryUtils.toHex(hash(canonicalRequest));
String stringToSign = requestParams.getSigningAlgorithm() +
SignerConstant.LINE_SEPARATOR +
requestParams.getFormattedRequestSigningDateTime() +
SignerConstant.LINE_SEPARATOR +
requestParams.getScope() +
SignerConstant.LINE_SEPARATOR +
requestHash;
LOG.debug(() -> "AWS4 String to sign: " + stringToSign);
return stringToSign;
}
private String createSigningCacheKeyName(AwsCredentials credentials,
String regionName,
String serviceName) {
return credentials.secretAccessKey() + "-" + regionName + "-" + serviceName;
}
/**
* 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
*/
private byte[] computeSignature(String stringToSign, byte[] signingKey) {
return sign(stringToSign.getBytes(StandardCharsets.UTF_8), signingKey,
SigningAlgorithm.HmacSHA256);
}
/**
* Creates the authorization header to be included in the request.
*/
private String buildAuthorizationHeader(byte[] signature,
AwsCredentials credentials,
Aws4SignerRequestParams signerParams,
CanonicalRequest canonicalRequest) {
String accessKeyId = credentials.accessKeyId();
String scope = signerParams.getScope();
StringBuilder stringBuilder = canonicalRequest.signedHeaderStringBuilder();
String signatureHex = BinaryUtils.toHex(signature);
return SignerConstant.AWS4_SIGNING_ALGORITHM
+ " Credential="
+ accessKeyId
+ "/"
+ scope
+ ", SignedHeaders="
+ stringBuilder
+ ", Signature="
+ signatureHex;
}
/**
* Includes all the signing headers as request parameters for pre-signing.
*/
private void addPreSignInformationToRequest(SdkHttpFullRequest.Builder mutableRequest,
CanonicalRequest canonicalRequest,
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, canonicalRequest.signedHeaderString());
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_EXPIRES, Long.toString(expirationInSeconds));
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_CREDENTIAL, signingCredentials);
}
/**
* Tests a char to see if is it whitespace.
* This method considers the same characters to be white
* space as the Pattern class does when matching \s
*
* @param ch the character to be tested
* @return true if the character is white space, false otherwise.
*/
private static boolean isWhiteSpace(char ch) {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\u000b' || ch == '\r' || ch == '\f';
}
private void addHostHeader(SdkHttpFullRequest.Builder mutableRequest) {
// AWS4 requires that we sign the Host header so we
// have to have it in the request by the time we sign.
StringBuilder hostHeaderBuilder = new StringBuilder(mutableRequest.host());
if (!SdkHttpUtils.isUsingStandardPort(mutableRequest.protocol(), mutableRequest.port())) {
hostHeaderBuilder.append(":").append(mutableRequest.port());
}
mutableRequest.putHeader(SignerConstant.HOST, hostHeaderBuilder.toString());
}
private void addDateHeader(SdkHttpFullRequest.Builder mutableRequest, String dateTime) {
mutableRequest.putHeader(SignerConstant.X_AMZ_DATE, dateTime);
}
/**
* Generates an expiration time for the presigned url. If user has specified
* an expiration time, check if it is in the given limit.
*/
private long getSignatureDurationInSeconds(Aws4SignerRequestParams requestParams,
U signingParams) {
long expirationInSeconds = signingParams.expirationTime()
.map(t -> t.getEpochSecond() -
(requestParams.getRequestSigningDateTimeMilli() / 1000))
.orElse(SignerConstant.PRESIGN_URL_MAX_EXPIRATION_SECONDS);
if (expirationInSeconds > SignerConstant.PRESIGN_URL_MAX_EXPIRATION_SECONDS) {
throw SdkClientException.builder()
.message("Requests that are pre-signed by SigV4 algorithm are valid for at most 7" +
" days. The expiration date set on the current request [" +
Aws4SignerUtils.formatTimestamp(expirationInSeconds * 1000L) + "] +" +
" has exceeded this limit.")
.build();
}
return expirationInSeconds;
}
/**
* 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(StandardCharsets.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);
}
protected <B extends Aws4PresignerParams.Builder> B extractPresignerParams(B builder,
ExecutionAttributes executionAttributes) {
builder = extractSignerParams(builder, executionAttributes);
builder.expirationTime(executionAttributes.getAttribute(AwsSignerExecutionAttribute.PRESIGNER_EXPIRATION));
return builder;
}
protected <B extends Aws4SignerParams.Builder> B extractSignerParams(B paramsBuilder,
ExecutionAttributes executionAttributes) {
paramsBuilder.awsCredentials(executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS))
.signingName(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME))
.signingRegion(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION))
.timeOffset(executionAttributes.getAttribute(AwsSignerExecutionAttribute.TIME_OFFSET))
.signingClockOverride(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_CLOCK));
Boolean doubleUrlEncode = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE);
if (doubleUrlEncode != null) {
paramsBuilder.doubleUrlEncode(doubleUrlEncode);
}
Boolean normalizePath =
executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH);
if (normalizePath != null) {
paramsBuilder.normalizePath(normalizePath);
}
ChecksumSpecs checksumSpecs = executionAttributes.getAttribute(RESOLVED_CHECKSUM_SPECS);
if (checksumSpecs != null && checksumSpecs.algorithm() != null) {
paramsBuilder.checksumParams(buildSignerChecksumParams(checksumSpecs));
}
return paramsBuilder;
}
private void putChecksumHeader(SignerChecksumParams checksumSigner, SdkChecksum sdkChecksum,
SdkHttpFullRequest.Builder mutableRequest, String contentHashString) {
if (checksumSigner != null && sdkChecksum != null && !UNSIGNED_PAYLOAD.equals(contentHashString)
&& !"STREAMING-UNSIGNED-PAYLOAD-TRAILER".equals(contentHashString)) {
if (HttpChecksumUtils.isHttpChecksumPresent(mutableRequest.build(),
ChecksumSpecs.builder()
.headerName(checksumSigner.checksumHeaderName()).build())) {
LOG.debug(() -> "Checksum already added in header ");
return;
}
String headerChecksum = checksumSigner.checksumHeaderName();
if (StringUtils.isNotBlank(headerChecksum)) {
mutableRequest.putHeader(headerChecksum,
BinaryUtils.toBase64(sdkChecksum.getChecksumBytes()));
}
}
}
private SignerChecksumParams buildSignerChecksumParams(ChecksumSpecs checksumSpecs) {
return SignerChecksumParams.builder().algorithm(checksumSpecs.algorithm())
.isStreamingRequest(checksumSpecs.isRequestStreaming())
.checksumHeaderName(checksumSpecs.headerName())
.build();
}
private SdkChecksum createSdkChecksumFromParams(T signingParams, SdkHttpFullRequest request) {
SignerChecksumParams signerChecksumParams = signingParams.checksumParams();
boolean isValidChecksumHeader =
signerChecksumParams != null && StringUtils.isNotBlank(signerChecksumParams.checksumHeaderName());
if (isValidChecksumHeader
&& !HttpChecksumUtils.isHttpChecksumPresent(
request,
ChecksumSpecs.builder().headerName(signerChecksumParams.checksumHeaderName()).build())) {
return SdkChecksum.forAlgorithm(signerChecksumParams.algorithm());
}
return null;
}
static final class CanonicalRequest {
private final SdkHttpFullRequest request;
private final SdkHttpFullRequest.Builder requestBuilder;
private final String contentSha256;
private final boolean doubleUrlEncode;
private final boolean normalizePath;
private String canonicalRequestString;
private StringBuilder signedHeaderStringBuilder;
private List<Pair<String, List<String>>> canonicalHeaders;
private String signedHeaderString;
CanonicalRequest(SdkHttpFullRequest request,
SdkHttpFullRequest.Builder requestBuilder,
String contentSha256,
boolean doubleUrlEncode,
boolean normalizePath) {
this.request = request;
this.requestBuilder = requestBuilder;
this.contentSha256 = contentSha256;
this.doubleUrlEncode = doubleUrlEncode;
this.normalizePath = normalizePath;
}
public String string() {
if (canonicalRequestString == null) {
StringBuilder canonicalRequest = new StringBuilder(512);
canonicalRequest.append(requestBuilder.method().toString())
.append(SignerConstant.LINE_SEPARATOR);
addCanonicalizedResourcePath(canonicalRequest,
request,
doubleUrlEncode,
normalizePath);
canonicalRequest.append(SignerConstant.LINE_SEPARATOR);
addCanonicalizedQueryString(canonicalRequest, requestBuilder);
canonicalRequest.append(SignerConstant.LINE_SEPARATOR);
addCanonicalizedHeaderString(canonicalRequest, canonicalHeaders());
canonicalRequest.append(SignerConstant.LINE_SEPARATOR)
.append(signedHeaderStringBuilder())
.append(SignerConstant.LINE_SEPARATOR)
.append(contentSha256);
this.canonicalRequestString = canonicalRequest.toString();
}
return canonicalRequestString;
}
private void addCanonicalizedResourcePath(StringBuilder result,
SdkHttpRequest request,
boolean urlEncode,
boolean normalizePath) {
String path = normalizePath ? request.getUri().normalize().getRawPath()
: request.encodedPath();
if (StringUtils.isEmpty(path)) {
result.append("/");
return;
}
if (urlEncode) {
path = SdkHttpUtils.urlEncodeIgnoreSlashes(path);
}
if (!path.startsWith("/")) {
result.append("/");
}
result.append(path);
// Normalization can leave a trailing slash at the end of the resource path,
// even if the input path doesn't end with one. Example input: /foo/bar/.
// Remove the trailing slash if the input path doesn't end with one.
boolean trimTrailingSlash = normalizePath &&
path.length() > 1 &&
!request.encodedPath().endsWith("/") &&
result.charAt(result.length() - 1) == '/';
if (trimTrailingSlash) {
result.setLength(result.length() - 1);
}
}
/**
* Examines the specified query string parameters and returns a
* canonicalized form.
* <p>
* The canonicalized query string is formed by first sorting all the query
* string parameters, then URI encoding both the key and value and then
* joining them, in order, separating key value pairs with an '&'.
*
* @return A canonicalized form for the specified query string parameters.
*/
private void addCanonicalizedQueryString(StringBuilder result, SdkHttpRequest.Builder httpRequest) {
SortedMap<String, List<String>> sorted = new TreeMap<>();
/**
* Signing protocol expects the param values also to be sorted after url
* encoding in addition to sorted parameter names.
*/
httpRequest.forEachRawQueryParameter((key, values) -> {
if (StringUtils.isEmpty(key)) {
// Do not sign empty keys.
return;
}
String encodedParamName = SdkHttpUtils.urlEncode(key);
List<String> encodedValues = new ArrayList<>(values.size());
for (String value : values) {
String encodedValue = SdkHttpUtils.urlEncode(value);
// Null values should be treated as empty for the purposes of signing, not missing.
// For example "?foo=" instead of "?foo".
String signatureFormattedEncodedValue = encodedValue == null ? "" : encodedValue;
encodedValues.add(signatureFormattedEncodedValue);
}
Collections.sort(encodedValues);
sorted.put(encodedParamName, encodedValues);
});
SdkHttpUtils.flattenQueryParameters(result, sorted);
}
public StringBuilder signedHeaderStringBuilder() {
if (signedHeaderStringBuilder == null) {
signedHeaderStringBuilder = new StringBuilder();
addSignedHeaders(signedHeaderStringBuilder, canonicalHeaders());
}
return signedHeaderStringBuilder;
}
public String signedHeaderString() {
if (signedHeaderString == null) {
this.signedHeaderString = signedHeaderStringBuilder().toString();
}
return signedHeaderString;
}
private List<Pair<String, List<String>>> canonicalHeaders() {
if (canonicalHeaders == null) {
canonicalHeaders = canonicalizeSigningHeaders(requestBuilder);
}
return canonicalHeaders;
}
private void addCanonicalizedHeaderString(StringBuilder result, List<Pair<String, List<String>>> canonicalizedHeaders) {
canonicalizedHeaders.forEach(header -> {
result.append(header.left());
result.append(":");
for (String headerValue : header.right()) {
addAndTrim(result, headerValue);
result.append(",");
}
result.setLength(result.length() - 1);
result.append("\n");
});
}
private List<Pair<String, List<String>>> canonicalizeSigningHeaders(SdkHttpFullRequest.Builder headers) {
List<Pair<String, List<String>>> result = new ArrayList<>(headers.numHeaders());
headers.forEachHeader((key, value) -> {
String lowerCaseHeader = lowerCase(key);
if (!LIST_OF_HEADERS_TO_IGNORE_IN_LOWER_CASE.contains(lowerCaseHeader)) {
result.add(Pair.of(lowerCaseHeader, value));
}
});
result.sort(Comparator.comparing(Pair::left));
return result;
}
/**
* "The addAndTrim function removes excess white space before and after values,
* and converts sequential spaces to a single space."
* <p>
* https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
* <p>
* The collapse-whitespace logic is equivalent to:
* <pre>
* value.replaceAll("\\s+", " ")
* </pre>
* but does not create a Pattern object that needs to compile the match
* string; it also prevents us from having to make a Matcher object as well.
*/
private void addAndTrim(StringBuilder result, String value) {
int lengthBefore = result.length();
boolean isStart = true;
boolean previousIsWhiteSpace = false;
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (isWhiteSpace(ch)) {
if (previousIsWhiteSpace || isStart) {
continue;
}
result.append(' ');
previousIsWhiteSpace = true;
} else {
result.append(ch);
isStart = false;
previousIsWhiteSpace = false;
}
}
if (lengthBefore == result.length()) {
return;
}
int lastNonWhitespaceChar = result.length() - 1;
while (isWhiteSpace(result.charAt(lastNonWhitespaceChar))) {
--lastNonWhitespaceChar;
}
result.setLength(lastNonWhitespaceChar + 1);
}
private void addSignedHeaders(StringBuilder result, List<Pair<String, List<String>>> canonicalizedHeaders) {
for (Pair<String, List<String>> header : canonicalizedHeaders) {
result.append(header.left()).append(';');
}
if (!canonicalizedHeaders.isEmpty()) {
result.setLength(result.length() - 1);
}
}
}
}
| 1,447 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/FifoCache.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* A bounded cache that has a FIFO eviction policy when the cache is full.
*
* @param <T>
* value type
*/
@ThreadSafe
@SdkInternalApi
public final class FifoCache<T> {
private final BoundedLinkedHashMap<String, T> map;
private final ReadLock rlock;
private final WriteLock wlock;
/**
* @param maxSize
* the maximum number of entries of the cache
*/
public FifoCache(final int maxSize) {
if (maxSize < 1) {
throw new IllegalArgumentException("maxSize " + maxSize
+ " must be at least 1");
}
map = new BoundedLinkedHashMap<>(maxSize);
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
rlock = lock.readLock();
wlock = lock.writeLock();
}
/**
* Adds an entry to the cache, evicting the earliest entry if necessary.
*/
public T add(String key, T value) {
wlock.lock();
try {
return map.put(key, value);
} finally {
wlock.unlock();
}
}
/** Returns the value of the given key; or null of no such entry exists. */
public T get(String key) {
rlock.lock();
try {
return map.get(key);
} finally {
rlock.unlock();
}
}
/**
* Returns the current size of the cache.
*/
public int size() {
rlock.lock();
try {
return map.size();
} finally {
rlock.unlock();
}
}
/**
* Returns the maximum size of the cache.
*/
public int getMaxSize() {
return map.getMaxSize();
}
@Override
public String toString() {
rlock.lock();
try {
return map.toString();
} finally {
rlock.unlock();
}
}
}
| 1,448 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAwsSigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.io.SdkDigestInputStream;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.StringUtils;
/**
* Abstract base class for AWS signing protocol implementations. Provides
* utilities commonly needed by signing protocols such as computing
* canonicalized host names, query string parameters, etc.
* <p>
* Not intended to be sub-classed by developers.
*/
@SdkInternalApi
public abstract class AbstractAwsSigner implements Signer {
private static final ThreadLocal<MessageDigest> SHA256_MESSAGE_DIGEST;
static {
SHA256_MESSAGE_DIGEST = ThreadLocal.withInitial(() -> {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw SdkClientException.builder()
.message("Unable to get SHA256 Function" + e.getMessage())
.cause(e)
.build();
}
});
}
private static byte[] doHash(String text) throws SdkClientException {
try {
MessageDigest md = getMessageDigestInstance();
md.update(text.getBytes(StandardCharsets.UTF_8));
return md.digest();
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to compute hash while signing request: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Returns the re-usable thread local version of MessageDigest.
*/
private static MessageDigest getMessageDigestInstance() {
MessageDigest messageDigest = SHA256_MESSAGE_DIGEST.get();
messageDigest.reset();
return messageDigest;
}
/**
* Computes an RFC 2104-compliant HMAC signature and returns the result as a
* Base64 encoded string.
*/
protected String signAndBase64Encode(String data, String key,
SigningAlgorithm algorithm) throws SdkClientException {
return signAndBase64Encode(data.getBytes(StandardCharsets.UTF_8), key, algorithm);
}
/**
* Computes an RFC 2104-compliant HMAC signature for an array of bytes and
* returns the result as a Base64 encoded string.
*/
private String signAndBase64Encode(byte[] data, String key,
SigningAlgorithm algorithm) throws SdkClientException {
try {
byte[] signature = sign(data, key.getBytes(StandardCharsets.UTF_8), algorithm);
return BinaryUtils.toBase64(signature);
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
protected byte[] signWithMac(String stringData, Mac mac) {
try {
return mac.doFinal(stringData.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
protected byte[] sign(String stringData, byte[] key,
SigningAlgorithm algorithm) throws SdkClientException {
try {
byte[] data = stringData.getBytes(StandardCharsets.UTF_8);
return sign(data, key, algorithm);
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
protected byte[] sign(byte[] data, byte[] key, SigningAlgorithm algorithm) throws SdkClientException {
try {
Mac mac = algorithm.getMac();
mac.init(new SecretKeySpec(key, algorithm.toString()));
return mac.doFinal(data);
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Hashes the string contents (assumed to be UTF-8) using the SHA-256
* algorithm.
*
* @param text The string to hash.
* @return The hashed bytes from the specified string.
* @throws SdkClientException If the hash cannot be computed.
*/
static byte[] hash(String text) throws SdkClientException {
return AbstractAwsSigner.doHash(text);
}
byte[] hash(InputStream input, SdkChecksum sdkChecksum) throws SdkClientException {
try {
MessageDigest md = getMessageDigestInstance();
@SuppressWarnings("resource")
DigestInputStream digestInputStream = new SdkDigestInputStream(
input, md, sdkChecksum);
byte[] buffer = new byte[1024];
while (digestInputStream.read(buffer) > -1) {
;
}
return digestInputStream.getMessageDigest().digest();
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to compute hash while signing request: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Hashes the binary data using the SHA-256 algorithm.
*
* @param data The binary data to hash.
* @param sdkChecksum Checksum Instance which gets updated as data is read while hashing.
* @return The hashed bytes from the specified data.
* @throws SdkClientException If the hash cannot be computed.
*/
byte[] hash(byte[] data, SdkChecksum sdkChecksum) throws SdkClientException {
try {
MessageDigest md = getMessageDigestInstance();
md.update(data);
if (sdkChecksum != null) {
sdkChecksum.update(data);
}
return md.digest();
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to compute hash while signing request: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Hashes the binary data using the SHA-256 algorithm.
*
* @param data The binary data to hash.
* @return The hashed bytes from the specified data.
* @throws SdkClientException If the hash cannot be computed.
*/
byte[] hash(byte[] data) throws SdkClientException {
return hash(data, null);
}
protected InputStream getBinaryRequestPayloadStream(ContentStreamProvider streamProvider) {
try {
if (streamProvider == null) {
return new ByteArrayInputStream(new byte[0]);
}
return streamProvider.newStream();
} catch (SdkClientException e) {
throw e;
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to read request payload to sign request: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* 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);
}
/**
* Adds session credentials to the request given.
*
* @param mutableRequest The request to add session credentials information to
* @param credentials The session credentials to add to the request
*/
protected abstract void addSessionCredentials(SdkHttpFullRequest.Builder mutableRequest,
AwsSessionCredentials credentials);
}
| 1,449 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/DigestComputingSubscriber.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.exception.SdkClientException;
@SdkInternalApi
public final class DigestComputingSubscriber implements Subscriber<ByteBuffer> {
private final CompletableFuture<byte[]> digestBytes = new CompletableFuture<>();
private final MessageDigest messageDigest;
private volatile boolean canceled = false;
private volatile Subscription subscription;
private final SdkChecksum sdkChecksum;
public DigestComputingSubscriber(MessageDigest messageDigest, SdkChecksum sdkChecksum) {
this.messageDigest = messageDigest;
this.sdkChecksum = sdkChecksum;
digestBytes.whenComplete((r, t) -> {
if (t instanceof CancellationException) {
synchronized (DigestComputingSubscriber.this) {
canceled = true;
if (subscription != null) {
subscription.cancel();
}
}
}
});
}
@Override
public void onSubscribe(Subscription subscription) {
synchronized (this) {
if (!canceled) {
this.subscription = subscription;
subscription.request(Long.MAX_VALUE);
} else {
subscription.cancel();
}
}
}
@Override
public void onNext(ByteBuffer byteBuffer) {
if (!canceled) {
if (this.sdkChecksum != null) {
// check using flip
ByteBuffer duplicate = byteBuffer.duplicate();
sdkChecksum.update(duplicate);
}
messageDigest.update(byteBuffer);
}
}
@Override
public void onError(Throwable throwable) {
digestBytes.completeExceptionally(throwable);
}
@Override
public void onComplete() {
digestBytes.complete(messageDigest.digest());
}
public CompletableFuture<byte[]> digestBytes() {
return digestBytes;
}
public static DigestComputingSubscriber forSha256() {
try {
return new DigestComputingSubscriber(MessageDigest.getInstance("SHA-256"), null);
} catch (NoSuchAlgorithmException e) {
throw SdkClientException.create("Unable to create SHA-256 computing subscriber", e);
}
}
public static DigestComputingSubscriber forSha256(SdkChecksum sdkChecksum) {
try {
return new DigestComputingSubscriber(MessageDigest.getInstance("SHA-256"), sdkChecksum);
} catch (NoSuchAlgorithmException e) {
throw SdkClientException.create("Unable to create SHA-256 computing subscriber", e);
}
}
}
| 1,450 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/SignerKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.time.Instant;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.DateUtils;
/**
* Holds the signing key and the number of days since epoch for the date for
* which the signing key was generated.
*/
@Immutable
@SdkInternalApi
public final class SignerKey {
private final long daysSinceEpoch;
private final byte[] signingKey;
public SignerKey(Instant date, byte[] signingKey) {
if (date == null) {
throw new IllegalArgumentException(
"Not able to cache signing key. Signing date to be is null");
}
if (signingKey == null) {
throw new IllegalArgumentException(
"Not able to cache signing key. Signing Key to be cached are null");
}
this.daysSinceEpoch = DateUtils.numberOfDaysSinceEpoch(date.toEpochMilli());
this.signingKey = signingKey.clone();
}
public boolean isValidForDate(Instant other) {
return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli());
}
/**
* Returns a copy of the signing key.
*/
public byte[] getSigningKey() {
return signingKey.clone();
}
}
| 1,451 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/Aws4SignerUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.http.Header;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Utility methods that is used by the different AWS Signer implementations.
* This class is strictly internal and is subjected to change.
*/
@SdkInternalApi
public final class Aws4SignerUtils {
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter
.ofPattern("yyyyMMdd").withZone(ZoneId.of("UTC"));
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter
.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneId.of("UTC"));
private Aws4SignerUtils() {
}
/**
* Returns a string representation of the given date time in yyyyMMdd
* format. The date returned is in the UTC zone.
*
* For example, given a time "1416863450581", this method returns "20141124"
*/
public static String formatDateStamp(long timeMilli) {
return DATE_FORMATTER.format(Instant.ofEpochMilli(timeMilli));
}
public static String formatDateStamp(Instant instant) {
return DATE_FORMATTER.format(instant);
}
/**
* Returns a string representation of the given date time in
* yyyyMMdd'T'HHmmss'Z' format. The date returned is in the UTC zone.
*
* For example, given a time "1416863450581", this method returns
* "20141124T211050Z"
*/
public static String formatTimestamp(long timeMilli) {
return TIME_FORMATTER.format(Instant.ofEpochMilli(timeMilli));
}
public static String formatTimestamp(Instant instant) {
return TIME_FORMATTER.format(instant);
}
/**
* Calculates the content length of a request. If the content-length isn't in the header,
* the method reads the whole input stream to get the length.
*/
public static long calculateRequestContentLength(SdkHttpFullRequest.Builder mutableRequest) {
String contentLength = mutableRequest.firstMatchingHeader(Header.CONTENT_LENGTH)
.orElse(null);
long originalContentLength;
if (contentLength != null) {
originalContentLength = Long.parseLong(contentLength);
} else {
try {
originalContentLength = getContentLength(mutableRequest.contentStreamProvider().newStream());
} catch (IOException e) {
throw SdkClientException.builder()
.message("Cannot get the content-length of the request content.")
.cause(e)
.build();
}
}
return originalContentLength;
}
/**
* Read a stream to get the length.
*/
private static long getContentLength(InputStream content) throws IOException {
long contentLength = 0;
byte[] tmp = new byte[4096];
int read;
while ((read = content.read(tmp)) != -1) {
contentLength += read;
}
return contentLength;
}
}
| 1,452 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/BaseEventStreamAsyncAws4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import static software.amazon.awssdk.auth.signer.internal.SignerConstant.X_AMZ_CONTENT_SHA256;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.eventstream.HeaderValue;
import software.amazon.eventstream.Message;
@SdkInternalApi
public abstract class BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer {
//Constants for event stream headers
public static final String EVENT_STREAM_SIGNATURE = ":chunk-signature";
public static final String EVENT_STREAM_DATE = ":date";
private static final Logger LOG = Logger.loggerFor(BaseEventStreamAsyncAws4Signer.class);
private static final String HTTP_CONTENT_SHA_256 = "STREAMING-AWS4-HMAC-SHA256-EVENTS";
private static final String EVENT_STREAM_PAYLOAD = "AWS4-HMAC-SHA256-PAYLOAD";
private static final int PAYLOAD_TRUNCATE_LENGTH = 32;
protected BaseEventStreamAsyncAws4Signer() {
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
request = addContentSha256Header(request);
return super.sign(request, executionAttributes);
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams) {
request = addContentSha256Header(request);
return super.sign(request, signingParams);
}
@Override
protected AsyncRequestBody transformRequestProvider(String headerSignature,
Aws4SignerRequestParams signerRequestParams,
Aws4SignerParams signerParams,
AsyncRequestBody asyncRequestBody) {
/**
* Concat trailing empty frame to publisher
*/
Publisher<ByteBuffer> publisherWithTrailingEmptyFrame = appendEmptyFrame(asyncRequestBody);
/**
* Map publisher with signing function
*/
Publisher<ByteBuffer> publisherWithSignedFrame =
transformRequestBodyPublisher(publisherWithTrailingEmptyFrame, headerSignature,
signerParams.awsCredentials(), signerRequestParams);
AsyncRequestBody transformedRequestBody = AsyncRequestBody.fromPublisher(publisherWithSignedFrame);
return new SigningRequestBodyProvider(transformedRequestBody);
}
/**
* Returns the pre-defined header value and set other necessary headers if
* the request needs to be chunk-encoded. Otherwise calls the superclass
* method which calculates the hash of the whole content for signing.
*/
@Override
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, Aws4SignerParams signerParams,
SdkChecksum contentFlexibleChecksum) {
return HTTP_CONTENT_SHA_256;
}
private static Publisher<ByteBuffer> appendEmptyFrame(Publisher<ByteBuffer> publisher) {
return s -> {
Subscriber<ByteBuffer> adaptedSubscriber = new AsyncSigV4SubscriberAdapter(s);
publisher.subscribe(adaptedSubscriber);
};
}
private Publisher<ByteBuffer> transformRequestBodyPublisher(Publisher<ByteBuffer> publisher, String headerSignature,
AwsCredentials credentials,
Aws4SignerRequestParams signerRequestParams) {
return SdkPublisher.adapt(publisher)
.map(getDataFrameSigner(headerSignature, credentials, signerRequestParams));
}
private Function<ByteBuffer, ByteBuffer> getDataFrameSigner(String headerSignature,
AwsCredentials credentials,
Aws4SignerRequestParams signerRequestParams) {
return new Function<ByteBuffer, ByteBuffer>() {
final Aws4SignerRequestParams requestParams = signerRequestParams;
/**
* Initiate rolling signature with header signature
*/
String priorSignature = headerSignature;
@Override
public ByteBuffer apply(ByteBuffer byteBuffer) {
/**
* Signing Date
*/
Map<String, HeaderValue> nonSignatureHeaders = new HashMap<>();
Instant signingInstant = requestParams.getSigningClock().instant();
nonSignatureHeaders.put(EVENT_STREAM_DATE, HeaderValue.fromTimestamp(signingInstant));
/**
* Derive Signing Key
*/
AwsCredentials sanitizedCredentials = sanitizeCredentials(credentials);
byte[] signingKey = deriveSigningKey(sanitizedCredentials,
signingInstant,
requestParams.getRegionName(),
requestParams.getServiceSigningName());
/**
* Calculate rolling signature
*/
byte[] payload = byteBuffer.array();
byte[] signatureBytes = signEventStream(priorSignature, signingKey, signingInstant, requestParams,
nonSignatureHeaders, payload);
priorSignature = BinaryUtils.toHex(signatureBytes);
/**
* Add signing layer event-stream headers
*/
Map<String, HeaderValue> headers = new HashMap<>(nonSignatureHeaders);
//Signature headers
headers.put(EVENT_STREAM_SIGNATURE, HeaderValue.fromByteArray(signatureBytes));
/**
* Encode signed event to byte
*/
Message signedMessage = new Message(sortHeaders(headers), payload);
if (LOG.isLoggingLevelEnabled("trace")) {
LOG.trace(() -> "Signed message: " + toDebugString(signedMessage, false));
} else {
LOG.debug(() -> "Signed message: " + toDebugString(signedMessage, true));
}
return signedMessage.toByteBuffer();
}
};
}
/**
* Sign event stream with SigV4 signature
*
* @param priorSignature signature of previous frame (Header frame is the 0th frame)
* @param signingKey derived signing key
* @param signingInstant the instant at which this message is being signed
* @param requestParams request parameters
* @param nonSignatureHeaders non-signature headers
* @param payload event stream payload
* @return encoded event with signature
*/
private byte[] signEventStream(
String priorSignature,
byte[] signingKey,
Instant signingInstant,
Aws4SignerRequestParams requestParams,
Map<String, HeaderValue> nonSignatureHeaders,
byte[] payload) {
// String to sign
String stringToSign =
EVENT_STREAM_PAYLOAD +
SignerConstant.LINE_SEPARATOR +
Aws4SignerUtils.formatTimestamp(signingInstant) +
SignerConstant.LINE_SEPARATOR +
computeScope(signingInstant, requestParams) +
SignerConstant.LINE_SEPARATOR +
priorSignature +
SignerConstant.LINE_SEPARATOR +
BinaryUtils.toHex(hash(Message.encodeHeaders(sortHeaders(nonSignatureHeaders).entrySet()))) +
SignerConstant.LINE_SEPARATOR +
BinaryUtils.toHex(hash(payload));
// calculate signature
return sign(stringToSign.getBytes(StandardCharsets.UTF_8), signingKey,
SigningAlgorithm.HmacSHA256);
}
private String computeScope(Instant signingInstant, Aws4SignerRequestParams requestParams) {
return Aws4SignerUtils.formatDateStamp(signingInstant) + "/" +
requestParams.getRegionName() + "/" +
requestParams.getServiceSigningName() + "/" +
SignerConstant.AWS4_TERMINATOR;
}
/**
* Sort headers in alphabetic order, with exception that EVENT_STREAM_SIGNATURE header always at last
*
* @param headers unsorted headers
* @return sorted headers
*/
private TreeMap<String, HeaderValue> sortHeaders(Map<String, HeaderValue> headers) {
TreeMap<String, HeaderValue> sortedHeaders = new TreeMap<>((header1, header2) -> {
// signature header should always be the last header
if (header1.equals(EVENT_STREAM_SIGNATURE)) {
return 1; // put header1 at last
} else if (header2.equals(EVENT_STREAM_SIGNATURE)) {
return -1; // put header2 at last
} else {
return header1.compareTo(header2);
}
});
sortedHeaders.putAll(headers);
return sortedHeaders;
}
private SdkHttpFullRequest addContentSha256Header(SdkHttpFullRequest request) {
return request.toBuilder()
.putHeader(X_AMZ_CONTENT_SHA256, "STREAMING-AWS4-HMAC-SHA256-EVENTS").build();
}
/**
* {@link AsyncRequestBody} implementation that use the provider that signs the events.
* Using anonymous class raises spot bug violation
*/
private static class SigningRequestBodyProvider implements AsyncRequestBody {
private AsyncRequestBody transformedRequestBody;
SigningRequestBodyProvider(AsyncRequestBody transformedRequestBody) {
this.transformedRequestBody = transformedRequestBody;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
transformedRequestBody.subscribe(s);
}
@Override
public Optional<Long> contentLength() {
return transformedRequestBody.contentLength();
}
@Override
public String contentType() {
return transformedRequestBody.contentType();
}
}
static String toDebugString(Message m, boolean truncatePayload) {
StringBuilder sb = new StringBuilder("Message = {headers={");
Map<String, HeaderValue> headers = m.getHeaders();
Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator();
while (headersIter.hasNext()) {
Map.Entry<String, HeaderValue> h = headersIter.next();
sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}");
if (headersIter.hasNext()) {
sb.append(", ");
}
}
sb.append("}, payload=");
byte[] payload = m.getPayload();
byte[] payloadToLog;
// We don't actually need to truncate if the payload length is already within the truncate limit
truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH;
if (truncatePayload) {
// Would be nice if BinaryUtils.toHex() could take an array index range instead so we don't need to copy
payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH);
} else {
payloadToLog = payload;
}
sb.append(BinaryUtils.toHex(payloadToLog));
if (truncatePayload) {
sb.append("...");
}
sb.append("}");
return sb.toString();
}
}
| 1,453 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/BaseAws4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Abstract base class for concrete implementations of Aws4 signers.
*/
@SdkInternalApi
public abstract class BaseAws4Signer extends AbstractAws4Signer<Aws4SignerParams, Aws4PresignerParams> {
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
Aws4SignerParams signingParams = extractSignerParams(Aws4SignerParams.builder(), executionAttributes)
.build();
return sign(request, signingParams);
}
public SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return request;
}
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return doSign(request, requestParams, signingParams).build();
}
@Override
public SdkHttpFullRequest presign(SdkHttpFullRequest requestToSign, ExecutionAttributes executionAttributes) {
Aws4PresignerParams signingParams = extractPresignerParams(Aws4PresignerParams.builder(),
executionAttributes)
.build();
return presign(requestToSign, signingParams);
}
public SdkHttpFullRequest presign(SdkHttpFullRequest request, Aws4PresignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return request;
}
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return doPresign(request, requestParams, signingParams).build();
}
/**
* Subclass could override this method to perform any additional procedure
* on the request payload, with access to the result from signing the
* header. (e.g. Signing the payload by chunk-encoding). The default
* implementation doesn't need to do anything.
*/
@Override
protected void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
Aws4SignerParams signerParams) {
processRequestPayload(mutableRequest, signature, signingKey,
signerRequestParams, signerParams, null);
}
/**
* This method overloads processRequestPayload with sdkChecksum.
* The sdkChecksum if passed, is computed while processing request payload.
*/
@Override
protected void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
Aws4SignerParams signerParams,
SdkChecksum sdkChecksum) {
}
/**
* Calculate the hash of the request's payload. In case of pre-sign, the
* existing code would generate the hash of an empty byte array and returns
* it. This method can be overridden by sub classes to provide different
* values (e.g) For S3 pre-signing, the content hash calculation is
* different from the general implementation.
*/
@Override
protected String calculateContentHashPresign(SdkHttpFullRequest.Builder mutableRequest,
Aws4PresignerParams signerParams) {
return calculateContentHash(mutableRequest, signerParams);
}
}
| 1,454 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAwsS3V4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import static software.amazon.awssdk.auth.signer.internal.Aws4SignerUtils.calculateRequestContentLength;
import static software.amazon.awssdk.auth.signer.internal.SignerConstant.X_AMZ_CONTENT_SHA256;
import java.io.InputStream;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsS3V4ChunkSigner;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.auth.signer.params.AwsS3V4SignerParams;
import software.amazon.awssdk.core.checksums.ChecksumSpecs;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig;
import software.amazon.awssdk.core.internal.util.HttpChecksumUtils;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.StringUtils;
/**
* AWS4 signer implementation for AWS S3
*/
@SdkInternalApi
public abstract class AbstractAwsS3V4Signer extends AbstractAws4Signer<AwsS3V4SignerParams, Aws4PresignerParams> {
public static final String CONTENT_SHA_256_WITH_CHECKSUM = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER";
public static final String STREAMING_UNSIGNED_PAYLOAD_TRAILER = "STREAMING-UNSIGNED-PAYLOAD-TRAILER";
private static final String CONTENT_SHA_256 = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD";
/**
* Sent to S3 in lieu of a payload hash when unsigned payloads are enabled
*/
private static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
private static final String CONTENT_LENGTH = "Content-Length";
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
AwsS3V4SignerParams signingParams = constructAwsS3SignerParams(executionAttributes);
return sign(request, signingParams);
}
/**
* A method to sign the given #request. The parameters required for signing are provided through the modeled
* {@link AbstractAwsS3V4Signer} class.
*
* @param request The request to sign
* @param signingParams Class with the parameters used for signing the request
* @return A signed version of the input request
*/
public SdkHttpFullRequest sign(SdkHttpFullRequest request, AwsS3V4SignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return request;
}
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return doSign(request, requestParams, signingParams).build();
}
private AwsS3V4SignerParams constructAwsS3SignerParams(ExecutionAttributes executionAttributes) {
AwsS3V4SignerParams.Builder signerParams = extractSignerParams(AwsS3V4SignerParams.builder(),
executionAttributes);
Optional.ofNullable(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING))
.ifPresent(signerParams::enableChunkedEncoding);
Optional.ofNullable(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING))
.ifPresent(signerParams::enablePayloadSigning);
return signerParams.build();
}
@Override
public SdkHttpFullRequest presign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
Aws4PresignerParams signingParams =
extractPresignerParams(Aws4PresignerParams.builder(), executionAttributes).build();
return presign(request, signingParams);
}
/**
* A method to pre sign the given #request. The parameters required for pre signing are provided through the modeled
* {@link Aws4PresignerParams} class.
*
* @param request The request to pre-sign
* @param signingParams Class with the parameters used for pre signing the request
* @return A pre signed version of the input request
*/
public SdkHttpFullRequest presign(SdkHttpFullRequest request, Aws4PresignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return request;
}
signingParams = signingParams.copy(b -> b.normalizePath(false));
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return doPresign(request, requestParams, signingParams).build();
}
/**
* If necessary, creates a chunk-encoding wrapper on the request payload.
*/
@Override
protected void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
AwsS3V4SignerParams signerParams) {
processRequestPayload(mutableRequest, signature, signingKey,
signerRequestParams, signerParams, null);
}
/**
* Overloads processRequestPayload with sdkChecksum.
* Flexible Checksum for Payload is calculated if sdkChecksum is passed.
*/
@Override
protected void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
AwsS3V4SignerParams signerParams,
SdkChecksum sdkChecksum) {
if (useChunkEncoding(mutableRequest, signerParams)) {
if (mutableRequest.contentStreamProvider() != null) {
ContentStreamProvider streamProvider = mutableRequest.contentStreamProvider();
String headerForTrailerChecksumLocation = signerParams.checksumParams() != null
? signerParams.checksumParams().checksumHeaderName() : null;
mutableRequest.contentStreamProvider(() -> AbstractAwsS3V4Signer.this.asChunkEncodedStream(
streamProvider.newStream(),
signature,
signingKey,
signerRequestParams,
sdkChecksum,
headerForTrailerChecksumLocation)
);
}
}
}
@Override
protected String calculateContentHashPresign(SdkHttpFullRequest.Builder mutableRequest, Aws4PresignerParams signerParams) {
return UNSIGNED_PAYLOAD;
}
private AwsSignedChunkedEncodingInputStream asChunkEncodedStream(InputStream inputStream,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
SdkChecksum sdkChecksum,
String checksumHeaderForTrailer) {
AwsS3V4ChunkSigner chunkSigner = new AwsS3V4ChunkSigner(signingKey,
signerRequestParams.getFormattedRequestSigningDateTime(),
signerRequestParams.getScope());
return AwsSignedChunkedEncodingInputStream.builder()
.inputStream(inputStream)
.sdkChecksum(sdkChecksum)
.checksumHeaderForTrailer(checksumHeaderForTrailer)
.awsChunkSigner(chunkSigner)
.headerSignature(BinaryUtils.toHex(signature))
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
}
/**
* Returns the pre-defined header value and set other necessary headers if
* the request needs to be chunk-encoded. Otherwise calls the superclass
* method which calculates the hash of the whole content for signing.
*/
@Override
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, AwsS3V4SignerParams signerParams) {
return calculateContentHash(mutableRequest, signerParams, null);
}
/**
* This method overloads calculateContentHash with contentFlexibleChecksum.
* The contentFlexibleChecksum is computed at the same time while hash is calculated for Content.
*/
@Override
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, AwsS3V4SignerParams signerParams,
SdkChecksum contentFlexibleChecksum) {
// x-amz-content-sha256 marked as STREAMING_UNSIGNED_PAYLOAD_TRAILER in interceptors if Flexible checksum is set.
boolean isUnsignedStreamingTrailer = mutableRequest.firstMatchingHeader("x-amz-content-sha256")
.map(STREAMING_UNSIGNED_PAYLOAD_TRAILER::equals)
.orElse(false);
if (!isUnsignedStreamingTrailer) {
// To be consistent with other service clients using sig-v4,
// we just set the header as "required", and AWS4Signer.sign() will be
// notified to pick up the header value returned by this method.
mutableRequest.putHeader(X_AMZ_CONTENT_SHA256, "required");
}
if (isPayloadSigningEnabled(mutableRequest, signerParams)) {
if (useChunkEncoding(mutableRequest, signerParams)) {
long originalContentLength = calculateRequestContentLength(mutableRequest);
mutableRequest.putHeader("x-amz-decoded-content-length", Long.toString(originalContentLength));
boolean isTrailingChecksum = false;
if (signerParams.checksumParams() != null) {
String headerForTrailerChecksumLocation =
signerParams.checksumParams().checksumHeaderName();
if (StringUtils.isNotBlank(headerForTrailerChecksumLocation) &&
!HttpChecksumUtils.isHttpChecksumPresent(
mutableRequest.build(),
ChecksumSpecs.builder().headerName(signerParams.checksumParams().checksumHeaderName()).build())) {
isTrailingChecksum = true;
mutableRequest.putHeader("x-amz-trailer", headerForTrailerChecksumLocation);
mutableRequest.appendHeader("Content-Encoding", "aws-chunked");
}
}
// Make sure "Content-Length" header is not empty so that HttpClient
// won't cache the stream again to recover Content-Length
long calculateStreamContentLength = AwsSignedChunkedEncodingInputStream
.calculateStreamContentLength(
originalContentLength, AwsS3V4ChunkSigner.getSignatureLength(),
AwsChunkedEncodingConfig.create(), isTrailingChecksum);
long checksumTrailerLength = isTrailingChecksum ? getChecksumTrailerLength(signerParams) : 0;
mutableRequest.putHeader(CONTENT_LENGTH, Long.toString(
calculateStreamContentLength + checksumTrailerLength));
return isTrailingChecksum ? CONTENT_SHA_256_WITH_CHECKSUM : CONTENT_SHA_256;
} else {
return super.calculateContentHash(mutableRequest, signerParams, contentFlexibleChecksum);
}
}
return isUnsignedStreamingTrailer ? STREAMING_UNSIGNED_PAYLOAD_TRAILER : UNSIGNED_PAYLOAD;
}
/**
* Determine whether to use aws-chunked for signing
*/
private boolean useChunkEncoding(SdkHttpFullRequest.Builder mutableRequest, AwsS3V4SignerParams signerParams) {
// Chunked encoding only makes sense to do when the payload is signed
return isPayloadSigningEnabled(mutableRequest, signerParams) && isChunkedEncodingEnabled(signerParams);
}
/**
* @return True if chunked encoding has been enabled. Otherwise false.
*/
private boolean isChunkedEncodingEnabled(AwsS3V4SignerParams signerParams) {
Boolean isChunkedEncodingEnabled = signerParams.enableChunkedEncoding();
return isChunkedEncodingEnabled != null && isChunkedEncodingEnabled;
}
/**
* @return True if payload signing is explicitly enabled.
*/
private boolean isPayloadSigningEnabled(SdkHttpFullRequest.Builder request, AwsS3V4SignerParams signerParams) {
/**
* If we aren't using https we should always sign the payload unless there is no payload
*/
if (!request.protocol().equals("https") && request.contentStreamProvider() != null) {
return true;
}
Boolean isPayloadSigningEnabled = signerParams.enablePayloadSigning();
return isPayloadSigningEnabled != null && isPayloadSigningEnabled;
}
public static long getChecksumTrailerLength(AwsS3V4SignerParams signerParams) {
return signerParams.checksumParams() == null ? 0
: AwsSignedChunkedEncodingInputStream.calculateChecksumContentLength(
signerParams.checksumParams().algorithm(),
signerParams.checksumParams().checksumHeaderName(),
AwsS3V4ChunkSigner.SIGNATURE_LENGTH);
}
}
| 1,455 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AsyncSigV4SubscriberAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* AsyncSigV4SubscriberAdapter appends an empty frame at the end of original Publisher
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The trailing empty frame is sent only if there is demand from the downstream subscriber</dd>
* </dl>
*/
@SdkInternalApi
final class AsyncSigV4SubscriberAdapter implements Subscriber<ByteBuffer> {
private final AtomicBoolean upstreamDone = new AtomicBoolean(false);
private final AtomicLong downstreamDemand = new AtomicLong();
private final Object lock = new Object();
private volatile boolean sentTrailingFrame = false;
private Subscriber<? super ByteBuffer> delegate;
AsyncSigV4SubscriberAdapter(Subscriber<? super ByteBuffer> actual) {
this.delegate = actual;
}
@Override
public void onSubscribe(Subscription s) {
delegate.onSubscribe(new Subscription() {
@Override
public void request(long n) {
if (n <= 0) {
throw new IllegalArgumentException("n > 0 required but it was " + n);
}
downstreamDemand.getAndAdd(n);
if (upstreamDone.get()) {
sendTrailingEmptyFrame();
} else {
s.request(n);
}
}
@Override
public void cancel() {
s.cancel();
}
});
}
@Override
public void onNext(ByteBuffer byteBuffer) {
downstreamDemand.decrementAndGet();
delegate.onNext(byteBuffer);
}
@Override
public void onError(Throwable t) {
upstreamDone.compareAndSet(false, true);
delegate.onError(t);
}
@Override
public void onComplete() {
upstreamDone.compareAndSet(false, true);
if (downstreamDemand.get() > 0) {
sendTrailingEmptyFrame();
}
}
private void sendTrailingEmptyFrame() {
//when upstream complete, send a trailing empty frame
synchronized (lock) {
if (!sentTrailingFrame) {
sentTrailingFrame = true;
delegate.onNext(ByteBuffer.wrap(new byte[] {}));
delegate.onComplete();
}
}
}
}
| 1,456 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/BaseAsyncAws4Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.AsyncRequestBodySigner;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public abstract class BaseAsyncAws4Signer extends BaseAws4Signer implements AsyncRequestBodySigner {
private static final Logger LOG = Logger.loggerFor(BaseAsyncAws4Signer.class);
private static final Pattern AUTHENTICATION_HEADER_PATTERN = Pattern.compile(
SignerConstant.AWS4_SIGNING_ALGORITHM + "\\s" + "Credential=(\\S+)" + "\\s" + "SignedHeaders=(\\S+)" + "\\s"
+ "Signature=(\\S+)");
protected BaseAsyncAws4Signer() {
}
@Override
public AsyncRequestBody signAsyncRequestBody(SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody,
ExecutionAttributes executionAttributes) {
Aws4SignerParams signingParams = extractSignerParams(Aws4SignerParams.builder(), executionAttributes)
.build();
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return signAsync(request, asyncRequestBody, requestParams, signingParams);
}
/**
* This method is only used in test, where clockOverride is passed in signingParams
*/
@SdkTestInternalApi
protected final AsyncRequestBody signAsync(SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody,
Aws4SignerRequestParams requestParams, Aws4SignerParams signingParams) {
String headerSignature = getHeaderSignature(request);
return transformRequestProvider(headerSignature, requestParams, signingParams, asyncRequestBody);
}
/**
* Transform the original requestProvider by adding signing operator and returns a new requestProvider
*
* Can be overriden by subclasses to provide specific signing method
*/
protected abstract AsyncRequestBody transformRequestProvider(String headerSignature,
Aws4SignerRequestParams signerRequestParams,
Aws4SignerParams signerParams,
AsyncRequestBody asyncRequestBody);
/**
* Extract signature from Authentication header
*
* @param request signed request with Authentication header
* @return signature (Hex) string
*/
private String getHeaderSignature(SdkHttpFullRequest request) {
Optional<String> authHeader = request.firstMatchingHeader(SignerConstant.AUTHORIZATION);
if (authHeader.isPresent()) {
Matcher matcher = AUTHENTICATION_HEADER_PATTERN.matcher(authHeader.get());
if (matcher.matches()) {
String headerSignature = matcher.group(3);
return headerSignature;
}
}
// Without header signature, signer can not proceed. Thus throw out exception
throw SdkClientException.builder().message("Signature is missing in AUTHORIZATION header!").build();
}
}
| 1,457 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/ContentChecksum.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.checksums.SdkChecksum;
/**
* Encapsulates Hash in String format and FlexibleChecksum Instance for a Request Content.
*/
@SdkInternalApi
public class ContentChecksum {
private final String hash;
private final SdkChecksum contentFlexibleChecksum;
public ContentChecksum(String hash, SdkChecksum contentFlexibleChecksum) {
this.hash = hash;
this.contentFlexibleChecksum = contentFlexibleChecksum;
}
public String contentHash() {
return hash;
}
public SdkChecksum contentFlexibleChecksum() {
return contentFlexibleChecksum;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ContentChecksum that = (ContentChecksum) o;
return Objects.equals(hash, that.hash) &&
Objects.equals(contentFlexibleChecksum, that.contentFlexibleChecksum);
}
@Override
public int hashCode() {
int result = hash != null ? hash.hashCode() : 0;
result = 31 * result + (contentFlexibleChecksum != null ? contentFlexibleChecksum.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ContentChecksum{" +
"hash='" + hash + '\'' +
", contentFlexibleChecksum=" + contentFlexibleChecksum +
'}';
}
}
| 1,458 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/SignerConstant.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class SignerConstant {
public static final String AWS4_TERMINATOR = "aws4_request";
public static final String AWS4_SIGNING_ALGORITHM = "AWS4-HMAC-SHA256";
/** Seconds in a week, which is the max expiration time Sig-v4 accepts. */
public static final long PRESIGN_URL_MAX_EXPIRATION_SECONDS = 60L * 60 * 24 * 7;
public static final String X_AMZ_CONTENT_SHA256 = "x-amz-content-sha256";
public static final String AUTHORIZATION = "Authorization";
static final String X_AMZ_SECURITY_TOKEN = "X-Amz-Security-Token";
static final String X_AMZ_CREDENTIAL = "X-Amz-Credential";
static final String X_AMZ_DATE = "X-Amz-Date";
static final String X_AMZ_EXPIRES = "X-Amz-Expires";
static final String X_AMZ_SIGNED_HEADER = "X-Amz-SignedHeaders";
static final String X_AMZ_SIGNATURE = "X-Amz-Signature";
static final String X_AMZ_ALGORITHM = "X-Amz-Algorithm";
static final String HOST = "Host";
static final String LINE_SEPARATOR = "\n";
private SignerConstant() {
}
}
| 1,459 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/util/HeaderTransformsHelper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal.util;
import static software.amazon.awssdk.utils.StringUtils.lowerCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Helper class for transforming headers required during signing of headers.
*/
@SdkInternalApi
public final class HeaderTransformsHelper {
private static final List<String> LIST_OF_HEADERS_TO_IGNORE_IN_LOWER_CASE =
Arrays.asList("connection", "x-amzn-trace-id", "user-agent", "expect");
private HeaderTransformsHelper() {
}
public static Map<String, List<String>> canonicalizeSigningHeaders(Map<String, List<String>> headers) {
Map<String, List<String>> result = new TreeMap<>();
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
String lowerCaseHeader = lowerCase(header.getKey());
if (LIST_OF_HEADERS_TO_IGNORE_IN_LOWER_CASE.contains(lowerCaseHeader)) {
continue;
}
result.computeIfAbsent(lowerCaseHeader, x -> new ArrayList<>()).addAll(header.getValue());
}
return result;
}
/**
* "The Trimall function removes excess white space before and after values,
* and converts sequential spaces to a single space."
* <p>
* https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
* <p>
* The collapse-whitespace logic is equivalent to:
* <pre>
* value.replaceAll("\\s+", " ")
* </pre>
* but does not create a Pattern object that needs to compile the match
* string; it also prevents us from having to make a Matcher object as well.
*/
public static String trimAll(String value) {
boolean previousIsWhiteSpace = false;
StringBuilder sb = new StringBuilder(value.length());
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (isWhiteSpace(ch)) {
if (previousIsWhiteSpace) {
continue;
}
sb.append(' ');
previousIsWhiteSpace = true;
} else {
sb.append(ch);
previousIsWhiteSpace = false;
}
}
return sb.toString().trim();
}
private static List<String> trimAll(List<String> values) {
return values.stream().map(HeaderTransformsHelper::trimAll).collect(Collectors.toList());
}
/**
* Tests a char to see if is it whitespace.
* This method considers the same characters to be white
* space as the Pattern class does when matching \s
*
* @param ch the character to be tested
* @return true if the character is white space, false otherwise.
*/
private static boolean isWhiteSpace(final char ch) {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\u000b' || ch == '\r' || ch == '\f';
}
public static String getCanonicalizedHeaderString(Map<String, List<String>> canonicalizedHeaders) {
StringBuilder buffer = new StringBuilder();
canonicalizedHeaders.forEach((headerName, headerValues) -> {
buffer.append(headerName);
buffer.append(":");
buffer.append(String.join(",", trimAll(headerValues)));
buffer.append("\n");
});
return buffer.toString();
}
}
| 1,460 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/util/SignerMethodResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal.util;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.Aws4UnsignedPayloadSigner;
import software.amazon.awssdk.auth.signer.AwsS3V4Signer;
import software.amazon.awssdk.auth.signer.internal.AbstractAwsS3V4Signer;
import software.amazon.awssdk.core.CredentialType;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.signer.SigningMethod;
import software.amazon.awssdk.core.signer.NoOpSigner;
import software.amazon.awssdk.core.signer.Signer;
@SdkInternalApi
public final class SignerMethodResolver {
public static final String S3_SIGV4A_SIGNER_CLASS_PATH = "software.amazon.awssdk.authcrt.signer.internal"
+ ".DefaultAwsCrtS3V4aSigner";
private SignerMethodResolver() {
}
/**
* The signing method can be Header-Auth, streaming-signing auth or Unsigned-payload.
* For Aws4UnsignedPayloadSigner and ENABLE_PAYLOAD_SIGNING the protocol of request decides
* whether the request will be Unsigned or Signed.
*
* @param signer Signer Used.
* @param executionAttributes Execution attributes.
* @param credentials Credentials configured for client.
* @return SigningMethodUsed Enum based on various attributes.
*/
public static SigningMethod resolveSigningMethodUsed(Signer signer, ExecutionAttributes executionAttributes,
AwsCredentials credentials) {
SigningMethod signingMethod = SigningMethod.UNSIGNED_PAYLOAD;
if (signer != null && !CredentialType.TOKEN.equals(signer.credentialType())) {
if (isProtocolBasedStreamingSigningAuth(signer, executionAttributes)) {
signingMethod = SigningMethod.PROTOCOL_STREAMING_SIGNING_AUTH;
} else if (isProtocolBasedUnsigned(signer, executionAttributes)) {
signingMethod = SigningMethod.PROTOCOL_BASED_UNSIGNED;
} else if (isAnonymous(credentials) || signer instanceof NoOpSigner) {
signingMethod = SigningMethod.UNSIGNED_PAYLOAD;
} else {
signingMethod = SigningMethod.HEADER_BASED_AUTH;
}
}
return signingMethod;
}
private static boolean isProtocolBasedStreamingSigningAuth(Signer signer, ExecutionAttributes executionAttributes) {
return (executionAttributes.getOptionalAttribute(ENABLE_PAYLOAD_SIGNING).orElse(false) &&
executionAttributes.getOptionalAttribute(ENABLE_CHUNKED_ENCODING).orElse(false)) ||
supportsPayloadSigning(signer)
&& executionAttributes.getOptionalAttribute(ENABLE_CHUNKED_ENCODING).orElse(false);
}
// S3 Signers like sigv4 abd sigv4a signers signs the payload with chucked encoding.
private static boolean supportsPayloadSigning(Signer signer) {
if (signer == null) {
return false;
}
// auth-crt package is not a dependency of core package, thus we are directly checking the Canonical name.
return signer instanceof AbstractAwsS3V4Signer ||
S3_SIGV4A_SIGNER_CLASS_PATH.equals(signer.getClass().getCanonicalName());
}
private static boolean isProtocolBasedUnsigned(Signer signer, ExecutionAttributes executionAttributes) {
return signer instanceof Aws4UnsignedPayloadSigner || signer instanceof AwsS3V4Signer
|| executionAttributes.getOptionalAttribute(ENABLE_PAYLOAD_SIGNING).orElse(false);
}
public static boolean isAnonymous(AwsCredentials credentials) {
return credentials.secretAccessKey() == null && credentials.accessKeyId() == null;
}
}
| 1,461 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/chunkedencoding/AwsSignedChunkedEncodingInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal.chunkedencoding;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig;
import software.amazon.awssdk.core.internal.io.AwsChunkedEncodingInputStream;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* A wrapper of InputStream that implements chunked encoding.
* <p/>
* Each chunk will be buffered for the calculation of the chunk signature
* which is added at the head of each chunk. The request signature and the chunk signatures will
* be assumed to be hex-encoded strings.
* <p/>
* This class will use the mark() & reset() of the wrapped InputStream if they
* are supported, otherwise it will create a buffer for bytes read from
* the wrapped stream.
*/
@SdkInternalApi
public final class AwsSignedChunkedEncodingInputStream extends AwsChunkedEncodingInputStream {
private static final String CHUNK_SIGNATURE_HEADER = ";chunk-signature=";
private static final String CHECKSUM_SIGNATURE_HEADER = "x-amz-trailer-signature:";
private String previousChunkSignature;
private String headerSignature;
private final AwsChunkSigner chunkSigner;
/**
* Creates a chunked encoding input stream initialized with the originating stream, an http request seed signature
* and a signer that can sign a chunk of bytes according to a chosen algorithm. The configuration allows
* specification of the size of each chunk, as well as the buffer size. Use the same values as when
* calculating total length of the stream {@link #calculateStreamContentLength(long, int, AwsChunkedEncodingConfig)}.
*
* @param in The original InputStream.
* @param headerSignature The signature of the signed headers of the request. This will be used for
* calculating the signature of the first chunk. Observe that the format of
* this parameter should be a hex-encoded string.
* @param chunkSigner The signer for each chunk of data, implementing the {@link AwsChunkSigner} interface.
* @param config The configuration allows the user to customize chunk size and buffer size.
* See {@link AwsChunkedEncodingConfig} for default values.
*/
private AwsSignedChunkedEncodingInputStream(InputStream in, SdkChecksum sdkChecksum,
String checksumHeaderForTrailer,
String headerSignature,
AwsChunkSigner chunkSigner,
AwsChunkedEncodingConfig config) {
super(in, sdkChecksum, checksumHeaderForTrailer, config);
this.chunkSigner = chunkSigner;
this.previousChunkSignature = headerSignature;
this.headerSignature = headerSignature;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder extends AwsChunkedEncodingInputStream.Builder<Builder> {
private AwsChunkSigner awsChunkSigner;
private String headerSignature;
/**
* @param headerSignature The signature of the signed headers. This will be used for
* calculating the signature of the first chunk
* @return This builder for method chaining.
*/
public Builder headerSignature(String headerSignature) {
this.headerSignature = headerSignature;
return this;
}
/**
*
* @param awsChunkSigner Chunk signer used to sign the data.
* @return This builder for method chaining.
*/
public Builder awsChunkSigner(AwsChunkSigner awsChunkSigner) {
this.awsChunkSigner = awsChunkSigner;
return this;
}
public AwsSignedChunkedEncodingInputStream build() {
return new AwsSignedChunkedEncodingInputStream(this.inputStream, this.sdkChecksum, this.checksumHeaderForTrailer,
this.headerSignature,
this.awsChunkSigner, this.awsChunkedEncodingConfig);
}
}
public static long calculateStreamContentLength(long originalLength,
int signatureLength,
AwsChunkedEncodingConfig config) {
return calculateStreamContentLength(originalLength, signatureLength, config, false);
}
/**
* Calculates the expected total length of signed payload chunked stream.
*
* @param originalLength The length of the data
* @param signatureLength The length of a calculated signature, dependent on which {@link AwsChunkSigner} is used
* @param config The chunked encoding config determines the size of the chunks. Use the same values as when
* initializing the stream.
*/
public static long calculateStreamContentLength(long originalLength,
int signatureLength,
AwsChunkedEncodingConfig config,
boolean isTrailingChecksumCalculated) {
if (originalLength < 0) {
throw new IllegalArgumentException("Nonnegative content length expected.");
}
int chunkSize = config.chunkSize();
long maxSizeChunks = originalLength / chunkSize;
long remainingBytes = originalLength % chunkSize;
return maxSizeChunks * calculateSignedChunkLength(chunkSize, signatureLength, false)
+ (remainingBytes > 0 ? calculateSignedChunkLength(remainingBytes, signatureLength, false) : 0)
+ calculateSignedChunkLength(0, signatureLength, isTrailingChecksumCalculated);
}
private static long calculateSignedChunkLength(long chunkDataSize, int signatureLength, boolean isTrailingCarriageReturn) {
return Long.toHexString(chunkDataSize).length()
+ CHUNK_SIGNATURE_HEADER.length()
+ signatureLength
+ CRLF.length()
+ chunkDataSize
+ (isTrailingCarriageReturn ? 0 : CRLF.length());
//For Trailing checksum we do not want additional CRLF as the checksum is appended after CRLF.
}
private byte[] createSignedChunk(byte[] chunkData) {
try {
byte[] header = createSignedChunkHeader(chunkData);
byte[] trailer = isTrailingTerminated ? CRLF.getBytes(StandardCharsets.UTF_8)
: "".getBytes(StandardCharsets.UTF_8);
byte[] signedChunk = new byte[header.length + chunkData.length + trailer.length];
System.arraycopy(header, 0, signedChunk, 0, header.length);
System.arraycopy(chunkData, 0, signedChunk, header.length, chunkData.length);
System.arraycopy(trailer, 0,
signedChunk, header.length + chunkData.length,
trailer.length);
return signedChunk;
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to sign the chunked data. " + e.getMessage())
.cause(e)
.build();
}
}
private byte[] createSignedChunkHeader(byte[] chunkData) {
String chunkSignature = chunkSigner.signChunk(chunkData, previousChunkSignature);
previousChunkSignature = chunkSignature;
StringBuilder chunkHeader = new StringBuilder();
chunkHeader.append(Integer.toHexString(chunkData.length));
chunkHeader.append(CHUNK_SIGNATURE_HEADER)
.append(chunkSignature)
.append(CRLF);
return chunkHeader.toString().getBytes(StandardCharsets.UTF_8);
}
@Override
protected byte[] createFinalChunk(byte[] finalChunk) {
return createChunk(FINAL_CHUNK);
}
@Override
protected byte[] createChunk(byte[] chunkData) {
return createSignedChunk(chunkData);
}
@Override
protected byte[] createChecksumChunkHeader() {
StringBuilder chunkHeader = new StringBuilder();
chunkHeader.append(checksumHeaderForTrailer)
.append(HEADER_COLON_SEPARATOR)
.append(BinaryUtils.toBase64(calculatedChecksum))
.append(CRLF)
.append(createSignedChecksumChunk());
return chunkHeader.toString().getBytes(StandardCharsets.UTF_8);
}
private String createSignedChecksumChunk() {
StringBuilder chunkHeader = new StringBuilder();
//signChecksumChunk
String chunkSignature =
chunkSigner.signChecksumChunk(calculatedChecksum, previousChunkSignature,
checksumHeaderForTrailer);
previousChunkSignature = chunkSignature;
chunkHeader.append(CHECKSUM_SIGNATURE_HEADER)
.append(chunkSignature)
.append(CRLF);
return chunkHeader.toString();
}
public static int calculateChecksumContentLength(Algorithm algorithm, String headerName, int signatureLength) {
int originalLength = algorithm.base64EncodedLength();
return (headerName.length()
+ HEADER_COLON_SEPARATOR.length()
+ originalLength
+ CRLF.length()
+ calculateSignedChecksumChunkLength(signatureLength)
+ CRLF.length());
}
private static int calculateSignedChecksumChunkLength(int signatureLength) {
return CHECKSUM_SIGNATURE_HEADER.length()
+ signatureLength
+ CRLF.length();
}
@Override
public void reset() throws IOException {
super.reset();
previousChunkSignature = headerSignature;
}
}
| 1,462 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/chunkedencoding/AwsS3V4ChunkSigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal.chunkedencoding;
import static software.amazon.awssdk.auth.signer.internal.util.HeaderTransformsHelper.canonicalizeSigningHeaders;
import static software.amazon.awssdk.auth.signer.internal.util.HeaderTransformsHelper.getCanonicalizedHeaderString;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.signer.internal.AbstractAws4Signer;
import software.amazon.awssdk.auth.signer.internal.SigningAlgorithm;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* An implementation of AwsChunkSigner that can calculate a Sigv4 compatible chunk
* signature.
*/
@SdkInternalApi
public class AwsS3V4ChunkSigner implements AwsChunkSigner {
public static final int SIGNATURE_LENGTH = 64;
private static final String CHUNK_STRING_TO_SIGN_PREFIX = "AWS4-HMAC-SHA256-PAYLOAD";
private static final String TRAILING_HEADER_STRING_TO_SIGN_PREFIX = "AWS4-HMAC-SHA256-TRAILER";
private final String dateTime;
private final String keyPath;
private final MessageDigest sha256;
private final MessageDigest sha256ForTrailer;
private final Mac hmacSha256;
private final Mac trailerHmacSha256;
public AwsS3V4ChunkSigner(byte[] signingKey, String datetime, String keyPath) {
try {
this.sha256 = MessageDigest.getInstance("SHA-256");
this.sha256ForTrailer = MessageDigest.getInstance("SHA-256");
String signingAlgo = SigningAlgorithm.HmacSHA256.toString();
this.hmacSha256 = Mac.getInstance(signingAlgo);
hmacSha256.init(new SecretKeySpec(signingKey, signingAlgo));
trailerHmacSha256 = Mac.getInstance(signingAlgo);
trailerHmacSha256.init(new SecretKeySpec(signingKey, signingAlgo));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (InvalidKeyException e) {
throw new IllegalArgumentException(e);
}
this.dateTime = datetime;
this.keyPath = keyPath;
}
@Override
public String signChunk(byte[] chunkData, String previousSignature) {
String chunkStringToSign =
CHUNK_STRING_TO_SIGN_PREFIX + "\n" +
dateTime + "\n" +
keyPath + "\n" +
previousSignature + "\n" +
AbstractAws4Signer.EMPTY_STRING_SHA256_HEX + "\n" +
BinaryUtils.toHex(sha256.digest(chunkData));
try {
byte[] bytes = hmacSha256.doFinal(chunkStringToSign.getBytes(StandardCharsets.UTF_8));
return BinaryUtils.toHex(bytes);
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Signed chunk must be of below format
* signature = Hex(HMAC(K,
* "AWS4-HMAC-SHA256-TRAILER"\n
* DATE\n
* KEYPATH\n
* final_chunk_signature\n
* Hex(SHA256(canonicalize(trailing-headers)))))
* @return Signed Checksum in above signature format.
*/
public String signChecksumChunk(byte[] calculatedChecksum, String previousSignature, String checksumHeaderForTrailer) {
Map<String, List<String>> canonicalizeSigningHeaders = canonicalizeSigningHeaders(
Collections.singletonMap(checksumHeaderForTrailer, Arrays.asList(BinaryUtils.toBase64(calculatedChecksum))));
String canonicalizedHeaderString = getCanonicalizedHeaderString(canonicalizeSigningHeaders);
String chunkStringToSign =
TRAILING_HEADER_STRING_TO_SIGN_PREFIX + "\n" +
dateTime + "\n" +
keyPath + "\n" +
previousSignature + "\n" +
BinaryUtils.toHex(sha256ForTrailer.digest(canonicalizedHeaderString.getBytes(StandardCharsets.UTF_8)));
return BinaryUtils.toHex(trailerHmacSha256.doFinal(chunkStringToSign.getBytes(StandardCharsets.UTF_8)));
}
public static int getSignatureLength() {
return SIGNATURE_LENGTH;
}
}
| 1,463 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/chunkedencoding/AwsChunkSigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.internal.chunkedencoding;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Represents a signer for a chunk of data, that returns a new signature based on the data and the
* previous signature. This signature should be a string of hex characters.
*/
@SdkInternalApi
public interface AwsChunkSigner {
String signChunk(byte[] chunkData, String previousSignature);
String signChecksumChunk(byte[] calculatedChecksum, String previousSignature, String checksumHeaderForTrailer);
}
| 1,464 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/Aws4PresignerParams.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.params;
import java.time.Instant;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.SignerConstant;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
@SdkPublicApi
public final class Aws4PresignerParams
extends Aws4SignerParams
implements ToCopyableBuilder<Aws4PresignerParams.Builder, Aws4PresignerParams> {
private final Instant expirationTime;
private Aws4PresignerParams(BuilderImpl builder) {
super(builder);
this.expirationTime = builder.expirationTime;
}
public Optional<Instant> expirationTime() {
return Optional.ofNullable(expirationTime);
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public interface Builder extends Aws4SignerParams.Builder<Builder>, CopyableBuilder<Builder, Aws4PresignerParams> {
/**
* Sets an expiration time for the presigned url. If this value is not specified,
* {@link SignerConstant#PRESIGN_URL_MAX_EXPIRATION_SECONDS} is used.
*
* @param expirationTime Expiration time for the presigned url expressed in {@link Instant}.
*/
Builder expirationTime(Instant expirationTime);
@Override
Aws4PresignerParams build();
}
private static final class BuilderImpl extends Aws4SignerParams.BuilderImpl<Builder> implements Builder {
private Instant expirationTime;
private BuilderImpl() {
}
private BuilderImpl(Aws4PresignerParams params) {
super(params);
this.expirationTime = params.expirationTime;
}
@Override
public Builder expirationTime(Instant expirationTime) {
this.expirationTime = expirationTime;
return this;
}
public void setExpirationTime(Instant expirationTime) {
expirationTime(expirationTime);
}
@Override
public Aws4PresignerParams build() {
return new Aws4PresignerParams(this);
}
}
}
| 1,465 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/AwsS3V4SignerParams.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.params;
import software.amazon.awssdk.annotations.SdkPublicApi;
@SdkPublicApi
public final class AwsS3V4SignerParams extends Aws4SignerParams {
private final Boolean enableChunkedEncoding;
private final Boolean enablePayloadSigning;
private AwsS3V4SignerParams(BuilderImpl builder) {
super(builder);
this.enableChunkedEncoding = builder.enableChunkedEncoding;
this.enablePayloadSigning = builder.enablePayloadSigning;
}
public Boolean enableChunkedEncoding() {
return enableChunkedEncoding;
}
public Boolean enablePayloadSigning() {
return enablePayloadSigning;
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder extends Aws4SignerParams.Builder<Builder> {
/**
* <p>
* Configures the client to enable chunked encoding for all requests.
* </p>
* <p>
* The default behavior is to enable chunked encoding automatically. Disable this flag will result in
* disabling chunked encoding for all requests.
* </p>
* <p>
* <b>Note:</b> Disabling this option has performance implications since the checksum for the
* payload will have to be pre-calculated before sending the data. If your payload is large this
* will affect the overall time required to upload an object. Using this option is recommended
* only if your endpoint does not implement chunked uploading.
* </p>
*
* @param enableChunkedEncoding True to enable chunked encoding and False to disable. Default value is True.
*/
Builder enableChunkedEncoding(Boolean enableChunkedEncoding);
/**
* <p>
* Configures the client to sign payloads in all situations.
* </p>
* <p>
* Payload signing is optional when chunked encoding is not used and requests are made
* against an HTTPS endpoint. Under these conditions the client will by default
* opt to not sign payloads to optimize performance. If this flag is set to true the
* client will instead always sign payloads.
* </p>
* <p>
* <b>Note:</b> Payload signing can be expensive, particularly if transferring
* large payloads in a single chunk. Enabling this option will result in a performance
* penalty.
* </p>
*
* @param enablePayloadSigning True to explicitly enable payload signing in all situations. Default value is False.
*/
Builder enablePayloadSigning(Boolean enablePayloadSigning);
@Override
AwsS3V4SignerParams build();
}
private static final class BuilderImpl extends Aws4SignerParams.BuilderImpl<Builder> implements Builder {
static final boolean DEFAULT_CHUNKED_ENCODING_ENABLED = false;
static final boolean DEFAULT_PAYLOAD_SIGNING_ENABLED = false;
private Boolean enableChunkedEncoding = DEFAULT_CHUNKED_ENCODING_ENABLED;
private Boolean enablePayloadSigning = DEFAULT_PAYLOAD_SIGNING_ENABLED;
private BuilderImpl() {
// By default, S3 should not normalize paths
normalizePath(false);
}
@Override
public Builder enableChunkedEncoding(Boolean enableChunkedEncoding) {
this.enableChunkedEncoding = enableChunkedEncoding;
return this;
}
public void setEnableChunkedEncoding(Boolean enableChunkedEncoding) {
enableChunkedEncoding(enableChunkedEncoding);
}
@Override
public Builder enablePayloadSigning(Boolean enablePayloadSigning) {
this.enablePayloadSigning = enablePayloadSigning;
return this;
}
public void setEnablePayloadSigning(Boolean enablePayloadSigning) {
enablePayloadSigning(enablePayloadSigning);
}
@Override
public AwsS3V4SignerParams build() {
return new AwsS3V4SignerParams(this);
}
}
}
| 1,466 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/SignerChecksumParams.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.params;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.utils.Validate;
/**
* Encapsulates the Checksum information like Algorithm and header name for the checksum in header/trailer locations.
*/
@SdkPublicApi
public class SignerChecksumParams {
private final Algorithm algorithm;
private final String checksumHeaderName;
private final boolean isStreamingRequest;
private SignerChecksumParams(Builder builder) {
Validate.notNull(builder.algorithm, "algorithm is null");
Validate.notNull(builder.checksumHeaderName, "checksumHeaderName is null");
this.algorithm = builder.algorithm;
this.checksumHeaderName = builder.checksumHeaderName;
this.isStreamingRequest = builder.isStreamingRequest;
}
public static Builder builder() {
return new Builder();
}
/**
* @return {@code Algorithm} that will be used to compute the checksum.
*/
public Algorithm algorithm() {
return algorithm;
}
/**
*
* @return Header name for the checksum.
*/
public String checksumHeaderName() {
return checksumHeaderName;
}
/**
*
* @return true if the checksum is for a streaming request member.
*/
public boolean isStreamingRequest() {
return isStreamingRequest;
}
public static final class Builder {
private Algorithm algorithm;
private String checksumHeaderName;
private boolean isStreamingRequest;
private Builder() {
}
/**
* @param algorithm {@code Algorithm} that will be used to compute checksum for the content.
* @return this builder for method chaining.
*/
public Builder algorithm(Algorithm algorithm) {
this.algorithm = algorithm;
return this;
}
/**
*
* @param checksumHeaderName Header name for the Checksum.
* @return this builder for method chaining.
*/
public Builder checksumHeaderName(String checksumHeaderName) {
this.checksumHeaderName = checksumHeaderName;
return this;
}
/**
*
* @param isStreamingRequest True if the request has a streaming memberin it.
* @return this builder for method chaining.
*/
public Builder isStreamingRequest(boolean isStreamingRequest) {
this.isStreamingRequest = isStreamingRequest;
return this;
}
/**
* Builds an instance of {@link SignerChecksumParams}.
*
* @return New instance of {@link SignerChecksumParams}.
*/
public SignerChecksumParams build() {
return new SignerChecksumParams(this);
}
}
}
| 1,467 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/Aws4SignerParams.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.params;
import java.time.Clock;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.utils.Validate;
/**
* Parameters that are used during signing.
*
* Required parameters vary based on signer implementations. Signer implementations might only use a
* subset of params in this class.
*/
@SdkPublicApi
public class Aws4SignerParams {
private final Boolean doubleUrlEncode;
private final Boolean normalizePath;
private final AwsCredentials awsCredentials;
private final String signingName;
private final Region signingRegion;
private final Integer timeOffset;
private final Clock signingClockOverride;
private final SignerChecksumParams checksumParams;
Aws4SignerParams(BuilderImpl<?> builder) {
this.doubleUrlEncode = Validate.paramNotNull(builder.doubleUrlEncode, "Double url encode");
this.normalizePath = Validate.paramNotNull(builder.normalizePath, "Normalize resource path");
this.awsCredentials = Validate.paramNotNull(builder.awsCredentials, "Credentials");
this.signingName = Validate.paramNotNull(builder.signingName, "service signing name");
this.signingRegion = Validate.paramNotNull(builder.signingRegion, "signing region");
this.timeOffset = builder.timeOffset;
this.signingClockOverride = builder.signingClockOverride;
this.checksumParams = builder.checksumParams;
}
public static Builder builder() {
return new BuilderImpl<>();
}
public Boolean doubleUrlEncode() {
return doubleUrlEncode;
}
public Boolean normalizePath() {
return normalizePath;
}
public AwsCredentials awsCredentials() {
return awsCredentials;
}
public String signingName() {
return signingName;
}
public Region signingRegion() {
return signingRegion;
}
public Optional<Integer> timeOffset() {
return Optional.ofNullable(timeOffset);
}
public Optional<Clock> signingClockOverride() {
return Optional.ofNullable(signingClockOverride);
}
public SignerChecksumParams checksumParams() {
return checksumParams;
}
public interface Builder<B extends Builder<B>> {
/**
* Set this value to double url-encode the resource path when constructing the
* canonical request.
*
* By default, all services except S3 enable double url-encoding.
*
* @param doubleUrlEncode Set true to enable double url encoding. Otherwise false.
*/
B doubleUrlEncode(Boolean doubleUrlEncode);
/**
* Whether the resource path should be "normalized" according to RFC3986 when
* constructing the canonical request.
*
* By default, all services except S3 enable resource path normalization.
*/
B normalizePath(Boolean normalizePath);
/**
* Sets the aws credentials to use for computing the signature.
*
* @param awsCredentials Aws Credentials to use for computing the signature.
*/
B awsCredentials(AwsCredentials awsCredentials);
/**
* The name of the AWS service to be used for computing the signature.
*
* @param signingName Name of the AWS service to be used for computing the signature.
*/
B signingName(String signingName);
/**
* The AWS region to be used for computing the signature.
*
* @param signingRegion AWS region to be used for computing the signature.
*/
B signingRegion(Region signingRegion);
/**
* The time offset (for clock skew correction) to use when computing the signing date for the request.
*
* @param timeOffset The time offset (for clock skew correction) to use when computing the signing date for the request.
*/
B timeOffset(Integer timeOffset);
/**
* The clock to use for overriding the signing time when computing signature for a request.
*
* By default, current time of the system is used for signing. This parameter can be used to set custom signing time.
* Useful option for testing.
*
* @param signingClockOverride The clock to use for overriding the signing time when computing signature for a request.
*/
B signingClockOverride(Clock signingClockOverride);
/**
* Checksum params required to compute the Checksum while data is read for signing the Checksum.
*
* @param checksumParams SignerChecksumParams that defines the Algorithm and headers to pass Checksum.
* @return
*/
B checksumParams(SignerChecksumParams checksumParams);
Aws4SignerParams build();
}
protected static class BuilderImpl<B extends Builder<B>> implements Builder<B> {
private static final Boolean DEFAULT_DOUBLE_URL_ENCODE = Boolean.TRUE;
private Boolean doubleUrlEncode = DEFAULT_DOUBLE_URL_ENCODE;
private Boolean normalizePath = Boolean.TRUE;
private AwsCredentials awsCredentials;
private String signingName;
private Region signingRegion;
private Integer timeOffset;
private Clock signingClockOverride;
private SignerChecksumParams checksumParams;
protected BuilderImpl() {
}
protected BuilderImpl(Aws4SignerParams params) {
doubleUrlEncode = params.doubleUrlEncode;
normalizePath = params.normalizePath;
awsCredentials = params.awsCredentials;
signingName = params.signingName;
signingRegion = params.signingRegion;
timeOffset = params.timeOffset;
signingClockOverride = params.signingClockOverride;
checksumParams = params.checksumParams;
}
@Override
public B doubleUrlEncode(Boolean doubleUrlEncode) {
this.doubleUrlEncode = doubleUrlEncode;
return (B) this;
}
public void setDoubleUrlEncode(Boolean doubleUrlEncode) {
doubleUrlEncode(doubleUrlEncode);
}
@Override
public B normalizePath(Boolean normalizePath) {
this.normalizePath = normalizePath;
return (B) this;
}
public void setNormalizePath(Boolean normalizePath) {
normalizePath(normalizePath);
}
@Override
public B awsCredentials(AwsCredentials awsCredentials) {
this.awsCredentials = awsCredentials;
return (B) this;
}
public void setAwsCredentials(AwsCredentials awsCredentials) {
awsCredentials(awsCredentials);
}
@Override
public B signingName(String signingName) {
this.signingName = signingName;
return (B) this;
}
public void setSigningName(String signingName) {
signingName(signingName);
}
@Override
public B signingRegion(Region signingRegion) {
this.signingRegion = signingRegion;
return (B) this;
}
public void setSigningRegion(Region signingRegion) {
signingRegion(signingRegion);
}
@Override
public B timeOffset(Integer timeOffset) {
this.timeOffset = timeOffset;
return (B) this;
}
public void setTimeOffset(Integer timeOffset) {
timeOffset(timeOffset);
}
@Override
public B signingClockOverride(Clock signingClockOverride) {
this.signingClockOverride = signingClockOverride;
return (B) this;
}
@Override
public B checksumParams(SignerChecksumParams checksumParams) {
this.checksumParams = checksumParams;
return (B) this;
}
public void setSigningClockOverride(Clock signingClockOverride) {
signingClockOverride(signingClockOverride);
}
@Override
public Aws4SignerParams build() {
return new Aws4SignerParams(this);
}
}
}
| 1,468 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/TokenSignerParams.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.signer.params;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.utils.Validate;
/**
* Parameters that are used during signing.
*
* Required parameters vary based on signer implementations. Signer implementations might only use a
* subset of params in this class.
*/
@SdkPublicApi
public class TokenSignerParams {
private final SdkToken token;
TokenSignerParams(BuilderImpl<?> builder) {
this.token = Validate.paramNotNull(builder.token, "Signing token");
}
public static Builder builder() {
return new BuilderImpl<>();
}
public SdkToken token() {
return token;
}
public interface Builder<B extends Builder> {
/**
* Set this value to provide a token for signing
*
* This is required for token signing.
*
* @param token A token implementing {@link SdkToken}
*/
B token(SdkToken token);
TokenSignerParams build();
}
protected static class BuilderImpl<B extends Builder> implements Builder<B> {
private SdkToken token;
protected BuilderImpl() {
}
@Override
public B token(SdkToken token) {
this.token = token;
return (B) this;
}
public void setToken(SdkToken token) {
token(token);
}
@Override
public TokenSignerParams build() {
return new TokenSignerParams(this);
}
}
}
| 1,469 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/DefaultCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.LazyAwsCredentialsProvider;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* AWS credentials provider chain that looks for credentials in this order:
* <ol>
* <li>Java System Properties - {@code aws.accessKeyId} and {@code aws.secretAccessKey}</li>
* <li>Environment Variables - {@code AWS_ACCESS_KEY_ID} and {@code AWS_SECRET_ACCESS_KEY}</li>
* <li>Web Identity Token credentials from system properties or environment variables</li>
* <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li>
* <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" environment
* variable is set and security manager has permission to access the variable,</li>
* <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li>
* </ol>
*
* @see SystemPropertyCredentialsProvider
* @see EnvironmentVariableCredentialsProvider
* @see ProfileCredentialsProvider
* @see WebIdentityTokenFileCredentialsProvider
* @see ContainerCredentialsProvider
* @see InstanceProfileCredentialsProvider
*/
@SdkPublicApi
public final class DefaultCredentialsProvider
implements AwsCredentialsProvider, SdkAutoCloseable,
ToCopyableBuilder<DefaultCredentialsProvider.Builder, DefaultCredentialsProvider> {
private static final DefaultCredentialsProvider DEFAULT_CREDENTIALS_PROVIDER = new DefaultCredentialsProvider(builder());
private final LazyAwsCredentialsProvider providerChain;
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private final Boolean reuseLastProviderEnabled;
private final Boolean asyncCredentialUpdateEnabled;
/**
* @see #builder()
*/
private DefaultCredentialsProvider(Builder builder) {
this.profileFile = builder.profileFile;
this.profileName = builder.profileName;
this.reuseLastProviderEnabled = builder.reuseLastProviderEnabled;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.providerChain = createChain(builder);
}
/**
* Create an instance of the {@link DefaultCredentialsProvider} using the default configuration. Configuration can be
* specified by creating an instance using the {@link #builder()}.
*/
public static DefaultCredentialsProvider create() {
return DEFAULT_CREDENTIALS_PROVIDER;
}
/**
* Create the default credential chain using the configuration in the provided builder.
*/
private static LazyAwsCredentialsProvider createChain(Builder builder) {
boolean asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
boolean reuseLastProviderEnabled = builder.reuseLastProviderEnabled;
return LazyAwsCredentialsProvider.create(() -> {
AwsCredentialsProvider[] credentialsProviders = new AwsCredentialsProvider[] {
SystemPropertyCredentialsProvider.create(),
EnvironmentVariableCredentialsProvider.create(),
WebIdentityTokenFileCredentialsProvider.builder()
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.build(),
ProfileCredentialsProvider.builder()
.profileFile(builder.profileFile)
.profileName(builder.profileName)
.build(),
ContainerCredentialsProvider.builder()
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.build(),
InstanceProfileCredentialsProvider.builder()
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.profileFile(builder.profileFile)
.profileName(builder.profileName)
.build()
};
return AwsCredentialsProviderChain.builder()
.reuseLastProviderEnabled(reuseLastProviderEnabled)
.credentialsProviders(credentialsProviders)
.build();
});
}
/**
* Get a builder for defining a {@link DefaultCredentialsProvider} with custom configuration.
*/
public static Builder builder() {
return new Builder();
}
@Override
public AwsCredentials resolveCredentials() {
return providerChain.resolveCredentials();
}
@Override
public void close() {
providerChain.close();
}
@Override
public String toString() {
return ToString.builder("DefaultCredentialsProvider")
.add("providerChain", providerChain)
.build();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* Configuration that defines the {@link DefaultCredentialsProvider}'s behavior.
*/
public static final class Builder implements CopyableBuilder<Builder, DefaultCredentialsProvider> {
private Supplier<ProfileFile> profileFile;
private String profileName;
private Boolean reuseLastProviderEnabled = true;
private Boolean asyncCredentialUpdateEnabled = false;
/**
* Created with {@link #builder()}.
*/
private Builder() {
}
private Builder(DefaultCredentialsProvider credentialsProvider) {
this.profileFile = credentialsProvider.profileFile;
this.profileName = credentialsProvider.profileName;
this.reuseLastProviderEnabled = credentialsProvider.reuseLastProviderEnabled;
this.asyncCredentialUpdateEnabled = credentialsProvider.asyncCredentialUpdateEnabled;
}
public Builder profileFile(ProfileFile profileFile) {
return profileFile(Optional.ofNullable(profileFile)
.map(ProfileFileSupplier::fixedProfileFile)
.orElse(null));
}
public Builder profileFile(Supplier<ProfileFile> profileFileSupplier) {
this.profileFile = profileFileSupplier;
return this;
}
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
/**
* Controls whether the provider should reuse the last successful credentials provider in the chain. Reusing the last
* successful credentials provider will typically return credentials faster than searching through the chain.
*
* <p>By default, this is enabled.</p>
*/
public Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
this.reuseLastProviderEnabled = reuseLastProviderEnabled;
return this;
}
/**
* Configure whether this provider should fetch credentials asynchronously in the background. If this is true, threads are
* less likely to block when {@link #resolveCredentials()} is called, but additional resources are used to maintain the
* provider.
*
* <p>By default, this is disabled.</p>
*/
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
/**
* Create a {@link DefaultCredentialsProvider} using the configuration defined in this builder.
*/
@Override
public DefaultCredentialsProvider build() {
return new DefaultCredentialsProvider(this);
}
}
}
| 1,470 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ProfileCredentialsProviderFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A factory for {@link AwsCredentialsProvider}s, which can be used to create different credentials providers with different
* Provider specifications like profile properties.
*/
@FunctionalInterface
@SdkProtectedApi
public interface ProfileCredentialsProviderFactory {
AwsCredentialsProvider create(ProfileProviderCredentialsContext profileProviderCredentialsContext);
}
| 1,471 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
/**
* Interface for loading {@link AwsCredentials} that are used for authentication.
*
* <p>Commonly-used implementations include {@link StaticCredentialsProvider} for a fixed set of credentials and the
* {@link DefaultCredentialsProvider} for discovering credentials from the host's environment. The AWS Security Token
* Service (STS) client also provides implementations of this interface for loading temporary, limited-privilege credentials from
* AWS STS.</p>
*/
@FunctionalInterface
@SdkPublicApi
public interface AwsCredentialsProvider extends IdentityProvider<AwsCredentialsIdentity> {
/**
* Returns {@link AwsCredentials} that can be used to authorize an AWS request. Each implementation of AWSCredentialsProvider
* can choose its own strategy for loading credentials. For example, an implementation might load credentials from an existing
* key management system, or load new credentials when credentials are rotated.
*
* <p>If an error occurs during the loading of credentials or credentials could not be found, a runtime exception will be
* raised.</p>
*
* @return AwsCredentials which the caller can use to authorize an AWS request.
*/
AwsCredentials resolveCredentials();
@Override
default Class<AwsCredentialsIdentity> identityType() {
return AwsCredentialsIdentity.class;
}
@Override
default CompletableFuture<AwsCredentialsIdentity> resolveIdentity(ResolveIdentityRequest request) {
return CompletableFuture.completedFuture(resolveCredentials());
}
}
| 1,472 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ProcessCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Platform;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* A credentials provider that can load credentials from an external process. This is used to support the credential_process
* setting in the profile credentials file. See
* <a href="https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#sourcing-credentials-from-external-processes">sourcing credentials
* from external processes</a> for more information.
*
* <p>
* This class can be initialized using {@link #builder()}.
*
* <p>
* Available settings:
* <ul>
* <li>Command - The command that should be executed to retrieve credentials.</li>
* <li>CredentialRefreshThreshold - The amount of time between when the credentials expire and when the credentials should
* start to be refreshed. This allows the credentials to be refreshed *before* they are reported to expire. Default: 15
* seconds.</li>
* <li>ProcessOutputLimit - The maximum amount of data that can be returned by the external process before an exception is
* raised. Default: 64000 bytes (64KB).</li>
* </ul>
*/
@SdkPublicApi
public final class ProcessCredentialsProvider
implements AwsCredentialsProvider,
SdkAutoCloseable,
ToCopyableBuilder<ProcessCredentialsProvider.Builder, ProcessCredentialsProvider> {
private static final JsonNodeParser PARSER = JsonNodeParser.builder()
.removeErrorLocations(true)
.build();
private final List<String> executableCommand;
private final Duration credentialRefreshThreshold;
private final long processOutputLimit;
private final CachedSupplier<AwsCredentials> processCredentialCache;
private final String commandFromBuilder;
private final Boolean asyncCredentialUpdateEnabled;
/**
* @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.executableCommand = Collections.unmodifiableList(cmd);
this.processOutputLimit = Validate.isPositive(builder.processOutputLimit, "processOutputLimit");
this.credentialRefreshThreshold = Validate.isPositive(builder.credentialRefreshThreshold, "expirationBuffer");
this.commandFromBuilder = builder.command;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
CachedSupplier.Builder<AwsCredentials> cacheBuilder = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString());
if (builder.asyncCredentialUpdateEnabled) {
cacheBuilder.prefetchStrategy(new NonBlocking("process-credentials-provider"));
}
this.processCredentialCache = cacheBuilder.build();
}
/**
* Retrieve a new builder that can be used to create and configure a {@link ProcessCredentialsProvider}.
*/
public static Builder builder() {
return new Builder();
}
@Override
public AwsCredentials resolveCredentials() {
return processCredentialCache.get();
}
private RefreshResult<AwsCredentials> refreshCredentials() {
try {
String processOutput = executeCommand();
JsonNode credentialsJson = parseProcessOutput(processOutput);
AwsCredentials credentials = credentials(credentialsJson);
Instant credentialExpirationTime = credentialExpirationTime(credentialsJson);
return RefreshResult.builder(credentials)
.staleTime(credentialExpirationTime)
.prefetchTime(credentialExpirationTime.minusMillis(credentialRefreshThreshold.toMillis()))
.build();
} catch (InterruptedException e) {
throw new IllegalStateException("Process-based credential refreshing has been interrupted.", e);
} catch (Exception e) {
throw new IllegalStateException("Failed to refresh process-based credentials.", e);
}
}
/**
* Parse the output from the credentials process.
*/
private JsonNode parseProcessOutput(String processOutput) {
JsonNode credentialsJson = PARSER.parse(processOutput);
if (!credentialsJson.isObject()) {
throw new IllegalStateException("Process did not return a JSON object.");
}
JsonNode version = credentialsJson.field("Version").orElse(null);
if (version == null || !version.isNumber() || !version.asNumber().equals("1")) {
throw new IllegalStateException("Unsupported credential version: " + version);
}
return credentialsJson;
}
/**
* 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);
}
}
/**
* Parse the process output to retrieve the expiration date and time.
*/
private Instant credentialExpirationTime(JsonNode credentialsJson) {
String expiration = getText(credentialsJson, "Expiration");
if (expiration != null) {
return DateUtils.parseIso8601Date(expiration);
} else {
return Instant.MAX;
}
}
/**
* Get a textual value from a json object.
*/
private String getText(JsonNode jsonObject, String nodeName) {
return jsonObject.field(nodeName).map(JsonNode::text).orElse(null);
}
/**
* Execute the external process to retrieve credentials.
*/
private String executeCommand() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(executableCommand);
ByteArrayOutputStream commandOutput = new ByteArrayOutputStream();
Process process = processBuilder.start();
try {
IoUtils.copy(process.getInputStream(), commandOutput, processOutputLimit);
process.waitFor();
if (process.exitValue() != 0) {
try (InputStream errorStream = process.getErrorStream()) {
String errorMessage = IoUtils.toUtf8String(errorStream);
throw new IllegalStateException(String.format("Command returned non-zero exit value (%s) with error message: "
+ "%s", process.exitValue(), errorMessage));
}
}
return new String(commandOutput.toByteArray(), StandardCharsets.UTF_8);
} finally {
process.destroy();
}
}
@Override
public void close() {
processCredentialCache.close();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* Used to configure and create a {@link ProcessCredentialsProvider}. See {@link #builder()} creation.
*/
public static class Builder implements CopyableBuilder<Builder, ProcessCredentialsProvider> {
private Boolean asyncCredentialUpdateEnabled = false;
private String command;
private Duration credentialRefreshThreshold = Duration.ofSeconds(15);
private long processOutputLimit = 64000;
/**
* @see #builder()
*/
private Builder() {
}
private Builder(ProcessCredentialsProvider provider) {
this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled;
this.command = provider.commandFromBuilder;
this.credentialRefreshThreshold = provider.credentialRefreshThreshold;
this.processOutputLimit = provider.processOutputLimit;
}
/**
* Configure whether the provider should fetch credentials asynchronously in the background. If this is true,
* threads are less likely to block when credentials are loaded, but additional resources are used to maintain
* the provider.
*
* <p>By default, this is disabled.</p>
*/
@SuppressWarnings("unchecked")
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
/**
* Configure the command that should be executed to retrieve credentials.
*/
public Builder command(String command) {
this.command = command;
return this;
}
/**
* Configure the amount of time between when the credentials expire and when the credentials should start to be
* refreshed. This allows the credentials to be refreshed *before* they are reported to expire.
*
* <p>Default: 15 seconds.</p>
*/
public Builder credentialRefreshThreshold(Duration credentialRefreshThreshold) {
this.credentialRefreshThreshold = credentialRefreshThreshold;
return this;
}
/**
* Configure the maximum amount of data that can be returned by the external process before an exception is
* raised.
*
* <p>Default: 64000 bytes (64KB).</p>
*/
public Builder processOutputLimit(long outputByteLimit) {
this.processOutputLimit = outputByteLimit;
return this;
}
public ProcessCredentialsProvider build() {
return new ProcessCredentialsProvider(this);
}
}
@Override
public String toString() {
return ToString.builder("ProcessCredentialsProvider")
.add("cmd", executableCommand)
.build();
}
} | 1,473 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/WebIdentityTokenCredentialsProviderFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties;
import software.amazon.awssdk.profiles.Profile;
/**
* A factory for {@link AwsCredentialsProvider}s that are derived from web identity tokens.
*
* Currently this is used to allow a {@link Profile} or environment variable configured with a role that should be assumed with
* a web identity token to create a credentials provider via the
* 'software.amazon.awssdk.services.sts.internal.StsWebIdentityCredentialsProviderFactory', assuming STS is on the classpath.
*/
@FunctionalInterface
@SdkProtectedApi
public interface WebIdentityTokenCredentialsProviderFactory {
AwsCredentialsProvider create(WebIdentityTokenCredentialProperties credentialProperties);
}
| 1,474 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/StaticCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link AwsCredentialsProvider} that returns a set implementation of {@link AwsCredentials}.
*/
@SdkPublicApi
public final class StaticCredentialsProvider implements AwsCredentialsProvider {
private final AwsCredentials credentials;
private StaticCredentialsProvider(AwsCredentials credentials) {
this.credentials = Validate.notNull(credentials, "Credentials must not be null.");
}
/**
* Create a credentials provider that always returns the provided set of credentials.
*/
public static StaticCredentialsProvider create(AwsCredentials credentials) {
return new StaticCredentialsProvider(credentials);
}
@Override
public AwsCredentials resolveCredentials() {
return credentials;
}
@Override
public String toString() {
return ToString.builder("StaticCredentialsProvider")
.add("credentials", credentials)
.build();
}
}
| 1,475 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsBasicCredentials.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static software.amazon.awssdk.utils.StringUtils.trimToNull;
import java.util.Objects;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Provides access to the AWS credentials used for accessing services: AWS access key ID and secret access key. These
* credentials are used to securely sign requests to services (e.g., AWS services) that use them for authentication.
*
* <p>For more details on AWS access keys, see:
* <a href="https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys">
* https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys</a></p>
*
* @see AwsCredentialsProvider
*/
@Immutable
@SdkPublicApi
public final class AwsBasicCredentials implements AwsCredentials {
/**
* A set of AWS credentials without an access key or secret access key, indicating that anonymous access should be used.
*
* This should be accessed via {@link AnonymousCredentialsProvider#resolveCredentials()}.
*/
@SdkInternalApi
static final AwsBasicCredentials ANONYMOUS_CREDENTIALS = new AwsBasicCredentials(null, null, false);
private final String accessKeyId;
private final String secretAccessKey;
/**
* Constructs a new credentials object, with the specified AWS access key and AWS secret key.
*
* @param accessKeyId The AWS access key, used to identify the user interacting with AWS.
* @param secretAccessKey The AWS secret access key, used to authenticate the user interacting with AWS.
*/
protected AwsBasicCredentials(String accessKeyId, String secretAccessKey) {
this(accessKeyId, secretAccessKey, true);
}
private AwsBasicCredentials(String accessKeyId, String secretAccessKey, boolean validateCredentials) {
this.accessKeyId = trimToNull(accessKeyId);
this.secretAccessKey = trimToNull(secretAccessKey);
if (validateCredentials) {
Validate.notNull(this.accessKeyId, "Access key ID cannot be blank.");
Validate.notNull(this.secretAccessKey, "Secret access key cannot be blank.");
}
}
/**
* Constructs a new credentials object, with the specified AWS access key and AWS secret key.
*
* @param accessKeyId The AWS access key, used to identify the user interacting with AWS.
* @param secretAccessKey The AWS secret access key, used to authenticate the user interacting with AWS.
* */
public static AwsBasicCredentials create(String accessKeyId, String secretAccessKey) {
return new AwsBasicCredentials(accessKeyId, secretAccessKey);
}
/**
* Retrieve the AWS access key, used to identify the user interacting with AWS.
*/
@Override
public String accessKeyId() {
return accessKeyId;
}
/**
* Retrieve the AWS secret access key, used to authenticate the user interacting with AWS.
*/
@Override
public String secretAccessKey() {
return secretAccessKey;
}
@Override
public String toString() {
return ToString.builder("AwsCredentials")
.add("accessKeyId", accessKeyId)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsBasicCredentials that = (AwsBasicCredentials) o;
return Objects.equals(accessKeyId, that.accessKeyId) &&
Objects.equals(secretAccessKey, that.secretAccessKey);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(accessKeyId());
hashCode = 31 * hashCode + Objects.hashCode(secretAccessKey());
return hashCode;
}
}
| 1,476 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/HttpCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* A base for many credential providers within the SDK that rely on calling a remote HTTP endpoint to refresh credentials.
*
* @see InstanceProfileCredentialsProvider
* @see ContainerCredentialsProvider
*/
@SdkPublicApi
public interface HttpCredentialsProvider extends AwsCredentialsProvider, SdkAutoCloseable {
interface Builder<TypeToBuildT extends HttpCredentialsProvider, BuilderT extends Builder<?, ?>> {
/**
* Configure whether the provider should fetch credentials asynchronously in the background. If this is true,
* threads are less likely to block when credentials are loaded, but additional resources are used to maintain
* the provider.
*
* <p>By default, this is disabled.</p>
*/
BuilderT asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled);
/**
* When {@link #asyncCredentialUpdateEnabled(Boolean)} is true, this configures the name of the threads used for
* credential refreshing.
*/
BuilderT asyncThreadName(String asyncThreadName);
/**
* Override the default hostname (not path) that is used for credential refreshing. Most users do not need to modify
* this behavior, except for testing purposes where mocking the HTTP credential source would be useful.
*/
BuilderT endpoint(String endpoint);
/**
* Build the credentials provider based on the configuration on this builder.
*/
TypeToBuildT build();
}
}
| 1,477 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/EnvironmentVariableCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.SystemSettingsCredentialsProvider;
import software.amazon.awssdk.utils.SystemSetting;
import software.amazon.awssdk.utils.ToString;
/**
* {@link AwsCredentialsProvider} implementation that loads credentials from the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and
* AWS_SESSION_TOKEN environment variables.
*/
@SdkPublicApi
public final class EnvironmentVariableCredentialsProvider extends SystemSettingsCredentialsProvider {
private EnvironmentVariableCredentialsProvider() {
}
public static EnvironmentVariableCredentialsProvider create() {
return new EnvironmentVariableCredentialsProvider();
}
@Override
protected Optional<String> loadSetting(SystemSetting setting) {
// CHECKSTYLE:OFF - Customers should be able to specify a credentials provider that only looks at the environment
// variables, but not the system properties. For that reason, we're only checking the environment variable here.
return SystemSetting.getStringValueFromEnvironmentVariable(setting.environmentVariable());
// CHECKSTYLE:ON
}
@Override
public String toString() {
return ToString.create("EnvironmentVariableCredentialsProvider");
}
}
| 1,478 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/WebIdentityTokenFileCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static software.amazon.awssdk.utils.StringUtils.trim;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityCredentialsUtils;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A credential provider that will read web identity token file path, aws role arn and aws session name from system properties or
* environment variables for using web identity token credentials with STS.
* <p>
* Use of this credentials provider requires the 'sts' module to be on the classpath.
* </p>
* <p>
* StsWebIdentityTokenFileCredentialsProvider in sts package can be used instead of this class if any one of following is
* required
* <ul>
* <li>Pass a custom StsClient to the provider. </li>
* <li>Periodically update credentials </li>
* </ul>
*
* @see AwsCredentialsProvider
*/
@SdkPublicApi
public class WebIdentityTokenFileCredentialsProvider
implements AwsCredentialsProvider, SdkAutoCloseable,
ToCopyableBuilder<WebIdentityTokenFileCredentialsProvider.Builder, WebIdentityTokenFileCredentialsProvider> {
private static final Logger log = Logger.loggerFor(WebIdentityTokenFileCredentialsProvider.class);
private final AwsCredentialsProvider credentialsProvider;
private final RuntimeException loadException;
private final String roleArn;
private final String roleSessionName;
private final Path webIdentityTokenFile;
private final Boolean asyncCredentialUpdateEnabled;
private final Duration prefetchTime;
private final Duration staleTime;
private final Duration roleSessionDuration;
private WebIdentityTokenFileCredentialsProvider(BuilderImpl builder) {
AwsCredentialsProvider credentialsProvider = null;
RuntimeException loadException = null;
String roleArn = null;
String roleSessionName = null;
Path webIdentityTokenFile = null;
Boolean asyncCredentialUpdateEnabled = null;
Duration prefetchTime = null;
Duration staleTime = null;
Duration roleSessionDuration = null;
try {
webIdentityTokenFile =
builder.webIdentityTokenFile != null ? builder.webIdentityTokenFile
: Paths.get(trim(SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE
.getStringValueOrThrow()));
roleArn = builder.roleArn != null ? builder.roleArn
: trim(SdkSystemSetting.AWS_ROLE_ARN.getStringValueOrThrow());
roleSessionName =
builder.roleSessionName != null ? builder.roleSessionName
: SdkSystemSetting.AWS_ROLE_SESSION_NAME.getStringValue().orElse(null);
asyncCredentialUpdateEnabled =
builder.asyncCredentialUpdateEnabled != null ? builder.asyncCredentialUpdateEnabled : false;
prefetchTime = builder.prefetchTime;
staleTime = builder.staleTime;
roleSessionDuration = builder.roleSessionDuration;
WebIdentityTokenCredentialProperties credentialProperties =
WebIdentityTokenCredentialProperties.builder()
.roleArn(roleArn)
.roleSessionName(roleSessionName)
.webIdentityTokenFile(webIdentityTokenFile)
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.prefetchTime(prefetchTime)
.staleTime(staleTime)
.roleSessionDuration(roleSessionDuration)
.build();
credentialsProvider = WebIdentityCredentialsUtils.factory().create(credentialProperties);
} catch (RuntimeException e) {
// If we couldn't load the credentials provider for some reason, save an exception describing why. This exception
// will only be raised on calls to getCredentials. We don't want to raise an exception here because it may be
// expected (eg. in the default credential chain).
loadException = e;
}
this.loadException = loadException;
this.credentialsProvider = credentialsProvider;
this.roleArn = roleArn;
this.roleSessionName = roleSessionName;
this.webIdentityTokenFile = webIdentityTokenFile;
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
this.prefetchTime = prefetchTime;
this.staleTime = staleTime;
this.roleSessionDuration = roleSessionDuration;
}
public static WebIdentityTokenFileCredentialsProvider create() {
return WebIdentityTokenFileCredentialsProvider.builder().build();
}
@Override
public AwsCredentials resolveCredentials() {
if (loadException != null) {
throw loadException;
}
return credentialsProvider.resolveCredentials();
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public String toString() {
return ToString.create("WebIdentityTokenCredentialsProvider");
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
@Override
public void close() {
IoUtils.closeIfCloseable(credentialsProvider, null);
}
/**
* A builder for creating a custom {@link WebIdentityTokenFileCredentialsProvider}.
*/
public interface Builder extends CopyableBuilder<Builder, WebIdentityTokenFileCredentialsProvider> {
/**
* Define the role arn that should be used by this credentials provider.
*/
Builder roleArn(String roleArn);
/**
* Define the role session name that should be used by this credentials provider.
*/
Builder roleSessionName(String roleSessionName);
/**
* Define the absolute path to the web identity token file that should be used by this credentials provider.
*/
Builder webIdentityTokenFile(Path webIdentityTokenFile);
/**
* Define whether the provider should fetch credentials asynchronously in the background.
*/
Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled);
/**
* Configure the amount of time, relative to STS token expiration, that the cached credentials are considered close to
* stale and should be updated.
*
* <p>Prefetch updates will occur between the specified time and the stale time of the provider. Prefetch
* updates may be asynchronous. See {@link #asyncCredentialUpdateEnabled}.
*
* <p>By default, this is 5 minutes.
*/
Builder prefetchTime(Duration prefetchTime);
/**
* Configure the amount of time, relative to STS token expiration, that the cached credentials are considered stale and
* must be updated. All threads will block until the value is updated.
*
* <p>By default, this is 1 minute.
*/
Builder staleTime(Duration staleTime);
/**
* @param sessionDuration
* @return
*/
Builder roleSessionDuration(Duration sessionDuration);
/**
* Create a {@link WebIdentityTokenFileCredentialsProvider} using the configuration applied to this builder.
*/
WebIdentityTokenFileCredentialsProvider build();
}
static final class BuilderImpl implements Builder {
private String roleArn;
private String roleSessionName;
private Path webIdentityTokenFile;
private Boolean asyncCredentialUpdateEnabled;
private Duration prefetchTime;
private Duration staleTime;
private Duration roleSessionDuration;
BuilderImpl() {
}
private BuilderImpl(WebIdentityTokenFileCredentialsProvider provider) {
this.roleArn = provider.roleArn;
this.roleSessionName = provider.roleSessionName;
this.webIdentityTokenFile = provider.webIdentityTokenFile;
this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled;
this.prefetchTime = provider.prefetchTime;
this.staleTime = provider.staleTime;
this.roleSessionDuration = provider.roleSessionDuration;
}
@Override
public Builder roleArn(String roleArn) {
this.roleArn = roleArn;
return this;
}
public void setRoleArn(String roleArn) {
roleArn(roleArn);
}
@Override
public Builder roleSessionName(String roleSessionName) {
this.roleSessionName = roleSessionName;
return this;
}
public void setRoleSessionName(String roleSessionName) {
roleSessionName(roleSessionName);
}
@Override
public Builder webIdentityTokenFile(Path webIdentityTokenFile) {
this.webIdentityTokenFile = webIdentityTokenFile;
return this;
}
public void setWebIdentityTokenFile(Path webIdentityTokenFile) {
webIdentityTokenFile(webIdentityTokenFile);
}
@Override
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
public void setAsyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled);
}
@Override
public Builder prefetchTime(Duration prefetchTime) {
this.prefetchTime = prefetchTime;
return this;
}
public void setPrefetchTime(Duration prefetchTime) {
prefetchTime(prefetchTime);
}
@Override
public Builder staleTime(Duration staleTime) {
this.staleTime = staleTime;
return this;
}
public void setStaleTime(Duration staleTime) {
staleTime(staleTime);
}
@Override
public Builder roleSessionDuration(Duration sessionDuration) {
this.roleSessionDuration = sessionDuration;
return this;
}
public void setRoleSessionDuration(Duration roleSessionDuration) {
roleSessionDuration(roleSessionDuration);
}
@Override
public WebIdentityTokenFileCredentialsProvider build() {
return new WebIdentityTokenFileCredentialsProvider(this);
}
}
}
| 1,479 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ProfileCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.credentials.internal.ProfileCredentialsUtils;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Credentials provider based on AWS configuration profiles. This loads credentials from a {@link ProfileFile}, allowing you to
* share multiple sets of AWS security credentials between different tools like the AWS SDK for Java and the AWS CLI.
*
* <p>See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html</p>
*
* <p>If this credentials provider is loading assume-role credentials from STS, it should be cleaned up with {@link #close()} if
* it is no longer being used.</p>
*
* @see ProfileFile
*/
@SdkPublicApi
public final class ProfileCredentialsProvider
implements AwsCredentialsProvider,
SdkAutoCloseable,
ToCopyableBuilder<ProfileCredentialsProvider.Builder, ProfileCredentialsProvider> {
private volatile AwsCredentialsProvider credentialsProvider;
private final RuntimeException loadException;
private final Supplier<ProfileFile> profileFile;
private volatile ProfileFile currentProfileFile;
private final String profileName;
private final Supplier<ProfileFile> defaultProfileFileLoader;
private final Object credentialsProviderLock = new Object();
/**
* @see #builder()
*/
private ProfileCredentialsProvider(BuilderImpl builder) {
this.defaultProfileFileLoader = builder.defaultProfileFileLoader;
RuntimeException thrownException = null;
String selectedProfileName = null;
Supplier<ProfileFile> selectedProfileSupplier = null;
try {
selectedProfileName = Optional.ofNullable(builder.profileName)
.orElseGet(ProfileFileSystemSetting.AWS_PROFILE::getStringValueOrThrow);
selectedProfileSupplier = Optional.ofNullable(builder.profileFile)
.orElseGet(() -> builder.defaultProfileFileLoader);
} catch (RuntimeException e) {
// If we couldn't load the credentials provider for some reason, save an exception describing why. This exception
// will only be raised on calls to resolveCredentials. We don't want to raise an exception here because it may be
// expected (eg. in the default credential chain).
thrownException = e;
}
this.loadException = thrownException;
this.profileName = selectedProfileName;
this.profileFile = selectedProfileSupplier;
}
/**
* Create a {@link ProfileCredentialsProvider} using the {@link ProfileFile#defaultProfileFile()} and default profile name.
* Use {@link #builder()} for defining a custom {@link ProfileCredentialsProvider}.
*/
public static ProfileCredentialsProvider create() {
return builder().build();
}
/**
* Create a {@link ProfileCredentialsProvider} using the given profile name and {@link ProfileFile#defaultProfileFile()}. Use
* {@link #builder()} for defining a custom {@link ProfileCredentialsProvider}.
*
* @param profileName the name of the profile to use from the {@link ProfileFile#defaultProfileFile()}
*/
public static ProfileCredentialsProvider create(String profileName) {
return builder().profileName(profileName).build();
}
/**
* Get a builder for creating a custom {@link ProfileCredentialsProvider}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
public AwsCredentials resolveCredentials() {
if (loadException != null) {
throw loadException;
}
ProfileFile cachedOrRefreshedProfileFile = refreshProfileFile();
if (shouldUpdateCredentialsProvider(cachedOrRefreshedProfileFile)) {
synchronized (credentialsProviderLock) {
if (shouldUpdateCredentialsProvider(cachedOrRefreshedProfileFile)) {
currentProfileFile = cachedOrRefreshedProfileFile;
handleProfileFileReload(cachedOrRefreshedProfileFile);
}
}
}
return credentialsProvider.resolveCredentials();
}
private void handleProfileFileReload(ProfileFile profileFile) {
credentialsProvider = createCredentialsProvider(profileFile, profileName);
}
private ProfileFile refreshProfileFile() {
return profileFile.get();
}
private boolean shouldUpdateCredentialsProvider(ProfileFile profileFile) {
return credentialsProvider == null || !Objects.equals(currentProfileFile, profileFile);
}
@Override
public String toString() {
return ToString.builder("ProfileCredentialsProvider")
.add("profileName", profileName)
.add("profileFile", currentProfileFile)
.build();
}
@Override
public void close() {
// The delegate credentials provider may be closeable (eg. if it's an STS credentials provider). In this case, we should
// clean it up when this credentials provider is closed.
IoUtils.closeIfCloseable(credentialsProvider, null);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
private AwsCredentialsProvider createCredentialsProvider(ProfileFile profileFile, String profileName) {
// Load the profile and credentials provider
return profileFile.profile(profileName)
.flatMap(p -> new ProfileCredentialsUtils(profileFile, p, profileFile::profile).credentialsProvider())
.orElseThrow(() -> {
String errorMessage = String.format("Profile file contained no credentials for " +
"profile '%s': %s", profileName, profileFile);
return SdkClientException.builder().message(errorMessage).build();
});
}
/**
* A builder for creating a custom {@link ProfileCredentialsProvider}.
*/
public interface Builder extends CopyableBuilder<Builder, ProfileCredentialsProvider> {
/**
* Define the profile file that should be used by this credentials provider. By default, the
* {@link ProfileFile#defaultProfileFile()} is used.
* @see #profileFile(Supplier)
*/
Builder profileFile(ProfileFile profileFile);
/**
* Similar to {@link #profileFile(ProfileFile)}, but takes a lambda to configure a new {@link ProfileFile.Builder}. This
* removes the need to called {@link ProfileFile#builder()} and {@link ProfileFile.Builder#build()}.
*/
Builder profileFile(Consumer<ProfileFile.Builder> profileFile);
/**
* Define the mechanism for loading profile files.
*
* @param profileFileSupplier Supplier interface for generating a ProfileFile instance.
* @see #profileFile(ProfileFile)
*/
Builder profileFile(Supplier<ProfileFile> profileFileSupplier);
/**
* Define the name of the profile that should be used by this credentials provider. By default, the value in
* {@link ProfileFileSystemSetting#AWS_PROFILE} is used.
*/
Builder profileName(String profileName);
/**
* Create a {@link ProfileCredentialsProvider} using the configuration applied to this builder.
*/
@Override
ProfileCredentialsProvider build();
}
static final class BuilderImpl implements Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
private Supplier<ProfileFile> defaultProfileFileLoader = ProfileFile::defaultProfileFile;
BuilderImpl() {
}
BuilderImpl(ProfileCredentialsProvider provider) {
this.profileName = provider.profileName;
this.defaultProfileFileLoader = provider.defaultProfileFileLoader;
this.profileFile = provider.profileFile;
}
@Override
public Builder profileFile(ProfileFile profileFile) {
return profileFile(Optional.ofNullable(profileFile)
.map(ProfileFileSupplier::fixedProfileFile)
.orElse(null));
}
public void setProfileFile(ProfileFile profileFile) {
profileFile(profileFile);
}
@Override
public Builder profileFile(Consumer<ProfileFile.Builder> profileFile) {
return profileFile(ProfileFile.builder().applyMutation(profileFile).build());
}
@Override
public Builder profileFile(Supplier<ProfileFile> profileFileSupplier) {
this.profileFile = profileFileSupplier;
return this;
}
public void setProfileFile(Supplier<ProfileFile> supplier) {
profileFile(supplier);
}
@Override
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public void setProfileName(String profileName) {
profileName(profileName);
}
@Override
public ProfileCredentialsProvider build() {
return new ProfileCredentialsProvider(this);
}
/**
* Override the default configuration file to be used when the customer does not explicitly set
* profileFile(ProfileFile) or profileFileSupplier(supplier);
* {@link #profileFile(ProfileFile)}. Use of this method is
* only useful for testing the default behavior.
*/
@SdkTestInternalApi
Builder defaultProfileFileLoader(Supplier<ProfileFile> defaultProfileFileLoader) {
this.defaultProfileFileLoader = defaultProfileFileLoader;
return this;
}
}
}
| 1,480 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/CredentialUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.utils.CompletableFutureUtils;
@SdkProtectedApi
public final class CredentialUtils {
private CredentialUtils() {
}
/**
* Determine whether the provided credentials are anonymous credentials, indicating that the customer is not attempting to
* authenticate themselves.
*/
public static boolean isAnonymous(AwsCredentials credentials) {
return isAnonymous((AwsCredentialsIdentity) credentials);
}
/**
* Determine whether the provided credentials are anonymous credentials, indicating that the customer is not attempting to
* authenticate themselves.
*/
public static boolean isAnonymous(AwsCredentialsIdentity credentials) {
return credentials.secretAccessKey() == null && credentials.accessKeyId() == null;
}
/**
* Converts an {@link AwsCredentialsIdentity} to {@link AwsCredentials}.
*
* <p>Usage of the new AwsCredentialsIdentity type is preferred over AwsCredentials. But some places may need to still
* convert to the older AwsCredentials type to work with existing code.</p>
*
* <p>The conversion is only aware of {@link AwsCredentialsIdentity} and {@link AwsSessionCredentialsIdentity} types. If the
* input is another sub-type that has other properties, they are not carried over. i.e.,
* <ul>
* <li>AwsSessionCredentialsIdentity -> AwsSessionCredentials</li>
* <li>AwsCredentialsIdentity -> AwsBasicCredentials</li>
* </ul>
* </p>
*
* @param awsCredentialsIdentity The {@link AwsCredentialsIdentity} to convert
* @return The corresponding {@link AwsCredentials}
*/
public static AwsCredentials toCredentials(AwsCredentialsIdentity awsCredentialsIdentity) {
if (awsCredentialsIdentity == null) {
return null;
}
if (awsCredentialsIdentity instanceof AwsCredentials) {
return (AwsCredentials) awsCredentialsIdentity;
}
// identity-spi defines 2 known types - AwsCredentialsIdentity and a sub-type AwsSessionCredentialsIdentity
if (awsCredentialsIdentity instanceof AwsSessionCredentialsIdentity) {
AwsSessionCredentialsIdentity awsSessionCredentialsIdentity = (AwsSessionCredentialsIdentity) awsCredentialsIdentity;
return AwsSessionCredentials.create(awsSessionCredentialsIdentity.accessKeyId(),
awsSessionCredentialsIdentity.secretAccessKey(),
awsSessionCredentialsIdentity.sessionToken());
}
if (isAnonymous(awsCredentialsIdentity)) {
return AwsBasicCredentials.ANONYMOUS_CREDENTIALS;
}
return AwsBasicCredentials.create(awsCredentialsIdentity.accessKeyId(),
awsCredentialsIdentity.secretAccessKey());
}
/**
* Converts an {@link IdentityProvider<? extends AwsCredentialsIdentity>} to {@link AwsCredentialsProvider} based on
* {@link #toCredentials(AwsCredentialsIdentity)}.
*
* <p>Usage of the new IdentityProvider type is preferred over AwsCredentialsProvider. But some places may need to still
* convert to the older AwsCredentialsProvider type to work with existing code.
* </p>
*
* @param identityProvider The {@link IdentityProvider<? extends AwsCredentialsIdentity>} to convert
* @return The corresponding {@link AwsCredentialsProvider}
*/
public static AwsCredentialsProvider toCredentialsProvider(
IdentityProvider<? extends AwsCredentialsIdentity> identityProvider) {
if (identityProvider == null) {
return null;
}
if (identityProvider instanceof AwsCredentialsProvider) {
return (AwsCredentialsProvider) identityProvider;
}
return () -> {
AwsCredentialsIdentity awsCredentialsIdentity =
CompletableFutureUtils.joinLikeSync(identityProvider.resolveIdentity());
return toCredentials(awsCredentialsIdentity);
};
}
}
| 1,481 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsCredentials.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
/**
* Provides access to the AWS credentials used for accessing services: AWS access key ID and secret access key. These
* credentials are used to securely sign requests to services (e.g., AWS services) that use them for authentication.
*
* <p>For more details on AWS access keys, see:
* <a href="https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys">
* https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys</a></p>
*
* @see AwsCredentialsProvider
*/
@SdkPublicApi
public interface AwsCredentials extends AwsCredentialsIdentity {
}
| 1,482 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ProfileProviderCredentialsContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
/**
* Context class that defines the required properties for creation of a Credentials provider.
*/
@SdkProtectedApi
public final class ProfileProviderCredentialsContext {
private final Profile profile;
private final ProfileFile profileFile;
private ProfileProviderCredentialsContext(Profile profile, ProfileFile profileFile) {
this.profile = profile;
this.profileFile = profileFile;
}
public static Builder builder() {
return new Builder();
}
/**
* Getter method for profile.
* @return The profile that should be used to load the configuration necessary to create the credential provider.
*/
public Profile profile() {
return profile;
}
/**
* Getter for profileFile.
* @return ProfileFile that has the profile which is used to create the credential provider.
*/
public ProfileFile profileFile() {
return profileFile;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProfileProviderCredentialsContext that = (ProfileProviderCredentialsContext) o;
return Objects.equals(profile, that.profile) && Objects.equals(profileFile, that.profileFile);
}
@Override
public int hashCode() {
int result = profile != null ? profile.hashCode() : 0;
result = 31 * result + (profileFile != null ? profileFile.hashCode() : 0);
return result;
}
public static final class Builder {
private Profile profile;
private ProfileFile profileFile;
private Builder() {
}
/**
* Builder interface to set profile.
* @param profile The profile that should be used to load the configuration necessary to create the credential provider.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder profile(Profile profile) {
this.profile = profile;
return this;
}
/**
* Builder interface to set ProfileFile.
* @param profileFile The ProfileFile that has the profile which is used to create the credential provider. This is *
* required to fetch the titles like sso-session defined in profile property* *
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder profileFile(ProfileFile profileFile) {
this.profileFile = profileFile;
return this;
}
public ProfileProviderCredentialsContext build() {
return new ProfileProviderCredentialsContext(profile, profileFile);
}
}
}
| 1,483 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsCredentialsProviderChain.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* {@link AwsCredentialsProvider} implementation that chains together multiple credentials providers.
*
* <p>When a caller first requests credentials from this provider, it calls all the providers in the chain, in the original order
* specified, until one can provide credentials, and then returns those credentials. If all of the credential providers in the
* chain have been called, and none of them can provide credentials, then this class will throw an exception indicated that no
* credentials are available.</p>
*
* <p>By default, this class will remember the first credentials provider in the chain that was able to provide credentials, and
* will continue to use that provider when credentials are requested in the future, instead of traversing the chain each time.
* This behavior can be controlled through the {@link Builder#reuseLastProviderEnabled(Boolean)} method.</p>
*
* <p>This chain implements {@link AutoCloseable}. When closed, it will call the {@link AutoCloseable#close()} on any credential
* providers in the chain that need to be closed.</p>
*/
@SdkPublicApi
public final class AwsCredentialsProviderChain
implements AwsCredentialsProvider,
SdkAutoCloseable,
ToCopyableBuilder<AwsCredentialsProviderChain.Builder, AwsCredentialsProviderChain> {
private static final Logger log = Logger.loggerFor(AwsCredentialsProviderChain.class);
private final List<IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders;
private final boolean reuseLastProviderEnabled;
private volatile IdentityProvider<? extends AwsCredentialsIdentity> lastUsedProvider;
/**
* @see #builder()
*/
private AwsCredentialsProviderChain(BuilderImpl builder) {
Validate.notEmpty(builder.credentialsProviders, "No credential providers were specified.");
this.reuseLastProviderEnabled = builder.reuseLastProviderEnabled;
this.credentialsProviders = Collections.unmodifiableList(builder.credentialsProviders);
}
/**
* Get a new builder for creating a {@link AwsCredentialsProviderChain}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create an AWS credentials provider chain with default configuration that checks the given credential providers.
* @param awsCredentialsProviders The credentials providers that should be checked for credentials, in the order they should
* be checked.
* @return A credential provider chain that checks the provided credential providers in order.
*/
public static AwsCredentialsProviderChain of(AwsCredentialsProvider... awsCredentialsProviders) {
return builder().credentialsProviders(awsCredentialsProviders).build();
}
/**
* Create an AWS credentials provider chain with default configuration that checks the given credential providers.
* @param awsCredentialsProviders The credentials providers that should be checked for credentials, in the order they should
* be checked.
* @return A credential provider chain that checks the provided credential providers in order.
*/
public static AwsCredentialsProviderChain of(IdentityProvider<? extends AwsCredentialsIdentity>... awsCredentialsProviders) {
return builder().credentialsProviders(awsCredentialsProviders).build();
}
@Override
public AwsCredentials resolveCredentials() {
if (reuseLastProviderEnabled && lastUsedProvider != null) {
return CredentialUtils.toCredentials(CompletableFutureUtils.joinLikeSync(lastUsedProvider.resolveIdentity()));
}
List<String> exceptionMessages = null;
for (IdentityProvider<? extends AwsCredentialsIdentity> provider : credentialsProviders) {
try {
AwsCredentialsIdentity credentials = CompletableFutureUtils.joinLikeSync(provider.resolveIdentity());
log.debug(() -> "Loading credentials from " + provider);
lastUsedProvider = provider;
return CredentialUtils.toCredentials(credentials);
} catch (RuntimeException e) {
// Ignore any exceptions and move onto the next provider
String message = provider + ": " + e.getMessage();
log.debug(() -> "Unable to load credentials from " + message , e);
if (exceptionMessages == null) {
exceptionMessages = new ArrayList<>();
}
exceptionMessages.add(message);
}
}
throw SdkClientException.builder()
.message("Unable to load credentials from any of the providers in the chain " +
this + " : " + exceptionMessages)
.build();
}
@Override
public void close() {
credentialsProviders.forEach(c -> IoUtils.closeIfCloseable(c, null));
}
@Override
public String toString() {
return ToString.builder("AwsCredentialsProviderChain")
.add("credentialsProviders", credentialsProviders)
.build();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
/**
* A builder for a {@link AwsCredentialsProviderChain} that allows controlling its behavior.
*/
public interface Builder extends CopyableBuilder<Builder, AwsCredentialsProviderChain> {
/**
* Controls whether the chain should reuse the last successful credentials provider in the chain. Reusing the last
* successful credentials provider will typically return credentials faster than searching through the chain.
*
* <p>
* By default, this is enabled
*/
Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled);
/**
* Configure the credentials providers that should be checked for credentials, in the order they should be checked.
*/
Builder credentialsProviders(Collection<? extends AwsCredentialsProvider> credentialsProviders);
/**
* Configure the credentials providers that should be checked for credentials, in the order they should be checked.
*/
Builder credentialsIdentityProviders(
Collection<? extends IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders);
/**
* Configure the credentials providers that should be checked for credentials, in the order they should be checked.
*/
default Builder credentialsProviders(AwsCredentialsProvider... credentialsProviders) {
return credentialsProviders((IdentityProvider<? extends AwsCredentialsIdentity>[]) credentialsProviders);
}
/**
* Configure the credentials providers that should be checked for credentials, in the order they should be checked.
*/
default Builder credentialsProviders(IdentityProvider<? extends AwsCredentialsIdentity>... credentialsProviders) {
throw new UnsupportedOperationException();
}
/**
* Add a credential provider to the chain, after the credential providers that have already been configured.
*/
default Builder addCredentialsProvider(AwsCredentialsProvider credentialsProvider) {
return addCredentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider);
}
/**
* Add a credential provider to the chain, after the credential providers that have already been configured.
*/
default Builder addCredentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
throw new UnsupportedOperationException();
}
AwsCredentialsProviderChain build();
}
private static final class BuilderImpl implements Builder {
private Boolean reuseLastProviderEnabled = true;
private List<IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders = new ArrayList<>();
private BuilderImpl() {
}
private BuilderImpl(AwsCredentialsProviderChain provider) {
this.reuseLastProviderEnabled = provider.reuseLastProviderEnabled;
this.credentialsProviders = provider.credentialsProviders;
}
@Override
public Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
this.reuseLastProviderEnabled = reuseLastProviderEnabled;
return this;
}
public void setReuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
reuseLastProviderEnabled(reuseLastProviderEnabled);
}
@Override
public Builder credentialsProviders(Collection<? extends AwsCredentialsProvider> credentialsProviders) {
this.credentialsProviders = new ArrayList<>(credentialsProviders);
return this;
}
public void setCredentialsProviders(Collection<? extends AwsCredentialsProvider> credentialsProviders) {
credentialsProviders(credentialsProviders);
}
@Override
public Builder credentialsIdentityProviders(
Collection<? extends IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders) {
this.credentialsProviders = new ArrayList<>(credentialsProviders);
return this;
}
public void setCredentialsIdentityProviders(
Collection<? extends IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders) {
credentialsIdentityProviders(credentialsProviders);
}
@Override
public Builder credentialsProviders(IdentityProvider<? extends AwsCredentialsIdentity>... credentialsProviders) {
return credentialsIdentityProviders(Arrays.asList(credentialsProviders));
}
@Override
public Builder addCredentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
this.credentialsProviders.add(credentialsProvider);
return this;
}
@Override
public AwsCredentialsProviderChain build() {
return new AwsCredentialsProviderChain(this);
}
}
}
| 1,484 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/TokenUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.TokenIdentity;
import software.amazon.awssdk.utils.CompletableFutureUtils;
@SdkProtectedApi
public final class TokenUtils {
private TokenUtils() {
}
/**
* Converts an {@link TokenIdentity} to {@link SdkToken}.
*
* <p>Usage of the new TokenIdentity type is preferred over SdkToken. But some places may need to still
* convert to the older SdkToken type to work with existing code.</p>
*
* <p>The conversion is only aware of {@link TokenIdentity} interface. If the input is another sub-type that has other
* properties, they are not carried over.
* </p>
*
* @param tokenIdentity The {@link TokenIdentity} to convert
* @return The corresponding {@link SdkToken}
*/
public static SdkToken toSdkToken(TokenIdentity tokenIdentity) {
if (tokenIdentity == null) {
return null;
}
if (tokenIdentity instanceof SdkToken) {
return (SdkToken) tokenIdentity;
}
return () -> tokenIdentity.token();
}
/**
* Converts an {@link IdentityProvider<? extends TokenIdentity>} to {@link SdkTokenProvider} based on
* {@link #toSdkToken(TokenIdentity)}.
*
* <p>Usage of the new IdentityProvider type is preferred over SdkTokenProvider. But some places may need to still
* convert to the older SdkTokenProvider type to work with existing code.
* </p>
*
* @param identityProvider The {@link IdentityProvider<? extends TokenIdentity>} to convert
* @return The corresponding {@link SdkTokenProvider}
*/
public static SdkTokenProvider toSdkTokenProvider(
IdentityProvider<? extends TokenIdentity> identityProvider) {
if (identityProvider == null) {
return null;
}
if (identityProvider instanceof SdkTokenProvider) {
return (SdkTokenProvider) identityProvider;
}
return () -> toSdkToken(CompletableFutureUtils.joinLikeSync(identityProvider.resolveIdentity()));
}
}
| 1,485 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/SystemPropertyCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.SystemSettingsCredentialsProvider;
import software.amazon.awssdk.utils.SystemSetting;
import software.amazon.awssdk.utils.ToString;
/**
* {@link AwsCredentialsProvider} implementation that loads credentials from the aws.accessKeyId, aws.secretAccessKey and
* aws.sessionToken system properties.
*/
@SdkPublicApi
public final class SystemPropertyCredentialsProvider extends SystemSettingsCredentialsProvider {
private SystemPropertyCredentialsProvider() {
}
public static SystemPropertyCredentialsProvider create() {
return new SystemPropertyCredentialsProvider();
}
@Override
protected Optional<String> loadSetting(SystemSetting setting) {
// CHECKSTYLE:OFF - Customers should be able to specify a credentials provider that only looks at the system properties,
// but not the environment variables. For that reason, we're only checking the system properties here.
return Optional.ofNullable(System.getProperty(setting.property()));
// CHECKSTYLE:ON
}
@Override
public String toString() {
return ToString.create("SystemPropertyCredentialsProvider");
}
}
| 1,486 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ChildProfileCredentialsProviderFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.profiles.Profile;
/**
* A factory for {@link AwsCredentialsProvider}s that are derived from another set of credentials in a profile file.
*
* Currently this is used to allow a {@link Profile} configured with a role that should be assumed to create a credentials
* provider via the 'software.amazon.awssdk.services.sts.internal.StsProfileCredentialsProviderFactory', assuming STS is on the
* classpath.
*/
@FunctionalInterface
@SdkProtectedApi
public interface ChildProfileCredentialsProviderFactory {
/**
* Create a credentials provider for the provided profile, using the provided source credentials provider to authenticate
* with AWS. In the case of STS, the returned credentials provider is for a role that has been assumed, and the provided
* source credentials provider is the credentials that should be used to authenticate that the user is allowed to assume
* that role.
*
* @param sourceCredentialsProvider The credentials provider that should be used to authenticate the child credentials
* provider. This credentials provider should be closed when it is no longer used.
* @param profile The profile that should be used to load the configuration necessary to create the child credentials
* provider.
* @return The credentials provider with permissions derived from the source credentials provider and profile.
*/
AwsCredentialsProvider create(AwsCredentialsProvider sourceCredentialsProvider, Profile profile);
}
| 1,487 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AnonymousCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
/**
* Credentials provider that always returns anonymous {@link AwsCredentials}. Anonymous AWS credentials result in un-authenticated
* requests and will fail unless the resource or API's policy has been configured to specifically allow anonymous access.
*/
@SdkPublicApi
public final class AnonymousCredentialsProvider implements AwsCredentialsProvider {
private AnonymousCredentialsProvider() {
}
public static AnonymousCredentialsProvider create() {
return new AnonymousCredentialsProvider();
}
@Override
public AwsCredentials resolveCredentials() {
return AwsBasicCredentials.ANONYMOUS_CREDENTIALS;
}
@Override
public String toString() {
return ToString.create("AnonymousCredentialsProvider");
}
}
| 1,488 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ContainerCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.ContainerCredentialsRetryPolicy;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader.LoadedCredentials;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.util.SdkUserAgent;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.regions.util.ResourcesEndpointRetryPolicy;
import software.amazon.awssdk.utils.ComparableUtils;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* {@link AwsCredentialsProvider} implementation that loads credentials from a local metadata service.
*
* Currently supported containers:
* <ul>
* <li>Amazon Elastic Container Service (ECS)</li>
* <li>AWS Greengrass</li>
* </ul>
*
* <p>The URI path is retrieved from the environment variable "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" or
* "AWS_CONTAINER_CREDENTIALS_FULL_URI" in the container's environment. If the environment variable is not set, this credentials
* provider will throw an exception.</p>
*
* @see <a href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html">Amazon Elastic Container
* Service (ECS)</a>
*/
@SdkPublicApi
public final class ContainerCredentialsProvider
implements HttpCredentialsProvider,
ToCopyableBuilder<ContainerCredentialsProvider.Builder, ContainerCredentialsProvider> {
private static final Predicate<InetAddress> IS_LOOPBACK_ADDRESS = InetAddress::isLoopbackAddress;
private static final Predicate<InetAddress> ALLOWED_HOSTS_RULES = IS_LOOPBACK_ADDRESS;
private static final String HTTPS = "https";
private final String endpoint;
private final HttpCredentialsLoader httpCredentialsLoader;
private final CachedSupplier<AwsCredentials> credentialsCache;
private final Boolean asyncCredentialUpdateEnabled;
private final String asyncThreadName;
/**
* @see #builder()
*/
private ContainerCredentialsProvider(BuilderImpl builder) {
this.endpoint = builder.endpoint;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.asyncThreadName = builder.asyncThreadName;
this.httpCredentialsLoader = HttpCredentialsLoader.create();
if (Boolean.TRUE.equals(builder.asyncCredentialUpdateEnabled)) {
Validate.paramNotBlank(builder.asyncThreadName, "asyncThreadName");
this.credentialsCache = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString())
.prefetchStrategy(new NonBlocking(builder.asyncThreadName))
.build();
} else {
this.credentialsCache = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString())
.build();
}
}
/**
* Create a builder for creating a {@link ContainerCredentialsProvider}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
public String toString() {
return ToString.create("ContainerCredentialsProvider");
}
private RefreshResult<AwsCredentials> refreshCredentials() {
LoadedCredentials loadedCredentials =
httpCredentialsLoader.loadCredentials(new ContainerCredentialsEndpointProvider(endpoint));
Instant expiration = loadedCredentials.getExpiration().orElse(null);
return RefreshResult.builder(loadedCredentials.getAwsCredentials())
.staleTime(staleTime(expiration))
.prefetchTime(prefetchTime(expiration))
.build();
}
private Instant staleTime(Instant expiration) {
if (expiration == null) {
return null;
}
return expiration.minus(1, ChronoUnit.MINUTES);
}
private Instant prefetchTime(Instant expiration) {
Instant oneHourFromNow = Instant.now().plus(1, ChronoUnit.HOURS);
if (expiration == null) {
return oneHourFromNow;
}
Instant fifteenMinutesBeforeExpiration = expiration.minus(15, ChronoUnit.MINUTES);
return ComparableUtils.minimum(oneHourFromNow, fifteenMinutesBeforeExpiration);
}
@Override
public AwsCredentials resolveCredentials() {
return credentialsCache.get();
}
@Override
public void close() {
credentialsCache.close();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
static final class ContainerCredentialsEndpointProvider implements ResourcesEndpointProvider {
private final String endpoint;
ContainerCredentialsEndpointProvider(String endpoint) {
this.endpoint = endpoint;
}
@Override
public URI endpoint() throws IOException {
if (!SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.getStringValue().isPresent() &&
!SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI.getStringValue().isPresent()) {
throw SdkClientException.builder()
.message(String.format("Cannot fetch credentials from container - neither %s or %s " +
"environment variables are set.",
SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(),
SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.environmentVariable()))
.build();
}
try {
return SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.getStringValue()
.map(this::createUri)
.orElseGet(this::createGenericContainerUrl);
} catch (SdkClientException e) {
throw e;
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to fetch credentials from container.")
.cause(e)
.build();
}
}
@Override
public ResourcesEndpointRetryPolicy retryPolicy() {
return new ContainerCredentialsRetryPolicy();
}
@Override
public Map<String, String> headers() {
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("User-Agent", SdkUserAgent.create().userAgent());
SdkSystemSetting.AWS_CONTAINER_AUTHORIZATION_TOKEN.getStringValue()
.filter(StringUtils::isNotBlank)
.ifPresent(t -> requestHeaders.put("Authorization", t));
return requestHeaders;
}
private URI createUri(String relativeUri) {
String host = endpoint != null ? endpoint : SdkSystemSetting.AWS_CONTAINER_SERVICE_ENDPOINT.getStringValueOrThrow();
return URI.create(host + relativeUri);
}
private URI createGenericContainerUrl() {
URI uri = URI.create(SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI.getStringValueOrThrow());
if (!isHttps(uri) && !isAllowedHost(uri.getHost())) {
String envVarName = SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable();
throw SdkClientException.builder()
.message(String.format("The full URI (%s) contained within environment variable " +
"%s has an invalid host. Host should resolve to a loopback " +
"address or have the full URI be HTTPS.",
uri, envVarName))
.build();
}
return uri;
}
private boolean isHttps(URI endpoint) {
return Objects.equals(HTTPS, endpoint.getScheme());
}
/**
* Determines if the addresses for a given host are resolved to a loopback address.
* <p>
* This is a best-effort in determining what address a host will be resolved to. DNS caching might be disabled,
* or could expire between this check and when the API is invoked.
* </p>
* @param host The name or IP address of the host.
* @return A boolean specifying whether the host is allowed as an endpoint for credentials loading.
*/
private boolean isAllowedHost(String host) {
try {
InetAddress[] addresses = InetAddress.getAllByName(host);
return addresses.length > 0 && Arrays.stream(addresses)
.allMatch(this::matchesAllowedHostRules);
} catch (UnknownHostException e) {
throw SdkClientException.builder()
.cause(e)
.message(String.format("host (%s) could not be resolved to an IP address.", host))
.build();
}
}
private boolean matchesAllowedHostRules(InetAddress inetAddress) {
return ALLOWED_HOSTS_RULES.test(inetAddress);
}
}
/**
* A builder for creating a custom a {@link ContainerCredentialsProvider}.
*/
public interface Builder extends HttpCredentialsProvider.Builder<ContainerCredentialsProvider, Builder>,
CopyableBuilder<Builder, ContainerCredentialsProvider> {
}
private static final class BuilderImpl implements Builder {
private String endpoint;
private Boolean asyncCredentialUpdateEnabled;
private String asyncThreadName;
private BuilderImpl() {
asyncThreadName("container-credentials-provider");
}
private BuilderImpl(ContainerCredentialsProvider credentialsProvider) {
this.endpoint = credentialsProvider.endpoint;
this.asyncCredentialUpdateEnabled = credentialsProvider.asyncCredentialUpdateEnabled;
this.asyncThreadName = credentialsProvider.asyncThreadName;
}
@Override
public Builder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public void setEndpoint(String endpoint) {
endpoint(endpoint);
}
@Override
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
public void setAsyncCredentialUpdateEnabled(boolean asyncCredentialUpdateEnabled) {
asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled);
}
@Override
public Builder asyncThreadName(String asyncThreadName) {
this.asyncThreadName = asyncThreadName;
return this;
}
public void setAsyncThreadName(String asyncThreadName) {
asyncThreadName(asyncThreadName);
}
@Override
public ContainerCredentialsProvider build() {
return new ContainerCredentialsProvider(this);
}
}
}
| 1,489 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsSessionCredentials.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A special type of {@link AwsCredentials} that provides a session token to be used in service authentication. Session
* tokens are typically provided by a token broker service, like AWS Security Token Service, and provide temporary access to an
* AWS service.
*/
@Immutable
@SdkPublicApi
public final class AwsSessionCredentials implements AwsCredentials, AwsSessionCredentialsIdentity {
private final String accessKeyId;
private final String secretAccessKey;
private final String sessionToken;
private final Instant expirationTime;
private AwsSessionCredentials(Builder builder) {
this.accessKeyId = Validate.paramNotNull(builder.accessKeyId, "accessKey");
this.secretAccessKey = Validate.paramNotNull(builder.secretAccessKey, "secretKey");
this.sessionToken = Validate.paramNotNull(builder.sessionToken, "sessionToken");
this.expirationTime = builder.expirationTime;
}
/**
* Returns a builder for this object.
*/
public static Builder builder() {
return new Builder();
}
/**
* Constructs a new session credentials object, with the specified AWS access key, AWS secret key and AWS session token.
*
* @param accessKey The AWS access key, used to identify the user interacting with AWS.
* @param secretKey The AWS secret access key, used to authenticate the user interacting with AWS.
* @param sessionToken The AWS session token, retrieved from an AWS token service, used for authenticating that this user has
* received temporary permission to access some resource.
*/
public static AwsSessionCredentials create(String accessKey, String secretKey, String sessionToken) {
return builder().accessKeyId(accessKey).secretAccessKey(secretKey).sessionToken(sessionToken).build();
}
/**
* Retrieve the AWS access key, used to identify the user interacting with AWS.
*/
@Override
public String accessKeyId() {
return accessKeyId;
}
/**
* Retrieve the AWS secret access key, used to authenticate the user interacting with AWS.
*/
@Override
public String secretAccessKey() {
return secretAccessKey;
}
/**
* Retrieve the expiration time of these credentials, if it exists.
*/
@Override
public Optional<Instant> expirationTime() {
return Optional.ofNullable(expirationTime);
}
/**
* Retrieve the AWS session token. This token is retrieved from an AWS token service, and is used for authenticating that this
* user has received temporary permission to access some resource.
*/
public String sessionToken() {
return sessionToken;
}
@Override
public String toString() {
return ToString.builder("AwsSessionCredentials")
.add("accessKeyId", accessKeyId())
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsSessionCredentials that = (AwsSessionCredentials) o;
return Objects.equals(accessKeyId, that.accessKeyId) &&
Objects.equals(secretAccessKey, that.secretAccessKey) &&
Objects.equals(sessionToken, that.sessionToken) &&
Objects.equals(expirationTime, that.expirationTime().orElse(null));
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(accessKeyId());
hashCode = 31 * hashCode + Objects.hashCode(secretAccessKey());
hashCode = 31 * hashCode + Objects.hashCode(sessionToken());
hashCode = 31 * hashCode + Objects.hashCode(expirationTime);
return hashCode;
}
/**
* A builder for creating an instance of {@link AwsSessionCredentials}. This can be created with the static
* {@link #builder()} method.
*/
public static final class Builder {
private String accessKeyId;
private String secretAccessKey;
private String sessionToken;
private Instant expirationTime;
/**
* The AWS access key, used to identify the user interacting with services. Required.
*/
public Builder accessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
return this;
}
/**
* The AWS secret access key, used to authenticate the user interacting with services. Required
*/
public Builder secretAccessKey(String secretAccessKey) {
this.secretAccessKey = secretAccessKey;
return this;
}
/**
* The AWS session token, retrieved from an AWS token service, used for authenticating that this user has
* received temporary permission to access some resource. Required
*/
public Builder sessionToken(String sessionToken) {
this.sessionToken = sessionToken;
return this;
}
/**
* The time after which this identity will no longer be valid. If this is empty,
* an expiration time is not known (but the identity may still expire at some
* time in the future).
*/
public Builder expirationTime(Instant expirationTime) {
this.expirationTime = expirationTime;
return this;
}
public AwsSessionCredentials build() {
return new AwsSessionCredentials(this);
}
}
}
| 1,490 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/InstanceProfileCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials;
import static java.time.temporal.ChronoUnit.MINUTES;
import static software.amazon.awssdk.utils.ComparableUtils.maximum;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.cache.CachedSupplier.StaleValueBehavior.ALLOW;
import java.net.URI;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.credentials.internal.Ec2MetadataConfigProvider;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader.LoadedCredentials;
import software.amazon.awssdk.auth.credentials.internal.StaticResourcesEndpointProvider;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.regions.util.HttpResourcesUtils;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* Credentials provider implementation that loads credentials from the Amazon EC2 Instance Metadata Service.
*
* <P>
* If {@link SdkSystemSetting#AWS_EC2_METADATA_DISABLED} is set to true, it will not try to load
* credentials from EC2 metadata service and will return null.
*/
@SdkPublicApi
public final class InstanceProfileCredentialsProvider
implements HttpCredentialsProvider,
ToCopyableBuilder<InstanceProfileCredentialsProvider.Builder, InstanceProfileCredentialsProvider> {
private static final Logger log = Logger.loggerFor(InstanceProfileCredentialsProvider.class);
private static final String EC2_METADATA_TOKEN_HEADER = "x-aws-ec2-metadata-token";
private static final String SECURITY_CREDENTIALS_RESOURCE = "/latest/meta-data/iam/security-credentials/";
private static final String TOKEN_RESOURCE = "/latest/api/token";
private static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds";
private static final String DEFAULT_TOKEN_TTL = "21600";
private final Clock clock;
private final String endpoint;
private final Ec2MetadataConfigProvider configProvider;
private final HttpCredentialsLoader httpCredentialsLoader;
private final CachedSupplier<AwsCredentials> credentialsCache;
private final Boolean asyncCredentialUpdateEnabled;
private final String asyncThreadName;
private final Supplier<ProfileFile> profileFile;
private final String profileName;
/**
* @see #builder()
*/
private InstanceProfileCredentialsProvider(BuilderImpl builder) {
this.clock = builder.clock;
this.endpoint = builder.endpoint;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.asyncThreadName = builder.asyncThreadName;
this.profileFile = builder.profileFile;
this.profileName = builder.profileName;
this.httpCredentialsLoader = HttpCredentialsLoader.create();
this.configProvider =
Ec2MetadataConfigProvider.builder()
.profileFile(builder.profileFile)
.profileName(builder.profileName)
.build();
if (Boolean.TRUE.equals(builder.asyncCredentialUpdateEnabled)) {
Validate.paramNotBlank(builder.asyncThreadName, "asyncThreadName");
this.credentialsCache = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString())
.prefetchStrategy(new NonBlocking(builder.asyncThreadName))
.staleValueBehavior(ALLOW)
.clock(clock)
.build();
} else {
this.credentialsCache = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString())
.staleValueBehavior(ALLOW)
.clock(clock)
.build();
}
}
/**
* Create a builder for creating a {@link InstanceProfileCredentialsProvider}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create a {@link InstanceProfileCredentialsProvider} with default values.
*
* @return a {@link InstanceProfileCredentialsProvider}
*/
public static InstanceProfileCredentialsProvider create() {
return builder().build();
}
@Override
public AwsCredentials resolveCredentials() {
return credentialsCache.get();
}
private RefreshResult<AwsCredentials> refreshCredentials() {
if (isLocalCredentialLoadingDisabled()) {
throw SdkClientException.create("IMDS credentials have been disabled by environment variable or system property.");
}
try {
LoadedCredentials credentials = httpCredentialsLoader.loadCredentials(createEndpointProvider());
Instant expiration = credentials.getExpiration().orElse(null);
log.debug(() -> "Loaded credentials from IMDS with expiration time of " + expiration);
return RefreshResult.builder(credentials.getAwsCredentials())
.staleTime(staleTime(expiration))
.prefetchTime(prefetchTime(expiration))
.build();
} catch (RuntimeException e) {
throw SdkClientException.create("Failed to load credentials from IMDS.", e);
}
}
private boolean isLocalCredentialLoadingDisabled() {
return SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow();
}
private Instant staleTime(Instant expiration) {
if (expiration == null) {
return null;
}
return expiration.minusSeconds(1);
}
private Instant prefetchTime(Instant expiration) {
Instant now = clock.instant();
if (expiration == null) {
return now.plus(60, MINUTES);
}
Duration timeUntilExpiration = Duration.between(now, expiration);
if (timeUntilExpiration.isNegative()) {
// IMDS gave us a time in the past. We're already stale. Don't prefetch.
return null;
}
return now.plus(maximum(timeUntilExpiration.dividedBy(2), Duration.ofMinutes(5)));
}
@Override
public void close() {
credentialsCache.close();
}
@Override
public String toString() {
return ToString.create("InstanceProfileCredentialsProvider");
}
private ResourcesEndpointProvider createEndpointProvider() {
String imdsHostname = getImdsEndpoint();
String token = getToken(imdsHostname);
String[] securityCredentials = getSecurityCredentials(imdsHostname, token);
return new StaticResourcesEndpointProvider(URI.create(imdsHostname + SECURITY_CREDENTIALS_RESOURCE +
securityCredentials[0]),
getTokenHeaders(token));
}
private String getImdsEndpoint() {
if (endpoint != null) {
return endpoint;
}
return configProvider.getEndpoint();
}
private String getToken(String imdsHostname) {
Map<String, String> tokenTtlHeaders = Collections.singletonMap(EC2_METADATA_TOKEN_TTL_HEADER, DEFAULT_TOKEN_TTL);
ResourcesEndpointProvider tokenEndpoint = new StaticResourcesEndpointProvider(getTokenEndpoint(imdsHostname),
tokenTtlHeaders);
try {
return HttpResourcesUtils.instance().readResource(tokenEndpoint, "PUT");
} catch (SdkServiceException e) {
if (e.statusCode() == 400) {
throw SdkClientException.builder()
.message("Unable to fetch metadata token.")
.cause(e)
.build();
}
log.debug(() -> "Ignoring non-fatal exception while attempting to load metadata token from instance profile.", e);
return null;
} catch (Exception e) {
log.debug(() -> "Ignoring non-fatal exception while attempting to load metadata token from instance profile.", e);
return null;
}
}
private URI getTokenEndpoint(String imdsHostname) {
String finalHost = imdsHostname;
if (finalHost.endsWith("/")) {
finalHost = finalHost.substring(0, finalHost.length() - 1);
}
return URI.create(finalHost + TOKEN_RESOURCE);
}
private String[] getSecurityCredentials(String imdsHostname, String metadataToken) {
ResourcesEndpointProvider securityCredentialsEndpoint =
new StaticResourcesEndpointProvider(URI.create(imdsHostname + SECURITY_CREDENTIALS_RESOURCE),
getTokenHeaders(metadataToken));
String securityCredentialsList =
invokeSafely(() -> HttpResourcesUtils.instance().readResource(securityCredentialsEndpoint));
String[] securityCredentials = securityCredentialsList.trim().split("\n");
if (securityCredentials.length == 0) {
throw SdkClientException.builder().message("Unable to load credentials path").build();
}
return securityCredentials;
}
private Map<String, String> getTokenHeaders(String metadataToken) {
if (metadataToken == null) {
return Collections.emptyMap();
}
return Collections.singletonMap(EC2_METADATA_TOKEN_HEADER, metadataToken);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
/**
* A builder for creating a custom a {@link InstanceProfileCredentialsProvider}.
*/
public interface Builder extends HttpCredentialsProvider.Builder<InstanceProfileCredentialsProvider, Builder>,
CopyableBuilder<Builder, InstanceProfileCredentialsProvider> {
/**
* Configure the profile file used for loading IMDS-related configuration, like the endpoint mode (IPv4 vs IPv6).
*
* <p>By default, {@link ProfileFile#defaultProfileFile()} is used.
*
* @see #profileFile(Supplier)
*/
Builder profileFile(ProfileFile profileFile);
/**
* Define the mechanism for loading profile files.
*
* @param profileFileSupplier Supplier interface for generating a ProfileFile instance.
* @see #profileFile(ProfileFile)
*/
Builder profileFile(Supplier<ProfileFile> profileFileSupplier);
/**
* Configure the profile name used for loading IMDS-related configuration, like the endpoint mode (IPv4 vs IPv6).
*
* <p>By default, {@link ProfileFileSystemSetting#AWS_PROFILE} is used.
*/
Builder profileName(String profileName);
/**
* Build a {@link InstanceProfileCredentialsProvider} from the provided configuration.
*/
@Override
InstanceProfileCredentialsProvider build();
}
@SdkTestInternalApi
static final class BuilderImpl implements Builder {
private Clock clock = Clock.systemUTC();
private String endpoint;
private Boolean asyncCredentialUpdateEnabled;
private String asyncThreadName;
private Supplier<ProfileFile> profileFile;
private String profileName;
private BuilderImpl() {
asyncThreadName("instance-profile-credentials-provider");
}
private BuilderImpl(InstanceProfileCredentialsProvider provider) {
this.clock = provider.clock;
this.endpoint = provider.endpoint;
this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled;
this.asyncThreadName = provider.asyncThreadName;
this.profileFile = provider.profileFile;
this.profileName = provider.profileName;
}
Builder clock(Clock clock) {
this.clock = clock;
return this;
}
@Override
public Builder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public void setEndpoint(String endpoint) {
endpoint(endpoint);
}
@Override
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
public void setAsyncCredentialUpdateEnabled(boolean asyncCredentialUpdateEnabled) {
asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled);
}
@Override
public Builder asyncThreadName(String asyncThreadName) {
this.asyncThreadName = asyncThreadName;
return this;
}
public void setAsyncThreadName(String asyncThreadName) {
asyncThreadName(asyncThreadName);
}
@Override
public Builder profileFile(ProfileFile profileFile) {
return profileFile(Optional.ofNullable(profileFile)
.map(ProfileFileSupplier::fixedProfileFile)
.orElse(null));
}
public void setProfileFile(ProfileFile profileFile) {
profileFile(profileFile);
}
@Override
public Builder profileFile(Supplier<ProfileFile> profileFileSupplier) {
this.profileFile = profileFileSupplier;
return this;
}
public void setProfileFile(Supplier<ProfileFile> profileFileSupplier) {
profileFile(profileFileSupplier);
}
@Override
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public void setProfileName(String profileName) {
profileName(profileName);
}
@Override
public InstanceProfileCredentialsProvider build() {
return new InstanceProfileCredentialsProvider(this);
}
}
}
| 1,491 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/Ec2MetadataConfigProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
@SdkInternalApi
// TODO: Remove or consolidate this class with the one from the regions module.
// There's currently no good way for both auth and regions to share the same
// class since there's no suitable common dependency between the two where this
// can live. Ideally, we can do this when the EC2MetadataUtils is replaced with
// the IMDS client.
public final class Ec2MetadataConfigProvider {
/** Default IPv4 endpoint for the Amazon EC2 Instance Metadata Service. */
private static final String EC2_METADATA_SERVICE_URL_IPV4 = "http://169.254.169.254";
/** Default IPv6 endpoint for the Amazon EC2 Instance Metadata Service. */
private static final String EC2_METADATA_SERVICE_URL_IPV6 = "http://[fd00:ec2::254]";
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private Ec2MetadataConfigProvider(Builder builder) {
this.profileFile = builder.profileFile;
this.profileName = builder.profileName;
}
public enum EndpointMode {
IPV4,
IPV6,
;
public static EndpointMode fromValue(String s) {
if (s == null) {
return null;
}
for (EndpointMode value : EndpointMode.values()) {
if (value.name().equalsIgnoreCase(s)) {
return value;
}
}
throw new IllegalArgumentException("Unrecognized value for endpoint mode: " + s);
}
}
public String getEndpoint() {
String endpointOverride = getEndpointOverride();
if (endpointOverride != null) {
return endpointOverride;
}
EndpointMode endpointMode = getEndpointMode();
switch (endpointMode) {
case IPV4:
return EC2_METADATA_SERVICE_URL_IPV4;
case IPV6:
return EC2_METADATA_SERVICE_URL_IPV6;
default:
throw SdkClientException.create("Unknown endpoint mode: " + endpointMode);
}
}
public EndpointMode getEndpointMode() {
Optional<String> endpointMode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.getNonDefaultStringValue();
if (endpointMode.isPresent()) {
return EndpointMode.fromValue(endpointMode.get());
}
return configFileEndpointMode().orElseGet(() ->
EndpointMode.fromValue(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.defaultValue()));
}
public String getEndpointOverride() {
Optional<String> endpointOverride = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.getNonDefaultStringValue();
if (endpointOverride.isPresent()) {
return endpointOverride.get();
}
Optional<String> configFileValue = configFileEndpointOverride();
return configFileValue.orElse(null);
}
public static Builder builder() {
return new Builder();
}
private Optional<EndpointMode> configFileEndpointMode() {
return resolveProfile().flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT_MODE))
.map(EndpointMode::fromValue);
}
private Optional<String> configFileEndpointOverride() {
return resolveProfile().flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT));
}
private Optional<Profile> resolveProfile() {
ProfileFile profileFileToUse = resolveProfileFile();
String profileNameToUse = resolveProfileName();
return profileFileToUse.profile(profileNameToUse);
}
private ProfileFile resolveProfileFile() {
if (profileFile != null) {
return profileFile.get();
}
return ProfileFile.defaultProfileFile();
}
private String resolveProfileName() {
if (profileName != null) {
return profileName;
}
return ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
}
public static class Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public Ec2MetadataConfigProvider build() {
return new Ec2MetadataConfigProvider(this);
}
}
}
| 1,492 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/SystemSettingsCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import static software.amazon.awssdk.utils.StringUtils.trim;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.auth.credentials.SystemPropertyCredentialsProvider;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.SystemSetting;
/**
* Loads credentials providers from the {@link SdkSystemSetting#AWS_ACCESS_KEY_ID},
* {@link SdkSystemSetting#AWS_SECRET_ACCESS_KEY}, and {@link SdkSystemSetting#AWS_SESSION_TOKEN} system settings.
*
* This does not load the credentials directly. Instead, the actual mapping of setting to credentials is done by child classes.
* This allows us to separately load the credentials from system properties and environment variables so that customers can
* remove one or the other from their credential chain, or build a different chain with these pieces of functionality separated.
*
* @see EnvironmentVariableCredentialsProvider
* @see SystemPropertyCredentialsProvider
*/
@SdkInternalApi
public abstract class SystemSettingsCredentialsProvider implements AwsCredentialsProvider {
@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.isBlank(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.isBlank(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 StringUtils.isBlank(sessionToken) ? AwsBasicCredentials.create(accessKey, secretKey)
: AwsSessionCredentials.create(accessKey, secretKey, sessionToken);
}
/**
* Implemented by child classes to load the requested setting.
*/
protected abstract Optional<String> loadSetting(SystemSetting setting);
}
| 1,493 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/HttpCredentialsLoader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.io.IOException;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.regions.util.HttpResourcesUtils;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.Validate;
/**
* Helper class that contains the common behavior of the CredentialsProviders that loads the credentials from a local endpoint on
* a container (e.g. an EC2 instance).
*/
@SdkInternalApi
public final class HttpCredentialsLoader {
private static final JsonNodeParser SENSITIVE_PARSER =
JsonNodeParser.builder()
.removeErrorLocations(true)
.build();
private static final Pattern TRAILING_ZERO_OFFSET_TIME_PATTERN = Pattern.compile("\\+0000$");
private HttpCredentialsLoader() {
}
public static HttpCredentialsLoader create() {
return new HttpCredentialsLoader();
}
public LoadedCredentials loadCredentials(ResourcesEndpointProvider endpoint) {
try {
String credentialsResponse = HttpResourcesUtils.instance().readResource(endpoint);
Map<String, JsonNode> node = SENSITIVE_PARSER.parse(credentialsResponse).asObject();
JsonNode accessKey = node.get("AccessKeyId");
JsonNode secretKey = node.get("SecretAccessKey");
JsonNode token = node.get("Token");
JsonNode expiration = node.get("Expiration");
Validate.notNull(accessKey, "Failed to load access key from metadata service.");
Validate.notNull(secretKey, "Failed to load secret key from metadata service.");
return new LoadedCredentials(accessKey.text(),
secretKey.text(),
token != null ? token.text() : null,
expiration != null ? expiration.text() : null);
} catch (SdkClientException e) {
throw e;
} catch (RuntimeException | IOException e) {
throw SdkClientException.builder()
.message("Failed to load credentials from metadata service.")
.cause(e)
.build();
}
}
public static final class LoadedCredentials {
private final String accessKeyId;
private final String secretKey;
private final String token;
private final Instant expiration;
private LoadedCredentials(String accessKeyId, String secretKey, String token, String expiration) {
this.accessKeyId = Validate.paramNotBlank(accessKeyId, "accessKeyId");
this.secretKey = Validate.paramNotBlank(secretKey, "secretKey");
this.token = token;
this.expiration = expiration == null ? null : parseExpiration(expiration);
}
public AwsCredentials getAwsCredentials() {
if (token == null) {
return AwsBasicCredentials.create(accessKeyId, secretKey);
} else {
return AwsSessionCredentials.create(accessKeyId, secretKey, token);
}
}
public Optional<Instant> getExpiration() {
return Optional.ofNullable(expiration);
}
private static Instant parseExpiration(String expiration) {
if (expiration == null) {
return null;
}
// Convert the expirationNode string to ISO-8601 format.
String expirationValue = TRAILING_ZERO_OFFSET_TIME_PATTERN.matcher(expiration).replaceAll("Z");
try {
return DateUtils.parseIso8601Date(expirationValue);
} catch (RuntimeException e) {
throw new IllegalStateException("Unable to parse credentials expiration date from metadata service.", e);
}
}
}
}
| 1,494 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/ProfileCredentialsUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.ChildProfileCredentialsProviderFactory;
import software.amazon.awssdk.auth.credentials.ContainerCredentialsProvider;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProcessCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProviderFactory;
import software.amazon.awssdk.auth.credentials.ProfileProviderCredentialsContext;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.auth.credentials.SystemPropertyCredentialsProvider;
import software.amazon.awssdk.core.internal.util.ClassLoaderHelper;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.profiles.internal.ProfileSection;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.Validate;
/**
* Utility class to load {@link #credentialsProvider()} configured in a profile.
*/
@SdkInternalApi
public final class ProfileCredentialsUtils {
private static final String STS_PROFILE_CREDENTIALS_PROVIDER_FACTORY =
"software.amazon.awssdk.services.sts.internal.StsProfileCredentialsProviderFactory";
private static final String SSO_PROFILE_CREDENTIALS_PROVIDER_FACTORY =
"software.amazon.awssdk.services.sso.auth.SsoProfileCredentialsProviderFactory";
/**
* The profile file containing {@code profile}.
*/
private final ProfileFile profileFile;
private final Profile profile;
/**
* The name of this profile (minus any profile prefixes).
*/
private final String name;
/**
* The raw properties in this profile.
*/
private final Map<String, String> properties;
/**
* A function to resolve the profile from which this profile should derive its credentials.
*
* This is used by assume-role credentials providers to find the credentials it should use for authentication when assuming
* the role.
*/
private final Function<String, Optional<Profile>> credentialsSourceResolver;
public ProfileCredentialsUtils(ProfileFile profileFile,
Profile profile,
Function<String, Optional<Profile>> credentialsSourceResolver) {
this.profileFile = Validate.paramNotNull(profileFile, "profileFile");
this.profile = Validate.paramNotNull(profile, "profile");
this.name = profile.name();
this.properties = profile.properties();
this.credentialsSourceResolver = credentialsSourceResolver;
}
/**
* Retrieve the credentials provider for which this profile has been configured, if available.
*
* If this profile is configured for role-based credential loading, the returned {@link AwsCredentialsProvider} implements
* {@link SdkAutoCloseable} and should be cleaned up to prevent resource leaks in the event that multiple credentials
* providers will be created.
*/
public Optional<AwsCredentialsProvider> credentialsProvider() {
return credentialsProvider(new HashSet<>());
}
/**
* Retrieve the credentials provider for which this profile has been configured, if available.
*
* @param children The child profiles that source credentials from this profile.
*/
private Optional<AwsCredentialsProvider> credentialsProvider(Set<String> children) {
if (properties.containsKey(ProfileProperty.ROLE_ARN) && properties.containsKey(ProfileProperty.WEB_IDENTITY_TOKEN_FILE)) {
return Optional.ofNullable(roleAndWebIdentityTokenProfileCredentialsProvider());
}
if (properties.containsKey(ProfileProperty.SSO_ROLE_NAME)
|| properties.containsKey(ProfileProperty.SSO_ACCOUNT_ID)
|| properties.containsKey(ProfileProperty.SSO_REGION)
|| properties.containsKey(ProfileProperty.SSO_START_URL)
|| properties.containsKey(ProfileSection.SSO_SESSION.getPropertyKeyName())) {
return Optional.ofNullable(ssoProfileCredentialsProvider());
}
if (properties.containsKey(ProfileProperty.ROLE_ARN)) {
boolean hasSourceProfile = properties.containsKey(ProfileProperty.SOURCE_PROFILE);
boolean hasCredentialSource = properties.containsKey(ProfileProperty.CREDENTIAL_SOURCE);
Validate.validState(!(hasSourceProfile && hasCredentialSource),
"Invalid profile file: profile has both %s and %s.",
ProfileProperty.SOURCE_PROFILE, ProfileProperty.CREDENTIAL_SOURCE);
if (hasSourceProfile) {
return Optional.ofNullable(roleAndSourceProfileBasedProfileCredentialsProvider(children));
}
if (hasCredentialSource) {
return Optional.ofNullable(roleAndCredentialSourceBasedProfileCredentialsProvider());
}
}
if (properties.containsKey(ProfileProperty.CREDENTIAL_PROCESS)) {
return Optional.ofNullable(credentialProcessCredentialsProvider());
}
if (properties.containsKey(ProfileProperty.AWS_SESSION_TOKEN)) {
return Optional.of(sessionProfileCredentialsProvider());
}
if (properties.containsKey(ProfileProperty.AWS_ACCESS_KEY_ID)) {
return Optional.of(basicProfileCredentialsProvider());
}
return Optional.empty();
}
/**
* 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);
}
/**
* 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);
}
private AwsCredentialsProvider credentialProcessCredentialsProvider() {
requireProperties(ProfileProperty.CREDENTIAL_PROCESS);
return ProcessCredentialsProvider.builder()
.command(properties.get(ProfileProperty.CREDENTIAL_PROCESS))
.build();
}
/**
* Create the SSO credentials provider based on the related profile properties.
*/
private AwsCredentialsProvider ssoProfileCredentialsProvider() {
validateRequiredPropertiesForSsoCredentialsProvider();
return ssoCredentialsProviderFactory().create(
ProfileProviderCredentialsContext.builder()
.profile(profile)
.profileFile(profileFile)
.build());
}
private void validateRequiredPropertiesForSsoCredentialsProvider() {
requireProperties(ProfileProperty.SSO_ACCOUNT_ID,
ProfileProperty.SSO_ROLE_NAME);
if (!properties.containsKey(ProfileSection.SSO_SESSION.getPropertyKeyName())) {
requireProperties(ProfileProperty.SSO_REGION, ProfileProperty.SSO_START_URL);
}
}
private AwsCredentialsProvider roleAndWebIdentityTokenProfileCredentialsProvider() {
requireProperties(ProfileProperty.ROLE_ARN, ProfileProperty.WEB_IDENTITY_TOKEN_FILE);
String roleArn = properties.get(ProfileProperty.ROLE_ARN);
String roleSessionName = properties.get(ProfileProperty.ROLE_SESSION_NAME);
Path webIdentityTokenFile = Paths.get(properties.get(ProfileProperty.WEB_IDENTITY_TOKEN_FILE));
WebIdentityTokenCredentialProperties credentialProperties =
WebIdentityTokenCredentialProperties.builder()
.roleArn(roleArn)
.roleSessionName(roleSessionName)
.webIdentityTokenFile(webIdentityTokenFile)
.build();
return WebIdentityCredentialsUtils.factory().create(credentialProperties);
}
/**
* Load an assumed-role credentials provider that has been configured in this profile. This will attempt to locate the STS
* module in order to generate the credentials provider. If it's not available, an illegal state exception will be raised.
*
* @param children The child profiles that source credentials from this profile.
*/
private AwsCredentialsProvider roleAndSourceProfileBasedProfileCredentialsProvider(Set<String> children) {
requireProperties(ProfileProperty.SOURCE_PROFILE);
Validate.validState(!children.contains(name),
"Invalid profile file: Circular relationship detected with profiles %s.", children);
Validate.validState(credentialsSourceResolver != null,
"The profile '%s' must be configured with a source profile in order to use assumed roles.", name);
children.add(name);
AwsCredentialsProvider sourceCredentialsProvider =
credentialsSourceResolver.apply(properties.get(ProfileProperty.SOURCE_PROFILE))
.flatMap(p -> new ProfileCredentialsUtils(profileFile, p, credentialsSourceResolver)
.credentialsProvider(children))
.orElseThrow(this::noSourceCredentialsException);
return stsCredentialsProviderFactory().create(sourceCredentialsProvider, profile);
}
/**
* Load an assumed-role credentials provider that has been configured in this profile. This will attempt to locate the STS
* module in order to generate the credentials provider. If it's not available, an illegal state exception will be raised.
*/
private AwsCredentialsProvider roleAndCredentialSourceBasedProfileCredentialsProvider() {
requireProperties(ProfileProperty.CREDENTIAL_SOURCE);
CredentialSourceType credentialSource = CredentialSourceType.parse(properties.get(ProfileProperty.CREDENTIAL_SOURCE));
AwsCredentialsProvider credentialsProvider = credentialSourceCredentialProvider(credentialSource);
return stsCredentialsProviderFactory().create(credentialsProvider, profile);
}
private AwsCredentialsProvider credentialSourceCredentialProvider(CredentialSourceType credentialSource) {
switch (credentialSource) {
case ECS_CONTAINER:
return ContainerCredentialsProvider.builder().build();
case EC2_INSTANCE_METADATA:
// The IMDS credentials provider should source the endpoint config properties from the currently active profile
Ec2MetadataConfigProvider configProvider = Ec2MetadataConfigProvider.builder()
.profileFile(() -> profileFile)
.profileName(name)
.build();
return InstanceProfileCredentialsProvider.builder()
.endpoint(configProvider.getEndpoint())
.build();
case ENVIRONMENT:
return AwsCredentialsProviderChain.builder()
.addCredentialsProvider(SystemPropertyCredentialsProvider.create())
.addCredentialsProvider(EnvironmentVariableCredentialsProvider.create())
.build();
default:
throw noSourceCredentialsException();
}
}
/**
* Require that the provided properties are configured in this profile.
*/
private void requireProperties(String... requiredProperties) {
Arrays.stream(requiredProperties)
.forEach(p -> Validate.isTrue(properties.containsKey(p),
"Profile property '%s' was not configured for '%s'.", p, name));
}
private IllegalStateException noSourceCredentialsException() {
String error = String.format("The source profile of '%s' was configured to be '%s', but that source profile has no "
+ "credentials configured.", name, properties.get(ProfileProperty.SOURCE_PROFILE));
return new IllegalStateException(error);
}
/**
* Load the factory that can be used to create the STS credentials provider, assuming it is on the classpath.
*/
private ChildProfileCredentialsProviderFactory stsCredentialsProviderFactory() {
try {
Class<?> stsCredentialsProviderFactory = ClassLoaderHelper.loadClass(STS_PROFILE_CREDENTIALS_PROVIDER_FACTORY,
getClass());
return (ChildProfileCredentialsProviderFactory) stsCredentialsProviderFactory.getConstructor().newInstance();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("To use assumed roles in the '" + name + "' profile, the 'sts' service module must "
+ "be on the class path.", e);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create the '" + name + "' profile credentials provider.", e);
}
}
/**
* Load the factory that can be used to create the SSO credentials provider, assuming it is on the classpath.
*/
private ProfileCredentialsProviderFactory ssoCredentialsProviderFactory() {
try {
Class<?> ssoProfileCredentialsProviderFactory = ClassLoaderHelper.loadClass(SSO_PROFILE_CREDENTIALS_PROVIDER_FACTORY,
getClass());
return (ProfileCredentialsProviderFactory) ssoProfileCredentialsProviderFactory.getConstructor().newInstance();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("To use Sso related properties in the '" + name + "' profile, the 'sso' service "
+ "module must be on the class path.", e);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create the '" + name + "' profile credentials provider.", e);
}
}
}
| 1,495 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/StaticResourcesEndpointProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class StaticResourcesEndpointProvider implements ResourcesEndpointProvider {
private final URI endpoint;
private final Map<String, String> headers;
public StaticResourcesEndpointProvider(URI endpoint,
Map<String, String> additionalHeaders) {
this.endpoint = Validate.paramNotNull(endpoint, "endpoint");
this.headers = ResourcesEndpointProvider.super.headers();
if (additionalHeaders != null) {
this.headers.putAll(additionalHeaders);
}
}
@Override
public URI endpoint() throws IOException {
return endpoint;
}
@Override
public Map<String, String> headers() {
return Collections.unmodifiableMap(headers);
}
}
| 1,496 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/WebIdentityTokenCredentialProperties.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.nio.file.Path;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A container for credential properties.
*/
@SdkProtectedApi
public class WebIdentityTokenCredentialProperties {
private final String roleArn;
private final String roleSessionName;
private final Path webIdentityTokenFile;
private final Boolean asyncCredentialUpdateEnabled;
private final Duration prefetchTime;
private final Duration staleTime;
private final Duration roleSessionDuration;
private WebIdentityTokenCredentialProperties(Builder builder) {
this.roleArn = builder.roleArn;
this.roleSessionName = builder.roleSessionName;
this.webIdentityTokenFile = builder.webIdentityTokenFile;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.prefetchTime = builder.prefetchTime;
this.staleTime = builder.staleTime;
this.roleSessionDuration = builder.roleSessionDuration;
}
public String roleArn() {
return roleArn;
}
public String roleSessionName() {
return roleSessionName;
}
public Path webIdentityTokenFile() {
return webIdentityTokenFile;
}
public Boolean asyncCredentialUpdateEnabled() {
return asyncCredentialUpdateEnabled;
}
public Duration prefetchTime() {
return prefetchTime;
}
public Duration staleTime() {
return staleTime;
}
public Duration roleSessionDuration() {
return this.roleSessionDuration;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String roleArn;
private String roleSessionName;
private Path webIdentityTokenFile;
private Boolean asyncCredentialUpdateEnabled;
private Duration prefetchTime;
private Duration staleTime;
private Duration roleSessionDuration;
public Builder roleArn(String roleArn) {
this.roleArn = roleArn;
return this;
}
public Builder roleSessionName(String roleSessionName) {
this.roleSessionName = roleSessionName;
return this;
}
public Builder webIdentityTokenFile(Path webIdentityTokenFile) {
this.webIdentityTokenFile = webIdentityTokenFile;
return this;
}
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
public Builder prefetchTime(Duration prefetchTime) {
this.prefetchTime = prefetchTime;
return this;
}
public Builder staleTime(Duration staleTime) {
this.staleTime = staleTime;
return this;
}
public Builder roleSessionDuration(Duration roleSessionDuration) {
this.roleSessionDuration = roleSessionDuration;
return this;
}
public WebIdentityTokenCredentialProperties build() {
return new WebIdentityTokenCredentialProperties(this);
}
}
}
| 1,497 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/LazyAwsCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
/**
* A wrapper for {@link AwsCredentialsProvider} that defers creation of the underlying provider until the first time the
* {@link AwsCredentialsProvider#resolveCredentials()} method is invoked.
*/
@SdkInternalApi
public class LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable {
private final Lazy<AwsCredentialsProvider> delegate;
private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> delegateConstructor) {
this.delegate = new Lazy<>(delegateConstructor);
}
public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) {
return new LazyAwsCredentialsProvider(delegateConstructor);
}
@Override
public AwsCredentials resolveCredentials() {
return delegate.getValue().resolveCredentials();
}
@Override
public void close() {
IoUtils.closeIfCloseable(delegate, null);
}
@Override
public String toString() {
return ToString.builder("LazyAwsCredentialsProvider")
.add("delegate", delegate)
.build();
}
}
| 1,498 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/WebIdentityCredentialsUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.lang.reflect.InvocationTargetException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.WebIdentityTokenCredentialsProviderFactory;
import software.amazon.awssdk.core.internal.util.ClassLoaderHelper;
import software.amazon.awssdk.utils.Logger;
/**
* Utility class used to configure credential providers based on JWT web identity tokens.
*/
@SdkInternalApi
public final class WebIdentityCredentialsUtils {
private static final Logger log = Logger.loggerFor(WebIdentityCredentialsUtils.class);
private static final String STS_WEB_IDENTITY_CREDENTIALS_PROVIDER_FACTORY =
"software.amazon.awssdk.services.sts.internal.StsWebIdentityCredentialsProviderFactory";
private WebIdentityCredentialsUtils() {
}
/**
* Resolves the StsWebIdentityCredentialsProviderFactory from the Sts module if on the classpath to allow
* JWT web identity tokens to be used as credentials.
*
* @return WebIdentityTokenCredentialsProviderFactory
*/
public static WebIdentityTokenCredentialsProviderFactory factory() {
try {
Class<?> stsCredentialsProviderFactory = ClassLoaderHelper.loadClass(STS_WEB_IDENTITY_CREDENTIALS_PROVIDER_FACTORY,
WebIdentityCredentialsUtils.class);
return (WebIdentityTokenCredentialsProviderFactory) stsCredentialsProviderFactory.getConstructor().newInstance();
} catch (ClassNotFoundException e) {
String message = "To use web identity tokens, the 'sts' service module must be on the class path.";
log.warn(() -> message);
throw new IllegalStateException(message, e);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create a web identity token credentials provider.", e);
}
}
}
| 1,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.