From 47f67717a00802f104b30acd295b533120352b17 Mon Sep 17 00:00:00 2001 From: idawda Date: Thu, 16 Nov 2023 18:57:00 +0530 Subject: [PATCH 01/17] Unit test for newrelic-security-api module --- newrelic-security-api/build.gradle | 9 + .../helpers/FileHelperTest.java | 116 +++++++++++ .../helpers/GenericHelperTest.java | 90 ++++++++ .../helpers/InputStreamHelperTest.java | 54 +++++ .../helpers/JdbcHelperTest.java | 114 +++++++++++ .../helpers/LowSeverityHelperTest.java | 111 ++++++++++ .../helpers/R2dbcHelperTest.java | 192 ++++++++++++++++++ .../helpers/ServletHelperTest.java | 50 +++++ .../security/schema/StringUtilsTest.java | 175 ++++++++++++++++ .../agent/security/utils/SSRFUtilsTest.java | 19 ++ 10 files changed, 930 insertions(+) create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/FileHelperTest.java create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/GenericHelperTest.java create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/InputStreamHelperTest.java create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/JdbcHelperTest.java create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/LowSeverityHelperTest.java create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/R2dbcHelperTest.java create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/ServletHelperTest.java create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/schema/StringUtilsTest.java create mode 100644 newrelic-security-api/src/test/java/com/newrelic/api/agent/security/utils/SSRFUtilsTest.java diff --git a/newrelic-security-api/build.gradle b/newrelic-security-api/build.gradle index 8e6b52026..543f0fcb1 100644 --- a/newrelic-security-api/build.gradle +++ b/newrelic-security-api/build.gradle @@ -185,3 +185,12 @@ artifacts { archives newrelicVersionedAPIJar } +dependencies { + testImplementation("org.junit.jupiter:junit-jupiter-engine:5.6.2") + testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.2") + testImplementation('org.mockito:mockito-inline:4.5.1') +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/FileHelperTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/FileHelperTest.java new file mode 100644 index 000000000..d11c72931 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/FileHelperTest.java @@ -0,0 +1,116 @@ +package com.newrelic.api.agent.security.instrumentation.helpers; + +import com.newrelic.api.agent.security.NewRelicSecurity; +import com.newrelic.api.agent.security.schema.SecurityMetaData; +import com.newrelic.api.agent.security.schema.operation.FileIntegrityOperation; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import static com.newrelic.api.agent.security.instrumentation.helpers.FileHelper.NR_SEC_CUSTOM_ATTRIB_NAME; + +public class FileHelperTest { + private final String CLASS_NAME = "className", METHOD_NAME = "methodName"; + private final File file = new File(String.format("/tmp/%s_file.java", UUID.randomUUID())); + @Test + public void getFileExtension(){ + Assertions.assertEquals("", FileHelper.getFileExtension("file")); + Assertions.assertEquals("txt", FileHelper.getFileExtension("file.txt")); + } + @Test + public void createEntryOfFileIntegrityNull(){ + Assertions.assertNull(FileHelper.createEntryOfFileIntegrity("file", CLASS_NAME, METHOD_NAME)); + Assertions.assertNull(FileHelper.createEntryOfFileIntegrity("file.txt", CLASS_NAME, METHOD_NAME)); + } + @Test + public void createEntryOfFileIntegrity(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData().getFileLocalMap().containsKey(file.getAbsolutePath())).thenReturn(false); + assertion(file.exists(), file.getAbsolutePath(), FileHelper.createEntryOfFileIntegrity(file.getAbsolutePath(), CLASS_NAME, METHOD_NAME)); + } + } + @Test + public void createEntryOfFileIntegrity1(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData().getFileLocalMap().containsKey(file.getAbsolutePath())).thenReturn(true); + Assertions.assertNull(FileHelper.createEntryOfFileIntegrity(file.getAbsolutePath(), CLASS_NAME, METHOD_NAME)); + } + } + @Test + public void createEntryOfFileIntegrity2() throws IOException { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + file.createNewFile(); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData().getFileLocalMap().containsKey(file.getAbsolutePath())).thenReturn(false); + assertion(file.exists(), file.getAbsolutePath(), FileHelper.createEntryOfFileIntegrity(file.getAbsolutePath(), CLASS_NAME, METHOD_NAME)); + file.delete(); + } + } + @Test + public void createEntryOfFileIntegrity3() throws IOException { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + file.createNewFile(); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData().getFileLocalMap().containsKey(file.getAbsolutePath())).thenReturn(true); + Assertions.assertNull(FileHelper.createEntryOfFileIntegrity(file.getAbsolutePath(), CLASS_NAME, METHOD_NAME)); + file.delete(); + } + } + + @Test + public void isFileLockAcquired(){ + Assertions.assertFalse(FileHelper.isFileLockAcquired()); + } + @Test + public void isFileLockAcquired1() { + String customAttribute = NR_SEC_CUSTOM_ATTRIB_NAME + Thread.currentThread().getId(); + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData().getCustomAttribute(customAttribute, Boolean.class)).thenReturn(true); + Assertions.assertTrue(FileHelper.isFileLockAcquired()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + + @Test + public void acquireLockIfPossible(){ + Assertions.assertFalse(FileHelper.acquireFileLockIfPossible()); + } + @Test + public void acquireLockIfPossible1() { + String customAttribute = NR_SEC_CUSTOM_ATTRIB_NAME + Thread.currentThread().getId(); + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + SecurityMetaData metaData = new SecurityMetaData(); + metaData.addCustomAttribute(customAttribute, true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + Assertions.assertFalse(FileHelper.acquireFileLockIfPossible()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void acquireLockIfPossible2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(new SecurityMetaData()); + Assertions.assertTrue(FileHelper.acquireFileLockIfPossible()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + + private void assertion(boolean exists, String fileName, FileIntegrityOperation op){ + Assertions.assertNotNull(op); + Assertions.assertEquals(exists, op.getExists()); + Assertions.assertEquals(fileName, op.getFileName()); + Assertions.assertEquals(CLASS_NAME, op.getClassName()); + Assertions.assertEquals(METHOD_NAME, op.getMethodName()); + } + +} diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/GenericHelperTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/GenericHelperTest.java new file mode 100644 index 000000000..082954ed9 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/GenericHelperTest.java @@ -0,0 +1,90 @@ +package com.newrelic.api.agent.security.instrumentation.helpers; + +import com.newrelic.api.agent.security.NewRelicSecurity; +import com.newrelic.api.agent.security.schema.SecurityMetaData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +public class GenericHelperTest { + private final String nrSecCustomAttrName = "CUSTOM_ATTRIBUTE"; + private final int hashCode = 0; + + @Test + public void skipExistsEvent() { + Assertions.assertTrue(GenericHelper.skipExistsEvent()); + } + @Test + public void skipExistsEvent1() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + Assertions.assertTrue(GenericHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void skipExistsEvent2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(false); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(false); + Assertions.assertTrue(GenericHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void skipExistsEvent3() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(true); + Assertions.assertFalse(GenericHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void isLockAcquired(){ + Assertions.assertFalse(GenericHelper.isLockAcquired(nrSecCustomAttrName)); + } + @Test + public void isLockAcquired1() { + String customAttribute = nrSecCustomAttrName + Thread.currentThread().getId() + hashCode; + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData().getCustomAttribute(customAttribute, Boolean.class)).thenReturn(true); + Assertions.assertTrue(GenericHelper.isLockAcquired(nrSecCustomAttrName)); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void acquireLockIfPossible(){ + Assertions.assertFalse(GenericHelper.acquireLockIfPossible(nrSecCustomAttrName)); + } + @Test + public void acquireLockIfPossible1() { + String customAttribute = nrSecCustomAttrName + Thread.currentThread().getId() + hashCode; + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + SecurityMetaData metaData = new SecurityMetaData(); + metaData.addCustomAttribute(customAttribute, true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + Assertions.assertFalse(GenericHelper.acquireLockIfPossible(nrSecCustomAttrName)); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void acquireLockIfPossible2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(new SecurityMetaData()); + Assertions.assertTrue(GenericHelper.acquireLockIfPossible(nrSecCustomAttrName)); + nrMock.clearInvocations(); + nrMock.reset(); + } + } +} diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/InputStreamHelperTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/InputStreamHelperTest.java new file mode 100644 index 000000000..031eda796 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/InputStreamHelperTest.java @@ -0,0 +1,54 @@ +package com.newrelic.api.agent.security.instrumentation.helpers; + +import com.newrelic.api.agent.security.NewRelicSecurity; +import com.newrelic.api.agent.security.schema.SecurityMetaData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.util.Collections; +import java.util.HashSet; + +public class InputStreamHelperTest { + @Test + public void processRequestInputStreamHookData(){ + Assertions.assertFalse(InputStreamHelper.processRequestInputStreamHookData(null)); + } + @Test + public void processRequestInputStreamHookData1(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + Assertions.assertFalse(InputStreamHelper.processRequestInputStreamHookData(null)); + } + } + @Test + public void processRequestInputStreamHookData2(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(new SecurityMetaData()); + Assertions.assertFalse(InputStreamHelper.processRequestInputStreamHookData(null)); + } + } + @Test + public void processRequestInputStreamHookData3(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + SecurityMetaData metaData = new SecurityMetaData(); + metaData.addCustomAttribute("REQUEST_INPUTSTREAM_HASH", new HashSet<>()); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + Assertions.assertFalse(InputStreamHelper.processRequestInputStreamHookData(0)); + } + } + @Test + public void processRequestInputStreamHookData4(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + SecurityMetaData metaData = new SecurityMetaData(); + metaData.addCustomAttribute("REQUEST_INPUTSTREAM_HASH", new HashSet<>(Collections.singletonList(hashCode()))); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + Assertions.assertTrue(InputStreamHelper.processRequestInputStreamHookData(hashCode())); + } + } +} diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/JdbcHelperTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/JdbcHelperTest.java new file mode 100644 index 000000000..a4f7936f9 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/JdbcHelperTest.java @@ -0,0 +1,114 @@ +package com.newrelic.api.agent.security.instrumentation.helpers; + +import com.newrelic.api.agent.security.NewRelicSecurity; +import com.newrelic.api.agent.security.schema.JDBCVendor; +import com.newrelic.api.agent.security.schema.SecurityMetaData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import static com.newrelic.api.agent.security.instrumentation.helpers.JdbcHelper.NR_SEC_CUSTOM_ATTRIB_NAME; + +public class JdbcHelperTest { + @Test + public void skipExistsEvent() { + Assertions.assertTrue(JdbcHelper.skipExistsEvent()); + } + @Test + public void skipExistsEvent1() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + Assertions.assertTrue(JdbcHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void skipExistsEvent2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(false); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(false); + Assertions.assertTrue(JdbcHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void skipExistsEvent3() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(true); + Assertions.assertFalse(JdbcHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + + @Test + public void isLockAcquired(){ + Assertions.assertFalse(JdbcHelper.isLockAcquired()); + } + @Test + public void isLockAcquired1() { + String customAttribute = NR_SEC_CUSTOM_ATTRIB_NAME + Thread.currentThread().getId(); + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData().getCustomAttribute(customAttribute, Boolean.class)).thenReturn(true); + Assertions.assertTrue(JdbcHelper.isLockAcquired()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + + @Test + public void acquireLockIfPossible(){ + Assertions.assertFalse(JdbcHelper.acquireLockIfPossible()); + } + @Test + public void acquireLockIfPossible1() { + String customAttribute = NR_SEC_CUSTOM_ATTRIB_NAME + Thread.currentThread().getId(); + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + SecurityMetaData metaData = new SecurityMetaData(); + metaData.addCustomAttribute(customAttribute, true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + Assertions.assertFalse(JdbcHelper.acquireLockIfPossible()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void acquireLockIfPossible2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(new SecurityMetaData()); + Assertions.assertTrue(JdbcHelper.acquireLockIfPossible()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void detectDatabaseProduct() { + Assertions.assertEquals(JDBCVendor.MYSQL, JdbcHelper.detectDatabaseProduct(JdbcHelper.MY_SQL)); + Assertions.assertEquals(JDBCVendor.ORACLE, JdbcHelper.detectDatabaseProduct(JdbcHelper.ORACLE)); + Assertions.assertEquals(JDBCVendor.DERBY, JdbcHelper.detectDatabaseProduct(JdbcHelper.APACHE_DERBY)); + Assertions.assertEquals(JDBCVendor.HSQLDB, JdbcHelper.detectDatabaseProduct(JdbcHelper.HSQL_DATABASE_ENGINE)); + Assertions.assertEquals(JDBCVendor.SQLITE, JdbcHelper.detectDatabaseProduct(JdbcHelper.SQ_LITE)); + Assertions.assertEquals(JDBCVendor.H2, JdbcHelper.detectDatabaseProduct(JdbcHelper.H_2)); + Assertions.assertEquals(JDBCVendor.MSSQL, JdbcHelper.detectDatabaseProduct(JdbcHelper.MICROSOFT_SQL_SERVER)); + Assertions.assertEquals(JDBCVendor.ENTERPRISE_DB, JdbcHelper.detectDatabaseProduct(JdbcHelper.ENTERPRISE_DB)); + Assertions.assertEquals(JDBCVendor.PHOENIX, JdbcHelper.detectDatabaseProduct(JdbcHelper.PHOENIX)); + Assertions.assertEquals(JDBCVendor.POSTGRES, JdbcHelper.detectDatabaseProduct(JdbcHelper.POSTGRE_SQL)); + Assertions.assertEquals(JDBCVendor.IBMDB2, JdbcHelper.detectDatabaseProduct(JdbcHelper.DB_2)); + Assertions.assertEquals(JDBCVendor.VERTICA, JdbcHelper.detectDatabaseProduct(JdbcHelper.VERTICA)); + Assertions.assertEquals(JDBCVendor.SYBASE, JdbcHelper.detectDatabaseProduct(JdbcHelper.ASE)); + Assertions.assertEquals(JDBCVendor.SYBASE, JdbcHelper.detectDatabaseProduct(JdbcHelper.ADAPTIVE)); + Assertions.assertEquals(JDBCVendor.SYBASE, JdbcHelper.detectDatabaseProduct(JdbcHelper.SQL_SERVER)); + Assertions.assertEquals(JDBCVendor.SAPANA, JdbcHelper.detectDatabaseProduct(JdbcHelper.HDB)); + Assertions.assertEquals(JDBCVendor.GREENPLUM, JdbcHelper.detectDatabaseProduct(JdbcHelper.GREENPLUM)); + Assertions.assertEquals(JDBCVendor.SOLID_DB, JdbcHelper.detectDatabaseProduct(JdbcHelper.SOLID_DB)); + Assertions.assertEquals(JdbcHelper.UNKNOWN, JdbcHelper.detectDatabaseProduct("unknown")); + } +} diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/LowSeverityHelperTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/LowSeverityHelperTest.java new file mode 100644 index 000000000..65144e4b6 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/LowSeverityHelperTest.java @@ -0,0 +1,111 @@ +package com.newrelic.api.agent.security.instrumentation.helpers; + +import com.newrelic.api.agent.security.NewRelicSecurity; +import com.newrelic.api.agent.security.schema.HttpRequest; +import com.newrelic.api.agent.security.schema.K2RequestIdentifier; +import com.newrelic.api.agent.security.schema.SecurityMetaData; +import com.newrelic.api.agent.security.schema.StringUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +public class LowSeverityHelperTest { + @Test + public void addLowSeverityEventToEncounteredList(){ + Assertions.assertTrue(LowSeverityHelper.addLowSeverityEventToEncounteredList(hashCode())); + Assertions.assertFalse(LowSeverityHelper.addLowSeverityEventToEncounteredList(hashCode())); + } + @Test + public void checkIfLowSeverityEventAlreadyEncountered(){ + Assertions.assertFalse(LowSeverityHelper.checkIfLowSeverityEventAlreadyEncountered(hashCode())); + } + @Test + public void checkIfLowSeverityEventAlreadyEncountered1(){ + LowSeverityHelper.addLowSeverityEventToEncounteredList(hashCode()); + LowSeverityHelper.clearLowSeverityEventFilter(); + Assertions.assertFalse(LowSeverityHelper.checkIfLowSeverityEventAlreadyEncountered(hashCode())); + } + @Test + public void checkIfLowSeverityEventAlreadyEncountered2(){ + LowSeverityHelper.addLowSeverityEventToEncounteredList(hashCode()); + Assertions.assertTrue(LowSeverityHelper.checkIfLowSeverityEventAlreadyEncountered(hashCode())); + } + @Test + public void addRequestUriToEventFilterFalse(){ + Assertions.assertFalse(LowSeverityHelper.addRrequestUriToEventFilter(null)); + Assertions.assertFalse(LowSeverityHelper.addRrequestUriToEventFilter(Mockito.mock(HttpRequest.class))); + } + @Test + public void addRequestUriToEventFilterTrue(){ + HttpRequest req = new HttpRequest(); + req.setUrl("url"); + Assertions.assertTrue(LowSeverityHelper.addRrequestUriToEventFilter(req)); + Assertions.assertFalse(LowSeverityHelper.addRrequestUriToEventFilter(req)); + } + @Test + public void isOwaspHookProcessingNeeded(){ + Assertions.assertFalse(LowSeverityHelper.isOwaspHookProcessingNeeded()); + } + @Test + public void isOwaspHookProcessingNeeded1(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(new SecurityMetaData()); + Assertions.assertFalse(LowSeverityHelper.isOwaspHookProcessingNeeded()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void isOwaspHookProcessingNeeded2(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + SecurityMetaData metaData = new SecurityMetaData(); + + HttpRequest request = new HttpRequest(); request.setUrl(StringUtils.EMPTY); + metaData.setRequest(request); + + metaData.setFuzzRequestIdentifier(new K2RequestIdentifier()); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + Assertions.assertFalse(LowSeverityHelper.isOwaspHookProcessingNeeded()); + + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void isOwaspHookProcessingNeeded3(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + SecurityMetaData metaData = new SecurityMetaData(); + + HttpRequest request = new HttpRequest(); request.setUrl(StringUtils.EMPTY); + metaData.setRequest(request); + + K2RequestIdentifier identifier = new K2RequestIdentifier(); identifier.setK2Request(true); + metaData.setFuzzRequestIdentifier(identifier); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + + Assertions.assertTrue(LowSeverityHelper.isOwaspHookProcessingNeeded()); + + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void isOwaspHookProcessingNeeded4(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + SecurityMetaData metaData = new SecurityMetaData(); + + HttpRequest request = new HttpRequest(); request.setUrl("url"); + metaData.setRequest(request); + + K2RequestIdentifier identifier = new K2RequestIdentifier(); identifier.setK2Request(true); + metaData.setFuzzRequestIdentifier(identifier); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + Assertions.assertTrue(LowSeverityHelper.isOwaspHookProcessingNeeded()); + + nrMock.clearInvocations(); + nrMock.reset(); + } + } +} diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/R2dbcHelperTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/R2dbcHelperTest.java new file mode 100644 index 000000000..90fec4342 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/R2dbcHelperTest.java @@ -0,0 +1,192 @@ +package com.newrelic.api.agent.security.instrumentation.helpers; + +import com.newrelic.api.agent.security.NewRelicSecurity; +import com.newrelic.api.agent.security.schema.AbstractOperation; +import com.newrelic.api.agent.security.schema.JDBCVendor; +import com.newrelic.api.agent.security.schema.R2DBCVendor; +import com.newrelic.api.agent.security.schema.SecurityMetaData; +import com.newrelic.api.agent.security.schema.StringUtils; +import com.newrelic.api.agent.security.schema.operation.SQLOperation; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.util.Collections; +import java.util.Map; + +import static com.newrelic.api.agent.security.instrumentation.helpers.R2dbcHelper.NR_SEC_CUSTOM_ATTRIB_NAME; + +public class R2dbcHelperTest { + private final String SQL = "select * from users"; + public final String CLASS_NAME = "className"; + public final String METHOD_NAME = "methodName"; + @Test + public void skipExistsEvent() { + Assertions.assertTrue(R2dbcHelper.skipExistsEvent()); + } + @Test + public void skipExistsEvent1() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + Assertions.assertTrue(R2dbcHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void skipExistsEvent2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(false); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(false); + Assertions.assertTrue(R2dbcHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void skipExistsEvent3() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(true); + Assertions.assertFalse(R2dbcHelper.skipExistsEvent()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + + @Test + public void isLockAcquired(){ + Assertions.assertFalse(R2dbcHelper.isLockAcquired()); + } + @Test + public void isLockAcquired1() { + String customAttribute = NR_SEC_CUSTOM_ATTRIB_NAME + Thread.currentThread().getId(); + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData().getCustomAttribute(customAttribute, Boolean.class)).thenReturn(true); + Assertions.assertTrue(R2dbcHelper.isLockAcquired()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + + @Test + public void acquireLockIfPossible(){ + Assertions.assertFalse(R2dbcHelper.acquireLockIfPossible()); + } + @Test + public void acquireLockIfPossible1() { + String customAttribute = NR_SEC_CUSTOM_ATTRIB_NAME + Thread.currentThread().getId(); + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + SecurityMetaData metaData = new SecurityMetaData(); + metaData.addCustomAttribute(customAttribute, true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(metaData); + Assertions.assertFalse(R2dbcHelper.acquireLockIfPossible()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void acquireLockIfPossible2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(new SecurityMetaData()); + Assertions.assertTrue(R2dbcHelper.acquireLockIfPossible()); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void preprocessSecurityHookNull() { + Assertions.assertNull(R2dbcHelper.preprocessSecurityHook(SQL, METHOD_NAME, CLASS_NAME, null, false)); + } + @Test + public void preprocessSecurityHookNull1() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData()).thenReturn(null); + Assertions.assertNull(R2dbcHelper.preprocessSecurityHook(SQL, METHOD_NAME, CLASS_NAME, null, false)); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void preprocessSecurityHookNull2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + Assertions.assertNull(R2dbcHelper.preprocessSecurityHook(null, METHOD_NAME, CLASS_NAME, null, false)); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void preprocessSecurityHookNull3() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + Assertions.assertNull(R2dbcHelper.preprocessSecurityHook(StringUtils.EMPTY, METHOD_NAME, CLASS_NAME, null, false)); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void preprocessSecurityHookNull4() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + Assertions.assertNull(R2dbcHelper.preprocessSecurityHook(" ", METHOD_NAME, CLASS_NAME, null, false)); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void preprocessSecurityHook() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + Map param = null; + boolean isPrepared = false; + assertions(R2dbcHelper.preprocessSecurityHook(SQL, METHOD_NAME, CLASS_NAME, param, isPrepared), param, isPrepared, JdbcHelper.UNKNOWN); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void preprocessSecurityHook1() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData() + .getCustomAttribute(R2DBCVendor.META_CONST_R2DBC_VENDOR, String.class)).thenReturn(JDBCVendor.MYSQL); + Map param = Collections.emptyMap(); + boolean isPrepared = true; + assertions(R2dbcHelper.preprocessSecurityHook(SQL, METHOD_NAME, CLASS_NAME, param, isPrepared), param, isPrepared, JDBCVendor.MYSQL); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + @Test + public void preprocessSecurityHook2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.isHookProcessingActive()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getSecurityMetaData() + .getCustomAttribute(R2DBCVendor.META_CONST_R2DBC_VENDOR, String.class)).thenReturn(JDBCVendor.MYSQL); + Map param = Collections.singletonMap("key", "val"); + boolean isPrepared = true; + assertions(R2dbcHelper.preprocessSecurityHook(SQL, METHOD_NAME, CLASS_NAME, param, isPrepared), param, isPrepared, JDBCVendor.MYSQL); + nrMock.clearInvocations(); + nrMock.reset(); + } + } + + private void assertions(AbstractOperation actualOp, Map expectedParams, boolean expectedIsPrepared, String expectedDBName){ + Assertions.assertNotNull(actualOp); + Assertions.assertTrue(actualOp instanceof SQLOperation); + SQLOperation op = (SQLOperation) actualOp; + Assertions.assertEquals(SQL, op.getQuery()); + Assertions.assertEquals(CLASS_NAME, op.getClassName()); + Assertions.assertEquals(METHOD_NAME, op.getMethodName()); + Assertions.assertEquals(expectedParams, op.getParams()); + Assertions.assertEquals(expectedIsPrepared, op.isPreparedCall()); + Assertions.assertEquals(expectedDBName, op.getDbName()); + } +} diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/ServletHelperTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/ServletHelperTest.java new file mode 100644 index 000000000..ed1d187e8 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/instrumentation/helpers/ServletHelperTest.java @@ -0,0 +1,50 @@ +package com.newrelic.api.agent.security.instrumentation.helpers; + +import com.newrelic.api.agent.security.NewRelicSecurity; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import static com.newrelic.api.agent.security.schema.StringUtils.EMPTY; + +public class ServletHelperTest { + + @Test + public void parseFuzzRequestIdentifierHeader() { + Assertions.assertEquals(EMPTY, ServletHelper.parseFuzzRequestIdentifierHeader(EMPTY).getRaw()); + } + @Test + public void parseFuzzRequestIdentifierHeader1() { + Assertions.assertEquals("header", ServletHelper.parseFuzzRequestIdentifierHeader("header").getRaw()); + } + @Test + public void parseFuzzRequestIdentifierHeader2() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(true); + Assertions.assertEquals(EMPTY, ServletHelper.parseFuzzRequestIdentifierHeader(EMPTY).getRaw()); + } + } + @Test + public void parseFuzzRequestIdentifierHeader3() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(true); + String header = "1:IAST:1:IAST:pre-val:IAST:SAFE:IAST:1:IAST: "; + Assertions.assertEquals(header, ServletHelper.parseFuzzRequestIdentifierHeader(header).getRaw()); + } + } + @Test + public void parseFuzzRequestIdentifierHeader4() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelicSecurity.class, Answers.RETURNS_DEEP_STUBS)) { + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getEnabled()).thenReturn(true); + nrMock.when(() -> NewRelicSecurity.getAgent().getCurrentPolicy().getVulnerabilityScan().getIastScan().getEnabled()).thenReturn(true); + String header = "1:IAST:1:IAST:pre-val:IAST:SAFE:IAST:1:IAST:pre-key"; + Assertions.assertEquals(header, ServletHelper.parseFuzzRequestIdentifierHeader(header).getRaw()); + } + + } + +} diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/schema/StringUtilsTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/schema/StringUtilsTest.java new file mode 100644 index 000000000..9b9455fd3 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/schema/StringUtilsTest.java @@ -0,0 +1,175 @@ +package com.newrelic.api.agent.security.schema; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class StringUtilsTest { + @Test + public void testIsNotBlank(){ + Assertions.assertFalse(StringUtils.isNotBlank(StringUtils.EMPTY), "Should return false"); + Assertions.assertFalse(StringUtils.isNotBlank(null), "Should return false"); + Assertions.assertFalse(StringUtils.isNotBlank(" "), "Should return false"); + Assertions.assertTrue(StringUtils.isNotBlank("some"), "Should return true"); + Assertions.assertTrue(StringUtils.isNotBlank(" some "), "Should return true"); + } + @Test + public void testIsBlank(){ + Assertions.assertTrue(StringUtils.isBlank(StringUtils.EMPTY), "Should return true"); + Assertions.assertTrue(StringUtils.isBlank(null), "Should return true"); + Assertions.assertTrue(StringUtils.isBlank(" "), "Should return true"); + Assertions.assertFalse(StringUtils.isBlank("some"), "Should return false"); + Assertions.assertFalse(StringUtils.isBlank(" some "), "Should return false"); + } + @Test + public void testIsAnyBlank(){ + Assertions.assertTrue(StringUtils.isAnyBlank(StringUtils.EMPTY, null, " "), "Should return true"); + Assertions.assertTrue(StringUtils.isAnyBlank(null, " "), "Should return true"); + Assertions.assertTrue(StringUtils.isAnyBlank(StringUtils.EMPTY, " some"), "Should return true"); + Assertions.assertTrue(StringUtils.isAnyBlank(" ", "some"), "Should return true"); + Assertions.assertFalse(StringUtils.isAnyBlank(" some "), "Should return false"); + } + @Test + public void testSubstringBefore(){ + Assertions.assertNull(StringUtils.substringBefore(null, "*")); + Assertions.assertEquals(StringUtils.EMPTY, StringUtils.substringBefore(StringUtils.EMPTY, "*")); + Assertions.assertEquals(" ", StringUtils.substringBefore(" ", "*")); + Assertions.assertEquals( "some", StringUtils.substringBefore("some","a")); + Assertions.assertEquals("", StringUtils.substringBefore("some ", "s")); + Assertions.assertEquals(" ", StringUtils.substringBefore(" some ", "s")); + Assertions.assertEquals(" s", StringUtils.substringBefore(" some ", "o")); + } + @Test + public void testSubstringBeforeLast(){ + Assertions.assertNull(StringUtils.substringBeforeLast(null, "*")); + Assertions.assertEquals(StringUtils.EMPTY, StringUtils.substringBeforeLast(StringUtils.EMPTY, "*")); + Assertions.assertEquals(" ", StringUtils.substringBeforeLast(" ", "*")); + Assertions.assertEquals( "some", StringUtils.substringBeforeLast("some","a")); + Assertions.assertEquals( "some", StringUtils.substringBeforeLast("some",null)); + Assertions.assertEquals("", StringUtils.substringBeforeLast("some ", "s")); + Assertions.assertEquals(" ", StringUtils.substringBeforeLast(" some ", "s")); + Assertions.assertEquals(" s", StringUtils.substringBeforeLast(" some ", "o")); + Assertions.assertEquals(" s", StringUtils.substringBeforeLast(" somes ", "o")); + } + + @Test + public void testSubstring(){ + Assertions.assertNull(StringUtils.substring(null, 0, 0)); + Assertions.assertEquals(StringUtils.EMPTY, StringUtils.substring(StringUtils.EMPTY, 0, 0)); + Assertions.assertEquals("", StringUtils.substring(" ", 0, 0)); + Assertions.assertEquals( "", StringUtils.substring("some",0, 0)); + Assertions.assertEquals( "s", StringUtils.substring("some",0, 1)); + Assertions.assertEquals("o", StringUtils.substring("some ", 1, 2)); + Assertions.assertEquals("me", StringUtils.substring("some", 2, 5)); + Assertions.assertEquals("m", StringUtils.substring("some", -2, -1)); + Assertions.assertEquals("", StringUtils.substring("some", -5, -6)); + } + @Test + public void testAppendIfMissing0(){ + String FILES = "files"; + String FILES_EXT = "files.ext"; + Assertions.assertEquals(StringUtils.appendIfMissing(StringUtils.EMPTY, ""), ""); + Assertions.assertEquals(StringUtils.appendIfMissing(StringUtils.EMPTY, "", ""), ""); + Assertions.assertEquals(StringUtils.appendIfMissing(FILES, "", new CharSequence[]{null}), "files"); + Assertions.assertEquals(StringUtils.appendIfMissing(FILES, ".ext", ".txt"), "files.ext"); + Assertions.assertEquals(StringUtils.appendIfMissing(FILES_EXT, ".ext", ""), "files.ext"); + Assertions.assertEquals(StringUtils.appendIfMissing(FILES_EXT, ".Ext", ""), "files.ext"); + Assertions.assertEquals(StringUtils.appendIfMissing(FILES_EXT, ".txt", ".ext"), "files.ext"); + Assertions.assertEquals(StringUtils.appendIfMissing(FILES, ".txt", ".pdf", ".jar"), "files.txt"); + } + + @Test + public void testAppendIfMissingIgnoreCase(){ + String FILES = "files"; + String FILES_EXT = "files.ext"; + Assertions.assertEquals(StringUtils.appendIfMissingIgnoreCase(StringUtils.EMPTY, ""), ""); + Assertions.assertEquals(StringUtils.appendIfMissingIgnoreCase(StringUtils.EMPTY, "", ""), ""); + Assertions.assertEquals(StringUtils.appendIfMissingIgnoreCase(FILES, "", new CharSequence[]{null}), "files"); + Assertions.assertEquals(StringUtils.appendIfMissingIgnoreCase(FILES, ".ext", ".txt"), "files.ext"); + Assertions.assertEquals(StringUtils.appendIfMissingIgnoreCase(FILES_EXT, ".ext", ""), "files.ext"); + Assertions.assertEquals(StringUtils.appendIfMissingIgnoreCase(FILES_EXT, ".Ext", ""), "files.ext"); + Assertions.assertEquals(StringUtils.appendIfMissingIgnoreCase(FILES_EXT, ".txt", ".ext"), "files.ext"); + Assertions.assertEquals(StringUtils.appendIfMissingIgnoreCase(FILES, ".txt", ".pdf", ".jar"), "files.txt"); + } + @Test + public void testIsEmpty(){ + Assertions.assertTrue(StringUtils.isEmpty(StringUtils.EMPTY), "Should return false"); + Assertions.assertTrue(StringUtils.isEmpty(null), "Should return true"); + Assertions.assertFalse(StringUtils.isEmpty(" "), "Should return false"); + Assertions.assertFalse(StringUtils.isEmpty("some"), "Should return false"); + Assertions.assertFalse(StringUtils.isEmpty(" some "), "Should return false"); + } + + @Test + public void testSplitByWholeSeparatorWorker(){ + Assertions.assertNull(StringUtils.splitByWholeSeparatorWorker(null, "", 1, false), "Should return false"); + Assertions.assertArrayEquals(StringUtils.splitByWholeSeparatorWorker(StringUtils.EMPTY, "", 1, false), new String[]{},"Should return false"); + Assertions.assertTrue(StringUtils.isBlank(" "), "Should return false"); + Assertions.assertFalse(StringUtils.isBlank("some"), "Should return true"); + Assertions.assertFalse(StringUtils.isBlank(" some "), "Should return true"); + } + + + @Test + public void testReplace(){ + String txt = "some"; + Assertions.assertNull(StringUtils.replace(null, null, null), "Should return true"); + Assertions.assertEquals(StringUtils.EMPTY, StringUtils.replace(StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY)); + Assertions.assertEquals(txt, StringUtils.replace(txt, StringUtils.EMPTY, StringUtils.EMPTY)); + Assertions.assertEquals("sOMe", StringUtils.replace(txt, "om", "OM")); + Assertions.assertEquals(txt, StringUtils.replace(txt, "xyz", StringUtils.EMPTY)); + Assertions.assertEquals(StringUtils.EMPTY, StringUtils.replace(StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY)); + } + @Test + public void testEquals(){ + Assertions.assertTrue(StringUtils.equals(null, null), "Should return true"); + Assertions.assertFalse(StringUtils.equals(null, StringUtils.EMPTY), "Should return false"); + Assertions.assertTrue(StringUtils.equals(StringUtils.EMPTY, StringUtils.EMPTY), "Should return true"); + Assertions.assertTrue(StringUtils.equals("some", "some"), "Should return true"); + Assertions.assertFalse(StringUtils.equals("some", "Some"), "Should return false"); + Assertions.assertFalse(StringUtils.equals("some", "somE"), "Should return false"); + } + @Test + public void testEqualsAny(){ + Assertions.assertTrue(StringUtils.equalsAny(null, (CharSequence) null), "Should return true"); + Assertions.assertTrue(StringUtils.equalsAny(null, StringUtils.EMPTY, null), "Should return false"); + Assertions.assertTrue(StringUtils.equalsAny(StringUtils.EMPTY, StringUtils.EMPTY), "Should return true"); + Assertions.assertTrue(StringUtils.equalsAny("some", "some"), "Should return true"); + Assertions.assertFalse(StringUtils.equalsAny("some", "Some"), "Should return false"); + Assertions.assertFalse(StringUtils.equalsAny("some", "somE"), "Should return false"); + Assertions.assertTrue(StringUtils.equalsAny("some", "Some", "some"), "Should return true"); + Assertions.assertTrue(StringUtils.equalsAny("some", "somE", "some"), "Should return true"); + } + @Test + public void testStartsWith(){ + Assertions.assertTrue(StringUtils.startsWith(null, (CharSequence) null), "Should return true"); + Assertions.assertFalse(StringUtils.startsWith(null, StringUtils.EMPTY), "Should return false"); + Assertions.assertTrue(StringUtils.startsWith(StringUtils.EMPTY, StringUtils.EMPTY), "Should return true"); + Assertions.assertTrue(StringUtils.startsWith("some", "some"), "Should return true"); + Assertions.assertFalse(StringUtils.startsWith("some", "Some"), "Should return false"); + Assertions.assertTrue(StringUtils.startsWith("something", "some"), "Should return false"); + Assertions.assertFalse(StringUtils.startsWith("something", "thing"), "Should return true"); + } + @Test + public void testStartsWithAny(){ + Assertions.assertTrue(StringUtils.startsWith(null, (CharSequence) null), "Should return true"); + Assertions.assertFalse(StringUtils.startsWith(null, StringUtils.EMPTY), "Should return false"); + Assertions.assertTrue(StringUtils.startsWith(StringUtils.EMPTY, StringUtils.EMPTY), "Should return true"); + Assertions.assertTrue(StringUtils.startsWith("some", "some"), "Should return true"); + Assertions.assertFalse(StringUtils.startsWith("some", "Some"), "Should return false"); + Assertions.assertTrue(StringUtils.startsWithAny("something", "some"), "Should return false"); + Assertions.assertFalse(StringUtils.startsWithAny("something", "thing"), "Should return true"); + Assertions.assertTrue(StringUtils.startsWithAny("something", "thing", "so"), "Should return true"); + } + @Test + public void testStartsWithIgnoreCase(){ + Assertions.assertTrue(StringUtils.startsWithIgnoreCase(null, (CharSequence) null), "Should return true"); + Assertions.assertFalse(StringUtils.startsWithIgnoreCase(null, StringUtils.EMPTY), "Should return false"); + Assertions.assertTrue(StringUtils.startsWithIgnoreCase(StringUtils.EMPTY, StringUtils.EMPTY), "Should return true"); + Assertions.assertTrue(StringUtils.startsWithIgnoreCase("some", "some"), "Should return true"); + Assertions.assertTrue(StringUtils.startsWithIgnoreCase("some", "Some"), "Should return false"); + Assertions.assertTrue(StringUtils.startsWithIgnoreCase("something", "some"), "Should return false"); + Assertions.assertFalse(StringUtils.startsWithIgnoreCase("something", "thing"), "Should return true"); + } + + +} diff --git a/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/utils/SSRFUtilsTest.java b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/utils/SSRFUtilsTest.java new file mode 100644 index 000000000..03aed4485 --- /dev/null +++ b/newrelic-security-api/src/test/java/com/newrelic/api/agent/security/utils/SSRFUtilsTest.java @@ -0,0 +1,19 @@ +package com.newrelic.api.agent.security.utils; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static com.newrelic.api.agent.security.schema.StringUtils.EMPTY; + +public class SSRFUtilsTest { + + @Test + public void generateTracingHeaderValue() { + String previousVal = "prev", executionId = "executionId_"+ UUID.randomUUID(); + String apiId = "apiId_"+ UUID.randomUUID(), appUUID = "appUUID"+ UUID.randomUUID(); + Assertions.assertEquals(String.format("%s/%s/%s;", appUUID, apiId, executionId), SSRFUtils.generateTracingHeaderValue(EMPTY, apiId, executionId, appUUID)); + Assertions.assertEquals(String.format("%s;%s/%s/%s;", previousVal, appUUID, apiId, executionId), SSRFUtils.generateTracingHeaderValue(previousVal, apiId, executionId, appUUID)); + } +} From 28c0dd2f5c7a5a240cdeb794039870152a26046c Mon Sep 17 00:00:00 2001 From: idawda Date: Thu, 16 Nov 2023 18:50:25 +0530 Subject: [PATCH 02/17] Unit test for newrelic-security-agent module --- newrelic-security-agent/build.gradle | 2 + .../agent/security/AgentConfigTest.java | 60 +++ .../agent/security/AgentInfoTest.java | 91 +++++ .../dispatcher/DispatcherTest.java | 49 +++ .../helper/DynamoDBRequestConverterTest.java | 342 ++++++++++++++++++ .../instrumentator/utils/AgentUtilsTest.java | 113 ++++++ .../utils/CallbackUtilsTest.java | 43 +++ .../CollectorConfigurationUtilsTest.java | 69 ++++ .../utils/ExecutionIDGeneratorTest.java | 15 + .../filelogging/LogFileHelperTest.java | 70 ++++ .../schedulers/FileCleanerTest.java | 26 ++ .../websocket/JsonConverterTest.java | 37 ++ 12 files changed, 917 insertions(+) create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/AgentConfigTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/AgentInfoTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/dispatcher/DispatcherTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/helper/DynamoDBRequestConverterTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/AgentUtilsTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/CallbackUtilsTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/CollectorConfigurationUtilsTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/ExecutionIDGeneratorTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/intcodeagent/filelogging/LogFileHelperTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/intcodeagent/schedulers/FileCleanerTest.java create mode 100644 newrelic-security-agent/src/test/java/com/newrelic/agent/security/intcodeagent/websocket/JsonConverterTest.java diff --git a/newrelic-security-agent/build.gradle b/newrelic-security-agent/build.gradle index 5314eca31..d0fc9a579 100644 --- a/newrelic-security-agent/build.gradle +++ b/newrelic-security-agent/build.gradle @@ -77,6 +77,8 @@ dependencies { shadowIntoJar 'net.openhft:zero-allocation-hashing:0.16' shadowIntoJar 'com.github.oshi:oshi-core:6.4.1' shadowIntoJar "com.newrelic.agent.java:newrelic-api:${nrAPIVersion}" + testImplementation('org.mockito:mockito-inline:4.5.1') + testImplementation('software.amazon.awssdk:dynamodb:2.16.46') } /** diff --git a/newrelic-security-agent/src/test/java/com/newrelic/agent/security/AgentConfigTest.java b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/AgentConfigTest.java new file mode 100644 index 000000000..ed0ba2316 --- /dev/null +++ b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/AgentConfigTest.java @@ -0,0 +1,60 @@ +package com.newrelic.agent.security; + +import com.newrelic.agent.security.util.IUtilConstants; +import com.newrelic.api.agent.NewRelic; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + +public class AgentConfigTest { + + @Test + public void applyRequiredGroup() { + AgentConfig.getInstance().instantiate(); + Assert.assertEquals("IAST", AgentConfig.getInstance().getGroupName()); + } + @Test + public void applyRequiredGroup1() { + try (MockedStatic nrMock = Mockito.mockStatic(NewRelic.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(NewRelic.getAgent().getConfig().getValue(IUtilConstants.SECURITY_MODE)).thenReturn("RASP"); + nrMock.when(NewRelic.getAgent().getConfig().getValue(eq(IUtilConstants.NR_SECURITY_ENABLED), any())).thenReturn(false); + AgentConfig.getInstance().instantiate(); + Assert.assertEquals("RASP", AgentConfig.getInstance().getGroupName()); + nrMock.reset(); + nrMock.clearInvocations(); + } + } + @Test + public void isNRSecurityEnabled() { + AgentConfig.getInstance().instantiate(); + Assert.assertFalse(AgentConfig.getInstance().isNRSecurityEnabled()); + } + @Test + public void setK2HomePath() { + Assert.assertTrue(AgentConfig.getInstance().setK2HomePath()); + } + @Test + public void setK2HomePath1() throws IOException { + String AGENT_HOME = "/tmp/file_"+ UUID.randomUUID(); + try (MockedStatic nrMock = Mockito.mockStatic(NewRelic.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(NewRelic.getAgent().getConfig().getValue("agent_home")).thenReturn(AGENT_HOME); + + Assert.assertTrue(AgentConfig.getInstance().setK2HomePath()); + Assert.assertEquals(AGENT_HOME+"/nr-security-home", AgentConfig.getInstance().getK2Home()); + nrMock.reset(); + nrMock.clearInvocations(); + } finally { + FileUtils.forceDeleteOnExit(new File(AGENT_HOME)); + } + } +} diff --git a/newrelic-security-agent/src/test/java/com/newrelic/agent/security/AgentInfoTest.java b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/AgentInfoTest.java new file mode 100644 index 000000000..e60db81a4 --- /dev/null +++ b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/AgentInfoTest.java @@ -0,0 +1,91 @@ +package com.newrelic.agent.security; + +import com.newrelic.agent.security.intcodeagent.models.collectorconfig.CollectorConfig; +import com.newrelic.agent.security.intcodeagent.models.javaagent.ApplicationInfoBean; +import com.newrelic.agent.security.intcodeagent.models.javaagent.EventStats; +import com.newrelic.agent.security.intcodeagent.models.javaagent.Identifier; +import com.newrelic.agent.security.intcodeagent.models.javaagent.IdentifierEnvs; +import com.newrelic.agent.security.intcodeagent.models.javaagent.JAHealthCheck; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.concurrent.atomic.AtomicInteger; + +public class AgentInfoTest { + @BeforeClass + public static void setUp() { + Identifier identifier = new Identifier(); + identifier.setKind(IdentifierEnvs.HOST); + AgentInfo.getInstance().setIdentifier(identifier); + } + + @Test + public void generateAppInfo() { + ApplicationInfoBean appInfoBean = AgentInfo.getInstance().generateAppInfo(Mockito.mock(CollectorConfig.class)); + Assert.assertEquals(AgentInfo.getInstance().getApplicationUUID(), appInfoBean.getApplicationUUID()); + Assert.assertEquals("STATIC", appInfoBean.getAgentAttachmentType()); + Assert.assertEquals(AgentInfo.getInstance().getVMPID(), appInfoBean.getPid()); + Assert.assertEquals("JAVA", appInfoBean.getCollectorType()); + Assert.assertEquals("Java", appInfoBean.getLanguage()); + } + @Test + public void initializeHC() { + AgentInfo.getInstance().generateAppInfo(Mockito.mock(CollectorConfig.class)); + AgentInfo.getInstance().initialiseHC(); + JAHealthCheck jaHealthCheck = AgentInfo.getInstance().getJaHealthCheck(); + assertion(jaHealthCheck, new AtomicInteger(0), new EventStats()); + } + @Test + public void isAgentActive() { + Assert.assertFalse(AgentInfo.getInstance().isAgentActive()); + } + @Test + public void initializeHC1() { + AgentInfo.getInstance().generateAppInfo(Mockito.mock(CollectorConfig.class)); + AgentInfo.getInstance().initialiseHC(); + JAHealthCheck jaHealthCheck = AgentInfo.getInstance().getJaHealthCheck(); + jaHealthCheck.incrementInvokedHookCount(); + jaHealthCheck.incrementDropCount(); + jaHealthCheck.incrementProcessedCount(); + jaHealthCheck.incrementEventSentCount(); + jaHealthCheck.incrementHttpRequestCount(); + jaHealthCheck.incrementExitEventSentCount(); + jaHealthCheck.incrementEventRejectionCount(); + jaHealthCheck.incrementEventProcessingErrorCount(); + jaHealthCheck.incrementEventSendRejectionCount(); + jaHealthCheck.incrementEventSendErrorCount(); + assertion(jaHealthCheck, new AtomicInteger(1), new EventStats()); + + // resetting the JAHealthCheck + jaHealthCheck.reset(); + assertion(jaHealthCheck, new AtomicInteger(0), new EventStats()); + } + + private void assertion(JAHealthCheck jaHealthCheck, AtomicInteger atomicInteger, EventStats expectedEventStats) { + Assert.assertEquals(AgentInfo.getInstance().getApplicationUUID(), jaHealthCheck.getApplicationUUID()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getInvokedHookCount()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getEventDropCount().intValue()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getEventProcessed().intValue()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getEventSentCount().get()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getHttpRequestCount().get()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getExitEventSentCount().get()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getEventRejectionCount().get()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getEventProcessingErrorCount().get()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getEventSendRejectionCount().get()); + Assert.assertEquals(atomicInteger.get(), jaHealthCheck.getEventSendErrorCount().get()); + + assertEventStats(expectedEventStats, jaHealthCheck.getExitEventStats()); + assertEventStats(expectedEventStats, jaHealthCheck.getIastEventStats()); + assertEventStats(expectedEventStats, jaHealthCheck.getRaspEventStats()); + Assert.assertEquals("HOST", jaHealthCheck.getKind().name()); + } + + private void assertEventStats(EventStats expectedEventStats, EventStats actualEventStats) { + Assert.assertSame(expectedEventStats.getErrorCount().get(), actualEventStats.getErrorCount().get()); + Assert.assertSame(expectedEventStats.getProcessed().get(), actualEventStats.getProcessed().get()); + Assert.assertSame(expectedEventStats.getSent().get(), actualEventStats.getSent().get()); + Assert.assertSame(expectedEventStats.getRejected().get(), actualEventStats.getRejected().get()); + } +} diff --git a/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/dispatcher/DispatcherTest.java b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/dispatcher/DispatcherTest.java new file mode 100644 index 000000000..ab89a0bb6 --- /dev/null +++ b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/dispatcher/DispatcherTest.java @@ -0,0 +1,49 @@ +package com.newrelic.agent.security.instrumentator.dispatcher; + +import com.newrelic.agent.security.AgentInfo; +import com.newrelic.agent.security.intcodeagent.filelogging.FileLoggerThreadPool; +import com.newrelic.agent.security.intcodeagent.models.collectorconfig.CollectorConfig; +import com.newrelic.agent.security.intcodeagent.models.javaagent.Identifier; +import com.newrelic.agent.security.intcodeagent.models.javaagent.IdentifierEnvs; +import com.newrelic.api.agent.security.schema.AbstractOperation; +import com.newrelic.api.agent.security.schema.HttpRequest; +import com.newrelic.api.agent.security.schema.HttpResponse; +import com.newrelic.api.agent.security.schema.SecurityMetaData; +import com.newrelic.api.agent.security.schema.UserClassEntity; +import com.newrelic.api.agent.security.schema.VulnerabilityCaseType; +import com.newrelic.api.agent.security.schema.operation.*; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.HashMap; + +public class DispatcherTest { + + private final String CLASS_NAME = "className"; + private final String METHOD_NAME = "methodName"; + + @Mock + private FileLoggerThreadPool logger; + + + @BeforeClass + public static void beforeClass() { + CollectorConfig collectorConfig = Mockito.mock(CollectorConfig.class); + Identifier identifier = new Identifier(); + identifier.setKind(IdentifierEnvs.HOST); + AgentInfo.getInstance().setIdentifier(identifier); + AgentInfo.getInstance().generateAppInfo(collectorConfig); + AgentInfo.getInstance().initialiseHC(); + } + + @Test + public void testProcessNullEvent() throws Exception { + Dispatcher dispatcher = new Dispatcher(null, Mockito.mock(SecurityMetaData.class)); + Assert.assertNull(dispatcher.call()); + } + +} diff --git a/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/helper/DynamoDBRequestConverterTest.java b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/helper/DynamoDBRequestConverterTest.java new file mode 100644 index 000000000..baf12d197 --- /dev/null +++ b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/helper/DynamoDBRequestConverterTest.java @@ -0,0 +1,342 @@ +package com.newrelic.agent.security.instrumentator.helper; + +import com.newrelic.api.agent.security.schema.helper.DynamoDBRequest; +import org.json.simple.JSONObject; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +import static com.newrelic.api.agent.security.schema.operation.DynamoDBOperation.Category.*; + +public class DynamoDBRequestConverterTest { + public final String PARAMETERS = "parameters"; + private final String PAYLOAD = "payload"; + private final String QUERY = "query"; + private final String PAYLOAD_TYPE = "payloadType"; + private final String OP = "operation"; + private final String EXPRESSION = "#col = :val"; + private final String TABLE = "test"; + private final String STMT = "select * from test;"; + private final DynamoDBRequest REQUEST = new DynamoDBRequest(null, OP); + @Test(expected = RuntimeException.class) + public void testConvert0(){ + DynamoDBRequestConverter.convert(DQL, REQUEST); + } + @Test + public void testConvert1(){ + REQUEST.setQuery(new DynamoDBRequest.Query()); + REQUEST.setQueryType(null); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertNull(obj.get(PAYLOAD_TYPE)); + Assert.assertEquals("{}", obj.get(PAYLOAD).toString()); + } + @Test + public void testConvert2(){ + REQUEST.setQuery(new DynamoDBRequest.Query()); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + Assert.assertEquals("{}", obj.get(PAYLOAD).toString()); + } + @Test + public void testConvert3(){ + REQUEST.setQuery(new DynamoDBRequest.Query()); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + Assert.assertEquals("{}", obj.get(PAYLOAD).toString()); + } + + @Test + public void testPartiQL(){ + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setStatement(STMT); + query.setParameters(new Object()); + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(PARTIQL, REQUEST); + Assert.assertEquals(STMT, obj.get(QUERY)); + } + + @Test + public void testConvertKeyEx(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + map.put("key1", "val1"); + + ArrayList list = new ArrayList<>(); + list.add(map); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setKey(list); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("key")); + Assert.assertEquals(list, new ArrayList<>(Arrays.asList((Object[]) payload.get("key")))); + } + @Test + public void testConvertItemEx(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + map.put("key1", "val1"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setItem(map); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("item")); + Assert.assertEquals(map, payload.get("item")); + } + @Test + public void testConvertExAttNames(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + map.put("key1", "val1"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setExpressionAttributeNames(map); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("expressionAttributeNames")); + Assert.assertEquals(map, payload.get("expressionAttributeNames")); + } + @Test + public void testConvertExAttValues(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + map.put("key1", "val1"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setExpressionAttributeValues(map); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("expressionAttributeValues")); + Assert.assertEquals(map, payload.get("expressionAttributeValues")); + } + @Test + public void testConvertAttToGet(){ + ArrayList list1 = new ArrayList<>(); + list1.add("col1"); + list1.add("col2"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setAttributesToGet(list1); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("attributesToGet")); + Assert.assertEquals(list1, payload.get("attributesToGet")); + } + @Test + public void testConvertScanFilter(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + map.put("key1", "val1"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setScanFilter(map); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("scanFilter")); + Assert.assertEquals(map, payload.get("scanFilter")); + } + @Test + public void testConvertQueryFilter(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + map.put("key1", "val1"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setQueryFilter(map); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("queryFilter")); + Assert.assertEquals(map, payload.get("queryFilter")); + } + @Test + public void testConvertExpected(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + map.put("key1", "val1"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setExpected(map); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("expected")); + Assert.assertEquals(map, payload.get("expected")); + } + @Test + public void testConvertAttUpdates(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + map.put("key1", "val1"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setAttributeUpdates(map); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("attributeUpdates")); + Assert.assertEquals(map, payload.get("attributeUpdates")); + } + + @Test + public void testConvertParameters(){ + ArrayList list1 = new ArrayList<>(); + list1.add("val1"); + list1.add("val2"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setParameters(list1); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get(PARAMETERS)); + Assert.assertEquals(list1, new ArrayList<>(Arrays.asList((Object[]) payload.get(PARAMETERS)))); + } + @Test + public void testConvertAll(){ + HashMap map = new HashMap<>(); + map.put("key", "val"); + + ArrayList list1 = new ArrayList<>(); + list1.add("col1"); + + DynamoDBRequest.Query query = new DynamoDBRequest.Query(); + query.setKey(map); + query.setItem(list1); + query.setTableName(TABLE); + query.setConditionExpression(EXPRESSION); + query.setKeyConditionExpression(EXPRESSION); + query.setFilterExpression(EXPRESSION); + query.setUpdateExpression(EXPRESSION); + query.setProjectionExpression(EXPRESSION); + query.setExpressionAttributeNames(map); + query.setExpressionAttributeValues(map); + query.setAttributesToGet(list1); + query.setQueryFilter(map); + query.setScanFilter(map); + query.setExpected(list1); + query.setAttributeUpdates(map); + query.setStatement(STMT); + query.setParameters(map); + + REQUEST.setQuery(query); + JSONObject obj = DynamoDBRequestConverter.convert(DQL, REQUEST); + Assert.assertEquals(OP, obj.get(PAYLOAD_TYPE)); + + + JSONObject payload = (JSONObject) obj.get(PAYLOAD); + Assert.assertNotNull(payload); + + Assert.assertNotNull(payload.get("key")); + Assert.assertEquals(map, payload.get("key")); + + Assert.assertNotNull(payload.get("item")); + Assert.assertEquals(list1, new ArrayList<>(Arrays.asList(((Object[]) payload.get("item"))))); + + Assert.assertNotNull(payload.get("tableName")); + Assert.assertEquals(TABLE, payload.get("tableName")); + + Assert.assertNotNull(payload.get("conditionExpression")); + Assert.assertEquals(EXPRESSION, payload.get("conditionExpression")); + + Assert.assertNotNull(payload.get("keyConditionExpression")); + Assert.assertEquals(EXPRESSION, payload.get("keyConditionExpression")); + + Assert.assertNotNull(payload.get("filterExpression")); + Assert.assertEquals(EXPRESSION, payload.get("filterExpression")); + + Assert.assertNotNull(payload.get("updateExpression")); + Assert.assertEquals(EXPRESSION, payload.get("updateExpression")); + + Assert.assertNotNull(payload.get("projectionExpression")); + Assert.assertEquals(EXPRESSION, payload.get("projectionExpression")); + + Assert.assertNotNull(payload.get("expressionAttributeNames")); + Assert.assertEquals(map, payload.get("expressionAttributeNames")); + + Assert.assertNotNull(payload.get("expressionAttributeValues")); + Assert.assertEquals(map, payload.get("expressionAttributeValues")); + + Assert.assertNotNull(payload.get("attributesToGet")); + Assert.assertEquals(list1, payload.get("attributesToGet")); + + Assert.assertNotNull(payload.get("queryFilter")); + Assert.assertEquals(map, payload.get("queryFilter")); + + Assert.assertNotNull(payload.get("scanFilter")); + Assert.assertEquals(map, payload.get("scanFilter")); + + Assert.assertNotNull(payload.get("expected")); + Assert.assertEquals(list1, new ArrayList<>(Arrays.asList(((Object[]) payload.get("expected"))))); + + Assert.assertNotNull(payload.get("statement")); + Assert.assertEquals(STMT, payload.get("statement")); + + Assert.assertNotNull(payload.get("attributeUpdates")); + Assert.assertEquals(map, payload.get("attributeUpdates")); + + Assert.assertNotNull(payload.get(PARAMETERS)); + Assert.assertEquals(map, payload.get(PARAMETERS)); + } + +} diff --git a/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/AgentUtilsTest.java b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/AgentUtilsTest.java new file mode 100644 index 000000000..2ac52da45 --- /dev/null +++ b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/AgentUtilsTest.java @@ -0,0 +1,113 @@ +package com.newrelic.agent.security.instrumentator.utils; + +import com.newrelic.api.agent.NewRelic; +import com.newrelic.api.agent.security.schema.policy.AgentPolicy; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + +public class AgentUtilsTest { + + @Test + public void applyPolicyOverrideIfApplicable(){ + Assert.assertFalse(AgentUtils.getInstance().applyPolicyOverrideIfApplicable()); + } + + @Test + public void applyPolicyOverrideIfApplicable1(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelic.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(NewRelic.getAgent().getConfig().getValue(eq(INRSettingsKey.SECURITY_POLICY_ENFORCE), any())).thenReturn(false); + + Assert.assertFalse(AgentUtils.getInstance().applyPolicyOverrideIfApplicable()); + Assert.assertFalse(AgentUtils.getInstance().isPolicyOverridden()); + + + nrMock.reset(); + nrMock.clearInvocations(); + } + } + @Test + public void applyPolicyOverrideIfApplicable2(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelic.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(NewRelic.getAgent().getConfig().getValue(eq(INRSettingsKey.SECURITY_POLICY_ENFORCE), any())).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_VULNERABILITY_SCAN_ENABLE)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_VULNERABILITY_SCAN_IAST_SCAN_ENABLE)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_VULNERABILITY_SCAN_IAST_SCAN_PROBING_INTERVAL)).thenReturn(1); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_VULNERABILITY_SCAN_IAST_SCAN_PROBING_BATCH_SIZE)).thenReturn(1); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_ENABLE)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_IP_BLOCKING_ENABLE)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_IP_BLOCKING_ATTACKER_IP_BLOCKING)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_IP_BLOCKING_IP_DETECT_VIA_XFF)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_API_BLOCKING_ENABLE)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_API_BLOCKING_PROTECT_ALL_APIS)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_API_BLOCKING_PROTECT_KNOWN_VULNERABLE_APIS)).thenReturn(false); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_API_BLOCKING_PROTECT_ATTACKED_APIS)).thenReturn(false); + + Assert.assertFalse(AgentUtils.getInstance().applyPolicyOverrideIfApplicable()); + Assert.assertFalse(AgentUtils.getInstance().isPolicyOverridden()); + + AgentPolicy policy = AgentUtils.getInstance().getAgentPolicy(); + Assert.assertFalse(policy.getVulnerabilityScan().getEnabled()); + Assert.assertFalse(policy.getVulnerabilityScan().getIastScan().getEnabled()); + Assert.assertEquals(5, policy.getVulnerabilityScan().getIastScan().getProbing().getInterval().intValue()); + Assert.assertEquals(50, policy.getVulnerabilityScan().getIastScan().getProbing().getBatchSize().intValue()); + Assert.assertFalse(policy.getProtectionMode().getEnabled()); + Assert.assertFalse(policy.getProtectionMode().getIpBlocking().getEnabled()); + Assert.assertFalse(policy.getProtectionMode().getIpBlocking().getAttackerIpBlocking()); + Assert.assertFalse(policy.getProtectionMode().getIpBlocking().getIpDetectViaXFF()); + Assert.assertFalse(policy.getProtectionMode().getApiBlocking().getProtectAllApis()); + Assert.assertFalse(policy.getProtectionMode().getApiBlocking().getProtectKnownVulnerableApis()); + Assert.assertFalse(policy.getProtectionMode().getApiBlocking().getProtectAttackedApis()); + + nrMock.reset(); + nrMock.clearInvocations(); + } + } + @Test + public void applyPolicyOverrideIfApplicable3(){ + try (MockedStatic nrMock = Mockito.mockStatic(NewRelic.class, Answers.RETURNS_DEEP_STUBS)){ + nrMock.when(NewRelic.getAgent().getConfig().getValue(eq(INRSettingsKey.SECURITY_POLICY_ENFORCE), any())).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_VULNERABILITY_SCAN_ENABLE)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_VULNERABILITY_SCAN_IAST_SCAN_ENABLE)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_VULNERABILITY_SCAN_IAST_SCAN_PROBING_INTERVAL)).thenReturn(10); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_VULNERABILITY_SCAN_IAST_SCAN_PROBING_BATCH_SIZE)).thenReturn(10); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_ENABLE)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_IP_BLOCKING_ENABLE)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_IP_BLOCKING_ATTACKER_IP_BLOCKING)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_IP_BLOCKING_IP_DETECT_VIA_XFF)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_API_BLOCKING_ENABLE)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_API_BLOCKING_PROTECT_ALL_APIS)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_API_BLOCKING_PROTECT_KNOWN_VULNERABLE_APIS)).thenReturn(true); + nrMock.when(NewRelic.getAgent().getConfig().getValue(INRSettingsKey.SECURITY_POLICY_PROTECTION_MODE_API_BLOCKING_PROTECT_ATTACKED_APIS)).thenReturn(true); + + Assert.assertFalse(AgentUtils.getInstance().applyPolicyOverrideIfApplicable()); + Assert.assertTrue(AgentUtils.getInstance().isPolicyOverridden()); + + AgentPolicy policy = AgentUtils.getInstance().getAgentPolicy(); + Assert.assertTrue(policy.getVulnerabilityScan().getEnabled()); + Assert.assertTrue(policy.getVulnerabilityScan().getIastScan().getEnabled()); + Assert.assertEquals(10, policy.getVulnerabilityScan().getIastScan().getProbing().getInterval().intValue()); + Assert.assertEquals(10, policy.getVulnerabilityScan().getIastScan().getProbing().getBatchSize().intValue()); + Assert.assertTrue(policy.getProtectionMode().getEnabled()); + Assert.assertTrue(policy.getProtectionMode().getIpBlocking().getEnabled()); + Assert.assertTrue(policy.getProtectionMode().getIpBlocking().getAttackerIpBlocking()); + Assert.assertTrue(policy.getProtectionMode().getIpBlocking().getIpDetectViaXFF()); + Assert.assertTrue(policy.getProtectionMode().getApiBlocking().getProtectAllApis()); + Assert.assertTrue(policy.getProtectionMode().getApiBlocking().getProtectKnownVulnerableApis()); + Assert.assertTrue(policy.getProtectionMode().getApiBlocking().getProtectAttackedApis()); + + nrMock.reset(); + nrMock.clearInvocations(); + } + } + + @Test + public void applyPolicy() { + Assert.assertTrue(AgentUtils.applyPolicy(new AgentPolicy())); + } +} diff --git a/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/CallbackUtilsTest.java b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/CallbackUtilsTest.java new file mode 100644 index 000000000..e286af1e1 --- /dev/null +++ b/newrelic-security-agent/src/test/java/com/newrelic/agent/security/instrumentator/utils/CallbackUtilsTest.java @@ -0,0 +1,43 @@ +package com.newrelic.agent.security.instrumentator.utils; + +import com.newrelic.api.agent.security.schema.HttpRequest; +import com.newrelic.api.agent.security.schema.HttpResponse; +import com.newrelic.api.agent.security.schema.StringUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashSet; + +public class CallbackUtilsTest { + + @Test + public void checkForReflectedXSS () { + HashSet expected = new HashSet<>(); + expected.add(""); + Assert.assertEquals(expected, CallbackUtils.checkForReflectedXSS(new HttpRequest(), new HttpResponse())); + } + @Test + public void checkForReflectedXSS1 () { + HashSet expected = new HashSet<>(); + expected.add(""); + Assert.assertEquals(expected, CallbackUtils.checkForReflectedXSS(new HttpRequest(), new HttpResponse())); + } + @Test + public void checkForReflectedXSS2 () { + HashSet expected = new HashSet<>(); + expected.add(""); + Assert.assertEquals(expected, CallbackUtils.checkForReflectedXSS(new HttpRequest(), new HttpResponse())); + } + + @Test + public void urlDecode() { + Assert.assertEquals(StringUtils.EMPTY, CallbackUtils.urlDecode(StringUtils.EMPTY)); + Assert.assertEquals(" ", CallbackUtils.urlDecode(" ")); + Assert.assertEquals(""); + Set expected = new HashSet<>(); expected.add(""); + Set expected = new HashSet<>(); expected.add("\"}"); + + HttpResponse response = new HttpResponse(); response.getHeaders().put("key","%3Cscript%3Ehello%3C%2Fscript%3E"); + response.setResponseContentType("application/xml"); + response.getResponseBody().append("{\"script\":\"\"}"); + Assert.assertEquals(Collections.singleton("'\\''"); + + HttpResponse response = new HttpResponse(); response.getHeaders().put("key","%3Cscript%3Ehello%3C%2Fscript%3E"); + response.setResponseContentType("application/xml"); + response.getResponseBody().append("'\\'''\\''"); + Assert.assertEquals(Collections.singleton(""); - Set expected = new HashSet<>(); expected.add(""); - Set expected = new HashSet<>(); expected.add("