-
Notifications
You must be signed in to change notification settings - Fork 937
Feature ID implementation - CREDENTIALS_IMDS #6380
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
S-Saranya1
wants to merge
3
commits into
feature/master/feature-ids-implementation
from
somepal/Implement-FeatureIDs
+324
−0
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"type": "feature", | ||
"category": "AWS SDK for Java v2", | ||
"contributor": "", | ||
"description": "Implemented the CREDENTIALS_IMDS business metric feature that tracks when Instance Metadata Service (IMDS) credentials are being used in AWS SDK requests." | ||
} |
51 changes: 51 additions & 0 deletions
51
...are/amazon/awssdk/auth/credentials/internal/ImdsCredentialsBusinessMetricInterceptor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/* | ||
* 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 software.amazon.awssdk.annotations.SdkInternalApi; | ||
import software.amazon.awssdk.auth.credentials.AwsCredentials; | ||
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; | ||
import software.amazon.awssdk.core.SdkRequest; | ||
import software.amazon.awssdk.core.interceptor.Context; | ||
import software.amazon.awssdk.core.interceptor.ExecutionAttributes; | ||
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; | ||
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; | ||
import software.amazon.awssdk.core.useragent.BusinessMetricFeatureId; | ||
|
||
/** | ||
* Interceptor that adds the CREDENTIALS_IMDS business metric when IMDS credentials are being used. | ||
*/ | ||
@SdkInternalApi | ||
public final class ImdsCredentialsBusinessMetricInterceptor implements ExecutionInterceptor { | ||
|
||
@Override | ||
public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { | ||
AwsCredentials credentials = executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS); | ||
|
||
if (credentials != null && isImdsCredentials(credentials)) { | ||
executionAttributes.getAttribute(SdkInternalExecutionAttribute.BUSINESS_METRICS) | ||
.addMetric(BusinessMetricFeatureId.CREDENTIALS_IMDS.value()); | ||
} | ||
|
||
return context.request(); | ||
} | ||
|
||
private boolean isImdsCredentials(AwsCredentials credentials) { | ||
return credentials.providerName() | ||
.map(name -> name.contains("InstanceProfileCredentialsProvider")) | ||
.orElse(false); | ||
} | ||
} |
1 change: 1 addition & 0 deletions
1
core/auth/src/main/resources/software/amazon/awssdk/global/handlers/execution.interceptors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
software.amazon.awssdk.auth.credentials.internal.ImdsCredentialsBusinessMetricInterceptor |
113 changes: 113 additions & 0 deletions
113
...src/test/java/software/amazon/awssdk/auth/credentials/ImdsCredentialsInUserAgentTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
/* | ||
* 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.mockito.Mockito.mock; | ||
import static org.mockito.Mockito.when; | ||
|
||
import java.util.Optional; | ||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.Test; | ||
import software.amazon.awssdk.auth.credentials.internal.ImdsCredentialsBusinessMetricInterceptor; | ||
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; | ||
import software.amazon.awssdk.core.SdkRequest; | ||
import software.amazon.awssdk.core.interceptor.Context; | ||
import software.amazon.awssdk.core.interceptor.ExecutionAttributes; | ||
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; | ||
import software.amazon.awssdk.core.useragent.BusinessMetricCollection; | ||
import software.amazon.awssdk.core.useragent.BusinessMetricFeatureId; | ||
|
||
public class ImdsCredentialsInUserAgentTest { | ||
|
||
private ImdsCredentialsBusinessMetricInterceptor interceptor; | ||
private ExecutionAttributes executionAttributes; | ||
private BusinessMetricCollection businessMetrics; | ||
private Context.ModifyRequest context; | ||
|
||
@BeforeEach | ||
void setUp() { | ||
interceptor = new ImdsCredentialsBusinessMetricInterceptor(); | ||
executionAttributes = new ExecutionAttributes(); | ||
businessMetrics = new BusinessMetricCollection(); | ||
executionAttributes.putAttribute(SdkInternalExecutionAttribute.BUSINESS_METRICS, businessMetrics); | ||
|
||
context = mock(Context.ModifyRequest.class); | ||
SdkRequest request = mock(SdkRequest.class); | ||
when(context.request()).thenReturn(request); | ||
} | ||
|
||
@Test | ||
public void imdsCredentials_shouldHaveImdsCredentialsBusinessMetric() { | ||
// Create credentials with IMDS provider name | ||
AwsCredentials imdsCredentials = createCredentialsWithProviderName("InstanceProfileCredentialsProvider"); | ||
executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, imdsCredentials); | ||
|
||
interceptor.modifyRequest(context, executionAttributes); | ||
|
||
// Verify that the CREDENTIALS_IMDS metric is added to business metrics | ||
assertThat(businessMetrics.recordedMetrics()) | ||
.contains(BusinessMetricFeatureId.CREDENTIALS_IMDS.value()); | ||
|
||
// Verify that the metric appears in the user agent string | ||
String userAgentString = businessMetrics.asBoundedString(); | ||
assertThat(userAgentString).contains(BusinessMetricFeatureId.CREDENTIALS_IMDS.value()); | ||
} | ||
|
||
@Test | ||
public void containerCredentials_shouldNotHaveImdsCredentialsBusinessMetric() { | ||
// Test with "ContainerCredentialsProvider" provider name - should not be considered IMDS | ||
AwsCredentials containerCredentials = createCredentialsWithProviderName("ContainerCredentialsProvider"); | ||
executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, containerCredentials); | ||
|
||
interceptor.modifyRequest(context, executionAttributes); | ||
|
||
assertThat(businessMetrics.recordedMetrics()) | ||
.doesNotContain(BusinessMetricFeatureId.CREDENTIALS_IMDS.value()); | ||
} | ||
|
||
@Test | ||
public void credentialsWithoutProviderName_shouldNotHaveImdsCredentialsBusinessMetric() { | ||
// Test with credentials that don't have a provider name | ||
AwsCredentials credentialsWithoutProviderName = AwsBasicCredentials.create("accessKey", "secretKey"); | ||
executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, credentialsWithoutProviderName); | ||
|
||
interceptor.modifyRequest(context, executionAttributes); | ||
|
||
assertThat(businessMetrics.recordedMetrics()) | ||
.doesNotContain(BusinessMetricFeatureId.CREDENTIALS_IMDS.value()); | ||
} | ||
|
||
private AwsCredentials createCredentialsWithProviderName(String providerName) { | ||
AwsCredentials baseCredentials = AwsBasicCredentials.create("test-access-key", "test-secret-key"); | ||
return new AwsCredentials() { | ||
@Override | ||
public String accessKeyId() { | ||
return baseCredentials.accessKeyId(); | ||
} | ||
|
||
@Override | ||
public String secretAccessKey() { | ||
return baseCredentials.secretAccessKey(); | ||
} | ||
|
||
@Override | ||
public Optional<String> providerName() { | ||
return Optional.of(providerName); | ||
} | ||
}; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
152 changes: 152 additions & 0 deletions
152
...th-tests/src/it/java/software/amazon/awssdk/auth/source/ImdsCredentialsUserAgentTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
/* | ||
* 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.source; | ||
|
||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; | ||
import static com.github.tomakehurst.wiremock.client.WireMock.get; | ||
import static com.github.tomakehurst.wiremock.client.WireMock.put; | ||
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; | ||
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; | ||
import static org.assertj.core.api.Assertions.assertThat; | ||
|
||
import com.github.tomakehurst.wiremock.junit5.WireMockExtension; | ||
import com.github.tomakehurst.wiremock.junit5.WireMockTest; | ||
import java.io.UnsupportedEncodingException; | ||
import java.time.Duration; | ||
import java.time.Instant; | ||
import java.util.List; | ||
import java.util.stream.Stream; | ||
import org.junit.jupiter.api.AfterAll; | ||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.extension.RegisterExtension; | ||
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.AwsCredentials; | ||
import software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider; | ||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; | ||
import software.amazon.awssdk.core.SdkSystemSetting; | ||
import software.amazon.awssdk.http.AbortableInputStream; | ||
import software.amazon.awssdk.http.HttpExecuteResponse; | ||
import software.amazon.awssdk.http.SdkHttpClient; | ||
import software.amazon.awssdk.http.SdkHttpRequest; | ||
import software.amazon.awssdk.http.SdkHttpResponse; | ||
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; | ||
import software.amazon.awssdk.identity.spi.IdentityProvider; | ||
import software.amazon.awssdk.services.sts.StsClient; | ||
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; | ||
import software.amazon.awssdk.utils.DateUtils; | ||
import software.amazon.awssdk.utils.StringInputStream; | ||
|
||
@WireMockTest | ||
class ImdsCredentialsUserAgentTest { | ||
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 PROFILE_NAME = "some-profile"; | ||
private static final String TOKEN_STUB = "some-token"; | ||
|
||
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 AwsCredentials BASIC_IDENTITY = basicCredentialsBuilder().build(); | ||
|
||
@RegisterExtension | ||
static WireMockExtension wireMockServer = WireMockExtension.newInstance() | ||
.options(wireMockConfig().dynamicPort().dynamicPort()) | ||
.configureStaticDsl(true) | ||
.build(); | ||
|
||
private MockSyncHttpClient mockHttpClient; | ||
|
||
@BeforeEach | ||
public void setup() throws UnsupportedEncodingException { | ||
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), | ||
"http://localhost:" + wireMockServer.getPort()); | ||
|
||
stubSecureCredentialsResponse(); | ||
|
||
mockHttpClient = new MockSyncHttpClient(); | ||
mockHttpClient.stubNextResponse(mockResponse()); | ||
} | ||
|
||
@AfterAll | ||
public static void teardown() { | ||
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); | ||
} | ||
|
||
public static HttpExecuteResponse mockResponse() { | ||
return HttpExecuteResponse.builder() | ||
.response(SdkHttpResponse.builder().statusCode(200).build()) | ||
.responseBody(AbortableInputStream.create(new StringInputStream(""))) | ||
.build(); | ||
} | ||
|
||
@ParameterizedTest | ||
@MethodSource("credentialProviders") | ||
void userAgentString_containsCredentialProviderNames_IfPresent(IdentityProvider<? extends AwsCredentialsIdentity> provider, | ||
String expected) throws Exception { | ||
stsClient(provider, mockHttpClient).getCallerIdentity(); | ||
|
||
SdkHttpRequest lastRequest = mockHttpClient.getLastRequest(); | ||
assertThat(lastRequest).isNotNull(); | ||
|
||
List<String> userAgentHeaders = lastRequest.headers().get("User-Agent"); | ||
assertThat(userAgentHeaders).isNotNull().hasSize(1); | ||
|
||
String userAgent = userAgentHeaders.get(0); | ||
|
||
if ("m/0".equals(expected)) { | ||
assertThat(userAgent).matches(".*m/[^\\s]*0[^\\s]*.*"); | ||
} else { | ||
assertThat(userAgent).contains(expected); | ||
} | ||
} | ||
|
||
private static Stream<Arguments> credentialProviders() { | ||
return Stream.of( | ||
Arguments.of(createRealImdsCredentialsProvider(), "m/0"), | ||
Arguments.of(StaticCredentialsProvider.create(BASIC_IDENTITY), "stat") | ||
); | ||
} | ||
|
||
/** | ||
* Creates a InstanceProfileCredentialsProvider that uses mocked IMDS endpoints. | ||
*/ | ||
private static InstanceProfileCredentialsProvider createRealImdsCredentialsProvider() { | ||
return InstanceProfileCredentialsProvider.builder().build(); | ||
} | ||
|
||
private static void stubSecureCredentialsResponse() { | ||
wireMockServer.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(TOKEN_STUB))); | ||
wireMockServer.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody(PROFILE_NAME))); | ||
wireMockServer.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + PROFILE_NAME)).willReturn(aResponse().withBody(STUB_CREDENTIALS))); | ||
} | ||
|
||
private static StsClient stsClient(IdentityProvider<? extends AwsCredentialsIdentity> provider, SdkHttpClient httpClient) { | ||
return StsClient.builder() | ||
.credentialsProvider(provider) | ||
.httpClient(httpClient) | ||
.build(); | ||
} | ||
|
||
private static AwsBasicCredentials.Builder basicCredentialsBuilder() { | ||
return AwsBasicCredentials.builder() | ||
.accessKeyId("akid") | ||
.secretAccessKey("secret"); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is there any chances
getAttribute
could return null?