Skip to content

Commit

Permalink
WIP on list shared with resources
Browse files Browse the repository at this point in the history
Signed-off-by: Craig Perkins <[email protected]>
  • Loading branch information
cwperks committed Oct 15, 2024
1 parent 8057cba commit 9577c32
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ public Collection<Object> createComponents(
RESOURCE_INDEX_NAME,
SampleResource.class
);
SampleResourceSharingService.getInstance().initialize(sharingService);
if (!SampleResourceSharingService.getInstance().isInitialized()) {
SampleResourceSharingService.getInstance().initialize(sharingService);
}
return Collections.emptyList();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,11 @@

import java.util.List;

import org.opensearch.action.search.SearchRequest;
import org.opensearch.action.support.ActionFilters;
import org.opensearch.action.support.HandledTransportAction;
import org.opensearch.client.Client;
import org.opensearch.common.inject.Inject;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.action.ActionListener;
import org.opensearch.index.query.MatchAllQueryBuilder;
import org.opensearch.search.builder.SearchSourceBuilder;
import org.opensearch.security.sampleextension.resource.SampleResourceSharingService;
import org.opensearch.tasks.Task;
import org.opensearch.transport.TransportService;
Expand All @@ -39,19 +35,19 @@ public ListSampleResourceTransportAction(TransportService transportService, Acti

@Override
protected void doExecute(Task task, ListSampleResourceRequest request, ActionListener<ListSampleResourceResponse> listener) {
try (ThreadContext.StoredContext ignore = transportService.getThreadPool().getThreadContext().stashContext()) {
SearchRequest sr = new SearchRequest(".resource-sharing");
SearchSourceBuilder matchAllQuery = new SearchSourceBuilder();
matchAllQuery.query(new MatchAllQueryBuilder());
sr.source(matchAllQuery);
ActionListener<List<SampleResource>> sampleResourceListener = ActionListener.wrap(sampleResourcesList -> {
System.out.println("sampleResourcesList: " + sampleResourcesList);
listener.onResponse(new ListSampleResourceResponse(sampleResourcesList));
}, listener::onFailure);
SampleResourceSharingService.getInstance().getSharingService().listResources(sampleResourceListener);
// listener.onResponse(new ListSampleResourceResponse(sampleResources));
/* Index already exists, ignore and continue */
// nodeClient.search(sr, searchListener);
}
ActionListener<List<SampleResource>> sampleResourceListener = ActionListener.wrap(sampleResourcesList -> {
System.out.println("sampleResourcesList: " + sampleResourcesList);
listener.onResponse(new ListSampleResourceResponse(sampleResourcesList));
}, listener::onFailure);
SampleResourceSharingService.getInstance().getSharingService().listResources(sampleResourceListener);
// try (ThreadContext.StoredContext ignore = transportService.getThreadPool().getThreadContext().stashContext()) {
// SearchRequest sr = new SearchRequest(".resource-sharing");
// SearchSourceBuilder matchAllQuery = new SearchSourceBuilder();
// matchAllQuery.query(new MatchAllQueryBuilder());
// sr.source(matchAllQuery);
// listener.onResponse(new ListSampleResourceResponse(sampleResources));
/* Index already exists, ignore and continue */
// nodeClient.search(sr, searchListener);
// }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ public void assignResourceSharingService(ResourceSharingService<? extends Abstra
// Only called if security plugin is installed
System.out.println("assignResourceSharingService called");
ResourceSharingService<SampleResource> sharingService = (ResourceSharingService<SampleResource>) service;
SampleResourceSharingService.getInstance().setSharingService(sharingService);
if (SampleResourceSharingService.getInstance().isInitialized()) {
throw new IllegalStateException("Resource sharing service already initialized");
}
SampleResourceSharingService.getInstance().initialize(sharingService);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,4 @@ public boolean isInitialized() {
public ResourceSharingService<SampleResource> getSharingService() {
return sharingService;
}

public void setSharingService(ResourceSharingService<SampleResource> sharingService) {
this.sharingService = sharingService;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,6 @@ public Set<String> getBackendRoles() {

@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
return builder.startObject().field("username", name).field("backend_roles", backendRoles).endObject();
return builder.startObject().field("name", name).field("backend_roles", backendRoles).endObject();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@ public final class OpenSearchSecurityPlugin extends OpenSearchSecuritySSLPlugin
private volatile OpensearchDynamicSetting<Boolean> transportPassiveAuthSetting;
private volatile PasswordHasher passwordHasher;
private final Set<String> indicesToListen = new HashSet<>();
// CS-SUPPRESS-SINGLE: RegexpSingleline SPI Extensions are unrelated to OpenSearch extensions
private final List<ResourceSharingExtension> resourceSharingExtensions = new ArrayList<>();
// CS-ENFORCE-SINGLE

public static boolean isActionTraceEnabled() {

Expand Down Expand Up @@ -1070,6 +1073,16 @@ public Collection<Object> createComponents(
}

ResourceSharingListener.getInstance().initialize(threadPool, localClient);
// CS-SUPPRESS-SINGLE: RegexpSingleline SPI Extensions are unrelated to OpenSearch extensions
for (ResourceSharingExtension extension : resourceSharingExtensions) {
ResourceSharingService<?> resourceSharingService = new SecurityResourceSharingService<>(
localClient,
extension.getResourceIndex(),
extension.getResourceClass()
);
extension.assignResourceSharingService(resourceSharingService);
}
// CS-ENFORCE-SINGLE

// Register opensearch dynamic settings
transportPassiveAuthSetting.registerClusterSettingsChangeListener(clusterService.getClusterSettings());
Expand Down Expand Up @@ -2186,14 +2199,11 @@ public Optional<SecureSettingsFactory> getSecureSettingFactory(Settings settings
public void loadExtensions(ExtensiblePlugin.ExtensionLoader loader) {
for (ResourceSharingExtension extension : loader.loadExtensions(ResourceSharingExtension.class)) {
String resourceIndexName = extension.getResourceIndex();
ResourceSharingService<?> resourceSharingService = new SecurityResourceSharingService<>(
localClient,
extension.getResourceIndex(),
extension.getResourceClass()
);
System.out.println("loadExtensions");
System.out.println("localClient: " + localClient);
this.indicesToListen.add(resourceIndexName);
resourceSharingExtensions.add(extension);
log.info("Loaded resource, index: {}", resourceIndexName);
extension.assignResourceSharingService(resourceSharingService);
}
}
// CS-ENFORCE-SINGLE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,17 @@
import org.opensearch.client.Client;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.action.ActionListener;
import org.opensearch.index.query.MatchAllQueryBuilder;
import org.opensearch.index.query.BoolQueryBuilder;
import org.opensearch.index.query.QueryBuilders;
import org.opensearch.search.SearchHit;
import org.opensearch.search.builder.SearchSourceBuilder;
import org.opensearch.security.spi.AbstractResource;
import org.opensearch.security.spi.AbstractResourceSharingService;
import org.opensearch.security.support.ConfigConstants;
import org.opensearch.security.user.User;

import static org.opensearch.security.resource.ResourceSharingListener.RESOURCE_SHARING_INDEX;

public class SecurityResourceSharingService<T extends AbstractResource> extends AbstractResourceSharingService<T> {
public SecurityResourceSharingService(Client client, String resourceIndex, Class<T> resourceClass) {
super(client, resourceIndex, resourceClass);
Expand All @@ -36,29 +39,50 @@ public SecurityResourceSharingService(Client client, String resourceIndex, Class
@SuppressWarnings("unchecked")
@Override
public void listResources(ActionListener<List<T>> listResourceListener) {
System.out.println("SecurityResourceSharingService.listResources");
// TODO Flip this around. First query .resource-sharing and then use MGet to get all resources
T resource = newResource();
User authenticatedUser = client.threadPool().getThreadContext().getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER);
try (ThreadContext.StoredContext ignore = client.threadPool().getThreadContext().stashContext()) {
SearchRequest sr = new SearchRequest(resourceIndex);
SearchSourceBuilder matchAllQuery = new SearchSourceBuilder();
matchAllQuery.query(new MatchAllQueryBuilder());
sr.source(matchAllQuery);
/* Index already exists, ignore and continue */
SearchRequest rsr = new SearchRequest(RESOURCE_SHARING_INDEX);
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

// 1. The resource_user is the currently authenticated user
boolQuery.should(QueryBuilders.termQuery("resource_user.name", authenticatedUser.getName()));

// 2. The resource has been shared with the authenticated user
boolQuery.should(QueryBuilders.termQuery("share_with.users", authenticatedUser.getName()));

// 3. The resource has been shared with a backend role that the authenticated user has
if (!authenticatedUser.getRoles().isEmpty()) {
BoolQueryBuilder roleQuery = QueryBuilders.boolQuery();
for (String role : authenticatedUser.getRoles()) {
roleQuery.should(QueryBuilders.termQuery("share_with.backend_roles", role));
}
boolQuery.should(roleQuery);
}

// Set minimum should match to 1 to ensure at least one of the conditions is met
boolQuery.minimumShouldMatch(1);

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(boolQuery);
rsr.source(searchSourceBuilder);

ActionListener<SearchResponse> searchListener = new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse searchResponse) {
List<T> resources = new ArrayList<>();
for (SearchHit hit : searchResponse.getHits().getHits()) {
// TODO Combine with an MGET request to get resourceUser and sharedWith data
System.out.println("SearchHit: " + hit);
resource.fromSource(hit.getId(), hit.getSourceAsMap());
// TODO check what resources have been shared with the authenticatedUser
System.out.println("authenticatedUser: " + authenticatedUser);
System.out.println("resource.getResourceUser(): " + resource.getResourceUser());
if (resource.getResourceUser() != null
&& authenticatedUser.getName().equals(resource.getResourceUser().getName())) {
resources.add(resource);
}
// resource.fromSource(hit.getId(), hit.getSourceAsMap());
// // TODO check what resources have been shared with the authenticatedUser
// System.out.println("authenticatedUser: " + authenticatedUser);
// System.out.println("resource.getResourceUser(): " + resource.getResourceUser());
// if (resource.getResourceUser() != null
// && authenticatedUser.getName().equals(resource.getResourceUser().getName())) {
// resources.add(resource);
// }
}
listResourceListener.onResponse(resources);
}
Expand All @@ -68,7 +92,37 @@ public void onFailure(Exception e) {
throw new OpenSearchException("Caught exception while loading resources: " + e.getMessage());
}
};
client.search(sr, searchListener);
client.search(rsr, searchListener);

// SearchRequest sr = new SearchRequest(resourceIndex);
// SearchSourceBuilder matchAllQuery = new SearchSourceBuilder();
// matchAllQuery.query(new MatchAllQueryBuilder());
// sr.source(matchAllQuery);
// /* Index already exists, ignore and continue */
// ActionListener<SearchResponse> searchListener = new ActionListener<SearchResponse>() {
// @Override
// public void onResponse(SearchResponse searchResponse) {
// List<T> resources = new ArrayList<>();
// for (SearchHit hit : searchResponse.getHits().getHits()) {
// System.out.println("SearchHit: " + hit);
// resource.fromSource(hit.getId(), hit.getSourceAsMap());
// // TODO check what resources have been shared with the authenticatedUser
// System.out.println("authenticatedUser: " + authenticatedUser);
// System.out.println("resource.getResourceUser(): " + resource.getResourceUser());
// if (resource.getResourceUser() != null
// && authenticatedUser.getName().equals(resource.getResourceUser().getName())) {
// resources.add(resource);
// }
// }
// listResourceListener.onResponse(resources);
// }
//
// @Override
// public void onFailure(Exception e) {
// throw new OpenSearchException("Caught exception while loading resources: " + e.getMessage());
// }
// };
// client.search(sr, searchListener);
}
}
}

0 comments on commit 9577c32

Please sign in to comment.