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

Subset of permissions check on creation #5012

Open
wants to merge 20 commits into
base: feature/api-tokens
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -38,15 +38,19 @@
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.security.action.apitokens.ApiToken;
import org.opensearch.security.action.apitokens.Permissions;
import org.opensearch.security.resolver.IndexResolverReplacer;
import org.opensearch.security.securityconf.FlattenedActionGroups;
import org.opensearch.security.securityconf.impl.CType;
import org.opensearch.security.securityconf.impl.SecurityDynamicConfiguration;
import org.opensearch.security.securityconf.impl.v7.ActionGroupsV7;
import org.opensearch.security.securityconf.impl.v7.RoleV7;
import org.opensearch.security.user.User;
import org.opensearch.security.util.MockIndexMetadataBuilder;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.opensearch.security.privileges.ActionPrivilegesTest.IndexPrivileges.IndicesAndAliases.resolved;
import static org.opensearch.security.privileges.PrivilegeEvaluatorResponseMatcher.isAllowed;
import static org.opensearch.security.privileges.PrivilegeEvaluatorResponseMatcher.isForbidden;
import static org.opensearch.security.privileges.PrivilegeEvaluatorResponseMatcher.isPartiallyOk;
Expand Down Expand Up @@ -258,6 +262,69 @@ public void hasAny_wildcard() throws Exception {
isForbidden(missingPrivileges("cluster:whatever"))
);
}

