Skip to content

Commit

Permalink
Simplify the general logic of CommandManagerSettings. Apply Singleton…
Browse files Browse the repository at this point in the history
… pattern to CommanfManagerSettings.
  • Loading branch information
mcasas993 committed Oct 24, 2024
1 parent 9ff0ff5 commit a6f60ae
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 113 deletions.
6 changes: 3 additions & 3 deletions plugins/command-manager/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,9 @@ testClusters.integTest {
plugin(project.tasks.bundlePlugin.archiveFile)

// add customized keystore
keystore 'm.api.username', 'admin'
keystore 'm.api.password', 'test'
keystore 'm.api.uri', 'https://httpbin.org/post'
keystore 'm_api.auth.username', 'admin'
keystore 'm_api.auth.password', 'test'
keystore 'm_api.uri', 'https://httpbin.org/post'
}

run {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public class CommandManagerPlugin extends Plugin implements ActionPlugin, Reload

private CommandIndex commandIndex;
private CommandManagerSettings commandManagerSettings;
// private static final Logger log = LogManager.getLogger(CommandManagerSettings.class);

@Override
public Collection<Object> createComponents(
Expand All @@ -68,7 +69,10 @@ public Collection<Object> createComponents(
Supplier<RepositoriesService> repositoriesServiceSupplier) {
this.commandIndex = new CommandIndex(client, clusterService, threadPool);

this.commandManagerSettings = CommandManagerSettings.getSettings(environment, null);
this.commandManagerSettings = CommandManagerSettings.getInstance(environment);
//log.info("Plugin uri: {}", commandManagerSettings.getUri());
//log.info("Plugin username: {}", commandManagerSettings.getAuthUsername());
//log.info("Plugin password: {}", commandManagerSettings.getAuthPassword());

// HttpRestClient stuff
// String uri = "https://httpbin.org/post";
Expand All @@ -93,8 +97,8 @@ public List<RestHandler> getRestHandlers(
public List<Setting<?>> getSettings() {
return Arrays.asList(
// Register API settings
CommandManagerSettings.M_API_USERNAME,
CommandManagerSettings.M_API_PASSWORD,
CommandManagerSettings.M_API_AUTH_USERNAME,
CommandManagerSettings.M_API_AUTH_PASSWORD,
CommandManagerSettings.M_API_URI);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,50 +10,41 @@

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.common.settings.KeyStoreWrapper;
import org.opensearch.common.settings.SecureSetting;
import org.opensearch.common.settings.Setting;
import org.opensearch.common.settings.Settings;
import org.opensearch.core.common.settings.SecureString;
import org.opensearch.env.Environment;

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

import com.wazuh.commandmanager.CommandManagerSettingsException;

public final class CommandManagerSettings {
public class CommandManagerSettings {

/** The access key (ie login username) for connecting to api. */
public static final Setting<SecureString> M_API_USERNAME =
SecureSetting.secureString("m.api.username", null);
public static final Setting<SecureString> M_API_AUTH_USERNAME =
SecureSetting.secureString("m_api.auth.username", null);

/** The secret key (ie password) for connecting to api. */
public static final Setting<SecureString> M_API_PASSWORD =
SecureSetting.secureString("m.api.password", null);
public static final Setting<SecureString> M_API_AUTH_PASSWORD =
SecureSetting.secureString("m_api.auth.password", null);

/** The uri for connecting to api. */
public static final Setting<SecureString> M_API_URI =
SecureSetting.secureString("m.api.uri", null);

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

/** The name of own keystore. */
private static final String KEYSTORE_FILENAME = "opensearch.keystore";
SecureSetting.secureString("m_api.uri", null);

/** The access key (ie login username) for connecting to api. */
final String authUsername;
private final String authUsername;

/** The password for connecting to api. */
final String authPassword;
private final String authPassword;

/** The uri for connecting to api. */
final String uri;
private final String uri;

private static final Logger log = LogManager.getLogger(CommandManagerSettings.class);
private static CommandManagerSettings instance;
private final Settings settings;

/** Private default constructor */
private CommandManagerSettings(
String authUsername, String authPassword, String uri, Settings settings) {
this.authUsername = authUsername;
Expand All @@ -63,74 +54,48 @@ private CommandManagerSettings(
log.info("CommandManagerSettings created ");
}

/** Parse settings for a single client. */
public static CommandManagerSettings getSettings(
Environment environment, SecureString secureSettingsPassword) {
KeyStoreWrapper keyStoreWrapper = null;
Path keystoreFile = Path.of(environment.configFile() + "/" + KEYSTORE_FILENAME);
try {
if (!Files.exists(keystoreFile)) {
log.error(
CommandManagerSettingsException.keystoreNotExist(
keystoreFile.toAbsolutePath().toString())
.getMessage());
return null;
} else {
keyStoreWrapper = KeyStoreWrapper.load(environment.configFile(), KEYSTORE_FILENAME);
log.info("Keystore load: " + keystoreFile.toAbsolutePath().toString());
}
} catch (Exception e) {
log.error(
CommandManagerSettingsException.loadKeystoreFailed(keystoreFile.toString())
.getMessage());
return null;
/**
* Singleton instance accessor
*
* @return {@link CommandManagerSettings#instance}
*/
public static CommandManagerSettings getInstance(Environment environment) {
if (CommandManagerSettings.instance == null) {
instance = CommandManagerSettings.getSettings(environment);
}
return CommandManagerSettings.instance;
}

if (keyStoreWrapper == null) {
log.error(
CommandManagerSettingsException.keystoreNotExist(keystoreFile.toString())
.getMessage());
return null;
} else {
// Decrypt the keystore using the password from the request
try {
log.info("Decrypting the keystore.");
if (secureSettingsPassword == null || secureSettingsPassword.length() == 0) {
keyStoreWrapper.decrypt(new char[0]);
} else {
keyStoreWrapper.decrypt(secureSettingsPassword.getChars());
}
} catch (GeneralSecurityException | IOException e) {
log.error(
CommandManagerSettingsException.decryptKeystoreFailed(KEYSTORE_FILENAME)
.getMessage());
}
/** Parse settings for a single client. */
public static CommandManagerSettings getSettings(
Environment environment) {

final Settings settings = Settings.builder().setSecureSettings(keyStoreWrapper).build();
log.info("Settings created with the keystore information.");
final Settings settings = environment.settings();
assert settings != null;
log.info("Settings created with the keystore information.");

try (SecureString authUsername = M_API_USERNAME.get(settings);
SecureString authPassword = M_API_PASSWORD.get(settings);
SecureString uri = M_API_URI.get(settings); ) {
try (SecureString authUsername = M_API_AUTH_USERNAME.get(settings);
SecureString authPassword = M_API_AUTH_PASSWORD.get(settings);
SecureString uri = M_API_URI.get(settings); ) {
return new CommandManagerSettings(
authUsername.toString(),
authPassword.toString(),
uri.toString(),
environment.settings());
settings);
}
}
}


public String getAuthPassword() {
return M_API_PASSWORD.get(this.settings).toString();
return authPassword;
}

public String getAuthUsername() {
return M_API_USERNAME.get(this.settings).toString();
return authUsername;
}

public String getUri() {
return this.uri;
return uri;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
package com.wazuh.commandmanager;
package com.wazuh.commandmanager.settings;

public class CommandManagerSettingsException extends Exception {

Expand All @@ -30,27 +30,9 @@ public CommandManagerSettingsException(Throwable cause) {
super(cause);
}

// Exception for the case when the keystore does not exist
public static CommandManagerSettingsException keystoreNotExist(String keystorePath) {
return new CommandManagerSettingsException(
"The keystore does not exist at the path: " + keystorePath);
}

// Exception for the case when the keystore is empty
public static CommandManagerSettingsException keystoreEmpty(String keystorePath) {
return new CommandManagerSettingsException(
"The keystore is empty at the path: " + keystorePath);
}

// Exception for the case when load keystore failed
public static CommandManagerSettingsException loadKeystoreFailed(String keyStorePath) {
return new CommandManagerSettingsException("Load keystore: " + keyStorePath + " failed.");
}

// Exception for the case when load keystore failed
public static CommandManagerSettingsException decryptKeystoreFailed(String keyStorePath) {
return new CommandManagerSettingsException(
"Decrypt keystore: " + keyStorePath + " failed.");
public static CommandManagerSettingsException loadSettingsFailed(String keyStorePath, String errorMessage) {
return new CommandManagerSettingsException("Load settings from: " + keyStorePath + " failed. Error: " + errorMessage);
}

// Exception for the case when reload plugin with the keystore failed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public void testKeystoreFileNotExistReturnsNull() {
.thenReturn(keyStorePath.toString());

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

assertNull(
"Expected settings to be null when keystore file does not exist.",
Expand Down Expand Up @@ -111,7 +111,7 @@ public void testKeystoreFileExistsButLoadReturnsNull() {
}

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

assertNull(
"Expected settings to be null when keystore load returns null.",
Expand Down Expand Up @@ -165,28 +165,28 @@ public void testShouldDecryptKeystoreWhenPasswordIsNull() {
SecureString uri =
new SecureString("http://localhost".toCharArray());

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

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

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

return null;
Expand Down Expand Up @@ -241,28 +241,28 @@ public void testShouldDecryptKeystoreWithPassword() {
SecureString uri =
new SecureString("http://localhost".toCharArray());

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

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

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

return null;
Expand Down Expand Up @@ -294,7 +294,7 @@ public void testValuesOfGetSettings_keystoreExists() {

this.commandManagerSettings =
CommandManagerSettings.getSettings(
mockEnvironment, null);
mockEnvironment);

assertNotNull(commandManagerSettings);
log.info(
Expand Down

0 comments on commit a6f60ae

Please sign in to comment.