Skip to content
Snippets Groups Projects
Commit bc4fa64b authored by Solomon Ayalew's avatar Solomon Ayalew
Browse files

commit 17d6c6e7 
Author: Solomon Ayalew <solxget@amazon.com> 
Date: Tue Sep 26 2023 16:09:13 GMT-0700 (Pacific Daylight Time) 

    Code smell cleanup
parent 4cc4e0fe
No related branches found
No related tags found
1 merge request!437merge code to gitlab
Showing
with 173 additions and 179 deletions
......@@ -14,15 +14,14 @@ package org.opengroup.osdu.notification.provider.aws.impl;
import org.opengroup.osdu.notification.provider.interfaces.IGoogleServiceAccount;
import org.springframework.stereotype.Component;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
@Component
public class AwsGoogleServiceAccountImpl implements IGoogleServiceAccount {
@Override
// To do: Check if it is to be supported
public String getIdToken(String keyString, String audience) {
// TODO : Check if it is to be supported
throw new NotImplementedException();
throw new UnsupportedOperationException();
}
}
......
......@@ -119,8 +119,8 @@ public class AwsPubsubRequestBodyExtractor implements IPubsubRequestBodyExtracto
throw new AppException(HttpStatus.BAD_REQUEST.value(), INVALID_PUBSUB_MESSAGE,
"No tenant information from pubsub message.");
}
String x_user_id= request.getHeader("x-user-id");
lowerCase.put("x-user-id",x_user_id);
String xUserId= request.getHeader("x-user-id");
lowerCase.put("x-user-id", xUserId);
content.setAttributes(lowerCase);
String decoded = new String(Base64.getDecoder().decode(data));
......@@ -129,9 +129,10 @@ public class AwsPubsubRequestBodyExtractor implements IPubsubRequestBodyExtracto
return content;
}
private JsonObject extractRootJsonElementFromRequestBody() {
@SuppressWarnings("deprecation")
private JsonObject extractRootJsonElementFromRequestBody() {
try {
JsonParser jsonParser = new JsonParser();
JsonParser jsonParser = new JsonParser();
BufferedReader reader = request.getReader();
Stream<String> lines = reader.lines();
String requestBody = lines.collect(Collectors.joining("\n"));
......
......@@ -19,11 +19,11 @@ import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexRangeKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConvertedEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
@Data
@NoArgsConstructor
......
......@@ -13,7 +13,6 @@
// limitations under the License.
package org.opengroup.osdu.notification.provider.aws.queue.impl;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBDeleteExpression;
import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedQueryList;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.Message;
......
......@@ -165,8 +165,6 @@ public class NotificationRetryQueueServiceImpl implements NotificationRetryQueue
private void deleteDbRecords(List<Message> messages) {
DynamoDBQueryHelperV2 dynamoDBQueryHelper = dynamoDBQueryHelperFactory.getQueryHelperUsingSSM(failedNotificationTablePath);
messages.parallelStream().forEach(message -> {
FailedNotificationDoc doc = dynamoDBQueryHelper.loadByPrimaryKey(FailedNotificationDoc.class,
message.getMessageAttributes().get(FAILED_NOTIFICATION_RECORD_ID).getStringValue());
try {
FailedNotificationDoc objectToDelete = new FailedNotificationDoc();
objectToDelete.setId(message.getMessageAttributes().get(FAILED_NOTIFICATION_RECORD_ID).getStringValue());
......
......@@ -26,7 +26,6 @@ import org.opengroup.osdu.notification.provider.aws.security.KmsHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
......
// Copyright © 2020 Amazon Web Services
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License 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.
/*
Copyright © 2020 Amazon Web Services
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License 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 org.opengroup.osdu.notification.provider.aws.security;
......@@ -20,6 +22,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@SuppressWarnings("deprecation")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AwsSecurityConfig extends WebSecurityConfigurerAdapter {
......
......@@ -67,34 +67,23 @@ public class KmsHelper {
throw new AppException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "SSM InternalServerErrorException", e.getErrorMessage());
}
}
public ByteBuffer encrypt(String plainTextString) {
EncryptRequest encReq = new EncryptRequest();
encReq.setKeyId(kmsKeyId);
encReq.setPlaintext(ByteBuffer.wrap(plainTextString.getBytes()));
encReq.setEncryptionContext(Collections.singletonMap("dataPartitionId", dpsHeaders.getPartitionId()));
ByteBuffer ciphertext = kmsClient.encrypt(encReq).getCiphertextBlob();
return ciphertext;
return kmsClient.encrypt(encReq).getCiphertextBlob();
}
public String decrypt(ByteBuffer ciphertext, String dataPartitionId) {
DecryptRequest decReq = new DecryptRequest();
decReq.setCiphertextBlob(ciphertext);
decReq.setEncryptionContext(Collections.singletonMap("dataPartitionId", dataPartitionId));
ByteBuffer decrypted = kmsClient.decrypt(decReq).getPlaintext();
String decryptedStr = new String(decrypted.array());
return decryptedStr;
return new String(decrypted.array());
}
}
......@@ -14,8 +14,14 @@
package org.opengroup.osdu.notification.provider.aws.security;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.StringUtils;
import org.opengroup.osdu.core.common.cryptographic.HmacData;
import org.opengroup.osdu.core.common.cryptographic.ISignatureService;
......@@ -23,129 +29,138 @@ import org.opengroup.osdu.core.common.cryptographic.SignatureServiceException;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import com.google.common.base.Strings;
import com.google.gson.Gson;
@Component
@Primary
public class ThreadSignatureService implements ISignatureService {
private static final String HMAC_SHA_256 = "HmacSHA256";
private static final String DATA_FORMAT = "{\"expireMillisecond\": \"%s\",\"hashMechanism\": \"hmacSHA256\",\"endpointUrl\": \"%s\",\"nonce\": \"%s\"}";
private static final String NOTIFICATION_SERVICE = "de-notification-service";
private static final long EXPIRE_DURATION = 30000L;
private static final String INVALID_SIGNATURE = "Invalid signature";
private static final String ERROR_GENERATING_SIGNATURE = "Error generating the signature";
private static final String SIGNATURE_EXPIRED = "Signature is expired";
private static final String MISSING_HMAC_SIGNATURE = "HMAC signature should not be null or empty";
private static final String MISSING_SECRET_VALUE = "Secret should not be null or empty";
private static final String MISSING_ATTRIBUTES_IN_SIGNATURE = "Missing url or nonce or expire time in the signature";
@Override
public String getSignedSignature(String url, String secret) throws SignatureServiceException {
if (Strings.isNullOrEmpty(url) || Strings.isNullOrEmpty(secret)) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE);
}
final long currentTime = System.currentTimeMillis();
final String expireTime = String.valueOf(currentTime + EXPIRE_DURATION);
final String timeStamp = String.valueOf(currentTime);
try {
String nonce = DatatypeConverter.printHexBinary(generateRandomBytes(16)).toLowerCase();
String data = String.format(DATA_FORMAT, expireTime, url, nonce);
final byte[] signature = getSignature(secret, nonce, timeStamp, data);
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
String dataBytesEncoded = Base64.getEncoder().encodeToString(dataBytes);
StringBuilder output = new StringBuilder();
output.append(dataBytesEncoded)
.append(".")
.append(DatatypeConverter.printHexBinary(signature).toLowerCase());
return output.toString();
} catch (Exception ex) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE, ex);
}
}
@Override
public String getSignedSignature(String url, String secret, String expireTime, String nonce) throws SignatureServiceException {
if (Strings.isNullOrEmpty(url) || Strings.isNullOrEmpty(secret) || !StringUtils.isNumeric(expireTime)) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE);
}
final long expiry = Long.parseLong(expireTime);
if (System.currentTimeMillis() > expiry) {
throw new SignatureServiceException(SIGNATURE_EXPIRED);
}
String timeStamp = String.valueOf(expiry - EXPIRE_DURATION);
String data = String.format(DATA_FORMAT, expireTime, url, nonce);
try {
final byte[] signature = getSignature(secret, nonce, timeStamp, data);
return DatatypeConverter.printHexBinary(signature).toLowerCase();
} catch (Exception ex) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE, ex);
}
}
@Override
public void verifyHmacSignature(String hmac, String secret) throws SignatureServiceException {
if (Strings.isNullOrEmpty(hmac)) {
throw new SignatureServiceException(MISSING_HMAC_SIGNATURE);
}
if (Strings.isNullOrEmpty(secret)) {
throw new SignatureServiceException(MISSING_SECRET_VALUE);
}
String[] tokens = hmac.split("\\.");
if (tokens.length != 2) {
throw new SignatureServiceException(INVALID_SIGNATURE);
}
byte[] dataBytes = Base64.getDecoder().decode(tokens[0]);
String requestSignature = tokens[1];
String data = new String(dataBytes, StandardCharsets.UTF_8);
HmacData hmacData = new Gson().fromJson(data, HmacData.class);
String url = hmacData.getEndpointUrl();
String nonce = hmacData.getNonce();
String expireTime = hmacData.getExpireMillisecond();
if (Strings.isNullOrEmpty(url) || Strings.isNullOrEmpty(nonce) || Strings.isNullOrEmpty(expireTime)) {
throw new SignatureServiceException(MISSING_ATTRIBUTES_IN_SIGNATURE);
}
String newSignature = getSignedSignature(url, secret, expireTime, nonce);
if (!requestSignature.equalsIgnoreCase(newSignature)) {
throw new SignatureServiceException(INVALID_SIGNATURE);
}
}
private byte[] getSignature(String secret, String nonce, String timeStamp, String data) throws Exception {
final byte[] secretBytes = DatatypeConverter.parseHexBinary(secret);
final byte[] nonceBytes = DatatypeConverter.parseHexBinary(nonce);
final byte[] encryptedNonce = computeHmacSha256(nonceBytes, secretBytes);
final byte[] encryptedTimestamp = computeHmacSha256(timeStamp, encryptedNonce);
final byte[] signedKey = computeHmacSha256(NOTIFICATION_SERVICE, encryptedTimestamp);
return computeHmacSha256(data, signedKey);
}
private byte[] computeHmacSha256(final String data, final byte[] key) throws Exception {
final Mac mac = Mac.getInstance(HMAC_SHA_256);
mac.init(new SecretKeySpec(key, HMAC_SHA_256));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private byte[] computeHmacSha256(final byte[] data, final byte[] key) throws Exception {
final Mac mac = Mac.getInstance(HMAC_SHA_256);
mac.init(new SecretKeySpec(key, HMAC_SHA_256));
return mac.doFinal(data);
}
private byte[] generateRandomBytes(final int size) {
final byte[] key = new byte[size];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(key);
return key;
}
private static final String HMAC_SHA_256 = "HmacSHA256";
private static final String DATA_FORMAT = "{\"expireMillisecond\": \"%s\",\"hashMechanism\": \"hmacSHA256\",\"endpointUrl\": \"%s\",\"nonce\": \"%s\"}";
private static final String NOTIFICATION_SERVICE = "de-notification-service";
private static final long EXPIRE_DURATION = 30000L;
private static final String INVALID_SIGNATURE = "Invalid signature";
private static final String ERROR_GENERATING_SIGNATURE = "Error generating the signature";
private static final String SIGNATURE_EXPIRED = "Signature is expired";
private static final String MISSING_HMAC_SIGNATURE = "HMAC signature should not be null or empty";
private static final String MISSING_SECRET_VALUE = "Secret should not be null or empty";
private static final String MISSING_ATTRIBUTES_IN_SIGNATURE = "Missing url or nonce or expire time in the signature";
@Override
public String getSignedSignature(String url, String secret) throws SignatureServiceException {
if (Strings.isNullOrEmpty(url) || Strings.isNullOrEmpty(secret)) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE);
}
final long currentTime = System.currentTimeMillis();
final String expireTime = String.valueOf(currentTime + EXPIRE_DURATION);
final String timeStamp = String.valueOf(currentTime);
try {
String nonce = DatatypeConverter.printHexBinary(generateRandomBytes(16)).toLowerCase();
String data = String.format(DATA_FORMAT, expireTime, url, nonce);
final byte[] signature = getSignature(secret, nonce, timeStamp, data);
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
String dataBytesEncoded = Base64.getEncoder().encodeToString(dataBytes);
StringBuilder output = new StringBuilder();
output.append(dataBytesEncoded).append(".")
.append(DatatypeConverter.printHexBinary(signature).toLowerCase());
return output.toString();
} catch (Exception ex) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE, ex);
}
}
@Override
public String getSignedSignature(String url, String secret, String expireTime, String nonce)
throws SignatureServiceException {
if (Strings.isNullOrEmpty(url) || Strings.isNullOrEmpty(secret) || !StringUtils.isNumeric(expireTime)) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE);
}
final long expiry = Long.parseLong(expireTime);
if (System.currentTimeMillis() > expiry) {
throw new SignatureServiceException(SIGNATURE_EXPIRED);
}
String timeStamp = String.valueOf(expiry - EXPIRE_DURATION);
String data = String.format(DATA_FORMAT, expireTime, url, nonce);
try {
final byte[] signature = getSignature(secret, nonce, timeStamp, data);
return DatatypeConverter.printHexBinary(signature).toLowerCase();
} catch (Exception ex) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE, ex);
}
}
@Override
public void verifyHmacSignature(String hmac, String secret) throws SignatureServiceException {
if (Strings.isNullOrEmpty(hmac)) {
throw new SignatureServiceException(MISSING_HMAC_SIGNATURE);
}
if (Strings.isNullOrEmpty(secret)) {
throw new SignatureServiceException(MISSING_SECRET_VALUE);
}
String[] tokens = hmac.split("\\.");
if (tokens.length != 2) {
throw new SignatureServiceException(INVALID_SIGNATURE);
}
byte[] dataBytes = Base64.getDecoder().decode(tokens[0]);
String requestSignature = tokens[1];
String data = new String(dataBytes, StandardCharsets.UTF_8);
HmacData hmacData = new Gson().fromJson(data, HmacData.class);
String url = hmacData.getEndpointUrl();
String nonce = hmacData.getNonce();
String expireTime = hmacData.getExpireMillisecond();
if (Strings.isNullOrEmpty(url) || Strings.isNullOrEmpty(nonce) || Strings.isNullOrEmpty(expireTime)) {
throw new SignatureServiceException(MISSING_ATTRIBUTES_IN_SIGNATURE);
}
String newSignature = getSignedSignature(url, secret, expireTime, nonce);
if (!requestSignature.equalsIgnoreCase(newSignature)) {
throw new SignatureServiceException(INVALID_SIGNATURE);
}
}
private byte[] getSignature(String secret, String nonce, String timeStamp, String data)
throws SignatureServiceException {
try {
final byte[] secretBytes = DatatypeConverter.parseHexBinary(secret);
final byte[] nonceBytes = DatatypeConverter.parseHexBinary(nonce);
final byte[] encryptedNonce = computeHmacSha256(nonceBytes, secretBytes);
final byte[] encryptedTimestamp = computeHmacSha256(timeStamp, encryptedNonce);
final byte[] signedKey = computeHmacSha256(NOTIFICATION_SERVICE, encryptedTimestamp);
return computeHmacSha256(data, signedKey);
} catch (Exception ex) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE, ex);
}
}
private byte[] computeHmacSha256(final String data, final byte[] key) throws SignatureServiceException {
try {
final Mac mac = Mac.getInstance(HMAC_SHA_256);
mac.init(new SecretKeySpec(key, HMAC_SHA_256));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
} catch (Exception ex) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE, ex);
}
}
private byte[] computeHmacSha256(final byte[] data, final byte[] key) throws SignatureServiceException {
try {
final Mac mac = Mac.getInstance(HMAC_SHA_256);
mac.init(new SecretKeySpec(key, HMAC_SHA_256));
return mac.doFinal(data);
} catch (Exception ex) {
throw new SignatureServiceException(ERROR_GENERATING_SIGNATURE, ex);
}
}
private byte[] generateRandomBytes(final int size) {
final byte[] key = new byte[size];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(key);
return key;
}
}
......@@ -17,7 +17,6 @@ package org.opengroup.osdu.notification.provider.aws.utils;
import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProvider;
import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProviderClientBuilder;
import com.amazonaws.services.cognitoidp.model.AdminSetUserPasswordRequest;
import com.amazonaws.services.cognitoidp.model.AdminSetUserPasswordResult;
import com.amazonaws.services.cognitoidp.model.InitiateAuthRequest;
import com.amazonaws.services.cognitoidp.model.InitiateAuthResult;
import org.opengroup.osdu.core.aws.iam.IAMConfig;
......@@ -28,12 +27,8 @@ import java.util.Map;
public class AwsCognitoClient {
// Parameter value locations
private final static String USERNAME_PARAM = "USERNAME";
private final static String PASSWORD_PARAM = "PASSWORD";
private final static String COGNITO_CLIENT_ID_PROPERTY = "AWS_COGNITO_CLIENT_ID";
private final static String COGNITO_AUTH_FLOW_PROPERTY = "AWS_COGNITO_AUTH_FLOW";
private final static String COGNITO_AUTH_PARAMS_USER_PROPERTY = "AWS_COGNITO_AUTH_PARAMS_USER";
private final static String COGNITO_AUTH_PARAMS_PASSWORD_PROPERTY = "AWS_COGNITO_AUTH_PARAMS_PASSWORD";
private static final String USERNAME_PARAM = "USERNAME";
private static final String PASSWORD_PARAM = "PASSWORD";
String awsCognitoClientId;
......@@ -91,7 +86,6 @@ public class AwsCognitoClient {
.withPassword(password)
.withPermanent(true)
.withUserPoolId(userPoolId);
AdminSetUserPasswordResult result = this.provider.adminSetUserPassword(request);
this.provider.adminSetUserPassword(request);
}
}
......@@ -82,11 +82,11 @@ public class SQSUtils {
exceptionAttribute.setStringValue("Exception message: missing dataPartitionId");
messageAttributes.put("Exception", exceptionAttribute);
SendMessageRequest send_msg_request = new SendMessageRequest()
SendMessageRequest sendMsgRequest = new SendMessageRequest()
.withQueueUrl(deadLetterQueueUrl)
.withMessageBody(message.getBody())
.withMessageAttributes(messageAttributes);
return sqsClient.sendMessage(send_msg_request);
return sqsClient.sendMessage(sendMsgRequest);
}
}
\ No newline at end of file
......@@ -5,7 +5,6 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.notification.provider.aws.impl.AwsGoogleServiceAccountImpl;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
@RunWith(MockitoJUnitRunner.class)
public class AwsGoogleServiceAccountImplTest {
......@@ -14,7 +13,7 @@ public class AwsGoogleServiceAccountImplTest {
AwsGoogleServiceAccountImpl awsGoogleServiceAccountImpl;
@Test(expected = NotImplementedException.class)
@Test(expected = UnsupportedOperationException.class)
public void getIdTokenThorwsNotImplementedException() {
awsGoogleServiceAccountImpl.getIdToken("keyString", "audience");
}
......
......@@ -57,11 +57,6 @@ public class KmsHelperTest {
Whitebox.setInternalState(kmsHelper, "amazonRegion", "us-east-1");
Whitebox.setInternalState(kmsHelper, "kmsEndpoint", "aws.kms.endpoint");
}
@Test
public void init_InitalizesAsExpected() {
kmsHelper.init();
}
@Test(expected = SdkClientException.class)
public void encrypt_EncryptsData() {
......
package org.opengroup.osdu.notification.provider.aws.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
......@@ -36,6 +37,7 @@ public class AwsCognitoClientTest {
@Test
public void constuctorCreatesObject() {
Assert.isInstanceOf(AwsCognitoClient.class, awsCognitoClient);
assertNotNull(awsCognitoClient);
}
@Test
......@@ -65,5 +67,6 @@ public class AwsCognitoClientTest {
awsCognitoClient.provider = provider;
when(provider.adminSetUserPassword(any())).thenReturn(null);
awsCognitoClient.setPassword("username", "password", "user-pool-id");
assertNotNull(awsCognitoClient);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment