Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Check for and perform upgrades on security configurations #4102

Merged
merged 23 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,21 @@

import java.io.IOException;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.io.FileUtils;
import org.awaitility.Awaitility;
import org.junit.AfterClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.opensearch.test.framework.TestSecurityConfig.User;
import org.opensearch.test.framework.cluster.ClusterManager;
import org.opensearch.test.framework.cluster.LocalCluster;
import org.opensearch.test.framework.cluster.TestRestClient;
Expand All @@ -38,10 +42,9 @@
public class DefaultConfigurationTests {

private final static Path configurationFolder = ConfigurationFiles.createConfigurationDirectory();
public static final String ADMIN_USER_NAME = "admin";
public static final String DEFAULT_PASSWORD = "secret";
public static final String NEW_USER = "new-user";
public static final String LIMITED_USER = "limited-user";
private static final User ADMIN_USER = new User("admin");
private static final User NEW_USER = new User("new-user");
private static final User LIMITED_USER = new User("limited-user");

@ClassRule
public static LocalCluster cluster = new LocalCluster.Builder().clusterManager(ClusterManager.SINGLENODE)
Expand All @@ -64,15 +67,64 @@ public static void cleanConfigurationDirectory() throws IOException {

@Test
public void shouldLoadDefaultConfiguration() {
try (TestRestClient client = cluster.getRestClient(NEW_USER, DEFAULT_PASSWORD)) {
try (TestRestClient client = cluster.getRestClient(NEW_USER)) {
Awaitility.await().alias("Load default configuration").until(() -> client.getAuthInfo().getStatusCode(), equalTo(200));
}
try (TestRestClient client = cluster.getRestClient(ADMIN_USER_NAME, DEFAULT_PASSWORD)) {
client.confirmCorrectCredentials(ADMIN_USER_NAME);
try (TestRestClient client = cluster.getRestClient(ADMIN_USER)) {
client.confirmCorrectCredentials(ADMIN_USER.getName());
HttpResponse response = client.get("_plugins/_security/api/internalusers");
response.assertStatusCode(200);
Map<String, Object> users = response.getBodyAs(Map.class);
assertThat(users, allOf(aMapWithSize(3), hasKey(ADMIN_USER_NAME), hasKey(NEW_USER), hasKey(LIMITED_USER)));
assertThat(
users,
allOf(aMapWithSize(3), hasKey(ADMIN_USER.getName()), hasKey(NEW_USER.getName()), hasKey(LIMITED_USER.getName()))
);
}
}

@Test
peternied marked this conversation as resolved.
Show resolved Hide resolved
public void securityRolesUgrade() throws Exception {
try (var client = cluster.getRestClient(ADMIN_USER)) {
Awaitility.await().alias("Load default configuration").until(() -> client.getAuthInfo().getStatusCode(), equalTo(200));

final var defaultRolesResponse = client.get("_plugins/_security/api/roles/");
final var rolesNames = extractFieldNames(defaultRolesResponse.getBodyAs(JsonNode.class));

final var checkForUpgrade = client.get("_plugins/_security/api/_upgrade_check");
System.out.println("checkForUpgrade Response: " + checkForUpgrade.getBody());

final var roleToDelete = "flow_framework_full_access";
final var deleteRoleResponse = client.delete("_plugins/_security/api/roles/" + roleToDelete);
deleteRoleResponse.assertStatusCode(200);

final var checkForUpgrade3 = client.get("_plugins/_security/api/_upgrade_check");
System.out.println("checkForUpgrade3 Response: " + checkForUpgrade3.getBody());

final var roleToAlter = "flow_framework_read_access";
final String patchBody = "[{ \"op\": \"replace\", \"path\": \"/cluster_permissions\", \"value\":"
+ "[\"a\",\"b\",\"c\"]"
+ "},{ \"op\": \"add\", \"path\": \"/index_permissions\", \"value\":"
+ "[{\"index_patterns\":[\"*\"],\"allowed_actions\":[\"*\"]}]"
+ "}]";
final var updateRoleResponse = client.patch("_plugins/_security/api/roles/" + roleToAlter, patchBody);
updateRoleResponse.assertStatusCode(200);
System.out.println("Updated Role Response: " + updateRoleResponse.getBody());

final var checkForUpgrade2 = client.get("_plugins/_security/api/_upgrade_check");
System.out.println("checkForUpgrade2 Response: " + checkForUpgrade2.getBody());

final var upgradeResponse = client.post("_plugins/_security/api/_upgrade_perform");
System.out.println("upgrade Response: " + upgradeResponse.getBody());

final var afterUpgradeRolesResponse = client.get("_plugins/_security/api/roles/");
final var afterUpgradeRolesNames = extractFieldNames(afterUpgradeRolesResponse.getBodyAs(JsonNode.class));
assertThat(afterUpgradeRolesResponse.getBody(), afterUpgradeRolesNames, equalTo(rolesNames));
}
}

private Set<String> extractFieldNames(final JsonNode json) {
final var set = new HashSet<String>();
json.fieldNames().forEachRemaining(set::add);
return set;
}
}
18 changes: 18 additions & 0 deletions src/integrationTest/resources/roles.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,21 @@ user_limited-user__limited-role:
allowed_actions:
- "indices:data/read/get"
- "indices:data/read/search"
flow_framework_full_access:
cluster_permissions:
- 'cluster:admin/opensearch/flow_framework/*'
- 'cluster_monitor'
index_permissions:
- index_patterns:
- '*'
allowed_actions:
- 'indices:admin/aliases/get'
- 'indices:admin/mappings/get'
- 'indices_monitor'
flow_framework_read_access:
peternied marked this conversation as resolved.
Show resolved Hide resolved
cluster_permissions:
- 'cluster:admin/opensearch/flow_framework/workflow/get'
- 'cluster:admin/opensearch/flow_framework/workflow/search'
- 'cluster:admin/opensearch/flow_framework/workflow_state/get'
- 'cluster:admin/opensearch/flow_framework/workflow_state/search'
- 'cluster:admin/opensearch/flow_framework/workflow_step/get'
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,14 @@ private ConfigurationRepository(
configCache = CacheBuilder.newBuilder().build();
}

public String getConfigDirectory() {
String lookupDir = System.getProperty("security.default_init.dir");
final String cd = lookupDir != null
? (lookupDir + "/")
: new Environment(settings, configPath).configDir().toAbsolutePath().toString() + "/opensearch-security/";
return cd;
}

private void initalizeClusterConfiguration(final boolean installDefaultConfig) {
try {
LOGGER.info("Background init thread started. Install default config?: " + installDefaultConfig);
Expand All @@ -135,10 +143,7 @@ private void initalizeClusterConfiguration(final boolean installDefaultConfig) {
if (installDefaultConfig) {

try {
String lookupDir = System.getProperty("security.default_init.dir");
final String cd = lookupDir != null
? (lookupDir + "/")
: new Environment(settings, configPath).configDir().toAbsolutePath().toString() + "/opensearch-security/";
final String cd = getConfigDirectory();
File confFile = new File(cd + "config.yml");
if (confFile.exists()) {
final ThreadContext threadContext = threadPool.getThreadContext();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,16 @@
import org.opensearch.client.node.NodeClient;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.CheckedSupplier;
import org.opensearch.common.action.ActionFuture;
import org.opensearch.common.util.concurrent.ThreadContext.StoredContext;
import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.common.Strings;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.common.transport.TransportAddress;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentHelper;
import org.opensearch.index.engine.VersionConflictEngineException;
import org.opensearch.rest.BaseRestHandler;
import org.opensearch.rest.BytesRestResponse;
Expand Down Expand Up @@ -226,7 +229,7 @@ protected final ValidationResult<SecurityConfiguration> patchEntity(
);
}

protected final ValidationResult<SecurityConfiguration> patchEntities(
protected ValidationResult<SecurityConfiguration> patchEntities(
final RestRequest request,
final JsonNode patchContent,
final SecurityConfiguration securityConfiguration
Expand Down Expand Up @@ -336,7 +339,7 @@ final void saveOrUpdateConfiguration(
final SecurityDynamicConfiguration<?> configuration,
final OnSucessActionListener<IndexResponse> onSucessActionListener
) {
saveAndUpdateConfigs(securityApiDependencies.securityIndexName(), client, getConfigType(), configuration, onSucessActionListener);
saveAndUpdateConfigsAsync(securityApiDependencies, client, getConfigType(), configuration, onSucessActionListener);
peternied marked this conversation as resolved.
Show resolved Hide resolved
}

protected final String nameParam(final RestRequest request) {
Expand Down Expand Up @@ -367,7 +370,7 @@ protected final ValidationResult<SecurityConfiguration> loadConfiguration(final
);
}

protected final ValidationResult<SecurityDynamicConfiguration<?>> loadConfiguration(
protected ValidationResult<SecurityDynamicConfiguration<?>> loadConfiguration(
final CType cType,
boolean omitSensitiveData,
final boolean logComplianceEvent
Expand Down Expand Up @@ -485,30 +488,45 @@ public final void onFailure(Exception e) {

}

public static void saveAndUpdateConfigs(
final String indexName,
public static ActionFuture<IndexResponse> saveAndUpdateConfigs(
final SecurityApiDependencies dependencies,
final Client client,
final CType cType,
final SecurityDynamicConfiguration<?> configuration
) {
final var request = createIndexRequestForConfig(dependencies, cType, configuration);
return client.index(request);
}

public static void saveAndUpdateConfigsAsync(
final SecurityApiDependencies dependencies,
final Client client,
final CType cType,
final SecurityDynamicConfiguration<?> configuration,
final ActionListener<IndexResponse> actionListener
) {
final IndexRequest ir = new IndexRequest(indexName);
final String id = cType.toLCString();
final var ir = createIndexRequestForConfig(dependencies, cType, configuration);
client.index(ir, new ConfigUpdatingActionListener<>(new String[] { cType.toLCString() }, client, actionListener));
}

private static IndexRequest createIndexRequestForConfig(
final SecurityApiDependencies dependencies,
final CType cType,
final SecurityDynamicConfiguration<?> configuration
) {
configuration.removeStatic();

final BytesReference content;
try {
client.index(
ir.id(id)
.setRefreshPolicy(RefreshPolicy.IMMEDIATE)
.setIfSeqNo(configuration.getSeqNo())
.setIfPrimaryTerm(configuration.getPrimaryTerm())
.source(id, XContentHelper.toXContent(configuration, XContentType.JSON, false)),
new ConfigUpdatingActionListener<>(new String[] { id }, client, actionListener)
);
} catch (IOException e) {
content = XContentHelper.toXContent(configuration, XContentType.JSON, ToXContent.EMPTY_PARAMS, false);
} catch (final IOException e) {
throw ExceptionsHelper.convertToOpenSearchException(e);
}

return new IndexRequest(dependencies.securityIndexName()).id(cType.toLCString())
.setRefreshPolicy(RefreshPolicy.IMMEDIATE)
.setIfSeqNo(configuration.getSeqNo())
.setIfPrimaryTerm(configuration.getPrimaryTerm())
.source(cType.toLCString(), content);
}

protected static class ConfigUpdatingActionListener<Response> implements ActionListener<Response> {
Expand Down
Loading
Loading