Skip to content
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

Added a test case to verify password encryption in logs. #567

Closed
wants to merge 8 commits into from
Closed
40 changes: 40 additions & 0 deletions src/main/java/com/ericsson/ei/logFilter/LogFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.ericsson.ei.logFilter;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import org.springframework.context.annotation.PropertySource;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

@PropertySource("classpath:logback.xml")
public class LogFilter extends Filter<ILoggingEvent> {

public boolean filter(LocalDateTime start, LocalDateTime end, String logLine) {
DateTimeFormatter logFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss,SSS");
LocalDateTime current=start;
while(current.isBefore(end))
{
String time=current.format(logFormatter);
if(logLine.contains(time))
{
return (true);
}
else
{
current=current.plus(1, ChronoUnit.MILLIS);
}


}
return (false);
}

@Override
public FilterReply decide(ILoggingEvent iLoggingEvent) {
return null;
}
}

10 changes: 7 additions & 3 deletions src/main/java/com/ericsson/ei/services/SubscriptionService.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public class SubscriptionService implements ISubscriptionService {
private static final Logger LOGGER = LoggerFactory.getLogger(SubscriptionService.class);

@Value("${spring.application.name}")
private String SpringApplicationName;
private String springApplicationName;

@Value("${spring.data.mongodb.database}")
private String dataBaseName;
Expand Down Expand Up @@ -99,7 +99,7 @@ public Subscription getSubscription(String subscriptionName)
try {
subscription = mapper.readValue(input, Subscription.class);
// Inject aggregationtype
subscription.setAggregationtype(SpringApplicationName);
subscription.setAggregationtype(springApplicationName);
return subscription;
} catch (IOException e) {
LOGGER.error("Malformed JSON string", e);
Expand Down Expand Up @@ -129,6 +129,10 @@ public boolean modifySubscription(Subscription subscription, String subscription
ObjectMapper mapper = new ObjectMapper();
Document result = null;
try {
String password = subscription.getPassword();
if (isEncryptionReady(subscription.getAuthenticationType(), subscription.getUserName(), password)) {
subscription.setPassword(encryptPassword(password));
}
String stringSubscription = mapper.writeValueAsString(subscription);

final MongoCondition subscriptionNameCondition = MongoCondition.subscriptionNameCondition(
Expand Down Expand Up @@ -196,7 +200,7 @@ public List<Subscription> getSubscriptions() throws SubscriptionNotFoundExceptio
try {
subscription = mapper.readValue(input, Subscription.class);
// Inject aggregationtype
subscription.setAggregationtype(SpringApplicationName);
subscription.setAggregationtype(springApplicationName);
subscriptions.add(subscription);
} catch (IOException e) {
LOGGER.error("Failed to get subscription.", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.util.Iterator;
import java.util.List;

import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -97,11 +98,14 @@ private void extractConditions(String aggregatedObject,
try {
JsonNode subscriptionJson = new ObjectMapper().readTree(
subscriptionData);
LOGGER.debug("SubscriptionJson : " + subscriptionJson.toString());
LOGGER.debug("Aggregated Object : " + aggregatedObject + " for the event id: " + id);
// Remove password from subscription details and put empty value before logging.
JsonNode subscriptoinToDisplay = new ObjectMapper().readTree(subscriptionJson.toString());
LOGGER.debug("SubscriptionJson : {}",
((ObjectNode) subscriptoinToDisplay).put("password", "").toPrettyString());
LOGGER.debug("Aggregated Object : {} for event id: {}", aggregatedObject, id);
ArrayNode requirementNode = (ArrayNode) subscriptionJson.get(
"requirements");
LOGGER.debug("Requirements : " + requirementNode.toString());
LOGGER.debug("Requirements : {}", requirementNode);
Iterator<JsonNode> requirementIterator = requirementNode.elements();
SubscriptionField subscriptionField = new SubscriptionField(subscriptionJson);
String subscriptionName = subscriptionField.get("subscriptionName");
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,7 @@ threads.core.pool.size: 200
threads.queue.capacity: 7000
threads.max.pool.size: 250
scheduled.threadpool.size: 200

logging.file.path=/eiffel-intelligence/eiffel-intelligence.log
Copy link
Contributor

@jainadc9 jainadc9 Mar 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better to use /tmp as the root path might not be accesible in different hosts

logging.file.name= eiffel-intelligence.log
logging.pattern.file='%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n'
14 changes: 14 additions & 0 deletions src/main/resources/logback.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>eiffel-intelligence.log</file>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
<filter class="com.ericsson.ei.logFilter.LogFilter" />
</appender>

<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,21 @@
*/
package com.ericsson.ei.services;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.annotation.PostConstruct;


import com.ericsson.ei.logFilter.LogFilter;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
Expand Down Expand Up @@ -62,6 +66,8 @@
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoClient;

import static org.junit.Assert.*;

@TestPropertySource(properties = {
"spring.data.mongodb.database: SubscriptionServiceTest",
"failed.notifications.collection.name: SubscriptionServiceTest-failedNotifications",
Expand All @@ -83,11 +89,17 @@ public class SubscriptionServiceTest {
@Value("${subscriptions.repeat.handler.collection.name}")
private String repeatFlagHandlerCollection;

@Value("${logging.file.name}")
private File logFileName;

private String subscriptionName;

@Autowired
private ISubscriptionService subscriptionService;

@Autowired
private SubscriptionService subService;

@Autowired
private MongoDBHandler mongoDBHandler;

Expand Down Expand Up @@ -137,16 +149,16 @@ public void testUpdateSubscription() {
Subscription subscription2 = mapper.readValue(jsonArray.getJSONObject(0).toString(), Subscription.class);
String expectedSubscriptionName = subscription2.getSubscriptionName();
String expectedUserName = subscription2.getUserName();

subscriptionService.modifySubscription(subscription2, expectedSubscriptionName);
subscriptionService.addSubscription(subscription2);
// Fetch the inserted subscription
subscription2 = null;
subscription2 = subscriptionService.getSubscription(expectedSubscriptionName);
subscriptionName = subscription2.getSubscriptionName();

SecurityContextHolder.setContext(securityContext);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
Mockito.when(authentication.getName()).thenReturn("ABC");

assertEquals(subscriptionName, expectedSubscriptionName);
assertEquals(authentication.getName(), expectedUserName);

Expand All @@ -163,7 +175,6 @@ public void testUpdateSubscription() {
subscription = subscriptionService.getSubscription(expectedModifiedSubscriptionName);
subscriptionName = subscription.getSubscriptionName();
assertEquals(subscriptionName, expectedModifiedSubscriptionName);

assertEquals(authentication.getName(), expectedModifiedSubscriptionName);

// deleting the test data
Expand Down Expand Up @@ -360,4 +371,66 @@ private void deleteSubscriptionsByName(String subscriptionName) throws AccessExc
Mockito.when(authentication.getName()).thenReturn("ABC");
subscriptionService.deleteSubscription(subscriptionName);
}
}
@Test
public void testLogForPasswordAdd() throws Exception {

try {
Path logFilePath=Paths.get(String.valueOf(logFileName));
Scanner scanner = new Scanner(logFilePath);
LocalDateTime start = LocalDateTime.now();
Subscription subscription2 = mapper.readValue(jsonArray.getJSONObject(0).toString(), Subscription.class);
String expectedSubscriptionName = subscription2.getSubscriptionName();
subscription2.setAuthenticationType("BASIC_AUTH");
String expectedSubscriptionPassword = subscription2.getPassword();
subService.addSubscription(subscription2);
LocalDateTime end = LocalDateTime.now();
LogFilter log = new LogFilter();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (log.filter(start, end, line)) {
if ((line.contains(expectedSubscriptionName) && (line.contains("password")))) {
assertFalse(line.contains(expectedSubscriptionPassword));
}
}
}
// deleting the test data
deleteSubscriptionsByName(expectedSubscriptionName);
Files.delete(logFilePath);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

close the scanner

}
catch(Exception e) {
LOGGER.error(e.getMessage(),e);
}
}
@Test
public void testLogForPasswordUpdate() throws Exception {

try {
Path logFilePath=Paths.get(String.valueOf(logFileName));
Scanner scanner = new Scanner(logFilePath);
LocalDateTime start = LocalDateTime.now();
Subscription subscription2 = mapper.readValue(jsonArray.getJSONObject(0).toString(), Subscription.class);
String expectedSubscriptionName = subscription2.getSubscriptionName();
subscription2.setAuthenticationType("BASIC_AUTH");
subscription2.setPassword("token123");
String expectedSubscriptionPassword = subscription2.getPassword();
subscriptionService.modifySubscription(subscription2,expectedSubscriptionName);
subService.addSubscription(subscription2);
LocalDateTime end = LocalDateTime.now();
LogFilter log = new LogFilter();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (log.filter(start, end, line)) {
if ((line.contains(expectedSubscriptionName) && (line.contains("password")))) {
assertFalse(line.contains(expectedSubscriptionPassword));
}
}
}
// deleting the test data
deleteSubscriptionsByName(expectedSubscriptionName);
Files.delete(logFilePath);
}
catch(Exception e) {
LOGGER.error(e.getMessage(),e);
}
}
}
1 change: 1 addition & 0 deletions src/test/resources/subscription_CLME.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
],
"subscriptionName" : "Single_CLME_Subscription_Test",
"userName" : "ABC",
"password" : "token",
"ldapUserName": ""
}
]
Loading