Skip to content

Commit

Permalink
Add another test for the diferents possibilities on the method getSet…
Browse files Browse the repository at this point in the history
…tings of CommandManagerSettings
  • Loading branch information
mcasas993 committed Oct 21, 2024
1 parent a7cf4b6 commit 4c105dd
Show file tree
Hide file tree
Showing 3 changed files with 178 additions and 64 deletions.
50 changes: 2 additions & 48 deletions plugins/command-manager/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def versions = [
slf4j: "1.7.36",
log4j: "2.23.1",
conscrypt: "2.5.2",
mockito: "4.1.0",
mockito: "5.12.0",
junit:"4.13.2"
]

Expand All @@ -89,7 +89,7 @@ dependencies {
api "org.slf4j:slf4j-api:${versions.slf4j}"
api "org.conscrypt:conscrypt-openjdk-uber:${versions.conscrypt}"

testImplementation "org.mockito:mockito-inline:${versions.mockito}"
testImplementation "org.mockito:mockito-core:${versions.mockito}"
testImplementation "junit:junit:${versions.junit}"
}

Expand Down Expand Up @@ -125,52 +125,6 @@ task integTest(type: RestIntegTestTask) {
tasks.named("check").configure { dependsOn(integTest) }


//OPCION 1
/*
// needed to be consistent with ssl host checking
String host = InetAddress.getLoopbackAddress().getHostAddress()
// location of keystore and files to generate it
File keystore = new File(project.buildDir, 'keystore/wazuh-indexer.keystore.jks')
// generate the keystore
TaskProvider createKey = tasks.register("createKey", LoggedExec) {
doFirst {
delete(keystore.parentFile)
keystore.parentFile.mkdirs()
}
outputs.file(keystore).withPropertyName('keystoreFile')
executable = "${BuildParams.runtimeJavaHome}/bin/keytool"
standardInput = new ByteArrayInputStream('FirstName LastName\nUnit\nOrganization\nCity\nState\nNL\nyes\n\n'.getBytes('UTF-8'))
args '-genkey',
'-alias', 'test-node',
'-keystore', keystore,
'-keyalg', 'RSA',
'-keysize', '2048',
'-validity', '712',
'-dname', 'CN=' + host,
'-keypass', 'keypass',
'-storepass', 'keypass'
}
//no unit tests
tasks.named("test").configure { enabled = false }
// add keystore to test classpath: it expects it there
tasks.named("processInternalClusterTestResources").configure {
from createKey
}
normalization {
runtimeClasspath {
ignore 'test-node.jks'
}
}
*/

//OPCION 2

integTest {
// The --debug-jvm command-line option makes the cluster debuggable; this makes the tests debuggable
if (System.getProperty("test.debug") != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ public static CommandManagerSettings getSettings(Environment environment, Secure
return null;
} else {
// Decrypt the keystore using the password from the request

try {
log.info("Decrypting the keystore.");
if (secureSettingsPassword == null || secureSettingsPassword.length() == 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,29 @@

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.opensearch.common.settings.KeyStoreWrapper;
import org.opensearch.common.settings.Settings;
import org.opensearch.core.common.settings.SecureString;
import org.opensearch.env.Environment;
import org.opensearch.test.OpenSearchIntegTestCase;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.PrivilegedAction;

import org.mockito.Mock;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;

@OpenSearchIntegTestCase.ClusterScope(scope = OpenSearchIntegTestCase.Scope.SUITE)
public class CommandManagerSettingsTests extends OpenSearchIntegTestCase {
Expand All @@ -37,15 +42,21 @@ public class CommandManagerSettingsTests extends OpenSearchIntegTestCase {

@Mock KeyStoreWrapper mockedKeyStoreWrapper;

@Mock Path mockedPath;

@InjectMocks
private CommandManagerSettings commandManagerSettings;

private static final Logger log = LogManager.getLogger(CommandManagerSettingsTests.class);

private static final String KEYSTORE_FILENAME = "opensearch.keystore";

@Before
@Override
public void setUp() throws Exception {
mockedKeyStoreWrapper = mock(KeyStoreWrapper.class);
mockEnvironment = mock(Environment.class);
mockedPath = mock(Path.class);
super.setUp();
}

Expand All @@ -55,13 +66,166 @@ public void closeSecureString() {
secureString.close();
}

public void testGetSettings_keystoreExists() throws Exception {
// Set up the mock to return a specific path for the config file
@Test
public void keystoreFileNotExistReturnsNull() throws Exception {
Path keyStorePath = Path.of("plugins/command-manager/src/test/resources/").toAbsolutePath();
when(mockEnvironment.configFile()).thenReturn(keyStorePath);
Path keystoreFile = Path.of(keyStorePath.toString() + "/" + KEYSTORE_FILENAME);
when(mockEnvironment.configFile()).thenReturn(keystoreFile);

try {
AccessController.doPrivileged(
(PrivilegedAction<Void>)
() -> {
when(Files.exists(keyStorePath)).thenReturn(false);
when(keyStorePath.toAbsolutePath().toString()).thenReturn(keyStorePath.toString());

CommandManagerSettings result = CommandManagerSettings.getSettings(mockEnvironment, null);

assertNull("Expected settings to be null when keystore file does not exist.", result);

return null;
});
} catch (AccessControlException e) {

}
}

// logger.error(String.format(" Attempting to read file: %s%s",
// keyStorePath,"wazuh-indexer.keystore.json"));
@Test
public void keystoreFileExistsButLoadReturnsNull() throws Exception {
Path keyStorePath = Path.of("plugins/command-manager/src/test/resources/").toAbsolutePath();
Path keystoreFile = Path.of(keyStorePath.toString() + "/" + KEYSTORE_FILENAME);
when(mockEnvironment.configFile()).thenReturn(keystoreFile);

try {
AccessController.doPrivileged(
(PrivilegedAction<Void>)
() -> {
when(Files.exists(keystoreFile)).thenReturn(true);
try {
when(KeyStoreWrapper.load(keystoreFile, anyString())).thenReturn(null);
} catch (IOException e) {

}

CommandManagerSettings result = CommandManagerSettings.getSettings(mockEnvironment, null);

assertNull("Expected settings to be null when keystore load returns null.", result);

return null;
});
} catch (AccessControlException e) {

}
}

@Test
public void shouldDecryptKeystoreWhenPasswordIsNull() throws Exception {
Path keyStorePath = Path.of("plugins/command-manager/src/test/resources/").toAbsolutePath();
Path keystoreFile = Path.of(keyStorePath.toString() + "/" + KEYSTORE_FILENAME);
when(mockEnvironment.configFile()).thenReturn(keystoreFile);

try {
AccessController.doPrivileged(
(PrivilegedAction<Void>)
() -> {
when(Files.exists(keystoreFile)).thenReturn(true);
try {
when(KeyStoreWrapper.load(keystoreFile, anyString())).thenReturn(mockedKeyStoreWrapper);

} catch (IOException e) {
log.error("Error when tryng to mock load: " + e.getMessage());
}

try {
doNothing().when(mockedKeyStoreWrapper).decrypt(new char[0]);
} catch (GeneralSecurityException | IOException | RuntimeException e) {
log.error("Error when tryng to mock decrypt: " + e.getMessage());
}

Settings settingsMock = mock(Settings.class);
Settings.Builder builderMock = mock(Settings.Builder.class);
when(builderMock.setSecureSettings(mockedKeyStoreWrapper).build()).thenReturn(settingsMock);
//when(Settings.builder().setSecureSettings(mockedKeyStoreWrapper).build()).thenReturn(settingsMock);

SecureString authUsername = new SecureString("userTesting".toCharArray());
SecureString authPassword = new SecureString("passTesting".toCharArray());
SecureString uri = new SecureString("http://localhost".toCharArray());

when(CommandManagerSettings.M_API_USERNAME.get(any())).thenReturn(authUsername);
when(CommandManagerSettings.M_API_PASSWORD.get(any())).thenReturn(authPassword);
when(CommandManagerSettings.M_API_URI.get(any())).thenReturn(uri);

CommandManagerSettings result = CommandManagerSettings.getSettings(mockEnvironment, null);

assertNotNull("Expected CommandManagerSettings to be created.", result);
assertEquals("userTesting", result.authUsername, "The username should match the configured value.");
assertEquals("passTesting", result.authPassword, "The password should match the configured value.");
assertEquals("http://localhost", result.uri, "The URI should match the configured value.");

return null;
});
} catch (AccessControlException e) {
log.error("AccesControl Error: " + e.getMessage());
}
}

@Test
public void shouldDecryptKeystoreWithPassword() throws Exception {
Path keyStorePath = Path.of("plugins/command-manager/src/test/resources/").toAbsolutePath();
Path keystoreFile = Path.of(keyStorePath.toString() + "/" + KEYSTORE_FILENAME);
when(mockEnvironment.configFile()).thenReturn(keystoreFile);

try {
AccessController.doPrivileged(
(PrivilegedAction<Void>)
() -> {
when(Files.exists(keystoreFile)).thenReturn(true);
try {
when(KeyStoreWrapper.load(keystoreFile, anyString())).thenReturn(mockedKeyStoreWrapper);

} catch (IOException e) {
log.error("Error when tryng to mock load: " + e.getMessage());
}

try {
SecureString password = new SecureString("passwordTest".toCharArray());
doNothing().when(mockedKeyStoreWrapper).decrypt(password.getChars());
} catch (GeneralSecurityException | IOException | RuntimeException e) {
log.error("Error when tryng to mock decrypt: " + e.getMessage());
}

Settings settingsMock = mock(Settings.class);
Settings.Builder builderMock = mock(Settings.Builder.class);
when(builderMock.setSecureSettings(mockedKeyStoreWrapper).build()).thenReturn(settingsMock);
//when(Settings.builder().setSecureSettings(mockedKeyStoreWrapper).build()).thenReturn(settingsMock);

SecureString authUsername = new SecureString("userTesting".toCharArray());
SecureString authPassword = new SecureString("passTesting".toCharArray());
SecureString uri = new SecureString("http://localhost".toCharArray());

when(CommandManagerSettings.M_API_USERNAME.get(any())).thenReturn(authUsername);
when(CommandManagerSettings.M_API_PASSWORD.get(any())).thenReturn(authPassword);
when(CommandManagerSettings.M_API_URI.get(any())).thenReturn(uri);

CommandManagerSettings result = CommandManagerSettings.getSettings(mockEnvironment, null);

assertNotNull("Expected CommandManagerSettings to be created.", result);
assertEquals("userTesting", result.authUsername, "The username should match the configured value.");
assertEquals("passTesting", result.authPassword, "The password should match the configured value.");
assertEquals("http://localhost", result.uri, "The URI should match the configured value.");

return null;
});
} catch (AccessControlException e) {
log.error("AccesControl Error: " + e.getMessage());
}
}


public void testValuesOfGetSettings_keystoreExists() throws Exception {
// Set up the mock to return a specific path for the config file
Path keyStorePath = Path.of("command-manager/build/testclusters/integTest-0/config").toAbsolutePath();
when(mockEnvironment.configFile()).thenReturn(keyStorePath);

try {
AccessController.doPrivileged(
Expand All @@ -70,11 +234,9 @@ public void testGetSettings_keystoreExists() throws Exception {
// Simulate an existing keystore
try {
KeyStoreWrapper keyStoreWrapper =
KeyStoreWrapper.load(
keyStorePath, "wazuh-indexer.keystore.json");
when(KeyStoreWrapper.load(any(), any()))
.thenReturn(keyStoreWrapper);
log.warn("test INSIDE+EE");
KeyStoreWrapper.load(keyStorePath);

log.info("Is keyStoreWrapper loaded? "+keyStoreWrapper.isLoaded());

this.commandManagerSettings =
CommandManagerSettings.getSettings(mockEnvironment, null);
Expand All @@ -83,13 +245,12 @@ public void testGetSettings_keystoreExists() throws Exception {
log.info("Plugin settings: {}", commandManagerSettings.toString()); // verify(keyStoreWrapper,
// times(1)).decrypt(secureString.getChars());
} catch (IOException e) {
log.warn("ERROR TEST: " + e.getMessage());
log.error("IO Error: " + e.getMessage());
}
log.warn("RETURN");
return null;
});
} catch (AccessControlException e) {

log.error("AccesControl Error: " + e.getMessage());
}
}
}

0 comments on commit 4c105dd

Please sign in to comment.