Add a constructor for AWSSigV4Signer so that a request can be signed in a NAWS environment using only the IAM role and region , Add custom credential provider support ,Add fix to Junit test case and tests when building ,remove enable trust all mode code path

This commit is contained in:
Amrutha Reddy 2023-02-24 13:50:03 -05:00
parent cdda871726
commit 72c8d5a7cf
7 changed files with 104 additions and 59 deletions

View File

@ -71,7 +71,6 @@ public class ApiClient {
private int dateLength;
private InputStream sslCaCert;
private boolean verifyingSsl;
private KeyManager[] keyManagers;
private OkHttpClient httpClient;
@ -95,8 +94,6 @@ public class ApiClient {
httpClient.interceptors().add(new GzipRequestInterceptor());
{{/useGzipFeature}}
verifyingSsl = true;
json = new JSON();
// Set default User-Agent.
@ -171,29 +168,6 @@ public class ApiClient {
return this;
}
/**
* True if isVerifyingSsl flag is on
*
* @return True if isVerifySsl flag is on
*/
public boolean isVerifyingSsl() {
return verifyingSsl;
}
/**
* Configure whether to verify certificate and hostname when making https requests.
* Default to true.
* NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks.
*
* @param verifyingSsl True to verify TLS/SSL connection
* @return ApiClient
*/
public ApiClient setVerifyingSsl(boolean verifyingSsl) {
this.verifyingSsl = verifyingSsl;
applySslSettings();
return this;
}
/**
* Get SSL CA cert.
*
@ -1215,28 +1189,13 @@ public class ApiClient {
/**
* Apply SSL related settings to httpClient according to the current values of
* verifyingSsl and sslCaCert.
* sslCaCert.
*/
private void applySslSettings() {
try {
TrustManager[] trustManagers = null;
HostnameVerifier hostnameVerifier = null;
if (!verifyingSsl) {
TrustManager trustAll = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() { return null; }
};
SSLContext sslContext = SSLContext.getInstance("TLS");
trustManagers = new TrustManager[]{ trustAll };
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) { return true; }
};
} else if (sslCaCert != null) {
if (sslCaCert != null) {
char[] password = null; // Any password will work.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);

View File

@ -45,6 +45,7 @@ import java.util.Map;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCustomCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.AWSSigV4Signer;
import com.amazon.SellingPartnerAPIAA.LWAAccessTokenCache;
import com.amazon.SellingPartnerAPIAA.LWAAccessTokenCacheImpl;
@ -283,6 +284,7 @@ public class {{classname}} {
private Boolean disableAccessTokenCache = false;
private AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider;
private RateLimitConfiguration rateLimitConfiguration;
private AWSAuthenticationCustomCredentialsProvider awsAuthenticationCustomCredentialsProvider;
public Builder awsAuthenticationCredentials(AWSAuthenticationCredentials awsAuthenticationCredentials) {
this.awsAuthenticationCredentials = awsAuthenticationCredentials;
@ -323,11 +325,16 @@ public class {{classname}} {
this.rateLimitConfiguration = null;
return this;
}
public Builder awsAuthenticationCustomCredentialsProvider(AWSAuthenticationCustomCredentialsProvider awsAuthenticationCustomCredentialsProvider) {
this.awsAuthenticationCustomCredentialsProvider = awsAuthenticationCustomCredentialsProvider;
return this;
}
public {{classname}} build() {
if (awsAuthenticationCredentials == null) {
throw new RuntimeException("AWSAuthenticationCredentials not set");
if (awsAuthenticationCredentials == null && awsAuthenticationCustomCredentialsProvider == null) {
throw new RuntimeException("Neither AWSAuthenticationCredentials or AWSAuthenticationCustomCredentialsProvider are set");
}
if (lwaAuthorizationCredentials == null) {
@ -339,7 +346,10 @@ public class {{classname}} {
}
AWSSigV4Signer awsSigV4Signer;
if ( awsAuthenticationCredentialsProvider == null) {
if (awsAuthenticationCustomCredentialsProvider != null ) {
awsSigV4Signer = new AWSSigV4Signer(awsAuthenticationCustomCredentialsProvider);
}
else if (awsAuthenticationCredentialsProvider == null) {
awsSigV4Signer = new AWSSigV4Signer(awsAuthenticationCredentials);
}
else {

View File

@ -19,5 +19,5 @@ public class AWSAuthenticationCredentialsProvider {
*/
private String roleSessionName;
private String region;
}

View File

@ -0,0 +1,23 @@
package com.amazon.SellingPartnerAPIAA;
import lombok.Builder;
import lombok.Data;
import com.amazonaws.auth.AWSCredentialsProvider;
/**
* AWSAuthenticationCustomCredentialsProvider
*/
@Data
@Builder
public class AWSAuthenticationCustomCredentialsProvider {
/**
* AWS Region
*/
private String region;
/**
* AWS Credentials Provider
*/
private AWSCredentialsProvider awsCredentialsProvider;
}

View File

@ -41,7 +41,7 @@ public class AWSSigV4Signer {
awsAuthenticationCredentials.getSecretKey());
}
/**
/**
*
* @param awsAuthenticationCredentials and awsAuthenticationCredentialsProvider AWS Developer Account Credentials
*/
@ -49,18 +49,48 @@ public class AWSSigV4Signer {
AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider) {
aws4Signer = new AWS4Signer();
aws4Signer.setServiceName(SERVICE_NAME);
aws4Signer.setRegionName(awsAuthenticationCredentials.getRegion());
BasicAWSCredentials awsBasicCredentials = new BasicAWSCredentials(awsAuthenticationCredentials.getAccessKeyId(),
awsAuthenticationCredentials.getSecretKey());
final String region;
AWSSecurityTokenServiceClientBuilder stsClientBuilder = AWSSecurityTokenServiceClientBuilder.standard();
if (awsAuthenticationCredentials != null) {
region = awsAuthenticationCredentials.getRegion();
BasicAWSCredentials awsBasicCredentials = new BasicAWSCredentials(
awsAuthenticationCredentials.getAccessKeyId(),
awsAuthenticationCredentials.getSecretKey()
);
stsClientBuilder.withCredentials(new AWSStaticCredentialsProvider(awsBasicCredentials));
} else {
region = awsAuthenticationCredentialsProvider.getRegion();
}
aws4Signer.setRegionName(region);
awsCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(
awsAuthenticationCredentialsProvider.getRoleArn(),
awsAuthenticationCredentialsProvider.getRoleSessionName())
.withStsClient(AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(awsAuthenticationCredentials.getRegion())
.withCredentials(new AWSStaticCredentialsProvider(awsBasicCredentials)).build())
.withStsClient(stsClientBuilder.withRegion(region).build())
.build();
}
/**
*
* @param awsAuthenticationCustomCredentialsProvider AWS Credentials Provider
*/
public AWSSigV4Signer(AWSAuthenticationCustomCredentialsProvider awsAuthenticationCustomCredentialsProvider) {
aws4Signer = new AWS4Signer();
aws4Signer.setServiceName(SERVICE_NAME);
aws4Signer.setRegionName(awsAuthenticationCustomCredentialsProvider.getRegion());
this.awsCredentialsProvider = awsAuthenticationCustomCredentialsProvider.getAwsCredentialsProvider();
}
/**
*
* @param awsAuthenticationCredentialsProvider AWS Credentials Provider containing the role name to be assumed
*/
public AWSSigV4Signer(AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider) {
this(null, awsAuthenticationCredentialsProvider);
}
/**
* Signs a Request with AWS Signature Version 4
*
@ -76,4 +106,4 @@ public class AWSSigV4Signer {
}
return (Request) signableRequest.getOriginalRequestObject();
}
}
}

View File

@ -4,8 +4,6 @@ import com.amazonaws.SignableRequest;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider;
import com.squareup.okhttp.Request;
import org.junit.Before;
import org.junit.Test;
@ -121,6 +119,30 @@ public class AWSSigV4SignerTest {
assertEquals(((Request)actualSignableRequest.getOriginalRequestObject()).url(), actualSignedRequest.url());
}
@Test
public void returnSignedRequestWithCustomCredentialsProvider() {
ArgumentCaptor<SignableRequest> signableRequestArgumentCaptor = ArgumentCaptor.forClass(SignableRequest.class);
Mockito.when(mockAWSCredentialsProvider.getCredentials()).thenReturn(mockAWSCredentials);
underTestCredentialsProvider = new AWSSigV4Signer(AWSAuthenticationCustomCredentialsProvider.builder()
.awsCredentialsProvider(mockAWSCredentialsProvider)
.region(TEST_REGION)
.build());
underTestCredentialsProvider.setAws4Signer(mockAWS4Signer);
Request actualSignedRequest = underTestCredentialsProvider.sign(new Request.Builder()
.url("http://api.amazon.com")
.build());
verify(mockAWS4Signer)
.sign(signableRequestArgumentCaptor.capture(), any(AWSCredentials.class));
SignableRequest actualSignableRequest = signableRequestArgumentCaptor.getValue();
assertEquals(((Request)actualSignableRequest.getOriginalRequestObject()).url(), actualSignedRequest.url());
}
}

View File

@ -25,6 +25,7 @@ import java.util.HashSet;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@ -108,19 +109,19 @@ public class LWAAuthorizationSignerTest {
testAuthSigner.sign(request);
LWAAccessTokenRequestMeta actualLWAAccessTokenRequestMeta = lwaAccessTokenRequestMetaArgumentCaptor.getValue();
assertEquals(TEST_REFRESH_TOKEN, actualLWAAccessTokenRequestMeta.getRefreshToken());
assertEquals(TEST_CLIENT_SECRET, actualLWAAccessTokenRequestMeta.getClientSecret());
assertEquals(TEST_CLIENT_ID, actualLWAAccessTokenRequestMeta.getClientId());
if(sellerType.equals(SELLER_TYPE_SELLER)){
assertEquals(TEST_REFRESH_TOKEN, actualLWAAccessTokenRequestMeta.getRefreshToken());
Assert.assertTrue(actualLWAAccessTokenRequestMeta.getScopes().getScopes().isEmpty());
assertEquals("refresh_token", actualLWAAccessTokenRequestMeta.getGrantType());
}
else if (sellerType.equals(SELLER_TYPE_SELLERLESS)){
assertNull(actualLWAAccessTokenRequestMeta.getRefreshToken());
assertEquals(new HashSet<String>(Arrays.asList(TEST_SCOPE_1, TEST_SCOPE_2)), actualLWAAccessTokenRequestMeta.getScopes().getScopes());
assertEquals("client_credentials", actualLWAAccessTokenRequestMeta.getGrantType());
}
}
@ParameterizedTest