Merge pull request elastic/elasticsearch#592 from jasontedor/predicate-out-with-the-old-in-with-the-new

Remove and forbid the use of com.google.common.base.Predicate(s)?

Original commit: elastic/x-pack-elasticsearch@58e948884a
This commit is contained in:
Jason Tedor 2015-09-06 07:47:06 -04:00
commit 32812c2139
14 changed files with 137 additions and 124 deletions

View File

@ -5,7 +5,6 @@
*/ */
package org.elasticsearch.shield.action; package org.elasticsearch.shield.action;
import com.google.common.base.Predicate;
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.ActionResponse;
@ -29,7 +28,10 @@ import org.elasticsearch.shield.license.LicenseEventsNotifier;
import org.elasticsearch.shield.license.LicenseService; import org.elasticsearch.shield.license.LicenseService;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import static org.elasticsearch.shield.support.Exceptions.authorizationError; import static org.elasticsearch.shield.support.Exceptions.authorizationError;
@ -79,7 +81,7 @@ public class ShieldActionFilter extends AbstractComponent implements ActionFilte
A functional requirement - when the license of shield is disabled (invalid/expires), shield will continue A functional requirement - when the license of shield is disabled (invalid/expires), shield will continue
to operate normally, except all read operations will be blocked. to operate normally, except all read operations will be blocked.
*/ */
if (!licenseEnabled && LICENSE_EXPIRATION_ACTION_MATCHER.apply(action)) { if (!licenseEnabled && LICENSE_EXPIRATION_ACTION_MATCHER.test(action)) {
logger.error("blocking [{}] operation due to expired license. Cluster health, cluster stats and indices stats \n" + logger.error("blocking [{}] operation due to expired license. Cluster health, cluster stats and indices stats \n" +
"operations are blocked on shield license expiration. All data operations (read and write) continue to work. \n" + "operations are blocked on shield license expiration. All data operations (read and write) continue to work. \n" +
"If you have a new license, please update it. Otherwise, please reach out to your support contact.", action); "If you have a new license, please update it. Otherwise, please reach out to your support contact.", action);

View File

@ -400,7 +400,7 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
public void accessGranted(User user, String action, TransportMessage<?> message) { public void accessGranted(User user, String action, TransportMessage<?> message) {
if (!principalIsAuditor(user.principal())) { if (!principalIsAuditor(user.principal())) {
// special treatment for internal system actions - only log if explicitly told to // special treatment for internal system actions - only log if explicitly told to
if (user.isSystem() && Privilege.SYSTEM.predicate().apply(action)) { if (user.isSystem() && Privilege.SYSTEM.predicate().test(action)) {
if (events.contains(SYSTEM_ACCESS_GRANTED)) { if (events.contains(SYSTEM_ACCESS_GRANTED)) {
try { try {
enqueue(message("access_granted", action, user.principal(), null, indices(message), message), "access_granted"); enqueue(message("access_granted", action, user.principal(), null, indices(message), message), "access_granted");

View File

@ -168,7 +168,7 @@ public class LoggingAuditTrail implements AuditTrail {
String indices = indicesString(message); String indices = indicesString(message);
// special treatment for internal system actions - only log on trace // special treatment for internal system actions - only log on trace
if (user.isSystem() && Privilege.SYSTEM.predicate().apply(action)) { if (user.isSystem() && Privilege.SYSTEM.predicate().test(action)) {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
if (indices != null) { if (indices != null) {
logger.trace("{}[transport] [access_granted]\t{}, principal=[{}], action=[{}], indices=[{}], request=[{}]", prefix, originAttributes(message, transport), user.principal(), action, indices, message.getClass().getSimpleName()); logger.trace("{}[transport] [access_granted]\t{}, principal=[{}], action=[{}], indices=[{}], request=[{}]", prefix, originAttributes(message, transport), user.principal(), action, indices, message.getClass().getSimpleName());

View File

@ -19,7 +19,6 @@ import org.elasticsearch.shield.authc.support.SecuredString;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.google.common.base.Predicates.contains;
import static com.google.common.collect.Iterables.all; import static com.google.common.collect.Iterables.all;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
@ -129,8 +128,8 @@ public abstract class SessionFactory {
return true; return true;
} }
boolean allSecure = all(asList(ldapUrls), contains(STARTS_WITH_LDAPS)); boolean allSecure = all(asList(ldapUrls), s -> STARTS_WITH_LDAPS.matcher(s).find());
boolean allClear = all(asList(ldapUrls), contains(STARTS_WITH_LDAP)); boolean allClear = all(asList(ldapUrls), s -> STARTS_WITH_LDAP.matcher(s).find());
if (!allSecure && !allClear) { if (!allSecure && !allClear) {
//No mixing is allowed because we use the same socketfactory //No mixing is allowed because we use the same socketfactory

View File

@ -5,8 +5,6 @@
*/ */
package org.elasticsearch.shield.authz; package org.elasticsearch.shield.authz;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.action.CompositeIndicesRequest; import org.elasticsearch.action.CompositeIndicesRequest;
@ -33,7 +31,12 @@ import org.elasticsearch.shield.authz.indicesresolver.IndicesAndAliasesResolver;
import org.elasticsearch.shield.authz.store.RolesStore; import org.elasticsearch.shield.authz.store.RolesStore;
import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.transport.TransportRequest;
import java.util.*; import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import static org.elasticsearch.shield.support.Exceptions.authorizationError; import static org.elasticsearch.shield.support.Exceptions.authorizationError;
@ -80,12 +83,12 @@ public class InternalAuthorizationService extends AbstractComponent implements A
} }
List<String> indicesAndAliases = new ArrayList<>(); List<String> indicesAndAliases = new ArrayList<>();
Predicate<String> predicate = Predicates.or(predicates); Predicate<String> predicate = predicates.stream().reduce(s -> false, (p1, p2) -> p1.or(p2));
MetaData metaData = clusterService.state().metaData(); MetaData metaData = clusterService.state().metaData();
// TODO: can this be done smarter? I think there are usually more indices/aliases in the cluster then indices defined a roles? // TODO: can this be done smarter? I think there are usually more indices/aliases in the cluster then indices defined a roles?
for (Map.Entry<String, AliasOrIndex> entry : metaData.getAliasAndIndexLookup().entrySet()) { for (Map.Entry<String, AliasOrIndex> entry : metaData.getAliasAndIndexLookup().entrySet()) {
String aliasOrIndex = entry.getKey(); String aliasOrIndex = entry.getKey();
if (predicate.apply(aliasOrIndex)) { if (predicate.test(aliasOrIndex)) {
indicesAndAliases.add(aliasOrIndex); indicesAndAliases.add(aliasOrIndex);
} }
} }
@ -115,7 +118,7 @@ public class InternalAuthorizationService extends AbstractComponent implements A
// first, we'll check if the action is a cluster action. If it is, we'll only check it // first, we'll check if the action is a cluster action. If it is, we'll only check it
// against the cluster permissions // against the cluster permissions
if (Privilege.Cluster.ACTION_MATCHER.apply(action)) { if (Privilege.Cluster.ACTION_MATCHER.test(action)) {
Permission.Cluster cluster = permission.cluster(); Permission.Cluster cluster = permission.cluster();
if (cluster != null && cluster.check(action)) { if (cluster != null && cluster.check(action)) {
request.putInContext(INDICES_PERMISSIONS_KEY, IndicesAccessControl.ALLOW_ALL); request.putInContext(INDICES_PERMISSIONS_KEY, IndicesAccessControl.ALLOW_ALL);
@ -126,7 +129,7 @@ public class InternalAuthorizationService extends AbstractComponent implements A
} }
// ok... this is not a cluster action, let's verify it's an indices action // ok... this is not a cluster action, let's verify it's an indices action
if (!Privilege.Index.ACTION_MATCHER.apply(action)) { if (!Privilege.Index.ACTION_MATCHER.test(action)) {
throw denial(user, action, request); throw denial(user, action, request);
} }
@ -164,7 +167,7 @@ public class InternalAuthorizationService extends AbstractComponent implements A
} }
//if we are creating an index we need to authorize potential aliases created at the same time //if we are creating an index we need to authorize potential aliases created at the same time
if (Privilege.Index.CREATE_INDEX_MATCHER.apply(action)) { if (Privilege.Index.CREATE_INDEX_MATCHER.test(action)) {
assert request instanceof CreateIndexRequest; assert request instanceof CreateIndexRequest;
Set<Alias> aliases = ((CreateIndexRequest) request).aliases(); Set<Alias> aliases = ((CreateIndexRequest) request).aliases();
if (!aliases.isEmpty()) { if (!aliases.isEmpty()) {

View File

@ -5,7 +5,6 @@
*/ */
package org.elasticsearch.shield.authz; package org.elasticsearch.shield.authz;
import com.google.common.base.Predicate;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; import com.google.common.cache.LoadingCache;
@ -22,7 +21,17 @@ import org.elasticsearch.shield.authz.accesscontrol.IndicesAccessControl;
import org.elasticsearch.shield.support.AutomatonPredicate; import org.elasticsearch.shield.support.AutomatonPredicate;
import org.elasticsearch.shield.support.Automatons; import org.elasticsearch.shield.support.Automatons;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.function.Predicate;
/** /**
* Represents a permission in the system. There are 3 types of permissions: * Represents a permission in the system. There are 3 types of permissions:
@ -209,7 +218,7 @@ public interface Permission {
} }
public boolean check(String action) { public boolean check(String action) {
return predicate.apply(action); return predicate.test(action);
} }
@Override @Override
@ -279,7 +288,7 @@ public interface Permission {
public Predicate<String> load(String action) throws Exception { public Predicate<String> load(String action) throws Exception {
List<String> indices = new ArrayList<>(); List<String> indices = new ArrayList<>();
for (Group group : groups) { for (Group group : groups) {
if (group.actionMatcher.apply(action)) { if (group.actionMatcher.test(action)) {
indices.addAll(Arrays.asList(group.indices)); indices.addAll(Arrays.asList(group.indices));
} }
} }
@ -532,12 +541,12 @@ public interface Permission {
} }
public boolean indexNameMatch(String index) { public boolean indexNameMatch(String index) {
return indexNameMatcher.apply(index); return indexNameMatcher.test(index);
} }
public boolean check(String action, String index) { public boolean check(String action, String index) {
assert index != null; assert index != null;
return actionMatcher.apply(action) && indexNameMatcher.apply(index); return actionMatcher.test(action) && indexNameMatcher.test(index);
} }
} }
} }

View File

@ -5,7 +5,6 @@
*/ */
package org.elasticsearch.shield.authz; package org.elasticsearch.shield.authz;
import com.google.common.base.Predicate;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; import com.google.common.cache.LoadingCache;
@ -28,6 +27,7 @@ import org.elasticsearch.shield.support.Automatons;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Predicate;
import static org.elasticsearch.shield.support.Automatons.patterns; import static org.elasticsearch.shield.support.Automatons.patterns;
@ -206,7 +206,7 @@ public abstract class Privilege<P extends Privilege<P>> {
public static void addCustom(String name, String... actionPatterns) { public static void addCustom(String name, String... actionPatterns) {
for (String pattern : actionPatterns) { for (String pattern : actionPatterns) {
if (!Index.ACTION_MATCHER.apply(pattern)) { if (!Index.ACTION_MATCHER.test(pattern)) {
throw new IllegalArgumentException("cannot register custom index privilege [" + name + "]. index action must follow the 'indices:*' format"); throw new IllegalArgumentException("cannot register custom index privilege [" + name + "]. index action must follow the 'indices:*' format");
} }
} }
@ -252,7 +252,7 @@ public abstract class Privilege<P extends Privilege<P>> {
private static Index resolve(String name) { private static Index resolve(String name) {
name = name.toLowerCase(Locale.ROOT); name = name.toLowerCase(Locale.ROOT);
if (ACTION_MATCHER.apply(name)) { if (ACTION_MATCHER.test(name)) {
return action(name); return action(name);
} }
for (Index index : values) { for (Index index : values) {
@ -314,7 +314,7 @@ public abstract class Privilege<P extends Privilege<P>> {
public static void addCustom(String name, String... actionPatterns) { public static void addCustom(String name, String... actionPatterns) {
for (String pattern : actionPatterns) { for (String pattern : actionPatterns) {
if (!Cluster.ACTION_MATCHER.apply(pattern)) { if (!Cluster.ACTION_MATCHER.test(pattern)) {
throw new IllegalArgumentException("cannot register custom cluster privilege [" + name + "]. cluster aciton must follow the 'cluster:*' format"); throw new IllegalArgumentException("cannot register custom cluster privilege [" + name + "]. cluster aciton must follow the 'cluster:*' format");
} }
} }
@ -350,7 +350,7 @@ public abstract class Privilege<P extends Privilege<P>> {
private static Cluster resolve(String name) { private static Cluster resolve(String name) {
name = name.toLowerCase(Locale.ROOT); name = name.toLowerCase(Locale.ROOT);
if (ACTION_MATCHER.apply(name)) { if (ACTION_MATCHER.test(name)) {
return action(name); return action(name);
} }
for (Cluster cluster : values) { for (Cluster cluster : values) {

View File

@ -5,7 +5,7 @@
*/ */
package org.elasticsearch.shield.authz; package org.elasticsearch.shield.authz;
import com.google.common.base.Predicate; import java.util.function.Predicate;
/** /**
* *
@ -22,6 +22,6 @@ public class SystemRole {
} }
public boolean check(String action) { public boolean check(String action) {
return PREDICATE.apply(action); return PREDICATE.test(action);
} }
} }

View File

@ -5,10 +5,11 @@
*/ */
package org.elasticsearch.shield.support; package org.elasticsearch.shield.support;
import com.google.common.base.Predicate;
import dk.brics.automaton.Automaton; import dk.brics.automaton.Automaton;
import dk.brics.automaton.RunAutomaton; import dk.brics.automaton.RunAutomaton;
import java.util.function.Predicate;
/** /**
* *
*/ */
@ -25,7 +26,7 @@ public class AutomatonPredicate implements Predicate<String> {
} }
@Override @Override
public boolean apply(String input) { public boolean test(String input) {
return automaton.run(input); return automaton.run(input);
} }
} }

View File

@ -5,7 +5,6 @@
*/ */
package org.elasticsearch.shield.audit.index; package org.elasticsearch.shield.audit.index;
import com.google.common.base.Predicate;
import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateResponse; import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateResponse;
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse; import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse;
import org.elasticsearch.action.exists.ExistsResponse; import org.elasticsearch.action.exists.ExistsResponse;
@ -19,7 +18,7 @@ import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.is;
@ClusterScope(scope = Scope.TEST, randomDynamicTemplates = false) @ClusterScope(scope = Scope.TEST, randomDynamicTemplates = false)
public class IndexAuditTrailEnabledTests extends ShieldIntegTestCase { public class IndexAuditTrailEnabledTests extends ShieldIntegTestCase {
@ -69,16 +68,13 @@ public class IndexAuditTrailEnabledTests extends ShieldIntegTestCase {
void awaitIndexCreation() throws Exception { void awaitIndexCreation() throws Exception {
final String indexName = IndexNameResolver.resolve(IndexAuditTrail.INDEX_NAME_PREFIX, DateTime.now(DateTimeZone.UTC), rollover); final String indexName = IndexNameResolver.resolve(IndexAuditTrail.INDEX_NAME_PREFIX, DateTime.now(DateTimeZone.UTC), rollover);
boolean success = awaitBusy(new Predicate<Void>() { boolean success = awaitBusy(() -> {
@Override try {
public boolean apply(Void o) { ExistsResponse response =
try { client().prepareExists(indexName).execute().actionGet();
ExistsResponse response = return response.exists();
client().prepareExists(indexName).execute().actionGet(); } catch (Exception e) {
return response.exists(); return false;
} catch (Exception e) {
return false;
}
} }
}); });
@ -88,19 +84,16 @@ public class IndexAuditTrailEnabledTests extends ShieldIntegTestCase {
} }
void awaitIndexTemplateCreation() throws InterruptedException { void awaitIndexTemplateCreation() throws InterruptedException {
boolean found = awaitBusy(new Predicate<Void>() { boolean found = awaitBusy(() -> {
@Override GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates(IndexAuditTrail.INDEX_TEMPLATE_NAME).execute().actionGet();
public boolean apply(Void aVoid) { if (response.getIndexTemplates().size() > 0) {
GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates(IndexAuditTrail.INDEX_TEMPLATE_NAME).execute().actionGet(); for (IndexTemplateMetaData indexTemplateMetaData : response.getIndexTemplates()) {
if (response.getIndexTemplates().size() > 0) { if (IndexAuditTrail.INDEX_TEMPLATE_NAME.equals(indexTemplateMetaData.name())) {
for (IndexTemplateMetaData indexTemplateMetaData : response.getIndexTemplates()) { return true;
if (IndexAuditTrail.INDEX_TEMPLATE_NAME.equals(indexTemplateMetaData.name())) {
return true;
}
} }
} }
return false;
} }
return false;
}); });
if (!found) { if (!found) {

View File

@ -5,7 +5,6 @@
*/ */
package org.elasticsearch.shield.audit.index; package org.elasticsearch.shield.audit.index;
import com.google.common.base.Predicate;
import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
@ -54,7 +53,10 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.*; import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.DAILY;
import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.HOURLY;
import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.MONTHLY;
import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.WEEKLY;
import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE;
import static org.elasticsearch.test.InternalTestCluster.clusterName; import static org.elasticsearch.test.InternalTestCluster.clusterName;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
@ -62,7 +64,11 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** /**
* *
@ -704,16 +710,13 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase {
} }
private void awaitIndexCreation(final String indexName) throws InterruptedException { private void awaitIndexCreation(final String indexName) throws InterruptedException {
boolean found = awaitBusy(new Predicate<Void>() { boolean found = awaitBusy(() -> {
@Override try {
public boolean apply(Void o) { ExistsResponse response =
try { getClient().prepareExists(indexName).execute().actionGet();
ExistsResponse response = return response.exists();
getClient().prepareExists(indexName).execute().actionGet(); } catch (Exception e) {
return response.exists(); return false;
} catch (Exception e) {
return false;
}
} }
}); });
assertThat("[" + indexName + "] does not exist!", found, is(true)); assertThat("[" + indexName + "] does not exist!", found, is(true));

View File

@ -5,7 +5,6 @@
*/ */
package org.elasticsearch.shield.audit.index; package org.elasticsearch.shield.audit.index;
import com.google.common.base.Predicate;
import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
@ -127,12 +126,7 @@ public class RemoteIndexAuditTrailStartingTests extends ShieldIntegTestCase {
public void testThatRemoteAuditInstancesAreStarted() throws Exception { public void testThatRemoteAuditInstancesAreStarted() throws Exception {
Iterable<IndexAuditTrail> auditTrails = remoteCluster.getInstances(IndexAuditTrail.class); Iterable<IndexAuditTrail> auditTrails = remoteCluster.getInstances(IndexAuditTrail.class);
for (final IndexAuditTrail auditTrail : auditTrails) { for (final IndexAuditTrail auditTrail : auditTrails) {
awaitBusy(new Predicate<Void>() { awaitBusy(() -> auditTrail.state() == IndexAuditTrail.State.STARTED, 2L, TimeUnit.SECONDS);
@Override
public boolean apply(Void aVoid) {
return auditTrail.state() == IndexAuditTrail.State.STARTED;
}
}, 2L, TimeUnit.SECONDS);
assertThat(auditTrail.state(), is(IndexAuditTrail.State.STARTED)); assertThat(auditTrail.state(), is(IndexAuditTrail.State.STARTED));
} }
} }

View File

@ -5,7 +5,6 @@
*/ */
package org.elasticsearch.shield.authz; package org.elasticsearch.shield.authz;
import com.google.common.base.Predicate;
import org.elasticsearch.action.get.GetAction; import org.elasticsearch.action.get.GetAction;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import org.junit.Before; import org.junit.Before;
@ -14,9 +13,16 @@ import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.function.Predicate;
import static org.elasticsearch.shield.authz.Privilege.Index.*; import static org.elasticsearch.shield.authz.Privilege.Index.Cluster;
import static org.hamcrest.Matchers.*; import static org.elasticsearch.shield.authz.Privilege.Index.MONITOR;
import static org.elasticsearch.shield.authz.Privilege.Index.READ;
import static org.elasticsearch.shield.authz.Privilege.Index.SEARCH;
import static org.elasticsearch.shield.authz.Privilege.Index.union;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/** /**
* *
@ -72,11 +78,11 @@ public class PermissionTests extends ESTestCase {
// "baz_*foo", "/fool.*bar/" // "baz_*foo", "/fool.*bar/"
private void testAllowedIndicesMatcher(Predicate<String> indicesMatcher) { private void testAllowedIndicesMatcher(Predicate<String> indicesMatcher) {
assertThat(indicesMatcher.apply("foobar"), is(false)); assertThat(indicesMatcher.test("foobar"), is(false));
assertThat(indicesMatcher.apply("fool"), is(false)); assertThat(indicesMatcher.test("fool"), is(false));
assertThat(indicesMatcher.apply("fool2bar"), is(true)); assertThat(indicesMatcher.test("fool2bar"), is(true));
assertThat(indicesMatcher.apply("baz_foo"), is(true)); assertThat(indicesMatcher.test("baz_foo"), is(true));
assertThat(indicesMatcher.apply("barbapapa"), is(false)); assertThat(indicesMatcher.test("barbapapa"), is(false));
} }

View File

@ -5,7 +5,6 @@
*/ */
package org.elasticsearch.shield.authz; package org.elasticsearch.shield.authz;
import com.google.common.base.Predicate;
import org.elasticsearch.action.get.GetAction; import org.elasticsearch.action.get.GetAction;
import org.elasticsearch.action.get.MultiGetAction; import org.elasticsearch.action.get.MultiGetAction;
import org.elasticsearch.action.search.MultiSearchAction; import org.elasticsearch.action.search.MultiSearchAction;
@ -18,7 +17,11 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.*; import java.util.function.Predicate;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/** /**
* *
@ -48,10 +51,10 @@ public class PrivilegeTests extends ESTestCase {
@Test @Test
public void testSubActionPattern() throws Exception { public void testSubActionPattern() throws Exception {
AutomatonPredicate predicate = new AutomatonPredicate(Automatons.patterns("foo" + Privilege.SUB_ACTION_SUFFIX_PATTERN)); AutomatonPredicate predicate = new AutomatonPredicate(Automatons.patterns("foo" + Privilege.SUB_ACTION_SUFFIX_PATTERN));
assertThat(predicate.apply("foo[n][nodes]"), is(true)); assertThat(predicate.test("foo[n][nodes]"), is(true));
assertThat(predicate.apply("foo[n]"), is(true)); assertThat(predicate.test("foo[n]"), is(true));
assertThat(predicate.apply("bar[n][nodes]"), is(false)); assertThat(predicate.test("bar[n][nodes]"), is(false));
assertThat(predicate.apply("[n][nodes]"), is(false)); assertThat(predicate.test("[n][nodes]"), is(false));
} }
@Test @Test
@ -81,17 +84,17 @@ public class PrivilegeTests extends ESTestCase {
Privilege.Name name = new Privilege.Name("indices:admin/template/delete"); Privilege.Name name = new Privilege.Name("indices:admin/template/delete");
Privilege.Cluster cluster = Privilege.Cluster.get(name); Privilege.Cluster cluster = Privilege.Cluster.get(name);
assertThat(cluster, notNullValue()); assertThat(cluster, notNullValue());
assertThat(cluster.predicate().apply("indices:admin/template/delete"), is(true)); assertThat(cluster.predicate().test("indices:admin/template/delete"), is(true));
name = new Privilege.Name("indices:admin/template/get"); name = new Privilege.Name("indices:admin/template/get");
cluster = Privilege.Cluster.get(name); cluster = Privilege.Cluster.get(name);
assertThat(cluster, notNullValue()); assertThat(cluster, notNullValue());
assertThat(cluster.predicate().apply("indices:admin/template/get"), is(true)); assertThat(cluster.predicate().test("indices:admin/template/get"), is(true));
name = new Privilege.Name("indices:admin/template/put"); name = new Privilege.Name("indices:admin/template/put");
cluster = Privilege.Cluster.get(name); cluster = Privilege.Cluster.get(name);
assertThat(cluster, notNullValue()); assertThat(cluster, notNullValue());
assertThat(cluster.predicate().apply("indices:admin/template/put"), is(true)); assertThat(cluster.predicate().test("indices:admin/template/put"), is(true));
} }
@Test @Test
@ -106,8 +109,8 @@ public class PrivilegeTests extends ESTestCase {
Privilege.Name actionName = new Privilege.Name("cluster:admin/snapshot/delete"); Privilege.Name actionName = new Privilege.Name("cluster:admin/snapshot/delete");
Privilege.Cluster cluster = Privilege.Cluster.get(actionName); Privilege.Cluster cluster = Privilege.Cluster.get(actionName);
assertThat(cluster, notNullValue()); assertThat(cluster, notNullValue());
assertThat(cluster.predicate().apply("cluster:admin/snapshot/delete"), is(true)); assertThat(cluster.predicate().test("cluster:admin/snapshot/delete"), is(true));
assertThat(cluster.predicate().apply("cluster:admin/snapshot/dele"), is(false)); assertThat(cluster.predicate().test("cluster:admin/snapshot/dele"), is(false));
} }
@Test @Test
@ -117,14 +120,14 @@ public class PrivilegeTests extends ESTestCase {
for (Privilege.Cluster cluster : Privilege.Cluster.values()) { for (Privilege.Cluster cluster : Privilege.Cluster.values()) {
if ("foo".equals(cluster.name.toString())) { if ("foo".equals(cluster.name.toString())) {
found = true; found = true;
assertThat(cluster.predicate().apply("cluster:bar"), is(true)); assertThat(cluster.predicate().test("cluster:bar"), is(true));
} }
} }
assertThat(found, is(true)); assertThat(found, is(true));
Privilege.Cluster cluster = Privilege.Cluster.get(new Privilege.Name("foo")); Privilege.Cluster cluster = Privilege.Cluster.get(new Privilege.Name("foo"));
assertThat(cluster, notNullValue()); assertThat(cluster, notNullValue());
assertThat(cluster.name().toString(), is("foo")); assertThat(cluster.name().toString(), is("foo"));
assertThat(cluster.predicate().apply("cluster:bar"), is(true)); assertThat(cluster.predicate().test("cluster:bar"), is(true));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
@ -142,8 +145,8 @@ public class PrivilegeTests extends ESTestCase {
Privilege.Name actionName = new Privilege.Name("indices:admin/mapping/delete"); Privilege.Name actionName = new Privilege.Name("indices:admin/mapping/delete");
Privilege.Index index = Privilege.Index.get(actionName); Privilege.Index index = Privilege.Index.get(actionName);
assertThat(index, notNullValue()); assertThat(index, notNullValue());
assertThat(index.predicate().apply("indices:admin/mapping/delete"), is(true)); assertThat(index.predicate().test("indices:admin/mapping/delete"), is(true));
assertThat(index.predicate().apply("indices:admin/mapping/dele"), is(false)); assertThat(index.predicate().test("indices:admin/mapping/dele"), is(false));
} }
@Test @Test
@ -204,14 +207,14 @@ public class PrivilegeTests extends ESTestCase {
for (Privilege.Index index : Privilege.Index.values()) { for (Privilege.Index index : Privilege.Index.values()) {
if ("foo".equals(index.name.toString())) { if ("foo".equals(index.name.toString())) {
found = true; found = true;
assertThat(index.predicate().apply("indices:bar"), is(true)); assertThat(index.predicate().test("indices:bar"), is(true));
} }
} }
assertThat(found, is(true)); assertThat(found, is(true));
Privilege.Index index = Privilege.Index.get(new Privilege.Name("foo")); Privilege.Index index = Privilege.Index.get(new Privilege.Name("foo"));
assertThat(index, notNullValue()); assertThat(index, notNullValue());
assertThat(index.name().toString(), is("foo")); assertThat(index.name().toString(), is("foo"));
assertThat(index.predicate().apply("indices:bar"), is(true)); assertThat(index.predicate().test("indices:bar"), is(true));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
@ -227,42 +230,42 @@ public class PrivilegeTests extends ESTestCase {
@Test @Test
public void testSystem() throws Exception { public void testSystem() throws Exception {
Predicate<String> predicate = Privilege.SYSTEM.predicate(); Predicate<String> predicate = Privilege.SYSTEM.predicate();
assertThat(predicate.apply("indices:monitor/whatever"), is(true)); assertThat(predicate.test("indices:monitor/whatever"), is(true));
assertThat(predicate.apply("cluster:monitor/whatever"), is(true)); assertThat(predicate.test("cluster:monitor/whatever"), is(true));
assertThat(predicate.apply("cluster:admin/snapshot/status[nodes]"), is(false)); assertThat(predicate.test("cluster:admin/snapshot/status[nodes]"), is(false));
assertThat(predicate.apply("internal:whatever"), is(true)); assertThat(predicate.test("internal:whatever"), is(true));
assertThat(predicate.apply("indices:whatever"), is(false)); assertThat(predicate.test("indices:whatever"), is(false));
assertThat(predicate.apply("cluster:whatever"), is(false)); assertThat(predicate.test("cluster:whatever"), is(false));
assertThat(predicate.apply("cluster:admin/snapshot/status"), is(false)); assertThat(predicate.test("cluster:admin/snapshot/status"), is(false));
assertThat(predicate.apply("whatever"), is(false)); assertThat(predicate.test("whatever"), is(false));
assertThat(predicate.apply("cluster:admin/reroute"), is(true)); assertThat(predicate.test("cluster:admin/reroute"), is(true));
assertThat(predicate.apply("cluster:admin/whatever"), is(false)); assertThat(predicate.test("cluster:admin/whatever"), is(false));
assertThat(predicate.apply("indices:admin/mapping/put"), is(true)); assertThat(predicate.test("indices:admin/mapping/put"), is(true));
assertThat(predicate.apply("indices:admin/mapping/whatever"), is(false)); assertThat(predicate.test("indices:admin/mapping/whatever"), is(false));
} }
@Test @Test
public void testSearchPrivilege() throws Exception { public void testSearchPrivilege() throws Exception {
Predicate<String> predicate = Privilege.Index.SEARCH.predicate(); Predicate<String> predicate = Privilege.Index.SEARCH.predicate();
assertThat(predicate.apply(SearchAction.NAME), is(true)); assertThat(predicate.test(SearchAction.NAME), is(true));
assertThat(predicate.apply(SearchAction.NAME + "/whatever"), is(true)); assertThat(predicate.test(SearchAction.NAME + "/whatever"), is(true));
assertThat(predicate.apply(MultiSearchAction.NAME), is(true)); assertThat(predicate.test(MultiSearchAction.NAME), is(true));
assertThat(predicate.apply(MultiSearchAction.NAME + "/whatever"), is(true)); assertThat(predicate.test(MultiSearchAction.NAME + "/whatever"), is(true));
assertThat(predicate.apply(SuggestAction.NAME), is(true)); assertThat(predicate.test(SuggestAction.NAME), is(true));
assertThat(predicate.apply(SuggestAction.NAME + "/whatever"), is(true)); assertThat(predicate.test(SuggestAction.NAME + "/whatever"), is(true));
assertThat(predicate.apply(GetAction.NAME), is(false)); assertThat(predicate.test(GetAction.NAME), is(false));
assertThat(predicate.apply(GetAction.NAME + "/whatever"), is(false)); assertThat(predicate.test(GetAction.NAME + "/whatever"), is(false));
assertThat(predicate.apply(MultiGetAction.NAME), is(false)); assertThat(predicate.test(MultiGetAction.NAME), is(false));
assertThat(predicate.apply(MultiGetAction.NAME + "/whatever"), is(false)); assertThat(predicate.test(MultiGetAction.NAME + "/whatever"), is(false));
} }
@Test @Test
public void testGetPrivilege() throws Exception { public void testGetPrivilege() throws Exception {
Predicate<String> predicate = Privilege.Index.GET.predicate(); Predicate<String> predicate = Privilege.Index.GET.predicate();
assertThat(predicate.apply(GetAction.NAME), is(true)); assertThat(predicate.test(GetAction.NAME), is(true));
assertThat(predicate.apply(GetAction.NAME + "/whatever"), is(true)); assertThat(predicate.test(GetAction.NAME + "/whatever"), is(true));
assertThat(predicate.apply(MultiGetAction.NAME), is(true)); assertThat(predicate.test(MultiGetAction.NAME), is(true));
assertThat(predicate.apply(MultiGetAction.NAME + "/whatever"), is(true)); assertThat(predicate.test(MultiGetAction.NAME + "/whatever"), is(true));
} }
} }