@Test
public void apiToken_explicit_failsWithWildcard() throws Exception {
SecurityDynamicConfiguration<RoleV7> roles = SecurityDynamicConfiguration.fromYaml("test_role:\n" + //
" cluster_permissions:\n" + //
" - '*'", CType.ROLES);
ActionPrivileges subject = new ActionPrivileges(roles, FlattenedActionGroups.EMPTY, null, Settings.EMPTY);
String token = "blah";
PrivilegesEvaluationContext context = ctxWithUserName("apitoken:" + token);
context.getApiTokenIndexListenerCache().getJtis().put(token, new Permissions(List.of("*"), List.of()));
// Explicit fails
assertThat(
subject.hasExplicitClusterPrivilege(context, "cluster:whatever"),
isForbidden(missingPrivileges("cluster:whatever"))
);
// Not explicit succeeds
assertThat(subject.hasClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Any succeeds
assertThat(subject.hasAnyClusterPrivilege(context, ImmutableSet.of("cluster:whatever")), isAllowed());
}

@Test
public void apiToken_succeedsWithExactMatch() throws Exception {
SecurityDynamicConfiguration<RoleV7> roles = SecurityDynamicConfiguration.fromYaml("test_role:\n" + //
" cluster_permissions:\n" + //
" - '*'", CType.ROLES);
ActionPrivileges subject = new ActionPrivileges(roles, FlattenedActionGroups.EMPTY, null, Settings.EMPTY);
String token = "blah";
PrivilegesEvaluationContext context = ctxWithUserName("apitoken:" + token);
context.getApiTokenIndexListenerCache().getJtis().put(token, new Permissions(List.of("cluster:whatever"), List.of()));
// Explicit succeeds
assertThat(subject.hasExplicitClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Not explicit succeeds
assertThat(subject.hasClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Any succeeds
assertThat(subject.hasAnyClusterPrivilege(context, ImmutableSet.of("cluster:whatever")), isAllowed());
// Any succeeds
assertThat(subject.hasAnyClusterPrivilege(context, ImmutableSet.of("cluster:whatever", "cluster:other")), isAllowed());
}

@Test
public void apiToken_succeedsWithActionGroupsExapnded() throws Exception {
SecurityDynamicConfiguration<RoleV7> roles = SecurityDynamicConfiguration.fromYaml("test_role:\n" + //
" cluster_permissions:\n" + //
" - '*'", CType.ROLES);

SecurityDynamicConfiguration<ActionGroupsV7> config = SecurityDynamicConfiguration.fromYaml(
"CLUSTER_ALL:\n allowed_actions:\n - \"cluster:*\"",
CType.ACTIONGROUPS
);

FlattenedActionGroups actionGroups = new FlattenedActionGroups(config);
ActionPrivileges subject = new ActionPrivileges(roles, actionGroups, null, Settings.EMPTY);
String token = "blah";
PrivilegesEvaluationContext context = ctxWithUserName("apitoken:" + token);
context.getApiTokenIndexListenerCache().getJtis().put(token, new Permissions(List.of("CLUSTER_ALL"), List.of()));
// Explicit succeeds
assertThat(subject.hasExplicitClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Not explicit succeeds
assertThat(subject.hasClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Any succeeds
assertThat(subject.hasClusterPrivilege(context, "cluster:monitor/main"), isAllowed());
}
}

/**
Expand Down Expand Up @@ -292,6 +359,20 @@ public void positive_full() throws Exception {
assertThat(result, isAllowed());
}

@Test
public void apiTokens_positive_full() throws Exception {
String token = "blah";
PrivilegesEvaluationContext context = ctxWithUserName("apitoken:" + token);
context.getApiTokenIndexListenerCache()
.getJtis()
.put(
token,
new Permissions(List.of("index_a11"), List.of(new ApiToken.IndexPermission(List.of("index_a11"), List.of("*"))))
);
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(context, requiredActions, resolved("index_a11"));
assertThat(result, isAllowed());
}

@Test
public void positive_partial() throws Exception {
PrivilegesEvaluationContext ctx = ctx("test_role");
Expand Down Expand Up @@ -346,6 +427,18 @@ public void negative_wrongRole() throws Exception {
assertThat(result, isForbidden(missingPrivileges(requiredActions)));
}

@Test
public void apiToken_negative_noPermissions() throws Exception {
String token = "blah";
PrivilegesEvaluationContext context = ctxWithUserName("apitoken:" + token);
context.getApiTokenIndexListenerCache()
.getJtis()
.put(token, new Permissions(List.of(), List.of(new ApiToken.IndexPermission(List.of(), List.of()))));

PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(context, requiredActions, resolved("index_a11"));
assertThat(result, isForbidden(missingPrivileges(requiredActions)));
}

@Test
public void negative_wrongAction() throws Exception {
PrivilegesEvaluationContext ctx = ctx("test_role");
Expand Down Expand Up @@ -375,6 +468,23 @@ public void positive_hasExplicit_full() {
}
}

@Test
public void apiTokens_positive_hasExplicit_full() {
String token = "blah";
PrivilegesEvaluationContext context = ctxWithUserName("apitoken:" + token);
context.getApiTokenIndexListenerCache()
.getJtis()
.put(
token,
new Permissions(List.of("index_a11"), List.of(new ApiToken.IndexPermission(List.of("index_a11"), List.of("*"))))
);

PrivilegesEvaluatorResponse result = subject.hasExplicitIndexPrivilege(context, requiredActions, resolved("index_a11"));

assertThat(result, isForbidden(missingPrivileges(requiredActions)));

}

private boolean covers(PrivilegesEvaluationContext ctx, String... indices) {
for (String index : indices) {
if (!indexSpec.covers(ctx.getUser(), index)) {
Expand Down Expand Up @@ -1017,7 +1127,11 @@ static SecurityDynamicConfiguration<RoleV7> createRoles(int numberOfRoles, int n
}

static PrivilegesEvaluationContext ctx(String... roles) {
User user = new User("test_user");
return ctxWithUserName("test-user", roles);
}

static PrivilegesEvaluationContext ctxWithUserName(String userName, String... roles) {
User user = new User(userName);
user.addAttributes(ImmutableMap.of("attrs.dept_no", "a11"));
return new PrivilegesEvaluationContext(
user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@
import org.opensearch.search.internal.SearchContext;
import org.opensearch.search.query.QuerySearchResult;
import org.opensearch.security.action.apitokens.ApiTokenAction;
import org.opensearch.security.action.apitokens.ApiTokenIndexListenerCache;
import org.opensearch.security.action.apitokens.ApiTokenUpdateAction;
import org.opensearch.security.action.apitokens.TransportApiTokenUpdateAction;
import org.opensearch.security.action.configupdate.ConfigUpdateAction;
import org.opensearch.security.action.configupdate.TransportConfigUpdateAction;
import org.opensearch.security.action.onbehalf.CreateOnBehalfOfTokenAction;
Expand Down Expand Up @@ -643,7 +646,21 @@ public List<RestHandler> getRestHandlers(
)
);
handlers.add(new CreateOnBehalfOfTokenAction(tokenManager));
handlers.add(new ApiTokenAction(cs, localClient, tokenManager));
handlers.add(
new ApiTokenAction(
cs,
localClient,
tokenManager,
Objects.requireNonNull(threadPool),
cr,
evaluator,
settings,
adminDns,
auditLog,
configPath,
principalExtractor
)
);
handlers.addAll(
SecurityRestApiActions.getHandler(
settings,
Expand Down Expand Up @@ -685,6 +702,7 @@ public UnaryOperator<RestHandler> getRestHandlerWrapper(final ThreadContext thre
List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> actions = new ArrayList<>(1);
if (!disabled && !SSLConfig.isSslOnlyMode()) {
actions.add(new ActionHandler<>(ConfigUpdateAction.INSTANCE, TransportConfigUpdateAction.class));
actions.add(new ActionHandler<>(ApiTokenUpdateAction.INSTANCE, TransportApiTokenUpdateAction.class));
// external storage does not support reload and does not provide SSL certs info
if (!ExternalSecurityKeyStore.hasExternalSslContext(settings)) {
actions.add(new ActionHandler<>(CertificatesActionType.INSTANCE, TransportCertificatesInfoNodesAction.class));
Expand Down Expand Up @@ -717,6 +735,7 @@ public void onIndexModule(IndexModule indexModule) {
dlsFlsBaseContext
)
);

indexModule.forceQueryCacheProvider((indexSettings, nodeCache) -> new QueryCache() {

@Override
Expand Down Expand Up @@ -1095,6 +1114,7 @@ public Collection<Object> createComponents(
adminDns = new AdminDNs(settings);

cr = ConfigurationRepository.create(settings, this.configPath, threadPool, localClient, clusterService, auditLog);
ApiTokenIndexListenerCache.getInstance().initialize(clusterService, localClient);

this.passwordHasher = PasswordHasherFactory.createPasswordHasher(settings);

Expand Down Expand Up @@ -2132,7 +2152,11 @@ public Collection<SystemIndexDescriptor> getSystemIndexDescriptors(Settings sett
ConfigConstants.OPENDISTRO_SECURITY_DEFAULT_CONFIG_INDEX
);
final SystemIndexDescriptor systemIndexDescriptor = new SystemIndexDescriptor(indexPattern, "Security index");
return Collections.singletonList(systemIndexDescriptor);
final SystemIndexDescriptor apiTokenSystemIndexDescriptor = new SystemIndexDescriptor(
ConfigConstants.OPENSEARCH_API_TOKENS_INDEX,
"Security API token index"
);
return List.of(systemIndexDescriptor, apiTokenSystemIndexDescriptor);
}

@Override
Expand Down
Loading
Loading