Security: Rename IndexLifecycleManager to SecurityIndexManager (#30442)

This commit renames IndexLifecycleManager to SecurityIndexManager as it
is not actually a general purpose class, but specific to security. It
also removes indirection in code calling the lifecycle service, instead
calling the security index manager directly.
This commit is contained in:
Ryan Ernst 2018-05-08 10:03:11 -07:00 committed by GitHub
parent 3acca0b35c
commit ce008c446b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 161 additions and 199 deletions

View File

@ -197,7 +197,7 @@ import org.elasticsearch.xpack.security.rest.action.user.RestGetUsersAction;
import org.elasticsearch.xpack.security.rest.action.user.RestHasPrivilegesAction; import org.elasticsearch.xpack.security.rest.action.user.RestHasPrivilegesAction;
import org.elasticsearch.xpack.security.rest.action.user.RestPutUserAction; import org.elasticsearch.xpack.security.rest.action.user.RestPutUserAction;
import org.elasticsearch.xpack.security.rest.action.user.RestSetEnabledAction; import org.elasticsearch.xpack.security.rest.action.user.RestSetEnabledAction;
import org.elasticsearch.xpack.security.support.IndexLifecycleManager; import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.elasticsearch.xpack.security.transport.SecurityServerTransportInterceptor; import org.elasticsearch.xpack.security.transport.SecurityServerTransportInterceptor;
import org.elasticsearch.xpack.security.transport.filter.IPFilter; import org.elasticsearch.xpack.security.transport.filter.IPFilter;
import org.elasticsearch.xpack.security.transport.netty4.SecurityNetty4HttpServerTransport; import org.elasticsearch.xpack.security.transport.netty4.SecurityNetty4HttpServerTransport;
@ -233,7 +233,7 @@ import static org.elasticsearch.cluster.metadata.IndexMetaData.INDEX_FORMAT_SETT
import static org.elasticsearch.xpack.core.XPackSettings.HTTP_SSL_ENABLED; import static org.elasticsearch.xpack.core.XPackSettings.HTTP_SSL_ENABLED;
import static org.elasticsearch.xpack.core.security.SecurityLifecycleServiceField.SECURITY_TEMPLATE_NAME; import static org.elasticsearch.xpack.core.security.SecurityLifecycleServiceField.SECURITY_TEMPLATE_NAME;
import static org.elasticsearch.xpack.security.SecurityLifecycleService.SECURITY_INDEX_NAME; import static org.elasticsearch.xpack.security.SecurityLifecycleService.SECURITY_INDEX_NAME;
import static org.elasticsearch.xpack.security.support.IndexLifecycleManager.INTERNAL_INDEX_FORMAT; import static org.elasticsearch.xpack.security.support.SecurityIndexManager.INTERNAL_INDEX_FORMAT;
public class Security extends Plugin implements ActionPlugin, IngestPlugin, NetworkPlugin, ClusterPlugin, public class Security extends Plugin implements ActionPlugin, IngestPlugin, NetworkPlugin, ClusterPlugin,
DiscoveryPlugin, MapperPlugin, ExtensiblePlugin { DiscoveryPlugin, MapperPlugin, ExtensiblePlugin {
@ -424,8 +424,8 @@ public class Security extends Plugin implements ActionPlugin, IngestPlugin, Netw
components.add(realms); components.add(realms);
components.add(reservedRealm); components.add(reservedRealm);
securityLifecycleService.addSecurityIndexHealthChangeListener(nativeRoleMappingStore::onSecurityIndexHealthChange); securityLifecycleService.securityIndex().addIndexHealthChangeListener(nativeRoleMappingStore::onSecurityIndexHealthChange);
securityLifecycleService.addSecurityIndexOutOfDateListener(nativeRoleMappingStore::onSecurityIndexOutOfDateChange); securityLifecycleService.securityIndex().addIndexOutOfDateListener(nativeRoleMappingStore::onSecurityIndexOutOfDateChange);
AuthenticationFailureHandler failureHandler = null; AuthenticationFailureHandler failureHandler = null;
String extensionName = null; String extensionName = null;
@ -458,8 +458,8 @@ public class Security extends Plugin implements ActionPlugin, IngestPlugin, Netw
} }
final CompositeRolesStore allRolesStore = new CompositeRolesStore(settings, fileRolesStore, nativeRolesStore, final CompositeRolesStore allRolesStore = new CompositeRolesStore(settings, fileRolesStore, nativeRolesStore,
reservedRolesStore, rolesProviders, threadPool.getThreadContext(), getLicenseState()); reservedRolesStore, rolesProviders, threadPool.getThreadContext(), getLicenseState());
securityLifecycleService.addSecurityIndexHealthChangeListener(allRolesStore::onSecurityIndexHealthChange); securityLifecycleService.securityIndex().addIndexHealthChangeListener(allRolesStore::onSecurityIndexHealthChange);
securityLifecycleService.addSecurityIndexOutOfDateListener(allRolesStore::onSecurityIndexOutOfDateChange); securityLifecycleService.securityIndex().addIndexOutOfDateListener(allRolesStore::onSecurityIndexOutOfDateChange);
// to keep things simple, just invalidate all cached entries on license change. this happens so rarely that the impact should be // to keep things simple, just invalidate all cached entries on license change. this happens so rarely that the impact should be
// minimal // minimal
getLicenseState().addListener(allRolesStore::invalidateAll); getLicenseState().addListener(allRolesStore::invalidateAll);
@ -886,7 +886,7 @@ public class Security extends Plugin implements ActionPlugin, IngestPlugin, Netw
templates.remove(SECURITY_TEMPLATE_NAME); templates.remove(SECURITY_TEMPLATE_NAME);
final XContent xContent = XContentFactory.xContent(XContentType.JSON); final XContent xContent = XContentFactory.xContent(XContentType.JSON);
final byte[] auditTemplate = TemplateUtils.loadTemplate("/" + IndexAuditTrail.INDEX_TEMPLATE_NAME + ".json", final byte[] auditTemplate = TemplateUtils.loadTemplate("/" + IndexAuditTrail.INDEX_TEMPLATE_NAME + ".json",
Version.CURRENT.toString(), IndexLifecycleManager.TEMPLATE_VERSION_PATTERN).getBytes(StandardCharsets.UTF_8); Version.CURRENT.toString(), SecurityIndexManager.TEMPLATE_VERSION_PATTERN).getBytes(StandardCharsets.UTF_8);
try (XContentParser parser = xContent try (XContentParser parser = xContent
.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, auditTemplate)) { .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, auditTemplate)) {

View File

@ -22,7 +22,7 @@ import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.gateway.GatewayService; import org.elasticsearch.gateway.GatewayService;
import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.security.audit.index.IndexAuditTrail; import org.elasticsearch.xpack.security.audit.index.IndexAuditTrail;
import org.elasticsearch.xpack.security.support.IndexLifecycleManager; import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -46,7 +46,7 @@ import java.util.function.Predicate;
*/ */
public class SecurityLifecycleService extends AbstractComponent implements ClusterStateListener { public class SecurityLifecycleService extends AbstractComponent implements ClusterStateListener {
public static final String INTERNAL_SECURITY_INDEX = IndexLifecycleManager.INTERNAL_SECURITY_INDEX; public static final String INTERNAL_SECURITY_INDEX = SecurityIndexManager.INTERNAL_SECURITY_INDEX;
public static final String SECURITY_INDEX_NAME = ".security"; public static final String SECURITY_INDEX_NAME = ".security";
private static final Version MIN_READ_VERSION = Version.V_5_0_0; private static final Version MIN_READ_VERSION = Version.V_5_0_0;
@ -55,7 +55,7 @@ public class SecurityLifecycleService extends AbstractComponent implements Clust
private final ThreadPool threadPool; private final ThreadPool threadPool;
private final IndexAuditTrail indexAuditTrail; private final IndexAuditTrail indexAuditTrail;
private final IndexLifecycleManager securityIndex; private final SecurityIndexManager securityIndex;
public SecurityLifecycleService(Settings settings, ClusterService clusterService, public SecurityLifecycleService(Settings settings, ClusterService clusterService,
ThreadPool threadPool, Client client, ThreadPool threadPool, Client client,
@ -64,7 +64,7 @@ public class SecurityLifecycleService extends AbstractComponent implements Clust
this.settings = settings; this.settings = settings;
this.threadPool = threadPool; this.threadPool = threadPool;
this.indexAuditTrail = indexAuditTrail; this.indexAuditTrail = indexAuditTrail;
this.securityIndex = new IndexLifecycleManager(settings, client, SECURITY_INDEX_NAME); this.securityIndex = new SecurityIndexManager(settings, client, SECURITY_INDEX_NAME);
clusterService.addListener(this); clusterService.addListener(this);
clusterService.addLifecycleListener(new LifecycleListener() { clusterService.addLifecycleListener(new LifecycleListener() {
@Override @Override
@ -110,69 +110,10 @@ public class SecurityLifecycleService extends AbstractComponent implements Clust
} }
} }
IndexLifecycleManager securityIndex() { public SecurityIndexManager securityIndex() {
return securityIndex; return securityIndex;
} }
/**
* Returns {@code true} if the security index exists
*/
public boolean isSecurityIndexExisting() {
return securityIndex.indexExists();
}
/**
* Returns <code>true</code> if the security index does not exist or it exists and has the current
* value for the <code>index.format</code> index setting
*/
public boolean isSecurityIndexUpToDate() {
return securityIndex.isIndexUpToDate();
}
/**
* Returns <code>true</code> if the security index exists and all primary shards are active
*/
public boolean isSecurityIndexAvailable() {
return securityIndex.isAvailable();
}
/**
* Returns <code>true</code> if the security index does not exist or the mappings are up to date
* based on the version in the <code>_meta</code> field
*/
public boolean isSecurityIndexMappingUpToDate() {
return securityIndex().isMappingUpToDate();
}
/**
* Test whether the effective (active) version of the security mapping meets the
* <code>requiredVersion</code>.
*
* @return <code>true</code> if the effective version passes the predicate, or the security
* mapping does not exist (<code>null</code> version). Otherwise, <code>false</code>.
*/
public boolean checkSecurityMappingVersion(Predicate<Version> requiredVersion) {
return securityIndex.checkMappingVersion(requiredVersion);
}
/**
* Adds a listener which will be notified when the security index health changes. The previous and
* current health will be provided to the listener so that the listener can determine if any action
* needs to be taken.
*/
public void addSecurityIndexHealthChangeListener(BiConsumer<ClusterIndexHealth, ClusterIndexHealth> listener) {
securityIndex.addIndexHealthChangeListener(listener);
}
/**
* Adds a listener which will be notified when the security index out of date value changes. The previous and
* current value will be provided to the listener so that the listener can determine if any action
* needs to be taken.
*/
void addSecurityIndexOutOfDateListener(BiConsumer<Boolean, Boolean> listener) {
securityIndex.addIndexOutOfDateListener(listener);
}
// this is called in a lifecycle listener beforeStop on the cluster service // this is called in a lifecycle listener beforeStop on the cluster service
private void close() { private void close() {
if (indexAuditTrail != null) { if (indexAuditTrail != null) {
@ -193,29 +134,13 @@ public class SecurityLifecycleService extends AbstractComponent implements Clust
} }
private static boolean checkMappingVersions(ClusterState clusterState, Logger logger, Predicate<Version> versionPredicate) { private static boolean checkMappingVersions(ClusterState clusterState, Logger logger, Predicate<Version> versionPredicate) {
return IndexLifecycleManager.checkIndexMappingVersionMatches(SECURITY_INDEX_NAME, clusterState, logger, versionPredicate); return SecurityIndexManager.checkIndexMappingVersionMatches(SECURITY_INDEX_NAME, clusterState, logger, versionPredicate);
} }
public static List<String> indexNames() { public static List<String> indexNames() {
return Collections.unmodifiableList(Arrays.asList(SECURITY_INDEX_NAME, INTERNAL_SECURITY_INDEX)); return Collections.unmodifiableList(Arrays.asList(SECURITY_INDEX_NAME, INTERNAL_SECURITY_INDEX));
} }
/**
* Prepares the security index by creating it if it doesn't exist or updating the mappings if the mappings are
* out of date. After any tasks have been executed, the runnable is then executed.
*/
public void prepareIndexIfNeededThenExecute(final Consumer<Exception> consumer, final Runnable andThen) {
securityIndex.prepareIndexIfNeededThenExecute(consumer, andThen);
}
/**
* Checks if the security index is out of date with the current version. If the index does not exist
* we treat the index as up to date as we expect it to be created with the current format.
*/
public boolean isSecurityIndexOutOfDate() {
return securityIndex.isIndexUpToDate() == false;
}
/** /**
* Is the move from {@code previousHealth} to {@code currentHealth} a move from an unhealthy ("RED") index state to a healthy * Is the move from {@code previousHealth} to {@code currentHealth} a move from an unhealthy ("RED") index state to a healthy
* ("non-RED") state. * ("non-RED") state.

View File

@ -57,7 +57,7 @@ import org.elasticsearch.xpack.core.template.TemplateUtils;
import org.elasticsearch.xpack.security.audit.AuditLevel; import org.elasticsearch.xpack.security.audit.AuditLevel;
import org.elasticsearch.xpack.security.audit.AuditTrail; import org.elasticsearch.xpack.security.audit.AuditTrail;
import org.elasticsearch.xpack.security.rest.RemoteHostHeader; import org.elasticsearch.xpack.security.rest.RemoteHostHeader;
import org.elasticsearch.xpack.security.support.IndexLifecycleManager; import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule; import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
@ -105,7 +105,7 @@ import static org.elasticsearch.xpack.security.audit.AuditLevel.parse;
import static org.elasticsearch.xpack.security.audit.AuditUtil.indices; import static org.elasticsearch.xpack.security.audit.AuditUtil.indices;
import static org.elasticsearch.xpack.security.audit.AuditUtil.restRequestContent; import static org.elasticsearch.xpack.security.audit.AuditUtil.restRequestContent;
import static org.elasticsearch.xpack.security.audit.index.IndexNameResolver.resolve; import static org.elasticsearch.xpack.security.audit.index.IndexNameResolver.resolve;
import static org.elasticsearch.xpack.security.support.IndexLifecycleManager.SECURITY_VERSION_STRING; import static org.elasticsearch.xpack.security.support.SecurityIndexManager.SECURITY_VERSION_STRING;
/** /**
* Audit trail implementation that writes events into an index. * Audit trail implementation that writes events into an index.
@ -1001,7 +1001,7 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail {
private PutIndexTemplateRequest getPutIndexTemplateRequest(Settings customSettings) { private PutIndexTemplateRequest getPutIndexTemplateRequest(Settings customSettings) {
final byte[] template = TemplateUtils.loadTemplate("/" + INDEX_TEMPLATE_NAME + ".json", final byte[] template = TemplateUtils.loadTemplate("/" + INDEX_TEMPLATE_NAME + ".json",
Version.CURRENT.toString(), IndexLifecycleManager.TEMPLATE_VERSION_PATTERN).getBytes(StandardCharsets.UTF_8); Version.CURRENT.toString(), SecurityIndexManager.TEMPLATE_VERSION_PATTERN).getBytes(StandardCharsets.UTF_8);
final PutIndexTemplateRequest request = new PutIndexTemplateRequest(INDEX_TEMPLATE_NAME).source(template, XContentType.JSON); final PutIndexTemplateRequest request = new PutIndexTemplateRequest(INDEX_TEMPLATE_NAME).source(template, XContentType.JSON);
if (customSettings != null && customSettings.names().size() > 0) { if (customSettings != null && customSettings.names().size() > 0) {
Settings updatedSettings = Settings.builder() Settings updatedSettings = Settings.builder()

View File

@ -96,7 +96,7 @@ public final class InternalRealms {
map.put(FileRealmSettings.TYPE, config -> new FileRealm(config, resourceWatcherService)); map.put(FileRealmSettings.TYPE, config -> new FileRealm(config, resourceWatcherService));
map.put(NativeRealmSettings.TYPE, config -> { map.put(NativeRealmSettings.TYPE, config -> {
final NativeRealm nativeRealm = new NativeRealm(config, nativeUsersStore); final NativeRealm nativeRealm = new NativeRealm(config, nativeUsersStore);
securityLifecycleService.addSecurityIndexHealthChangeListener(nativeRealm::onSecurityIndexHealthChange); securityLifecycleService.securityIndex().addIndexHealthChangeListener(nativeRealm::onSecurityIndexHealthChange);
return nativeRealm; return nativeRealm;
}); });
map.put(LdapRealmSettings.AD_TYPE, config -> new LdapRealm(LdapRealmSettings.AD_TYPE, config, sslService, map.put(LdapRealmSettings.AD_TYPE, config -> new LdapRealm(LdapRealmSettings.AD_TYPE, config, sslService,

View File

@ -250,7 +250,7 @@ public final class TokenService extends AbstractComponent {
.setSource(builder) .setSource(builder)
.setRefreshPolicy(RefreshPolicy.WAIT_UNTIL) .setRefreshPolicy(RefreshPolicy.WAIT_UNTIL)
.request(); .request();
lifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> lifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client, SECURITY_ORIGIN, IndexAction.INSTANCE, request, executeAsyncWithOrigin(client, SECURITY_ORIGIN, IndexAction.INSTANCE, request,
ActionListener.wrap(indexResponse -> listener.onResponse(new Tuple<>(userToken, refreshToken)), ActionListener.wrap(indexResponse -> listener.onResponse(new Tuple<>(userToken, refreshToken)),
listener::onFailure)) listener::onFailure))
@ -354,7 +354,7 @@ public final class TokenService extends AbstractComponent {
if (version.onOrAfter(Version.V_6_2_0)) { if (version.onOrAfter(Version.V_6_2_0)) {
// we only have the id and need to get the token from the doc! // we only have the id and need to get the token from the doc!
decryptTokenId(in, cipher, version, ActionListener.wrap(tokenId -> decryptTokenId(in, cipher, version, ActionListener.wrap(tokenId ->
lifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { lifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
final GetRequest getRequest = final GetRequest getRequest =
client.prepareGet(SecurityLifecycleService.SECURITY_INDEX_NAME, TYPE, client.prepareGet(SecurityLifecycleService.SECURITY_INDEX_NAME, TYPE,
getTokenDocumentId(tokenId)).request(); getTokenDocumentId(tokenId)).request();
@ -524,7 +524,7 @@ public final class TokenService extends AbstractComponent {
.request(); .request();
final String tokenDocId = getTokenDocumentId(userToken); final String tokenDocId = getTokenDocumentId(userToken);
final Version version = userToken.getVersion(); final Version version = userToken.getVersion();
lifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> lifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, indexRequest, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, indexRequest,
ActionListener.<IndexResponse>wrap(indexResponse -> { ActionListener.<IndexResponse>wrap(indexResponse -> {
ActionListener<Boolean> wrappedListener = ActionListener<Boolean> wrappedListener =
@ -566,7 +566,7 @@ public final class TokenService extends AbstractComponent {
.setVersion(documentVersion) .setVersion(documentVersion)
.setRefreshPolicy(RefreshPolicy.WAIT_UNTIL) .setRefreshPolicy(RefreshPolicy.WAIT_UNTIL)
.request(); .request();
lifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> lifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, request, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, request,
ActionListener.<UpdateResponse>wrap(updateResponse -> { ActionListener.<UpdateResponse>wrap(updateResponse -> {
if (updateResponse.getGetResult() != null if (updateResponse.getGetResult() != null
@ -665,7 +665,7 @@ public final class TokenService extends AbstractComponent {
.setVersion(true) .setVersion(true)
.request(); .request();
lifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> lifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, request, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, request,
ActionListener.<SearchResponse>wrap(searchResponse -> { ActionListener.<SearchResponse>wrap(searchResponse -> {
if (searchResponse.isTimedOut()) { if (searchResponse.isTimedOut()) {
@ -847,7 +847,7 @@ public final class TokenService extends AbstractComponent {
.request(); .request();
final Supplier<ThreadContext.StoredContext> supplier = client.threadPool().getThreadContext().newRestorableContext(false); final Supplier<ThreadContext.StoredContext> supplier = client.threadPool().getThreadContext().newRestorableContext(false);
lifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> lifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
ScrollHelper.fetchAllByEntity(client, request, new ContextPreservingActionListener<>(supplier, listener), this::parseHit)); ScrollHelper.fetchAllByEntity(client, request, new ContextPreservingActionListener<>(supplier, listener), this::parseHit));
} }
@ -914,11 +914,11 @@ public final class TokenService extends AbstractComponent {
* have been explicitly cleared. * have been explicitly cleared.
*/ */
private void checkIfTokenIsRevoked(UserToken userToken, ActionListener<UserToken> listener) { private void checkIfTokenIsRevoked(UserToken userToken, ActionListener<UserToken> listener) {
if (lifecycleService.isSecurityIndexExisting() == false) { if (lifecycleService.securityIndex().indexExists() == false) {
// index doesn't exist so the token is considered valid. // index doesn't exist so the token is considered valid.
listener.onResponse(userToken); listener.onResponse(userToken);
} else { } else {
lifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { lifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
MultiGetRequest mGetRequest = client.prepareMultiGet() MultiGetRequest mGetRequest = client.prepareMultiGet()
.add(SecurityLifecycleService.SECURITY_INDEX_NAME, TYPE, getInvalidatedTokenDocumentId(userToken)) .add(SecurityLifecycleService.SECURITY_INDEX_NAME, TYPE, getInvalidatedTokenDocumentId(userToken))
.add(SecurityLifecycleService.SECURITY_INDEX_NAME, TYPE, getTokenDocumentId(userToken)) .add(SecurityLifecycleService.SECURITY_INDEX_NAME, TYPE, getTokenDocumentId(userToken))
@ -989,7 +989,7 @@ public final class TokenService extends AbstractComponent {
} }
private void maybeStartTokenRemover() { private void maybeStartTokenRemover() {
if (lifecycleService.isSecurityIndexAvailable()) { if (lifecycleService.securityIndex().isAvailable()) {
if (client.threadPool().relativeTimeInMillis() - lastExpirationRunMs > deleteInterval.getMillis()) { if (client.threadPool().relativeTimeInMillis() - lastExpirationRunMs > deleteInterval.getMillis()) {
expiredTokenRemover.submit(client.threadPool()); expiredTokenRemover.submit(client.threadPool());
lastExpirationRunMs = client.threadPool().relativeTimeInMillis(); lastExpirationRunMs = client.threadPool().relativeTimeInMillis();

View File

@ -114,7 +114,7 @@ public class NativeUsersStore extends AbstractComponent {
} }
}; };
if (securityLifecycleService.isSecurityIndexExisting() == false) { if (securityLifecycleService.securityIndex().indexExists() == false) {
// TODO remove this short circuiting and fix tests that fail without this! // TODO remove this short circuiting and fix tests that fail without this!
listener.onResponse(Collections.emptyList()); listener.onResponse(Collections.emptyList());
} else if (userNames.length == 1) { // optimization for single user lookup } else if (userNames.length == 1) { // optimization for single user lookup
@ -123,7 +123,7 @@ public class NativeUsersStore extends AbstractComponent {
(uap) -> listener.onResponse(uap == null ? Collections.emptyList() : Collections.singletonList(uap.user())), (uap) -> listener.onResponse(uap == null ? Collections.emptyList() : Collections.singletonList(uap.user())),
handleException)); handleException));
} else { } else {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
final QueryBuilder query; final QueryBuilder query;
if (userNames == null || userNames.length == 0) { if (userNames == null || userNames.length == 0) {
query = QueryBuilders.termQuery(Fields.TYPE.getPreferredName(), USER_DOC_TYPE); query = QueryBuilders.termQuery(Fields.TYPE.getPreferredName(), USER_DOC_TYPE);
@ -154,11 +154,11 @@ public class NativeUsersStore extends AbstractComponent {
* Async method to retrieve a user and their password * Async method to retrieve a user and their password
*/ */
private void getUserAndPassword(final String user, final ActionListener<UserAndPassword> listener) { private void getUserAndPassword(final String user, final ActionListener<UserAndPassword> listener) {
if (securityLifecycleService.isSecurityIndexExisting() == false) { if (securityLifecycleService.securityIndex().indexExists() == false) {
// TODO remove this short circuiting and fix tests that fail without this! // TODO remove this short circuiting and fix tests that fail without this!
listener.onResponse(null); listener.onResponse(null);
} else { } else {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareGet(SECURITY_INDEX_NAME, client.prepareGet(SECURITY_INDEX_NAME,
INDEX_TYPE, getIdForUser(USER_DOC_TYPE, user)).request(), INDEX_TYPE, getIdForUser(USER_DOC_TYPE, user)).request(),
@ -199,7 +199,7 @@ public class NativeUsersStore extends AbstractComponent {
docType = USER_DOC_TYPE; docType = USER_DOC_TYPE;
} }
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareUpdate(SECURITY_INDEX_NAME, INDEX_TYPE, getIdForUser(docType, username)) client.prepareUpdate(SECURITY_INDEX_NAME, INDEX_TYPE, getIdForUser(docType, username))
.setDoc(Requests.INDEX_CONTENT_TYPE, Fields.PASSWORD.getPreferredName(), .setDoc(Requests.INDEX_CONTENT_TYPE, Fields.PASSWORD.getPreferredName(),
@ -237,7 +237,7 @@ public class NativeUsersStore extends AbstractComponent {
* has been indexed * has been indexed
*/ */
private void createReservedUser(String username, char[] passwordHash, RefreshPolicy refresh, ActionListener<Void> listener) { private void createReservedUser(String username, char[] passwordHash, RefreshPolicy refresh, ActionListener<Void> listener) {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareIndex(SECURITY_INDEX_NAME, INDEX_TYPE, client.prepareIndex(SECURITY_INDEX_NAME, INDEX_TYPE,
getIdForUser(RESERVED_USER_TYPE, username)) getIdForUser(RESERVED_USER_TYPE, username))
@ -279,7 +279,7 @@ public class NativeUsersStore extends AbstractComponent {
private void updateUserWithoutPassword(final PutUserRequest putUserRequest, final ActionListener<Boolean> listener) { private void updateUserWithoutPassword(final PutUserRequest putUserRequest, final ActionListener<Boolean> listener) {
assert putUserRequest.passwordHash() == null; assert putUserRequest.passwordHash() == null;
// We must have an existing document // We must have an existing document
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareUpdate(SECURITY_INDEX_NAME, INDEX_TYPE, client.prepareUpdate(SECURITY_INDEX_NAME, INDEX_TYPE,
getIdForUser(USER_DOC_TYPE, putUserRequest.username())) getIdForUser(USER_DOC_TYPE, putUserRequest.username()))
@ -322,7 +322,7 @@ public class NativeUsersStore extends AbstractComponent {
private void indexUser(final PutUserRequest putUserRequest, final ActionListener<Boolean> listener) { private void indexUser(final PutUserRequest putUserRequest, final ActionListener<Boolean> listener) {
assert putUserRequest.passwordHash() != null; assert putUserRequest.passwordHash() != null;
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareIndex(SECURITY_INDEX_NAME, INDEX_TYPE, client.prepareIndex(SECURITY_INDEX_NAME, INDEX_TYPE,
getIdForUser(USER_DOC_TYPE, putUserRequest.username())) getIdForUser(USER_DOC_TYPE, putUserRequest.username()))
@ -366,7 +366,7 @@ public class NativeUsersStore extends AbstractComponent {
private void setRegularUserEnabled(final String username, final boolean enabled, final RefreshPolicy refreshPolicy, private void setRegularUserEnabled(final String username, final boolean enabled, final RefreshPolicy refreshPolicy,
final ActionListener<Void> listener) { final ActionListener<Void> listener) {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareUpdate(SECURITY_INDEX_NAME, INDEX_TYPE, client.prepareUpdate(SECURITY_INDEX_NAME, INDEX_TYPE,
getIdForUser(USER_DOC_TYPE, username)) getIdForUser(USER_DOC_TYPE, username))
@ -401,7 +401,7 @@ public class NativeUsersStore extends AbstractComponent {
private void setReservedUserEnabled(final String username, final boolean enabled, final RefreshPolicy refreshPolicy, private void setReservedUserEnabled(final String username, final boolean enabled, final RefreshPolicy refreshPolicy,
boolean clearCache, final ActionListener<Void> listener) { boolean clearCache, final ActionListener<Void> listener) {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareUpdate(SECURITY_INDEX_NAME, INDEX_TYPE, client.prepareUpdate(SECURITY_INDEX_NAME, INDEX_TYPE,
getIdForUser(RESERVED_USER_TYPE, username)) getIdForUser(RESERVED_USER_TYPE, username))
@ -431,7 +431,7 @@ public class NativeUsersStore extends AbstractComponent {
} }
public void deleteUser(final DeleteUserRequest deleteUserRequest, final ActionListener<Boolean> listener) { public void deleteUser(final DeleteUserRequest deleteUserRequest, final ActionListener<Boolean> listener) {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
DeleteRequest request = client.prepareDelete(SECURITY_INDEX_NAME, DeleteRequest request = client.prepareDelete(SECURITY_INDEX_NAME,
INDEX_TYPE, getIdForUser(USER_DOC_TYPE, deleteUserRequest.username())).request(); INDEX_TYPE, getIdForUser(USER_DOC_TYPE, deleteUserRequest.username())).request();
request.setRefreshPolicy(deleteUserRequest.getRefreshPolicy()); request.setRefreshPolicy(deleteUserRequest.getRefreshPolicy());
@ -470,11 +470,11 @@ public class NativeUsersStore extends AbstractComponent {
} }
void getReservedUserInfo(String username, ActionListener<ReservedUserInfo> listener) { void getReservedUserInfo(String username, ActionListener<ReservedUserInfo> listener) {
if (securityLifecycleService.isSecurityIndexExisting() == false) { if (securityLifecycleService.securityIndex().indexExists() == false) {
// TODO remove this short circuiting and fix tests that fail without this! // TODO remove this short circuiting and fix tests that fail without this!
listener.onResponse(null); listener.onResponse(null);
} else { } else {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareGet(SECURITY_INDEX_NAME, INDEX_TYPE, client.prepareGet(SECURITY_INDEX_NAME, INDEX_TYPE,
getIdForUser(RESERVED_USER_TYPE, username)).request(), getIdForUser(RESERVED_USER_TYPE, username)).request(),
@ -514,7 +514,7 @@ public class NativeUsersStore extends AbstractComponent {
} }
void getAllReservedUserInfo(ActionListener<Map<String, ReservedUserInfo>> listener) { void getAllReservedUserInfo(ActionListener<Map<String, ReservedUserInfo>> listener) {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareSearch(SECURITY_INDEX_NAME) client.prepareSearch(SECURITY_INDEX_NAME)
.setQuery(QueryBuilders.termQuery(Fields.TYPE.getPreferredName(), RESERVED_USER_TYPE)) .setQuery(QueryBuilders.termQuery(Fields.TYPE.getPreferredName(), RESERVED_USER_TYPE))

View File

@ -191,7 +191,7 @@ public class ReservedRealm extends CachingUsernamePasswordRealm {
if (userIsDefinedForCurrentSecurityMapping(username) == false) { if (userIsDefinedForCurrentSecurityMapping(username) == false) {
logger.debug("Marking user [{}] as disabled because the security mapping is not at the required version", username); logger.debug("Marking user [{}] as disabled because the security mapping is not at the required version", username);
listener.onResponse(DISABLED_DEFAULT_USER_INFO.deepClone()); listener.onResponse(DISABLED_DEFAULT_USER_INFO.deepClone());
} else if (securityLifecycleService.isSecurityIndexExisting() == false) { } else if (securityLifecycleService.securityIndex().indexExists() == false) {
listener.onResponse(getDefaultUserInfo(username)); listener.onResponse(getDefaultUserInfo(username));
} else { } else {
nativeUsersStore.getReservedUserInfo(username, ActionListener.wrap((userInfo) -> { nativeUsersStore.getReservedUserInfo(username, ActionListener.wrap((userInfo) -> {
@ -218,7 +218,7 @@ public class ReservedRealm extends CachingUsernamePasswordRealm {
private boolean userIsDefinedForCurrentSecurityMapping(String username) { private boolean userIsDefinedForCurrentSecurityMapping(String username) {
final Version requiredVersion = getDefinedVersion(username); final Version requiredVersion = getDefinedVersion(username);
return securityLifecycleService.checkSecurityMappingVersion(requiredVersion::onOrBefore); return securityLifecycleService.securityIndex().checkMappingVersion(requiredVersion::onOrBefore);
} }
private Version getDefinedVersion(String username) { private Version getDefinedVersion(String username) {

View File

@ -120,7 +120,7 @@ public class NativeRoleMappingStore extends AbstractComponent implements UserRol
* <em>package private</em> for unit testing * <em>package private</em> for unit testing
*/ */
void loadMappings(ActionListener<List<ExpressionRoleMapping>> listener) { void loadMappings(ActionListener<List<ExpressionRoleMapping>> listener) {
if (securityLifecycleService.isSecurityIndexOutOfDate()) { if (securityLifecycleService.securityIndex().isIndexUpToDate() == false) {
listener.onFailure(new IllegalStateException( listener.onFailure(new IllegalStateException(
"Security index is not on the current version - the native realm will not be operational until " + "Security index is not on the current version - the native realm will not be operational until " +
"the upgrade API is run on the security index")); "the upgrade API is run on the security index"));
@ -176,7 +176,7 @@ public class NativeRoleMappingStore extends AbstractComponent implements UserRol
private <Request, Result> void modifyMapping(String name, CheckedBiConsumer<Request, ActionListener<Result>, Exception> inner, private <Request, Result> void modifyMapping(String name, CheckedBiConsumer<Request, ActionListener<Result>, Exception> inner,
Request request, ActionListener<Result> listener) { Request request, ActionListener<Result> listener) {
if (securityLifecycleService.isSecurityIndexOutOfDate()) { if (securityLifecycleService.securityIndex().isIndexUpToDate() == false) {
listener.onFailure(new IllegalStateException( listener.onFailure(new IllegalStateException(
"Security index is not on the current version - the native realm will not be operational until " + "Security index is not on the current version - the native realm will not be operational until " +
"the upgrade API is run on the security index")); "the upgrade API is run on the security index"));
@ -192,7 +192,7 @@ public class NativeRoleMappingStore extends AbstractComponent implements UserRol
private void innerPutMapping(PutRoleMappingRequest request, ActionListener<Boolean> listener) { private void innerPutMapping(PutRoleMappingRequest request, ActionListener<Boolean> listener) {
final ExpressionRoleMapping mapping = request.getMapping(); final ExpressionRoleMapping mapping = request.getMapping();
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
final XContentBuilder xContentBuilder; final XContentBuilder xContentBuilder;
try { try {
xContentBuilder = mapping.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS, true); xContentBuilder = mapping.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS, true);
@ -222,7 +222,7 @@ public class NativeRoleMappingStore extends AbstractComponent implements UserRol
} }
private void innerDeleteMapping(DeleteRoleMappingRequest request, ActionListener<Boolean> listener) throws IOException { private void innerDeleteMapping(DeleteRoleMappingRequest request, ActionListener<Boolean> listener) throws IOException {
if (securityLifecycleService.isSecurityIndexOutOfDate()) { if (securityLifecycleService.securityIndex().isIndexUpToDate() == false) {
listener.onFailure(new IllegalStateException( listener.onFailure(new IllegalStateException(
"Security index is not on the current version - the native realm will not be operational until " + "Security index is not on the current version - the native realm will not be operational until " +
"the upgrade API is run on the security index")); "the upgrade API is run on the security index"));
@ -276,16 +276,16 @@ public class NativeRoleMappingStore extends AbstractComponent implements UserRol
} }
private void getMappings(ActionListener<List<ExpressionRoleMapping>> listener) { private void getMappings(ActionListener<List<ExpressionRoleMapping>> listener) {
if (securityLifecycleService.isSecurityIndexAvailable()) { if (securityLifecycleService.securityIndex().isAvailable()) {
loadMappings(listener); loadMappings(listener);
} else { } else {
logger.info("The security index is not yet available - no role mappings can be loaded"); logger.info("The security index is not yet available - no role mappings can be loaded");
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Security Index [{}] [exists: {}] [available: {}] [mapping up to date: {}]", logger.debug("Security Index [{}] [exists: {}] [available: {}] [mapping up to date: {}]",
SECURITY_INDEX_NAME, SECURITY_INDEX_NAME,
securityLifecycleService.isSecurityIndexExisting(), securityLifecycleService.securityIndex().indexExists(),
securityLifecycleService.isSecurityIndexAvailable(), securityLifecycleService.securityIndex().isAvailable(),
securityLifecycleService.isSecurityIndexMappingUpToDate() securityLifecycleService.securityIndex().isMappingUpToDate()
); );
} }
listener.onResponse(Collections.emptyList()); listener.onResponse(Collections.emptyList());
@ -302,7 +302,7 @@ public class NativeRoleMappingStore extends AbstractComponent implements UserRol
* </ul> * </ul>
*/ */
public void usageStats(ActionListener<Map<String, Object>> listener) { public void usageStats(ActionListener<Map<String, Object>> listener) {
if (securityLifecycleService.isSecurityIndexExisting() == false) { if (securityLifecycleService.securityIndex().indexExists() == false) {
reportStats(listener, Collections.emptyList()); reportStats(listener, Collections.emptyList());
} else { } else {
getMappings(ActionListener.wrap(mappings -> reportStats(listener, mappings), listener::onFailure)); getMappings(ActionListener.wrap(mappings -> reportStats(listener, mappings), listener::onFailure));

View File

@ -100,7 +100,7 @@ public class NativeRolesStore extends AbstractComponent {
* Retrieve a list of roles, if rolesToGet is null or empty, fetch all roles * Retrieve a list of roles, if rolesToGet is null or empty, fetch all roles
*/ */
public void getRoleDescriptors(String[] names, final ActionListener<Collection<RoleDescriptor>> listener) { public void getRoleDescriptors(String[] names, final ActionListener<Collection<RoleDescriptor>> listener) {
if (securityLifecycleService.isSecurityIndexExisting() == false) { if (securityLifecycleService.securityIndex().indexExists() == false) {
// TODO remove this short circuiting and fix tests that fail without this! // TODO remove this short circuiting and fix tests that fail without this!
listener.onResponse(Collections.emptyList()); listener.onResponse(Collections.emptyList());
} else if (names != null && names.length == 1) { } else if (names != null && names.length == 1) {
@ -108,7 +108,7 @@ public class NativeRolesStore extends AbstractComponent {
listener.onResponse(roleDescriptor == null ? Collections.emptyList() : Collections.singletonList(roleDescriptor)), listener.onResponse(roleDescriptor == null ? Collections.emptyList() : Collections.singletonList(roleDescriptor)),
listener::onFailure)); listener::onFailure));
} else { } else {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
QueryBuilder query; QueryBuilder query;
if (names == null || names.length == 0) { if (names == null || names.length == 0) {
query = QueryBuilders.termQuery(RoleDescriptor.Fields.TYPE.getPreferredName(), ROLE_TYPE); query = QueryBuilders.termQuery(RoleDescriptor.Fields.TYPE.getPreferredName(), ROLE_TYPE);
@ -133,7 +133,7 @@ public class NativeRolesStore extends AbstractComponent {
} }
public void deleteRole(final DeleteRoleRequest deleteRoleRequest, final ActionListener<Boolean> listener) { public void deleteRole(final DeleteRoleRequest deleteRoleRequest, final ActionListener<Boolean> listener) {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
DeleteRequest request = client.prepareDelete(SecurityLifecycleService.SECURITY_INDEX_NAME, DeleteRequest request = client.prepareDelete(SecurityLifecycleService.SECURITY_INDEX_NAME,
ROLE_DOC_TYPE, getIdForUser(deleteRoleRequest.name())).request(); ROLE_DOC_TYPE, getIdForUser(deleteRoleRequest.name())).request();
request.setRefreshPolicy(deleteRoleRequest.getRefreshPolicy()); request.setRefreshPolicy(deleteRoleRequest.getRefreshPolicy());
@ -166,7 +166,7 @@ public class NativeRolesStore extends AbstractComponent {
// pkg-private for testing // pkg-private for testing
void innerPutRole(final PutRoleRequest request, final RoleDescriptor role, final ActionListener<Boolean> listener) { void innerPutRole(final PutRoleRequest request, final RoleDescriptor role, final ActionListener<Boolean> listener) {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> { securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () -> {
final XContentBuilder xContentBuilder; final XContentBuilder xContentBuilder;
try { try {
xContentBuilder = role.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS, true); xContentBuilder = role.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS, true);
@ -197,13 +197,13 @@ public class NativeRolesStore extends AbstractComponent {
public void usageStats(ActionListener<Map<String, Object>> listener) { public void usageStats(ActionListener<Map<String, Object>> listener) {
Map<String, Object> usageStats = new HashMap<>(); Map<String, Object> usageStats = new HashMap<>();
if (securityLifecycleService.isSecurityIndexExisting() == false) { if (securityLifecycleService.securityIndex().indexExists() == false) {
usageStats.put("size", 0L); usageStats.put("size", 0L);
usageStats.put("fls", false); usageStats.put("fls", false);
usageStats.put("dls", false); usageStats.put("dls", false);
listener.onResponse(usageStats); listener.onResponse(usageStats);
} else { } else {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareMultiSearch() client.prepareMultiSearch()
.add(client.prepareSearch(SecurityLifecycleService.SECURITY_INDEX_NAME) .add(client.prepareSearch(SecurityLifecycleService.SECURITY_INDEX_NAME)
@ -259,11 +259,11 @@ public class NativeRolesStore extends AbstractComponent {
} }
private void getRoleDescriptor(final String roleId, ActionListener<RoleDescriptor> roleActionListener) { private void getRoleDescriptor(final String roleId, ActionListener<RoleDescriptor> roleActionListener) {
if (securityLifecycleService.isSecurityIndexExisting() == false) { if (securityLifecycleService.securityIndex().indexExists() == false) {
// TODO remove this short circuiting and fix tests that fail without this! // TODO remove this short circuiting and fix tests that fail without this!
roleActionListener.onResponse(null); roleActionListener.onResponse(null);
} else { } else {
securityLifecycleService.prepareIndexIfNeededThenExecute(roleActionListener::onFailure, () -> securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(roleActionListener::onFailure, () ->
executeGetRoleRequest(roleId, new ActionListener<GetResponse>() { executeGetRoleRequest(roleId, new ActionListener<GetResponse>() {
@Override @Override
public void onResponse(GetResponse response) { public void onResponse(GetResponse response) {
@ -288,7 +288,7 @@ public class NativeRolesStore extends AbstractComponent {
} }
private void executeGetRoleRequest(String role, ActionListener<GetResponse> listener) { private void executeGetRoleRequest(String role, ActionListener<GetResponse> listener) {
securityLifecycleService.prepareIndexIfNeededThenExecute(listener::onFailure, () -> securityLifecycleService.securityIndex().prepareIndexIfNeededThenExecute(listener::onFailure, () ->
executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN,
client.prepareGet(SecurityLifecycleService.SECURITY_INDEX_NAME, client.prepareGet(SecurityLifecycleService.SECURITY_INDEX_NAME,
ROLE_DOC_TYPE, getIdForUser(role)).request(), ROLE_DOC_TYPE, getIdForUser(role)).request(),

View File

@ -58,7 +58,7 @@ import static org.elasticsearch.xpack.core.security.SecurityLifecycleServiceFiel
/** /**
* Manages the lifecycle of a single index, its template, mapping and and data upgrades/migrations. * Manages the lifecycle of a single index, its template, mapping and and data upgrades/migrations.
*/ */
public class IndexLifecycleManager extends AbstractComponent { public class SecurityIndexManager extends AbstractComponent {
public static final String INTERNAL_SECURITY_INDEX = ".security-" + IndexUpgradeCheckVersion.UPRADE_VERSION; public static final String INTERNAL_SECURITY_INDEX = ".security-" + IndexUpgradeCheckVersion.UPRADE_VERSION;
public static final int INTERNAL_INDEX_FORMAT = 6; public static final int INTERNAL_INDEX_FORMAT = 6;
@ -74,7 +74,7 @@ public class IndexLifecycleManager extends AbstractComponent {
private volatile State indexState = new State(false, false, false, false, null); private volatile State indexState = new State(false, false, false, false, null);
public IndexLifecycleManager(Settings settings, Client client, String indexName) { public SecurityIndexManager(Settings settings, Client client, String indexName) {
super(settings); super(settings);
this.client = client; this.client = client;
this.indexName = indexName; this.indexName = indexName;
@ -347,7 +347,7 @@ public class IndexLifecycleManager extends AbstractComponent {
private Tuple<String, Settings> loadMappingAndSettingsSourceFromTemplate() { private Tuple<String, Settings> loadMappingAndSettingsSourceFromTemplate() {
final byte[] template = TemplateUtils.loadTemplate("/" + SECURITY_TEMPLATE_NAME + ".json", final byte[] template = TemplateUtils.loadTemplate("/" + SECURITY_TEMPLATE_NAME + ".json",
Version.CURRENT.toString(), IndexLifecycleManager.TEMPLATE_VERSION_PATTERN).getBytes(StandardCharsets.UTF_8); Version.CURRENT.toString(), SecurityIndexManager.TEMPLATE_VERSION_PATTERN).getBytes(StandardCharsets.UTF_8);
PutIndexTemplateRequest request = new PutIndexTemplateRequest(SECURITY_TEMPLATE_NAME).source(template, XContentType.JSON); PutIndexTemplateRequest request = new PutIndexTemplateRequest(SECURITY_TEMPLATE_NAME).source(template, XContentType.JSON);
return new Tuple<>(request.mappings().get("doc"), request.settings()); return new Tuple<>(request.mappings().get("doc"), request.settings());
} }

View File

@ -37,7 +37,7 @@ import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.MockTransportClient; import org.elasticsearch.transport.MockTransportClient;
import org.elasticsearch.xpack.core.security.SecurityLifecycleServiceField; import org.elasticsearch.xpack.core.security.SecurityLifecycleServiceField;
import org.elasticsearch.xpack.security.audit.index.IndexAuditTrail; import org.elasticsearch.xpack.security.audit.index.IndexAuditTrail;
import org.elasticsearch.xpack.security.support.IndexLifecycleManager; import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.elasticsearch.xpack.security.test.SecurityTestUtils; import org.elasticsearch.xpack.security.test.SecurityTestUtils;
import org.elasticsearch.xpack.core.template.TemplateUtils; import org.elasticsearch.xpack.core.template.TemplateUtils;
import org.junit.After; import org.junit.After;
@ -105,10 +105,10 @@ public class SecurityLifecycleServiceTests extends ESTestCase {
ClusterState.Builder clusterStateBuilder = createClusterStateWithTemplate(templateString); ClusterState.Builder clusterStateBuilder = createClusterStateWithTemplate(templateString);
final ClusterState clusterState = clusterStateBuilder.build(); final ClusterState clusterState = clusterStateBuilder.build();
assertTrue(IndexLifecycleManager.checkTemplateExistsAndVersionMatches( assertTrue(SecurityIndexManager.checkTemplateExistsAndVersionMatches(
SecurityLifecycleServiceField.SECURITY_TEMPLATE_NAME, clusterState, logger, SecurityLifecycleServiceField.SECURITY_TEMPLATE_NAME, clusterState, logger,
Version.V_5_0_0::before)); Version.V_5_0_0::before));
assertFalse(IndexLifecycleManager.checkTemplateExistsAndVersionMatches( assertFalse(SecurityIndexManager.checkTemplateExistsAndVersionMatches(
SecurityLifecycleServiceField.SECURITY_TEMPLATE_NAME, clusterState, logger, SecurityLifecycleServiceField.SECURITY_TEMPLATE_NAME, clusterState, logger,
Version.V_5_0_0::after)); Version.V_5_0_0::after));
} }
@ -126,7 +126,7 @@ public class SecurityLifecycleServiceTests extends ESTestCase {
ClusterState.Builder clusterStateBuilder = createClusterStateWithMappingAndTemplate(templateString); ClusterState.Builder clusterStateBuilder = createClusterStateWithMappingAndTemplate(templateString);
securityLifecycleService.clusterChanged(new ClusterChangedEvent("test-event", securityLifecycleService.clusterChanged(new ClusterChangedEvent("test-event",
clusterStateBuilder.build(), EMPTY_CLUSTER_STATE)); clusterStateBuilder.build(), EMPTY_CLUSTER_STATE));
final IndexLifecycleManager securityIndex = securityLifecycleService.securityIndex(); final SecurityIndexManager securityIndex = securityLifecycleService.securityIndex();
assertTrue(securityIndex.checkMappingVersion(Version.V_5_0_0::before)); assertTrue(securityIndex.checkMappingVersion(Version.V_5_0_0::before));
assertFalse(securityIndex.checkMappingVersion(Version.V_5_0_0::after)); assertFalse(securityIndex.checkMappingVersion(Version.V_5_0_0::after));
} }
@ -172,7 +172,7 @@ public class SecurityLifecycleServiceTests extends ESTestCase {
private static IndexMetaData.Builder createIndexMetadata(String indexName, String templateString) throws IOException { private static IndexMetaData.Builder createIndexMetadata(String indexName, String templateString) throws IOException {
String template = TemplateUtils.loadTemplate(templateString, Version.CURRENT.toString(), String template = TemplateUtils.loadTemplate(templateString, Version.CURRENT.toString(),
IndexLifecycleManager.TEMPLATE_VERSION_PATTERN); SecurityIndexManager.TEMPLATE_VERSION_PATTERN);
PutIndexTemplateRequest request = new PutIndexTemplateRequest(); PutIndexTemplateRequest request = new PutIndexTemplateRequest();
request.source(template, XContentType.JSON); request.source(template, XContentType.JSON);
IndexMetaData.Builder indexMetaData = IndexMetaData.builder(indexName); IndexMetaData.Builder indexMetaData = IndexMetaData.builder(indexName);
@ -219,7 +219,7 @@ public class SecurityLifecycleServiceTests extends ESTestCase {
String templateName, String templateString) throws IOException { String templateName, String templateString) throws IOException {
String template = TemplateUtils.loadTemplate(templateString, Version.CURRENT.toString(), String template = TemplateUtils.loadTemplate(templateString, Version.CURRENT.toString(),
IndexLifecycleManager.TEMPLATE_VERSION_PATTERN); SecurityIndexManager.TEMPLATE_VERSION_PATTERN);
PutIndexTemplateRequest request = new PutIndexTemplateRequest(); PutIndexTemplateRequest request = new PutIndexTemplateRequest();
request.source(template, XContentType.JSON); request.source(template, XContentType.JSON);
IndexTemplateMetaData.Builder templateBuilder = IndexTemplateMetaData.builder(templateName) IndexTemplateMetaData.Builder templateBuilder = IndexTemplateMetaData.builder(templateName)

View File

@ -63,7 +63,7 @@ import java.util.function.Predicate;
import static org.elasticsearch.cluster.metadata.IndexMetaData.INDEX_FORMAT_SETTING; import static org.elasticsearch.cluster.metadata.IndexMetaData.INDEX_FORMAT_SETTING;
import static org.elasticsearch.xpack.security.SecurityLifecycleService.SECURITY_INDEX_NAME; import static org.elasticsearch.xpack.security.SecurityLifecycleService.SECURITY_INDEX_NAME;
import static org.elasticsearch.xpack.security.support.IndexLifecycleManager.INTERNAL_INDEX_FORMAT; import static org.elasticsearch.xpack.security.support.SecurityIndexManager.INTERNAL_INDEX_FORMAT;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItem;

View File

@ -67,6 +67,7 @@ import org.elasticsearch.xpack.security.authc.saml.SamlRealm;
import org.elasticsearch.xpack.security.authc.saml.SamlRealmTestHelper; import org.elasticsearch.xpack.security.authc.saml.SamlRealmTestHelper;
import org.elasticsearch.xpack.security.authc.saml.SamlRealmTests; import org.elasticsearch.xpack.security.authc.saml.SamlRealmTests;
import org.elasticsearch.xpack.security.authc.saml.SamlTestCase; import org.elasticsearch.xpack.security.authc.saml.SamlTestCase;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.opensaml.saml.saml2.core.NameID; import org.opensaml.saml.saml2.core.NameID;
@ -161,10 +162,12 @@ public class TransportSamlInvalidateSessionActionTests extends SamlTestCase {
}; };
final SecurityLifecycleService lifecycleService = mock(SecurityLifecycleService.class); final SecurityLifecycleService lifecycleService = mock(SecurityLifecycleService.class);
final SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(lifecycleService.securityIndex()).thenReturn(securityIndex);
doAnswer(inv -> { doAnswer(inv -> {
((Runnable) inv.getArguments()[1]).run(); ((Runnable) inv.getArguments()[1]).run();
return null; return null;
}).when(lifecycleService).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class));
final ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool); final ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool);
tokenService = new TokenService(settings, Clock.systemUTC(), client, lifecycleService, clusterService); tokenService = new TokenService(settings, Clock.systemUTC(), client, lifecycleService, clusterService);

View File

@ -56,6 +56,7 @@ import org.elasticsearch.xpack.security.authc.saml.SamlRealm;
import org.elasticsearch.xpack.security.authc.saml.SamlRealmTests; import org.elasticsearch.xpack.security.authc.saml.SamlRealmTests;
import org.elasticsearch.xpack.security.authc.saml.SamlTestCase; import org.elasticsearch.xpack.security.authc.saml.SamlTestCase;
import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; import org.elasticsearch.xpack.security.authc.support.UserRoleMapper;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.opensaml.saml.saml2.core.NameID; import org.opensaml.saml.saml2.core.NameID;
@ -173,10 +174,12 @@ public class TransportSamlLogoutActionTests extends SamlTestCase {
}).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), any(ActionListener.class)); }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), any(ActionListener.class));
final SecurityLifecycleService lifecycleService = mock(SecurityLifecycleService.class); final SecurityLifecycleService lifecycleService = mock(SecurityLifecycleService.class);
final SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(lifecycleService.securityIndex()).thenReturn(securityIndex);
doAnswer(inv -> { doAnswer(inv -> {
((Runnable) inv.getArguments()[1]).run(); ((Runnable) inv.getArguments()[1]).run();
return null; return null;
}).when(lifecycleService).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class));
final ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool); final ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool);
tokenService = new TokenService(settings, Clock.systemUTC(), client, lifecycleService, clusterService); tokenService = new TokenService(settings, Clock.systemUTC(), client, lifecycleService, clusterService);

View File

@ -28,6 +28,7 @@ import org.elasticsearch.xpack.security.SecurityLifecycleService;
import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore;
import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm;
import org.elasticsearch.xpack.security.authc.esnative.ReservedRealmTests; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealmTests;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.Before; import org.junit.Before;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
@ -76,7 +77,9 @@ public class TransportGetUsersActionTests extends ESTestCase {
public void testAnonymousUser() { public void testAnonymousUser() {
NativeUsersStore usersStore = mock(NativeUsersStore.class); NativeUsersStore usersStore = mock(NativeUsersStore.class);
SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class); SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class);
when(securityLifecycleService.isSecurityIndexAvailable()).thenReturn(true); SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(securityLifecycleService.securityIndex()).thenReturn(securityIndex);
when(securityIndex.isAvailable()).thenReturn(true);
AnonymousUser anonymousUser = new AnonymousUser(settings); AnonymousUser anonymousUser = new AnonymousUser(settings);
ReservedRealm reservedRealm = ReservedRealm reservedRealm =
new ReservedRealm(mock(Environment.class), settings, usersStore, anonymousUser, securityLifecycleService, new ThreadContext(Settings.EMPTY)); new ReservedRealm(mock(Environment.class), settings, usersStore, anonymousUser, securityLifecycleService, new ThreadContext(Settings.EMPTY));
@ -146,8 +149,10 @@ public class TransportGetUsersActionTests extends ESTestCase {
public void testReservedUsersOnly() { public void testReservedUsersOnly() {
NativeUsersStore usersStore = mock(NativeUsersStore.class); NativeUsersStore usersStore = mock(NativeUsersStore.class);
SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class); SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class);
when(securityLifecycleService.isSecurityIndexAvailable()).thenReturn(true); SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(securityLifecycleService.checkSecurityMappingVersion(any())).thenReturn(true); when(securityLifecycleService.securityIndex()).thenReturn(securityIndex);
when(securityIndex.isAvailable()).thenReturn(true);
when(securityIndex.checkMappingVersion(any())).thenReturn(true);
ReservedRealmTests.mockGetAllReservedUserInfo(usersStore, Collections.emptyMap()); ReservedRealmTests.mockGetAllReservedUserInfo(usersStore, Collections.emptyMap());
ReservedRealm reservedRealm = ReservedRealm reservedRealm =
@ -194,7 +199,9 @@ public class TransportGetUsersActionTests extends ESTestCase {
Arrays.asList(new User("jane"), new User("fred")), randomUsers()); Arrays.asList(new User("jane"), new User("fred")), randomUsers());
NativeUsersStore usersStore = mock(NativeUsersStore.class); NativeUsersStore usersStore = mock(NativeUsersStore.class);
SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class); SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class);
when(securityLifecycleService.isSecurityIndexAvailable()).thenReturn(true); SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(securityLifecycleService.securityIndex()).thenReturn(securityIndex);
when(securityIndex.isAvailable()).thenReturn(true);
ReservedRealmTests.mockGetAllReservedUserInfo(usersStore, Collections.emptyMap()); ReservedRealmTests.mockGetAllReservedUserInfo(usersStore, Collections.emptyMap());
ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, new AnonymousUser(settings), ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, new AnonymousUser(settings),
securityLifecycleService, new ThreadContext(Settings.EMPTY)); securityLifecycleService, new ThreadContext(Settings.EMPTY));

View File

@ -29,6 +29,7 @@ import org.elasticsearch.xpack.security.SecurityLifecycleService;
import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore;
import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm;
import org.elasticsearch.xpack.security.authc.esnative.ReservedRealmTests; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealmTests;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
@ -118,7 +119,9 @@ public class TransportPutUserActionTests extends ESTestCase {
public void testReservedUser() { public void testReservedUser() {
NativeUsersStore usersStore = mock(NativeUsersStore.class); NativeUsersStore usersStore = mock(NativeUsersStore.class);
SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class); SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class);
when(securityLifecycleService.isSecurityIndexAvailable()).thenReturn(true); SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(securityLifecycleService.securityIndex()).thenReturn(securityIndex);
when(securityIndex.isAvailable()).thenReturn(true);
ReservedRealmTests.mockGetAllReservedUserInfo(usersStore, Collections.emptyMap()); ReservedRealmTests.mockGetAllReservedUserInfo(usersStore, Collections.emptyMap());
Settings settings = Settings.builder().put("path.home", createTempDir()).build(); Settings settings = Settings.builder().put("path.home", createTempDir()).build();
ReservedRealm reservedRealm = new ReservedRealm(TestEnvironment.newEnvironment(settings), settings, usersStore, ReservedRealm reservedRealm = new ReservedRealm(TestEnvironment.newEnvironment(settings), settings, usersStore,

View File

@ -68,6 +68,7 @@ import org.elasticsearch.xpack.security.SecurityLifecycleService;
import org.elasticsearch.xpack.security.audit.AuditTrailService; import org.elasticsearch.xpack.security.audit.AuditTrailService;
import org.elasticsearch.xpack.security.authc.AuthenticationService.Authenticator; import org.elasticsearch.xpack.security.authc.AuthenticationService.Authenticator;
import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@ -125,6 +126,7 @@ public class AuthenticationServiceTests extends ESTestCase {
private ThreadContext threadContext; private ThreadContext threadContext;
private TokenService tokenService; private TokenService tokenService;
private SecurityLifecycleService lifecycleService; private SecurityLifecycleService lifecycleService;
private SecurityIndexManager securityIndex;
private Client client; private Client client;
private InetSocketAddress remoteAddress; private InetSocketAddress remoteAddress;
@ -181,11 +183,13 @@ public class AuthenticationServiceTests extends ESTestCase {
return builder; return builder;
}).when(client).prepareGet(anyString(), anyString(), anyString()); }).when(client).prepareGet(anyString(), anyString(), anyString());
lifecycleService = mock(SecurityLifecycleService.class); lifecycleService = mock(SecurityLifecycleService.class);
securityIndex = mock(SecurityIndexManager.class);
when(lifecycleService.securityIndex()).thenReturn(securityIndex);
doAnswer(invocationOnMock -> { doAnswer(invocationOnMock -> {
Runnable runnable = (Runnable) invocationOnMock.getArguments()[1]; Runnable runnable = (Runnable) invocationOnMock.getArguments()[1];
runnable.run(); runnable.run();
return null; return null;
}).when(lifecycleService).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class));
ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool); ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool);
tokenService = new TokenService(settings, Clock.systemUTC(), client, lifecycleService, clusterService); tokenService = new TokenService(settings, Clock.systemUTC(), client, lifecycleService, clusterService);
service = new AuthenticationService(settings, realms, auditTrail, service = new AuthenticationService(settings, realms, auditTrail,
@ -924,8 +928,8 @@ public class AuthenticationServiceTests extends ESTestCase {
} }
public void testExpiredToken() throws Exception { public void testExpiredToken() throws Exception {
when(lifecycleService.isSecurityIndexAvailable()).thenReturn(true); when(securityIndex.isAvailable()).thenReturn(true);
when(lifecycleService.isSecurityIndexExisting()).thenReturn(true); when(lifecycleService.securityIndex().indexExists()).thenReturn(true);
User user = new User("_username", "r1"); User user = new User("_username", "r1");
final Authentication expected = new Authentication(user, new RealmRef("realm", "custom", "node"), null); final Authentication expected = new Authentication(user, new RealmRef("realm", "custom", "node"), null);
PlainActionFuture<Tuple<UserToken, String>> tokenFuture = new PlainActionFuture<>(); PlainActionFuture<Tuple<UserToken, String>> tokenFuture = new PlainActionFuture<>();
@ -963,7 +967,7 @@ public class AuthenticationServiceTests extends ESTestCase {
doAnswer(invocationOnMock -> { doAnswer(invocationOnMock -> {
((Runnable) invocationOnMock.getArguments()[1]).run(); ((Runnable) invocationOnMock.getArguments()[1]).run();
return null; return null;
}).when(lifecycleService).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class));
try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { try (ThreadContext.StoredContext ignore = threadContext.stashContext()) {
threadContext.putHeader("Authorization", "Bearer " + token); threadContext.putHeader("Authorization", "Bearer " + token);

View File

@ -18,6 +18,7 @@ import org.elasticsearch.xpack.core.ssl.SSLService;
import org.elasticsearch.xpack.security.SecurityLifecycleService; import org.elasticsearch.xpack.security.SecurityLifecycleService;
import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore;
import org.elasticsearch.xpack.security.authc.support.mapper.NativeRoleMappingStore; import org.elasticsearch.xpack.security.authc.support.mapper.NativeRoleMappingStore;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import java.util.Map; import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@ -30,11 +31,14 @@ import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class InternalRealmsTests extends ESTestCase { public class InternalRealmsTests extends ESTestCase {
public void testNativeRealmRegistersIndexHealthChangeListener() throws Exception { public void testNativeRealmRegistersIndexHealthChangeListener() throws Exception {
SecurityLifecycleService lifecycleService = mock(SecurityLifecycleService.class); SecurityLifecycleService lifecycleService = mock(SecurityLifecycleService.class);
SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(lifecycleService.securityIndex()).thenReturn(securityIndex);
Map<String, Realm.Factory> factories = InternalRealms.getFactories(mock(ThreadPool.class), mock(ResourceWatcherService.class), Map<String, Realm.Factory> factories = InternalRealms.getFactories(mock(ThreadPool.class), mock(ResourceWatcherService.class),
mock(SSLService.class), mock(NativeUsersStore.class), mock(NativeRoleMappingStore.class), lifecycleService); mock(SSLService.class), mock(NativeUsersStore.class), mock(NativeRoleMappingStore.class), lifecycleService);
assertThat(factories, hasEntry(is(NativeRealmSettings.TYPE), any(Realm.Factory.class))); assertThat(factories, hasEntry(is(NativeRealmSettings.TYPE), any(Realm.Factory.class)));
@ -43,10 +47,10 @@ public class InternalRealmsTests extends ESTestCase {
Settings settings = Settings.builder().put("path.home", createTempDir()).build(); Settings settings = Settings.builder().put("path.home", createTempDir()).build();
factories.get(NativeRealmSettings.TYPE).create(new RealmConfig("test", Settings.EMPTY, settings, factories.get(NativeRealmSettings.TYPE).create(new RealmConfig("test", Settings.EMPTY, settings,
TestEnvironment.newEnvironment(settings), new ThreadContext(settings))); TestEnvironment.newEnvironment(settings), new ThreadContext(settings)));
verify(lifecycleService).addSecurityIndexHealthChangeListener(isA(BiConsumer.class)); verify(securityIndex).addIndexHealthChangeListener(isA(BiConsumer.class));
factories.get(NativeRealmSettings.TYPE).create(new RealmConfig("test", Settings.EMPTY, settings, factories.get(NativeRealmSettings.TYPE).create(new RealmConfig("test", Settings.EMPTY, settings,
TestEnvironment.newEnvironment(settings), new ThreadContext(settings))); TestEnvironment.newEnvironment(settings), new ThreadContext(settings)));
verify(lifecycleService, times(2)).addSecurityIndexHealthChangeListener(isA(BiConsumer.class)); verify(securityIndex, times(2)).addIndexHealthChangeListener(isA(BiConsumer.class));
} }
} }

View File

@ -51,6 +51,7 @@ import org.elasticsearch.xpack.core.security.authc.TokenMetaData;
import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.core.watcher.watch.ClockMock; import org.elasticsearch.xpack.core.watcher.watch.ClockMock;
import org.elasticsearch.xpack.security.SecurityLifecycleService; import org.elasticsearch.xpack.security.SecurityLifecycleService;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -86,6 +87,7 @@ public class TokenServiceTests extends ESTestCase {
private Client client; private Client client;
private SecurityLifecycleService lifecycleService; private SecurityLifecycleService lifecycleService;
private SecurityIndexManager securityIndex;
private ClusterService clusterService; private ClusterService clusterService;
private Settings tokenServiceEnabledSettings = Settings.builder() private Settings tokenServiceEnabledSettings = Settings.builder()
.put(XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey(), true).build(); .put(XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey(), true).build();
@ -131,11 +133,13 @@ public class TokenServiceTests extends ESTestCase {
// setup lifecycle service // setup lifecycle service
lifecycleService = mock(SecurityLifecycleService.class); lifecycleService = mock(SecurityLifecycleService.class);
securityIndex = mock(SecurityIndexManager.class);
when(lifecycleService.securityIndex()).thenReturn(securityIndex);
doAnswer(invocationOnMock -> { doAnswer(invocationOnMock -> {
Runnable runnable = (Runnable) invocationOnMock.getArguments()[1]; Runnable runnable = (Runnable) invocationOnMock.getArguments()[1];
runnable.run(); runnable.run();
return null; return null;
}).when(lifecycleService).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class));
this.clusterService = ClusterServiceUtils.createClusterService(threadPool); this.clusterService = ClusterServiceUtils.createClusterService(threadPool);
} }
@ -376,7 +380,7 @@ public class TokenServiceTests extends ESTestCase {
} }
public void testInvalidatedToken() throws Exception { public void testInvalidatedToken() throws Exception {
when(lifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
TokenService tokenService = TokenService tokenService =
new TokenService(tokenServiceEnabledSettings, systemUTC(), client, lifecycleService, clusterService); new TokenService(tokenServiceEnabledSettings, systemUTC(), client, lifecycleService, clusterService);
Authentication authentication = new Authentication(new User("joe", "admin"), new RealmRef("native_realm", "native", "node1"), null); Authentication authentication = new Authentication(new User("joe", "admin"), new RealmRef("native_realm", "native", "node1"), null);
@ -563,8 +567,8 @@ public class TokenServiceTests extends ESTestCase {
UserToken serialized = future.get(); UserToken serialized = future.get();
assertEquals(authentication, serialized.getAuthentication()); assertEquals(authentication, serialized.getAuthentication());
when(lifecycleService.isSecurityIndexAvailable()).thenReturn(false); when(securityIndex.isAvailable()).thenReturn(false);
when(lifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
future = new PlainActionFuture<>(); future = new PlainActionFuture<>();
tokenService.getAndValidateToken(requestContext, future); tokenService.getAndValidateToken(requestContext, future);
assertNull(future.get()); assertNull(future.get());

View File

@ -55,7 +55,7 @@ import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDI
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoTimeout; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoTimeout;
import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.elasticsearch.xpack.security.SecurityLifecycleService.SECURITY_INDEX_NAME; import static org.elasticsearch.xpack.security.SecurityLifecycleService.SECURITY_INDEX_NAME;
import static org.elasticsearch.xpack.security.support.IndexLifecycleManager.INTERNAL_SECURITY_INDEX; import static org.elasticsearch.xpack.security.support.SecurityIndexManager.INTERNAL_SECURITY_INDEX;
import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;

View File

@ -33,6 +33,7 @@ import org.elasticsearch.xpack.core.security.user.KibanaUser;
import org.elasticsearch.xpack.core.security.user.LogstashSystemUser; import org.elasticsearch.xpack.core.security.user.LogstashSystemUser;
import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.security.SecurityLifecycleService; import org.elasticsearch.xpack.security.SecurityLifecycleService;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.Before; import org.junit.Before;
import java.io.IOException; import java.io.IOException;
@ -236,16 +237,17 @@ public class NativeUsersStoreTests extends ESTestCase {
private NativeUsersStore startNativeUsersStore() { private NativeUsersStore startNativeUsersStore() {
SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class); SecurityLifecycleService securityLifecycleService = mock(SecurityLifecycleService.class);
when(securityLifecycleService.isSecurityIndexAvailable()).thenReturn(true); SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityLifecycleService.securityIndex()).thenReturn(securityIndex);
when(securityLifecycleService.isSecurityIndexMappingUpToDate()).thenReturn(true); when(securityIndex.isAvailable()).thenReturn(true);
when(securityLifecycleService.isSecurityIndexOutOfDate()).thenReturn(false); when(securityIndex.indexExists()).thenReturn(true);
when(securityLifecycleService.isSecurityIndexUpToDate()).thenReturn(true); when(securityIndex.isMappingUpToDate()).thenReturn(true);
when(securityIndex.isIndexUpToDate()).thenReturn(true);
doAnswer((i) -> { doAnswer((i) -> {
Runnable action = (Runnable) i.getArguments()[1]; Runnable action = (Runnable) i.getArguments()[1];
action.run(); action.run();
return null; return null;
}).when(securityLifecycleService).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class));
return new NativeUsersStore(Settings.EMPTY, client, securityLifecycleService); return new NativeUsersStore(Settings.EMPTY, client, securityLifecycleService);
} }

View File

@ -29,6 +29,7 @@ import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.core.security.user.UsernamesField; import org.elasticsearch.xpack.core.security.user.UsernamesField;
import org.elasticsearch.xpack.security.SecurityLifecycleService; import org.elasticsearch.xpack.security.SecurityLifecycleService;
import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore.ReservedUserInfo; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore.ReservedUserInfo;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.Before; import org.junit.Before;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -63,13 +64,16 @@ public class ReservedRealmTests extends ESTestCase {
private static final SecureString EMPTY_PASSWORD = new SecureString("".toCharArray()); private static final SecureString EMPTY_PASSWORD = new SecureString("".toCharArray());
private NativeUsersStore usersStore; private NativeUsersStore usersStore;
private SecurityLifecycleService securityLifecycleService; private SecurityLifecycleService securityLifecycleService;
private SecurityIndexManager securityIndex;
@Before @Before
public void setupMocks() throws Exception { public void setupMocks() throws Exception {
usersStore = mock(NativeUsersStore.class); usersStore = mock(NativeUsersStore.class);
securityLifecycleService = mock(SecurityLifecycleService.class); securityLifecycleService = mock(SecurityLifecycleService.class);
when(securityLifecycleService.isSecurityIndexAvailable()).thenReturn(true); securityIndex = mock(SecurityIndexManager.class);
when(securityLifecycleService.checkSecurityMappingVersion(any())).thenReturn(true); when(securityLifecycleService.securityIndex()).thenReturn(securityIndex);
when(securityIndex.isAvailable()).thenReturn(true);
when(securityIndex.checkMappingVersion(any())).thenReturn(true);
mockGetAllReservedUserInfo(usersStore, Collections.emptyMap()); mockGetAllReservedUserInfo(usersStore, Collections.emptyMap());
} }
@ -90,7 +94,7 @@ public class ReservedRealmTests extends ESTestCase {
Settings settings = Settings.builder().put(XPackSettings.RESERVED_REALM_ENABLED_SETTING.getKey(), false).build(); Settings settings = Settings.builder().put(XPackSettings.RESERVED_REALM_ENABLED_SETTING.getKey(), false).build();
final boolean securityIndexExists = randomBoolean(); final boolean securityIndexExists = randomBoolean();
if (securityIndexExists) { if (securityIndexExists) {
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
} }
final ReservedRealm reservedRealm = final ReservedRealm reservedRealm =
new ReservedRealm(mock(Environment.class), settings, usersStore, new ReservedRealm(mock(Environment.class), settings, usersStore,
@ -120,7 +124,7 @@ public class ReservedRealmTests extends ESTestCase {
final User expectedUser = randomReservedUser(enabled); final User expectedUser = randomReservedUser(enabled);
final String principal = expectedUser.principal(); final String principal = expectedUser.principal();
final SecureString newPassword = new SecureString("foobar".toCharArray()); final SecureString newPassword = new SecureString("foobar".toCharArray());
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
doAnswer((i) -> { doAnswer((i) -> {
ActionListener callback = (ActionListener) i.getArguments()[1]; ActionListener callback = (ActionListener) i.getArguments()[1];
callback.onResponse(new ReservedUserInfo(Hasher.BCRYPT.hash(newPassword), enabled, false)); callback.onResponse(new ReservedUserInfo(Hasher.BCRYPT.hash(newPassword), enabled, false));
@ -146,10 +150,10 @@ public class ReservedRealmTests extends ESTestCase {
assertEquals(expectedUser, authenticated); assertEquals(expectedUser, authenticated);
assertThat(expectedUser.enabled(), is(enabled)); assertThat(expectedUser.enabled(), is(enabled));
verify(securityLifecycleService, times(2)).isSecurityIndexExisting(); verify(securityIndex, times(2)).indexExists();
verify(usersStore, times(2)).getReservedUserInfo(eq(principal), any(ActionListener.class)); verify(usersStore, times(2)).getReservedUserInfo(eq(principal), any(ActionListener.class));
final ArgumentCaptor<Predicate> predicateCaptor = ArgumentCaptor.forClass(Predicate.class); final ArgumentCaptor<Predicate> predicateCaptor = ArgumentCaptor.forClass(Predicate.class);
verify(securityLifecycleService, times(2)).checkSecurityMappingVersion(predicateCaptor.capture()); verify(securityIndex, times(2)).checkMappingVersion(predicateCaptor.capture());
verifyVersionPredicate(principal, predicateCaptor.getValue()); verifyVersionPredicate(principal, predicateCaptor.getValue());
verifyNoMoreInteractions(usersStore); verifyNoMoreInteractions(usersStore);
} }
@ -165,10 +169,10 @@ public class ReservedRealmTests extends ESTestCase {
reservedRealm.doLookupUser(principal, listener); reservedRealm.doLookupUser(principal, listener);
final User user = listener.actionGet(); final User user = listener.actionGet();
assertEquals(expectedUser, user); assertEquals(expectedUser, user);
verify(securityLifecycleService).isSecurityIndexExisting(); verify(securityIndex).indexExists();
final ArgumentCaptor<Predicate> predicateCaptor = ArgumentCaptor.forClass(Predicate.class); final ArgumentCaptor<Predicate> predicateCaptor = ArgumentCaptor.forClass(Predicate.class);
verify(securityLifecycleService).checkSecurityMappingVersion(predicateCaptor.capture()); verify(securityIndex).checkMappingVersion(predicateCaptor.capture());
verifyVersionPredicate(principal, predicateCaptor.getValue()); verifyVersionPredicate(principal, predicateCaptor.getValue());
PlainActionFuture<User> future = new PlainActionFuture<>(); PlainActionFuture<User> future = new PlainActionFuture<>();
@ -199,7 +203,7 @@ public class ReservedRealmTests extends ESTestCase {
new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY)); new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY));
final User expectedUser = randomReservedUser(true); final User expectedUser = randomReservedUser(true);
final String principal = expectedUser.principal(); final String principal = expectedUser.principal();
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
final RuntimeException e = new RuntimeException("store threw"); final RuntimeException e = new RuntimeException("store threw");
doAnswer((i) -> { doAnswer((i) -> {
ActionListener callback = (ActionListener) i.getArguments()[1]; ActionListener callback = (ActionListener) i.getArguments()[1];
@ -212,11 +216,11 @@ public class ReservedRealmTests extends ESTestCase {
ElasticsearchSecurityException securityException = expectThrows(ElasticsearchSecurityException.class, future::actionGet); ElasticsearchSecurityException securityException = expectThrows(ElasticsearchSecurityException.class, future::actionGet);
assertThat(securityException.getMessage(), containsString("failed to lookup")); assertThat(securityException.getMessage(), containsString("failed to lookup"));
verify(securityLifecycleService).isSecurityIndexExisting(); verify(securityIndex).indexExists();
verify(usersStore).getReservedUserInfo(eq(principal), any(ActionListener.class)); verify(usersStore).getReservedUserInfo(eq(principal), any(ActionListener.class));
final ArgumentCaptor<Predicate> predicateCaptor = ArgumentCaptor.forClass(Predicate.class); final ArgumentCaptor<Predicate> predicateCaptor = ArgumentCaptor.forClass(Predicate.class);
verify(securityLifecycleService).checkSecurityMappingVersion(predicateCaptor.capture()); verify(securityIndex).checkMappingVersion(predicateCaptor.capture());
verifyVersionPredicate(principal, predicateCaptor.getValue()); verifyVersionPredicate(principal, predicateCaptor.getValue());
verifyNoMoreInteractions(usersStore); verifyNoMoreInteractions(usersStore);
@ -269,7 +273,7 @@ public class ReservedRealmTests extends ESTestCase {
} }
public void testFailedAuthentication() throws Exception { public void testFailedAuthentication() throws Exception {
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
SecureString password = new SecureString("password".toCharArray()); SecureString password = new SecureString("password".toCharArray());
char[] hash = Hasher.BCRYPT.hash(password); char[] hash = Hasher.BCRYPT.hash(password);
ReservedUserInfo userInfo = new ReservedUserInfo(hash, true, false); ReservedUserInfo userInfo = new ReservedUserInfo(hash, true, false);
@ -302,7 +306,7 @@ public class ReservedRealmTests extends ESTestCase {
MockSecureSettings mockSecureSettings = new MockSecureSettings(); MockSecureSettings mockSecureSettings = new MockSecureSettings();
mockSecureSettings.setString("bootstrap.password", "foobar"); mockSecureSettings.setString("bootstrap.password", "foobar");
Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build(); Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build();
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore,
new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY)); new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY));
@ -324,7 +328,7 @@ public class ReservedRealmTests extends ESTestCase {
MockSecureSettings mockSecureSettings = new MockSecureSettings(); MockSecureSettings mockSecureSettings = new MockSecureSettings();
mockSecureSettings.setString("bootstrap.password", "foobar"); mockSecureSettings.setString("bootstrap.password", "foobar");
Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build(); Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build();
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore,
new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY)); new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY));
@ -351,7 +355,7 @@ public class ReservedRealmTests extends ESTestCase {
MockSecureSettings mockSecureSettings = new MockSecureSettings(); MockSecureSettings mockSecureSettings = new MockSecureSettings();
mockSecureSettings.setString("bootstrap.password", "foobar"); mockSecureSettings.setString("bootstrap.password", "foobar");
Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build(); Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build();
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(false); when(securityIndex.indexExists()).thenReturn(false);
final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore,
new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY)); new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY));
@ -369,7 +373,7 @@ public class ReservedRealmTests extends ESTestCase {
final String password = randomAlphaOfLengthBetween(8, 24); final String password = randomAlphaOfLengthBetween(8, 24);
mockSecureSettings.setString("bootstrap.password", password); mockSecureSettings.setString("bootstrap.password", password);
Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build(); Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build();
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true);
final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore,
new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY)); new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY));
@ -391,7 +395,7 @@ public class ReservedRealmTests extends ESTestCase {
final String password = randomAlphaOfLengthBetween(8, 24); final String password = randomAlphaOfLengthBetween(8, 24);
mockSecureSettings.setString("bootstrap.password", password); mockSecureSettings.setString("bootstrap.password", password);
Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build(); Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build();
when(securityLifecycleService.isSecurityIndexExisting()).thenReturn(false); when(securityIndex.indexExists()).thenReturn(false);
final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore,
new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY)); new AnonymousUser(Settings.EMPTY), securityLifecycleService, new ThreadContext(Settings.EMPTY));

View File

@ -30,6 +30,7 @@ import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.security.SecurityLifecycleService; import org.elasticsearch.xpack.security.SecurityLifecycleService;
import org.elasticsearch.xpack.security.authc.support.CachingUsernamePasswordRealm; import org.elasticsearch.xpack.security.authc.support.CachingUsernamePasswordRealm;
import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; import org.elasticsearch.xpack.security.authc.support.UserRoleMapper;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import java.util.Arrays; import java.util.Arrays;
@ -75,7 +76,9 @@ public class NativeRoleMappingStoreTests extends ESTestCase {
final Client client = mock(Client.class); final Client client = mock(Client.class);
final SecurityLifecycleService lifecycleService = mock(SecurityLifecycleService.class); final SecurityLifecycleService lifecycleService = mock(SecurityLifecycleService.class);
when(lifecycleService.isSecurityIndexAvailable()).thenReturn(true); SecurityIndexManager securityIndex = mock(SecurityIndexManager.class);
when(lifecycleService.securityIndex()).thenReturn(securityIndex);
when(securityIndex.isAvailable()).thenReturn(true);
final NativeRoleMappingStore store = new NativeRoleMappingStore(Settings.EMPTY, client, lifecycleService) { final NativeRoleMappingStore store = new NativeRoleMappingStore(Settings.EMPTY, client, lifecycleService) {
@Override @Override

View File

@ -21,7 +21,7 @@ import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class IndexLifecycleManagerIntegTests extends SecurityIntegTestCase { public class SecurityIndexManagerIntegTests extends SecurityIntegTestCase {
public void testConcurrentOperationsTryingToCreateSecurityIndexAndAlias() throws Exception { public void testConcurrentOperationsTryingToCreateSecurityIndexAndAlias() throws Exception {
assertSecurityIndexActive(); assertSecurityIndexActive();

View File

@ -52,17 +52,17 @@ import org.hamcrest.Matchers;
import org.junit.Before; import org.junit.Before;
import static org.elasticsearch.cluster.routing.RecoverySource.StoreRecoverySource.EXISTING_STORE_INSTANCE; import static org.elasticsearch.cluster.routing.RecoverySource.StoreRecoverySource.EXISTING_STORE_INSTANCE;
import static org.elasticsearch.xpack.security.support.IndexLifecycleManager.TEMPLATE_VERSION_PATTERN; import static org.elasticsearch.xpack.security.support.SecurityIndexManager.TEMPLATE_VERSION_PATTERN;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class IndexLifecycleManagerTests extends ESTestCase { public class SecurityIndexManagerTests extends ESTestCase {
private static final ClusterName CLUSTER_NAME = new ClusterName("index-lifecycle-manager-tests"); private static final ClusterName CLUSTER_NAME = new ClusterName("index-lifecycle-manager-tests");
private static final ClusterState EMPTY_CLUSTER_STATE = new ClusterState.Builder(CLUSTER_NAME).build(); private static final ClusterState EMPTY_CLUSTER_STATE = new ClusterState.Builder(CLUSTER_NAME).build();
public static final String INDEX_NAME = "IndexLifecycleManagerTests"; public static final String INDEX_NAME = "SecurityIndexManagerTests";
private static final String TEMPLATE_NAME = "IndexLifecycleManagerTests-template"; private static final String TEMPLATE_NAME = "SecurityIndexManagerTests-template";
private IndexLifecycleManager manager; private SecurityIndexManager manager;
private Map<Action<?, ?, ?>, Map<ActionRequest, ActionListener<?>>> actions; private Map<Action<?, ?, ?>, Map<ActionRequest, ActionListener<?>>> actions;
@Before @Before
@ -86,7 +86,7 @@ public class IndexLifecycleManagerTests extends ESTestCase {
actions.put(action, map); actions.put(action, map);
} }
}; };
manager = new IndexLifecycleManager(Settings.EMPTY, client, INDEX_NAME); manager = new SecurityIndexManager(Settings.EMPTY, client, INDEX_NAME);
} }
public void testIndexWithUpToDateMappingAndTemplate() throws IOException { public void testIndexWithUpToDateMappingAndTemplate() throws IOException {
@ -221,7 +221,7 @@ public class IndexLifecycleManagerTests extends ESTestCase {
// index doesn't exist and now exists with wrong format // index doesn't exist and now exists with wrong format
ClusterState.Builder clusterStateBuilder = createClusterState(INDEX_NAME, TEMPLATE_NAME, ClusterState.Builder clusterStateBuilder = createClusterState(INDEX_NAME, TEMPLATE_NAME,
IndexLifecycleManager.INTERNAL_INDEX_FORMAT - 1); SecurityIndexManager.INTERNAL_INDEX_FORMAT - 1);
markShardsAvailable(clusterStateBuilder); markShardsAvailable(clusterStateBuilder);
manager.clusterChanged(event(clusterStateBuilder)); manager.clusterChanged(event(clusterStateBuilder));
assertTrue(listenerCalled.get()); assertTrue(listenerCalled.get());
@ -235,7 +235,7 @@ public class IndexLifecycleManagerTests extends ESTestCase {
listenerCalled.set(false); listenerCalled.set(false);
// index doesn't exist and now exists with correct format // index doesn't exist and now exists with correct format
clusterStateBuilder = createClusterState(INDEX_NAME, TEMPLATE_NAME, IndexLifecycleManager.INTERNAL_INDEX_FORMAT); clusterStateBuilder = createClusterState(INDEX_NAME, TEMPLATE_NAME, SecurityIndexManager.INTERNAL_INDEX_FORMAT);
markShardsAvailable(clusterStateBuilder); markShardsAvailable(clusterStateBuilder);
manager.clusterChanged(event(clusterStateBuilder)); manager.clusterChanged(event(clusterStateBuilder));
assertFalse(listenerCalled.get()); assertFalse(listenerCalled.get());
@ -255,7 +255,7 @@ public class IndexLifecycleManagerTests extends ESTestCase {
} }
public static ClusterState.Builder createClusterState(String indexName, String templateName) throws IOException { public static ClusterState.Builder createClusterState(String indexName, String templateName) throws IOException {
return createClusterState(indexName, templateName, templateName, IndexLifecycleManager.INTERNAL_INDEX_FORMAT); return createClusterState(indexName, templateName, templateName, SecurityIndexManager.INTERNAL_INDEX_FORMAT);
} }
public static ClusterState.Builder createClusterState(String indexName, String templateName, int format) throws IOException { public static ClusterState.Builder createClusterState(String indexName, String templateName, int format) throws IOException {

View File

@ -23,7 +23,7 @@ import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.xpack.core.monitoring.exporter.MonitoringTemplateUtils; import org.elasticsearch.xpack.core.monitoring.exporter.MonitoringTemplateUtils;
import org.elasticsearch.xpack.core.watcher.client.WatchSourceBuilder; import org.elasticsearch.xpack.core.watcher.client.WatchSourceBuilder;
import org.elasticsearch.xpack.core.watcher.support.xcontent.ObjectPath; import org.elasticsearch.xpack.core.watcher.support.xcontent.ObjectPath;
import org.elasticsearch.xpack.security.support.IndexLifecycleManager; import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.elasticsearch.xpack.test.rest.XPackRestTestHelper; import org.elasticsearch.xpack.test.rest.XPackRestTestHelper;
import org.elasticsearch.xpack.watcher.actions.logging.LoggingAction; import org.elasticsearch.xpack.watcher.actions.logging.LoggingAction;
import org.elasticsearch.xpack.watcher.common.text.TextTemplate; import org.elasticsearch.xpack.watcher.common.text.TextTemplate;
@ -138,7 +138,7 @@ public class FullClusterRestartIT extends ESRestTestCase {
logger.info("settings map {}", settingsMap); logger.info("settings map {}", settingsMap);
if (settingsMap.containsKey("index")) { if (settingsMap.containsKey("index")) {
int format = Integer.parseInt(String.valueOf(((Map<String, Object>)settingsMap.get("index")).get("format"))); int format = Integer.parseInt(String.valueOf(((Map<String, Object>)settingsMap.get("index")).get("format")));
needsUpgrade = format == IndexLifecycleManager.INTERNAL_INDEX_FORMAT ? false : true; needsUpgrade = format == SecurityIndexManager.INTERNAL_INDEX_FORMAT ? false : true;
} else { } else {
needsUpgrade = true; needsUpgrade = true;
} }