Address license state update/read thread safety (#33396)

This change addresses some issues regarding thread safety around
updates and method calls on the XPackLicenseState object. There exists
a possibility that there could be a concurrent update to the
XPackLicenseState when there is a scheduled check to see if the license
is expired and a cluster state update. In order to address this, the
update method now has a synchronized block where member variables are
updated. Each method that reads these variables is now also
synchronized.

Along with the above change, there was a consistency issue around
security calls to the license state. The majority of security checks
make two calls to the license state, which could result in incorrect
behavior due to the checks being made against different license states.
The majority of this behavior was introduced for 6.3 with the inclusion
of x-pack in the default distribution. In order to resolve the majority
of these cases, the `isSecurityEnabled` method is no longer public and
the logic is also included in individual methods about security such as
`isAuthAllowed`. There were a few cases where this did not remove
multiple calls on the license state, so a new method has been added
which creates a copy of the current license state that will not change.
Callers can use this copy of the license state to make decisions based
on a consistent view of the license state.
This commit is contained in:
Jay Modi 2018-09-12 13:08:09 -06:00 committed by GitHub
parent 9b8fe85edb
commit 20c6c9c542
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 276 additions and 291 deletions

View File

@ -265,13 +265,15 @@ public class XPackLicenseState {
} }
} }
private volatile Status status = new Status(OperationMode.TRIAL, true); private final List<Runnable> listeners;
private final List<Runnable> listeners = new CopyOnWriteArrayList<>();
private final boolean isSecurityEnabled; private final boolean isSecurityEnabled;
private final boolean isSecurityExplicitlyEnabled; private final boolean isSecurityExplicitlyEnabled;
private volatile boolean isSecurityEnabledByTrialVersion;
private Status status = new Status(OperationMode.TRIAL, true);
private boolean isSecurityEnabledByTrialVersion;
public XPackLicenseState(Settings settings) { public XPackLicenseState(Settings settings) {
this.listeners = new CopyOnWriteArrayList<>();
this.isSecurityEnabled = XPackSettings.SECURITY_ENABLED.get(settings); this.isSecurityEnabled = XPackSettings.SECURITY_ENABLED.get(settings);
// 6.0+ requires TLS for production licenses, so if TLS is enabled and security is enabled // 6.0+ requires TLS for production licenses, so if TLS is enabled and security is enabled
// we can interpret this as an explicit enabling of security if the security enabled // we can interpret this as an explicit enabling of security if the security enabled
@ -281,6 +283,14 @@ public class XPackLicenseState {
this.isSecurityEnabledByTrialVersion = false; this.isSecurityEnabledByTrialVersion = false;
} }
private XPackLicenseState(XPackLicenseState xPackLicenseState) {
this.listeners = xPackLicenseState.listeners;
this.isSecurityEnabled = xPackLicenseState.isSecurityEnabled;
this.isSecurityExplicitlyEnabled = xPackLicenseState.isSecurityExplicitlyEnabled;
this.status = xPackLicenseState.status;
this.isSecurityEnabledByTrialVersion = xPackLicenseState.isSecurityEnabledByTrialVersion;
}
/** /**
* Updates the current state of the license, which will change what features are available. * Updates the current state of the license, which will change what features are available.
* *
@ -291,15 +301,17 @@ public class XPackLicenseState {
* trial was prior to this metadata being tracked (6.1) * trial was prior to this metadata being tracked (6.1)
*/ */
void update(OperationMode mode, boolean active, @Nullable Version mostRecentTrialVersion) { void update(OperationMode mode, boolean active, @Nullable Version mostRecentTrialVersion) {
status = new Status(mode, active); synchronized (this) {
if (isSecurityEnabled == true && isSecurityExplicitlyEnabled == false && mode == OperationMode.TRIAL status = new Status(mode, active);
&& isSecurityEnabledByTrialVersion == false) { if (isSecurityEnabled == true && isSecurityExplicitlyEnabled == false && mode == OperationMode.TRIAL
// Before 6.3, Trial licenses would default having security enabled. && isSecurityEnabledByTrialVersion == false) {
// If this license was generated before that version, then treat it as if security is explicitly enabled // Before 6.3, Trial licenses would default having security enabled.
if (mostRecentTrialVersion == null || mostRecentTrialVersion.before(Version.V_6_3_0)) { // If this license was generated before that version, then treat it as if security is explicitly enabled
Loggers.getLogger(getClass()).info("Automatically enabling security for older trial license ({})", if (mostRecentTrialVersion == null || mostRecentTrialVersion.before(Version.V_6_3_0)) {
mostRecentTrialVersion == null ? "[pre 6.1.0]" : mostRecentTrialVersion.toString()); Loggers.getLogger(getClass()).info("Automatically enabling security for older trial license ({})",
isSecurityEnabledByTrialVersion = true; mostRecentTrialVersion == null ? "[pre 6.1.0]" : mostRecentTrialVersion.toString());
isSecurityEnabledByTrialVersion = true;
}
} }
} }
listeners.forEach(Runnable::run); listeners.forEach(Runnable::run);
@ -316,12 +328,12 @@ public class XPackLicenseState {
} }
/** Return the current license type. */ /** Return the current license type. */
public OperationMode getOperationMode() { public synchronized OperationMode getOperationMode() {
return status.mode; return status.mode;
} }
/** Return true if the license is currently within its time boundaries, false otherwise. */ /** Return true if the license is currently within its time boundaries, false otherwise. */
public boolean isActive() { public synchronized boolean isActive() {
return status.active; return status.active;
} }
@ -329,28 +341,32 @@ public class XPackLicenseState {
* @return true if authentication and authorization should be enabled. this does not indicate what realms are available * @return true if authentication and authorization should be enabled. this does not indicate what realms are available
* @see #allowedRealmType() for the enabled realms * @see #allowedRealmType() for the enabled realms
*/ */
public boolean isAuthAllowed() { public synchronized boolean isAuthAllowed() {
OperationMode mode = status.mode; OperationMode mode = status.mode;
return mode == OperationMode.STANDARD || mode == OperationMode.GOLD || mode == OperationMode.PLATINUM final boolean isSecurityCurrentlyEnabled =
|| mode == OperationMode.TRIAL; isSecurityEnabled(mode, isSecurityExplicitlyEnabled, isSecurityEnabledByTrialVersion, isSecurityEnabled);
return isSecurityCurrentlyEnabled && (mode == OperationMode.STANDARD || mode == OperationMode.GOLD
|| mode == OperationMode.PLATINUM || mode == OperationMode.TRIAL);
} }
/** /**
* @return true if IP filtering should be enabled * @return true if IP filtering should be enabled
*/ */
public boolean isIpFilteringAllowed() { public synchronized boolean isIpFilteringAllowed() {
OperationMode mode = status.mode; OperationMode mode = status.mode;
return mode == OperationMode.GOLD || mode == OperationMode.PLATINUM final boolean isSecurityCurrentlyEnabled =
|| mode == OperationMode.TRIAL; isSecurityEnabled(mode, isSecurityExplicitlyEnabled, isSecurityEnabledByTrialVersion, isSecurityEnabled);
return isSecurityCurrentlyEnabled && (mode == OperationMode.GOLD || mode == OperationMode.PLATINUM || mode == OperationMode.TRIAL);
} }
/** /**
* @return true if auditing should be enabled * @return true if auditing should be enabled
*/ */
public boolean isAuditingAllowed() { public synchronized boolean isAuditingAllowed() {
OperationMode mode = status.mode; OperationMode mode = status.mode;
return mode == OperationMode.GOLD || mode == OperationMode.PLATINUM final boolean isSecurityCurrentlyEnabled =
|| mode == OperationMode.TRIAL; isSecurityEnabled(mode, isSecurityExplicitlyEnabled, isSecurityEnabledByTrialVersion, isSecurityEnabled);
return isSecurityCurrentlyEnabled && (mode == OperationMode.GOLD || mode == OperationMode.PLATINUM || mode == OperationMode.TRIAL);
} }
/** /**
@ -359,7 +375,7 @@ public class XPackLicenseState {
* *
* @return true if the license allows for the stats and health APIs to be used. * @return true if the license allows for the stats and health APIs to be used.
*/ */
public boolean isStatsAndHealthAllowed() { public synchronized boolean isStatsAndHealthAllowed() {
return status.active; return status.active;
} }
@ -375,9 +391,11 @@ public class XPackLicenseState {
* *
* @return {@code true} to enable DLS and FLS. Otherwise {@code false}. * @return {@code true} to enable DLS and FLS. Otherwise {@code false}.
*/ */
public boolean isDocumentAndFieldLevelSecurityAllowed() { public synchronized boolean isDocumentAndFieldLevelSecurityAllowed() {
OperationMode mode = status.mode; OperationMode mode = status.mode;
return mode == OperationMode.TRIAL || mode == OperationMode.PLATINUM; final boolean isSecurityCurrentlyEnabled =
isSecurityEnabled(mode, isSecurityExplicitlyEnabled, isSecurityEnabledByTrialVersion, isSecurityEnabled);
return isSecurityCurrentlyEnabled && (mode == OperationMode.TRIAL || mode == OperationMode.PLATINUM);
} }
/** Classes of realms that may be available based on the license type. */ /** Classes of realms that may be available based on the license type. */
@ -391,37 +409,45 @@ public class XPackLicenseState {
/** /**
* @return the type of realms that are enabled based on the license {@link OperationMode} * @return the type of realms that are enabled based on the license {@link OperationMode}
*/ */
public AllowedRealmType allowedRealmType() { public synchronized AllowedRealmType allowedRealmType() {
switch (status.mode) { final boolean isSecurityCurrentlyEnabled =
case PLATINUM: isSecurityEnabled(status.mode, isSecurityExplicitlyEnabled, isSecurityEnabledByTrialVersion, isSecurityEnabled);
case TRIAL: if (isSecurityCurrentlyEnabled) {
return AllowedRealmType.ALL; switch (status.mode) {
case GOLD: case PLATINUM:
return AllowedRealmType.DEFAULT; case TRIAL:
case STANDARD: return AllowedRealmType.ALL;
return AllowedRealmType.NATIVE; case GOLD:
default: return AllowedRealmType.DEFAULT;
return AllowedRealmType.NONE; case STANDARD:
return AllowedRealmType.NATIVE;
default:
return AllowedRealmType.NONE;
}
} else {
return AllowedRealmType.NONE;
} }
} }
/** /**
* @return whether custom role providers are allowed based on the license {@link OperationMode} * @return whether custom role providers are allowed based on the license {@link OperationMode}
*/ */
public boolean isCustomRoleProvidersAllowed() { public synchronized boolean isCustomRoleProvidersAllowed() {
final Status localStatus = status; final boolean isSecurityCurrentlyEnabled =
return (localStatus.mode == OperationMode.PLATINUM || localStatus.mode == OperationMode.TRIAL) isSecurityEnabled(status.mode, isSecurityExplicitlyEnabled, isSecurityEnabledByTrialVersion, isSecurityEnabled);
&& localStatus.active; return isSecurityCurrentlyEnabled && (status.mode == OperationMode.PLATINUM || status.mode == OperationMode.TRIAL)
&& status.active;
} }
/** /**
* @return whether "authorization_realms" are allowed based on the license {@link OperationMode} * @return whether "authorization_realms" are allowed based on the license {@link OperationMode}
* @see org.elasticsearch.xpack.core.security.authc.support.DelegatedAuthorizationSettings * @see org.elasticsearch.xpack.core.security.authc.support.DelegatedAuthorizationSettings
*/ */
public boolean isAuthorizationRealmAllowed() { public synchronized boolean isAuthorizationRealmAllowed() {
final Status localStatus = status; final boolean isSecurityCurrentlyEnabled =
return (localStatus.mode == OperationMode.PLATINUM || localStatus.mode == OperationMode.TRIAL) isSecurityEnabled(status.mode, isSecurityExplicitlyEnabled, isSecurityEnabledByTrialVersion, isSecurityEnabled);
&& localStatus.active; return isSecurityCurrentlyEnabled && (status.mode == OperationMode.PLATINUM || status.mode == OperationMode.TRIAL)
&& status.active;
} }
/** /**
@ -437,8 +463,7 @@ public class XPackLicenseState {
* *
* @return {@code true} as long as the license is valid. Otherwise {@code false}. * @return {@code true} as long as the license is valid. Otherwise {@code false}.
*/ */
public boolean isWatcherAllowed() { public synchronized boolean isWatcherAllowed() {
// status is volatile, so a local variable is used for a consistent view
Status localStatus = status; Status localStatus = status;
if (localStatus.active == false) { if (localStatus.active == false) {
@ -461,7 +486,7 @@ public class XPackLicenseState {
* *
* @return true if the license is active * @return true if the license is active
*/ */
public boolean isMonitoringAllowed() { public synchronized boolean isMonitoringAllowed() {
return status.active; return status.active;
} }
@ -471,7 +496,7 @@ public class XPackLicenseState {
* @return {@link #isWatcherAllowed()} * @return {@link #isWatcherAllowed()}
* @see #isWatcherAllowed() * @see #isWatcherAllowed()
*/ */
public boolean isMonitoringClusterAlertsAllowed() { public synchronized boolean isMonitoringClusterAlertsAllowed() {
return isWatcherAllowed(); return isWatcherAllowed();
} }
@ -484,7 +509,7 @@ public class XPackLicenseState {
* *
* @return {@code true} if the user is allowed to modify the retention. Otherwise {@code false}. * @return {@code true} if the user is allowed to modify the retention. Otherwise {@code false}.
*/ */
public boolean isUpdateRetentionAllowed() { public synchronized boolean isUpdateRetentionAllowed() {
final OperationMode mode = status.mode; final OperationMode mode = status.mode;
return mode != OperationMode.BASIC && mode != OperationMode.MISSING; return mode != OperationMode.BASIC && mode != OperationMode.MISSING;
} }
@ -500,8 +525,7 @@ public class XPackLicenseState {
* *
* @return {@code true} as long as the license is valid. Otherwise {@code false}. * @return {@code true} as long as the license is valid. Otherwise {@code false}.
*/ */
public boolean isGraphAllowed() { public synchronized boolean isGraphAllowed() {
// status is volatile
Status localStatus = status; Status localStatus = status;
OperationMode operationMode = localStatus.mode; OperationMode operationMode = localStatus.mode;
@ -523,8 +547,7 @@ public class XPackLicenseState {
* @return {@code true} as long as the license is valid. Otherwise * @return {@code true} as long as the license is valid. Otherwise
* {@code false}. * {@code false}.
*/ */
public boolean isMachineLearningAllowed() { public synchronized boolean isMachineLearningAllowed() {
// one-time volatile read as status could be updated on us while performing this check
final Status currentStatus = status; final Status currentStatus = status;
return currentStatus.active && isMachineLearningAllowedForOperationMode(currentStatus.mode); return currentStatus.active && isMachineLearningAllowedForOperationMode(currentStatus.mode);
} }
@ -538,7 +561,7 @@ public class XPackLicenseState {
* *
* @return true if the license is active * @return true if the license is active
*/ */
public boolean isRollupAllowed() { public synchronized boolean isRollupAllowed() {
return status.active; return status.active;
} }
@ -546,7 +569,7 @@ public class XPackLicenseState {
* Logstash is allowed as long as there is an active license of type TRIAL, STANDARD, GOLD or PLATINUM * Logstash is allowed as long as there is an active license of type TRIAL, STANDARD, GOLD or PLATINUM
* @return {@code true} as long as there is a valid license * @return {@code true} as long as there is a valid license
*/ */
public boolean isLogstashAllowed() { public synchronized boolean isLogstashAllowed() {
Status localStatus = status; Status localStatus = status;
return localStatus.active && (isBasic(localStatus.mode) == false); return localStatus.active && (isBasic(localStatus.mode) == false);
} }
@ -555,7 +578,7 @@ public class XPackLicenseState {
* Beats is allowed as long as there is an active license of type TRIAL, STANDARD, GOLD or PLATINUM * Beats is allowed as long as there is an active license of type TRIAL, STANDARD, GOLD or PLATINUM
* @return {@code true} as long as there is a valid license * @return {@code true} as long as there is a valid license
*/ */
public boolean isBeatsAllowed() { public synchronized boolean isBeatsAllowed() {
Status localStatus = status; Status localStatus = status;
return localStatus.active && (isBasic(localStatus.mode) == false); return localStatus.active && (isBasic(localStatus.mode) == false);
@ -565,7 +588,7 @@ public class XPackLicenseState {
* Deprecation APIs are always allowed as long as there is an active license * Deprecation APIs are always allowed as long as there is an active license
* @return {@code true} as long as there is a valid license * @return {@code true} as long as there is a valid license
*/ */
public boolean isDeprecationAllowed() { public synchronized boolean isDeprecationAllowed() {
return status.active; return status.active;
} }
@ -577,11 +600,9 @@ public class XPackLicenseState {
* @return {@code true} as long as the license is valid. Otherwise * @return {@code true} as long as the license is valid. Otherwise
* {@code false}. * {@code false}.
*/ */
public boolean isUpgradeAllowed() { public synchronized boolean isUpgradeAllowed() {
// status is volatile
Status localStatus = status;
// Should work on all active licenses // Should work on all active licenses
return localStatus.active; return status.active;
} }
/** /**
@ -589,7 +610,7 @@ public class XPackLicenseState {
* <p> * <p>
* SQL is available for all license types except {@link OperationMode#MISSING} * SQL is available for all license types except {@link OperationMode#MISSING}
*/ */
public boolean isSqlAllowed() { public synchronized boolean isSqlAllowed() {
return status.active; return status.active;
} }
@ -598,8 +619,7 @@ public class XPackLicenseState {
* <p> * <p>
* JDBC is available only in for {@link OperationMode#PLATINUM} and {@link OperationMode#TRIAL} licences * JDBC is available only in for {@link OperationMode#PLATINUM} and {@link OperationMode#TRIAL} licences
*/ */
public boolean isJdbcAllowed() { public synchronized boolean isJdbcAllowed() {
// status is volatile
Status localStatus = status; Status localStatus = status;
OperationMode operationMode = localStatus.mode; OperationMode operationMode = localStatus.mode;
@ -608,18 +628,35 @@ public class XPackLicenseState {
return licensed && localStatus.active; return licensed && localStatus.active;
} }
public boolean isTrialLicense() { public synchronized boolean isTrialLicense() {
return status.mode == OperationMode.TRIAL; return status.mode == OperationMode.TRIAL;
} }
public boolean isSecurityAvailable() { /**
* @return true if security is available to be used with the current license type
*/
public synchronized boolean isSecurityAvailable() {
OperationMode mode = status.mode; OperationMode mode = status.mode;
return mode == OperationMode.GOLD || mode == OperationMode.PLATINUM || mode == OperationMode.STANDARD || return mode == OperationMode.GOLD || mode == OperationMode.PLATINUM || mode == OperationMode.STANDARD ||
mode == OperationMode.TRIAL; mode == OperationMode.TRIAL;
} }
public boolean isSecurityEnabled() { /**
final OperationMode mode = status.mode; * @return true if security has been disabled by a trial license which is the case of the
* default distribution post 6.3.0. The conditions necessary for this are:
* <ul>
* <li>A trial license generated in 6.3.0+</li>
* <li>xpack.security.enabled not specified as a setting</li>
* </ul>
*/
public synchronized boolean isSecurityDisabledByTrialLicense() {
return status.mode == OperationMode.TRIAL && isSecurityEnabled
&& isSecurityExplicitlyEnabled == false
&& isSecurityEnabledByTrialVersion == false;
}
private static boolean isSecurityEnabled(final OperationMode mode, final boolean isSecurityExplicitlyEnabled,
final boolean isSecurityEnabledByTrialVersion, final boolean isSecurityEnabled) {
return mode == OperationMode.TRIAL ? (isSecurityExplicitlyEnabled || isSecurityEnabledByTrialVersion) : isSecurityEnabled; return mode == OperationMode.TRIAL ? (isSecurityExplicitlyEnabled || isSecurityEnabledByTrialVersion) : isSecurityEnabled;
} }
@ -634,8 +671,7 @@ public class XPackLicenseState {
* *
* @return true is the license is compatible, otherwise false * @return true is the license is compatible, otherwise false
*/ */
public boolean isCcrAllowed() { public synchronized boolean isCcrAllowed() {
// one-time volatile read as status could be updated on us while performing this check
final Status currentStatus = status; final Status currentStatus = status;
return currentStatus.active && isCcrAllowedForOperationMode(currentStatus.mode); return currentStatus.active && isCcrAllowedForOperationMode(currentStatus.mode);
} }
@ -648,4 +684,14 @@ public class XPackLicenseState {
return operationMode == OperationMode.PLATINUM || operationMode == OperationMode.TRIAL; return operationMode == OperationMode.PLATINUM || operationMode == OperationMode.TRIAL;
} }
/**
* Creates a copy of this object based on the state at the time the method was called. The
* returned object will not be modified by a license update/expiration so it can be used to
* make multiple method calls on the license state safely. This object should not be long
* lived but instead used within a method when a consistent view of the license state
* is needed for multiple interactions with the license state.
*/
public synchronized XPackLicenseState copyCurrentLicenseState() {
return new XPackLicenseState(this);
}
} }

View File

@ -110,7 +110,7 @@ public class SecurityIndexSearcherWrapper extends IndexSearcherWrapper {
@Override @Override
protected DirectoryReader wrap(DirectoryReader reader) { protected DirectoryReader wrap(DirectoryReader reader) {
if (licenseState.isSecurityEnabled() == false || licenseState.isDocumentAndFieldLevelSecurityAllowed() == false) { if (licenseState.isDocumentAndFieldLevelSecurityAllowed() == false) {
return reader; return reader;
} }
@ -171,7 +171,7 @@ public class SecurityIndexSearcherWrapper extends IndexSearcherWrapper {
@Override @Override
protected IndexSearcher wrap(IndexSearcher searcher) throws EngineException { protected IndexSearcher wrap(IndexSearcher searcher) throws EngineException {
if (licenseState.isSecurityEnabled() == false || licenseState.isDocumentAndFieldLevelSecurityAllowed() == false) { if (licenseState.isDocumentAndFieldLevelSecurityAllowed() == false) {
return searcher; return searcher;
} }

View File

@ -92,13 +92,13 @@ public class XPackLicenseStateTests extends ESTestCase {
assertThat(licenseState.isCustomRoleProvidersAllowed(), is(true)); assertThat(licenseState.isCustomRoleProvidersAllowed(), is(true));
licenseState = new XPackLicenseState(Settings.EMPTY); licenseState = new XPackLicenseState(Settings.EMPTY);
assertThat(licenseState.isAuthAllowed(), is(true)); assertThat(licenseState.isAuthAllowed(), is(false));
assertThat(licenseState.isIpFilteringAllowed(), is(true)); assertThat(licenseState.isIpFilteringAllowed(), is(false));
assertThat(licenseState.isAuditingAllowed(), is(true)); assertThat(licenseState.isAuditingAllowed(), is(false));
assertThat(licenseState.isStatsAndHealthAllowed(), is(true)); assertThat(licenseState.isStatsAndHealthAllowed(), is(true));
assertThat(licenseState.isDocumentAndFieldLevelSecurityAllowed(), is(true)); assertThat(licenseState.isDocumentAndFieldLevelSecurityAllowed(), is(false));
assertThat(licenseState.allowedRealmType(), is(XPackLicenseState.AllowedRealmType.ALL)); assertThat(licenseState.allowedRealmType(), is(XPackLicenseState.AllowedRealmType.NONE));
assertThat(licenseState.isCustomRoleProvidersAllowed(), is(true)); assertThat(licenseState.isCustomRoleProvidersAllowed(), is(false));
} }
public void testSecurityBasic() { public void testSecurityBasic() {
@ -217,21 +217,21 @@ public class XPackLicenseStateTests extends ESTestCase {
XPackLicenseState licenseState = new XPackLicenseState(Settings.EMPTY); XPackLicenseState licenseState = new XPackLicenseState(Settings.EMPTY);
licenseState.update(TRIAL, true, VersionUtils.randomVersionBetween(random(), Version.V_6_3_0, Version.CURRENT)); licenseState.update(TRIAL, true, VersionUtils.randomVersionBetween(random(), Version.V_6_3_0, Version.CURRENT));
assertThat(licenseState.isSecurityEnabled(), is(false)); assertThat(licenseState.isSecurityDisabledByTrialLicense(), is(true));
assertThat(licenseState.isAuthAllowed(), is(true)); assertThat(licenseState.isAuthAllowed(), is(false));
assertThat(licenseState.isIpFilteringAllowed(), is(true)); assertThat(licenseState.isIpFilteringAllowed(), is(false));
assertThat(licenseState.isAuditingAllowed(), is(true)); assertThat(licenseState.isAuditingAllowed(), is(false));
assertThat(licenseState.isStatsAndHealthAllowed(), is(true)); assertThat(licenseState.isStatsAndHealthAllowed(), is(true));
assertThat(licenseState.isDocumentAndFieldLevelSecurityAllowed(), is(true)); assertThat(licenseState.isDocumentAndFieldLevelSecurityAllowed(), is(false));
assertThat(licenseState.allowedRealmType(), is(XPackLicenseState.AllowedRealmType.ALL)); assertThat(licenseState.allowedRealmType(), is(XPackLicenseState.AllowedRealmType.NONE));
assertThat(licenseState.isCustomRoleProvidersAllowed(), is(true)); assertThat(licenseState.isCustomRoleProvidersAllowed(), is(false));
} }
public void testOldTrialDefaultsSecurityOn() { public void testOldTrialDefaultsSecurityOn() {
XPackLicenseState licenseState = new XPackLicenseState(Settings.EMPTY); XPackLicenseState licenseState = new XPackLicenseState(Settings.EMPTY);
licenseState.update(TRIAL, true, rarely() ? null : VersionUtils.randomVersionBetween(random(), Version.V_6_0_0, Version.V_6_2_4)); licenseState.update(TRIAL, true, rarely() ? null : VersionUtils.randomVersionBetween(random(), Version.V_6_0_0, Version.V_6_2_4));
assertThat(licenseState.isSecurityEnabled(), is(true)); assertThat(licenseState.isSecurityDisabledByTrialLicense(), is(false));
assertThat(licenseState.isAuthAllowed(), is(true)); assertThat(licenseState.isAuthAllowed(), is(true));
assertThat(licenseState.isIpFilteringAllowed(), is(true)); assertThat(licenseState.isIpFilteringAllowed(), is(true));
assertThat(licenseState.isAuditingAllowed(), is(true)); assertThat(licenseState.isAuditingAllowed(), is(true));

View File

@ -86,7 +86,6 @@ public class SecurityIndexSearcherWrapperIntegrationTests extends ESTestCase {
}); });
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true); when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(true);
SecurityIndexSearcherWrapper wrapper = new SecurityIndexSearcherWrapper(indexSettings, s -> queryShardContext, SecurityIndexSearcherWrapper wrapper = new SecurityIndexSearcherWrapper(indexSettings, s -> queryShardContext,
bitsetFilterCache, threadContext, licenseState, scriptService) { bitsetFilterCache, threadContext, licenseState, scriptService) {

View File

@ -131,7 +131,6 @@ public class SecurityIndexSearcherWrapperUnitTests extends ESTestCase {
ShardId shardId = new ShardId(index, 0); ShardId shardId = new ShardId(index, 0);
licenseState = mock(XPackLicenseState.class); licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true); when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true);
threadContext = new ThreadContext(Settings.EMPTY); threadContext = new ThreadContext(Settings.EMPTY);
IndexShard indexShard = mock(IndexShard.class); IndexShard indexShard = mock(IndexShard.class);

View File

@ -77,7 +77,7 @@ public class TransportPutDatafeedAction extends TransportMasterNodeAction<PutDat
ActionListener<PutDatafeedAction.Response> listener) { ActionListener<PutDatafeedAction.Response> listener) {
// If security is enabled only create the datafeed if the user requesting creation has // If security is enabled only create the datafeed if the user requesting creation has
// permission to read the indices the datafeed is going to read from // permission to read the indices the datafeed is going to read from
if (licenseState.isSecurityEnabled() && licenseState.isAuthAllowed()) { if (licenseState.isAuthAllowed()) {
final String username = securityContext.getUser().principal(); final String username = securityContext.getUser().principal();
ActionListener<HasPrivilegesResponse> privResponseListener = ActionListener.wrap( ActionListener<HasPrivilegesResponse> privResponseListener = ActionListener.wrap(
r -> handlePrivsResponse(username, request, r, listener), r -> handlePrivsResponse(username, request, r, listener),

View File

@ -971,7 +971,7 @@ public class Security extends Plugin implements ActionPlugin, IngestPlugin, Netw
public Function<String, Predicate<String>> getFieldFilter() { public Function<String, Predicate<String>> getFieldFilter() {
if (enabled) { if (enabled) {
return index -> { return index -> {
if (getLicenseState().isSecurityEnabled() == false || getLicenseState().isDocumentAndFieldLevelSecurityAllowed() == false) { if (getLicenseState().isDocumentAndFieldLevelSecurityAllowed() == false) {
return MapperPlugin.NOOP_FIELD_PREDICATE; return MapperPlugin.NOOP_FIELD_PREDICATE;
} }
IndicesAccessControl indicesAccessControl = threadContext.get().getTransient( IndicesAccessControl indicesAccessControl = threadContext.get().getTransient(

View File

@ -76,7 +76,11 @@ public class SecurityFeatureSet implements XPackFeatureSet {
@Override @Override
public boolean enabled() { public boolean enabled() {
return licenseState != null && licenseState.isSecurityEnabled(); if (licenseState != null) {
return XPackSettings.SECURITY_ENABLED.get(settings) &&
licenseState.isSecurityDisabledByTrialLicense() == false;
}
return false;
} }
@Override @Override

View File

@ -72,7 +72,6 @@ public class SecurityActionFilter extends AbstractComponent implements ActionFil
public <Request extends ActionRequest, Response extends ActionResponse> void apply(Task task, String action, Request request, public <Request extends ActionRequest, Response extends ActionResponse> void apply(Task task, String action, Request request,
ActionListener<Response> listener, ActionListener<Response> listener,
ActionFilterChain<Request, Response> chain) { ActionFilterChain<Request, Response> chain) {
/* /*
A functional requirement - when the license of security is disabled (invalid/expires), security will continue A functional requirement - when the license of security is disabled (invalid/expires), security will continue
to operate normally, except all read operations will be blocked. to operate normally, except all read operations will be blocked.
@ -84,8 +83,7 @@ public class SecurityActionFilter extends AbstractComponent implements ActionFil
throw LicenseUtils.newComplianceException(XPackField.SECURITY); throw LicenseUtils.newComplianceException(XPackField.SECURITY);
} }
final boolean securityEnabled = licenseState.isSecurityEnabled(); if (licenseState.isAuthAllowed()) {
if (securityEnabled && licenseState.isAuthAllowed()) {
final ActionListener<Response> contextPreservingListener = final ActionListener<Response> contextPreservingListener =
ContextPreservingActionListener.wrapPreservingContext(listener, threadContext); ContextPreservingActionListener.wrapPreservingContext(listener, threadContext);
ActionListener<Void> authenticatedListener = ActionListener.wrap( ActionListener<Void> authenticatedListener = ActionListener.wrap(
@ -117,7 +115,7 @@ public class SecurityActionFilter extends AbstractComponent implements ActionFil
listener.onFailure(e); listener.onFailure(e);
} }
} else if (SECURITY_ACTION_MATCHER.test(action)) { } else if (SECURITY_ACTION_MATCHER.test(action)) {
if (securityEnabled == false && licenseState.isTrialLicense()) { if (licenseState.isSecurityDisabledByTrialLicense()) {
listener.onFailure(new ElasticsearchException("Security must be explicitly enabled when using a trial license. " + listener.onFailure(new ElasticsearchException("Security must be explicitly enabled when using a trial license. " +
"Enable security by setting [xpack.security.enabled] to [true] in the elasticsearch.yml file " + "Enable security by setting [xpack.security.enabled] to [true] in the elasticsearch.yml file " +
"and restart the node.")); "and restart the node."));

View File

@ -37,25 +37,25 @@ public class BulkShardRequestInterceptor extends AbstractComponent implements Re
@Override @Override
public void intercept(BulkShardRequest request, Authentication authentication, Role userPermissions, String action) { public void intercept(BulkShardRequest request, Authentication authentication, Role userPermissions, String action) {
if (licenseState.isSecurityEnabled() == false || licenseState.isDocumentAndFieldLevelSecurityAllowed() == false) { if (licenseState.isDocumentAndFieldLevelSecurityAllowed()) {
return; IndicesAccessControl indicesAccessControl = threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
}
IndicesAccessControl indicesAccessControl = threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
for (BulkItemRequest bulkItemRequest : request.items()) { for (BulkItemRequest bulkItemRequest : request.items()) {
IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(bulkItemRequest.index()); IndicesAccessControl.IndexAccessControl indexAccessControl =
if (indexAccessControl != null) { indicesAccessControl.getIndexPermissions(bulkItemRequest.index());
boolean fls = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity(); if (indexAccessControl != null) {
boolean dls = indexAccessControl.getQueries() != null; boolean fls = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity();
if (fls || dls) { boolean dls = indexAccessControl.getQueries() != null;
if (bulkItemRequest.request() instanceof UpdateRequest) { if (fls || dls) {
throw new ElasticsearchSecurityException("Can't execute a bulk request with update requests embedded if " + if (bulkItemRequest.request() instanceof UpdateRequest) {
throw new ElasticsearchSecurityException("Can't execute a bulk request with update requests embedded if " +
"field or document level security is enabled", RestStatus.BAD_REQUEST); "field or document level security is enabled", RestStatus.BAD_REQUEST);
}
} }
} }
} logger.trace("intercepted bulk request for index [{}] without any update requests, continuing execution",
logger.trace("intercepted bulk request for index [{}] without any update requests, continuing execution",
bulkItemRequest.index()); bulkItemRequest.index());
}
} }
} }

View File

@ -34,26 +34,25 @@ abstract class FieldAndDocumentLevelSecurityRequestInterceptor<Request extends I
@Override @Override
public void intercept(Request request, Authentication authentication, Role userPermissions, String action) { public void intercept(Request request, Authentication authentication, Role userPermissions, String action) {
if (licenseState.isSecurityEnabled() == false || licenseState.isDocumentAndFieldLevelSecurityAllowed() == false) { if (licenseState.isDocumentAndFieldLevelSecurityAllowed()) {
return; final IndicesAccessControl indicesAccessControl = threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
} for (String index : request.indices()) {
final IndicesAccessControl indicesAccessControl = threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY); IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(index);
for (String index : request.indices()) { if (indexAccessControl != null) {
IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(index); boolean fieldLevelSecurityEnabled = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity();
if (indexAccessControl != null) { boolean documentLevelSecurityEnabled = indexAccessControl.getQueries() != null;
boolean fieldLevelSecurityEnabled = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity();
boolean documentLevelSecurityEnabled = indexAccessControl.getQueries() != null;
if (fieldLevelSecurityEnabled || documentLevelSecurityEnabled) {
if (fieldLevelSecurityEnabled || documentLevelSecurityEnabled) { if (fieldLevelSecurityEnabled || documentLevelSecurityEnabled) {
logger.trace("intercepted request for index [{}] with field level access controls [{}] document level access " + if (fieldLevelSecurityEnabled || documentLevelSecurityEnabled) {
"controls [{}]. disabling conflicting features", index, fieldLevelSecurityEnabled, logger.trace("intercepted request for index [{}] with field level access controls [{}] document level access " +
"controls [{}]. disabling conflicting features", index, fieldLevelSecurityEnabled,
documentLevelSecurityEnabled); documentLevelSecurityEnabled);
}
disableFeatures(request, fieldLevelSecurityEnabled, documentLevelSecurityEnabled);
return;
} }
disableFeatures(request, fieldLevelSecurityEnabled, documentLevelSecurityEnabled);
return;
} }
logger.trace("intercepted request for index [{}] without field or document level access controls", index);
} }
logger.trace("intercepted request for index [{}] without field or document level access controls", index);
} }
} }

View File

@ -38,42 +38,42 @@ public final class IndicesAliasesRequestInterceptor implements RequestIntercepto
@Override @Override
public void intercept(IndicesAliasesRequest request, Authentication authentication, Role userPermissions, String action) { public void intercept(IndicesAliasesRequest request, Authentication authentication, Role userPermissions, String action) {
if (licenseState.isSecurityEnabled() == false) { final XPackLicenseState frozenLicenseState = licenseState.copyCurrentLicenseState();
return; if (frozenLicenseState.isAuthAllowed()) {
} if (frozenLicenseState.isDocumentAndFieldLevelSecurityAllowed()) {
IndicesAccessControl indicesAccessControl = threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
if (licenseState.isDocumentAndFieldLevelSecurityAllowed()) { for (IndicesAliasesRequest.AliasActions aliasAction : request.getAliasActions()) {
IndicesAccessControl indicesAccessControl = threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY); if (aliasAction.actionType() == IndicesAliasesRequest.AliasActions.Type.ADD) {
for (IndicesAliasesRequest.AliasActions aliasAction : request.getAliasActions()) { for (String index : aliasAction.indices()) {
if (aliasAction.actionType() == IndicesAliasesRequest.AliasActions.Type.ADD) { IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(index);
for (String index : aliasAction.indices()) { if (indexAccessControl != null) {
IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(index); final boolean fls = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity();
if (indexAccessControl != null) { final boolean dls = indexAccessControl.getQueries() != null;
final boolean fls = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity(); if (fls || dls) {
final boolean dls = indexAccessControl.getQueries() != null; throw new ElasticsearchSecurityException("Alias requests are not allowed for users who have " +
if (fls || dls) {
throw new ElasticsearchSecurityException("Alias requests are not allowed for users who have " +
"field or document level security enabled on one of the indices", RestStatus.BAD_REQUEST); "field or document level security enabled on one of the indices", RestStatus.BAD_REQUEST);
}
} }
} }
} }
} }
} }
}
Map<String, Automaton> permissionsMap = new HashMap<>(); Map<String, Automaton> permissionsMap = new HashMap<>();
for (IndicesAliasesRequest.AliasActions aliasAction : request.getAliasActions()) { for (IndicesAliasesRequest.AliasActions aliasAction : request.getAliasActions()) {
if (aliasAction.actionType() == IndicesAliasesRequest.AliasActions.Type.ADD) { if (aliasAction.actionType() == IndicesAliasesRequest.AliasActions.Type.ADD) {
for (String index : aliasAction.indices()) { for (String index : aliasAction.indices()) {
Automaton indexPermissions = permissionsMap.computeIfAbsent(index, userPermissions.indices()::allowedActionsMatcher); Automaton indexPermissions =
for (String alias : aliasAction.aliases()) { permissionsMap.computeIfAbsent(index, userPermissions.indices()::allowedActionsMatcher);
Automaton aliasPermissions = for (String alias : aliasAction.aliases()) {
Automaton aliasPermissions =
permissionsMap.computeIfAbsent(alias, userPermissions.indices()::allowedActionsMatcher); permissionsMap.computeIfAbsent(alias, userPermissions.indices()::allowedActionsMatcher);
if (Operations.subsetOf(aliasPermissions, indexPermissions) == false) { if (Operations.subsetOf(aliasPermissions, indexPermissions) == false) {
// TODO we've already audited a access granted event so this is going to look ugly // TODO we've already audited a access granted event so this is going to look ugly
auditTrailService.accessDenied(authentication, action, request, userPermissions.names()); auditTrailService.accessDenied(authentication, action, request, userPermissions.names());
throw Exceptions.authorizationError("Adding an alias is not allowed when the alias " + throw Exceptions.authorizationError("Adding an alias is not allowed when the alias " +
"has more permissions than any of the indices"); "has more permissions than any of the indices");
}
} }
} }
} }

View File

@ -39,31 +39,33 @@ public final class ResizeRequestInterceptor extends AbstractComponent implements
@Override @Override
public void intercept(ResizeRequest request, Authentication authentication, Role userPermissions, String action) { public void intercept(ResizeRequest request, Authentication authentication, Role userPermissions, String action) {
if (licenseState.isSecurityEnabled() == false) { final XPackLicenseState frozenLicenseState = licenseState.copyCurrentLicenseState();
return; if (frozenLicenseState.isAuthAllowed()) {
} if (frozenLicenseState.isDocumentAndFieldLevelSecurityAllowed()) {
IndicesAccessControl indicesAccessControl =
if (licenseState.isDocumentAndFieldLevelSecurityAllowed()) { threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
IndicesAccessControl indicesAccessControl = threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY); IndicesAccessControl.IndexAccessControl indexAccessControl =
IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(request.getSourceIndex()); indicesAccessControl.getIndexPermissions(request.getSourceIndex());
if (indexAccessControl != null) { if (indexAccessControl != null) {
final boolean fls = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity(); final boolean fls = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity();
final boolean dls = indexAccessControl.getQueries() != null; final boolean dls = indexAccessControl.getQueries() != null;
if (fls || dls) { if (fls || dls) {
throw new ElasticsearchSecurityException("Resize requests are not allowed for users when " + throw new ElasticsearchSecurityException("Resize requests are not allowed for users when " +
"field or document level security is enabled on the source index", RestStatus.BAD_REQUEST); "field or document level security is enabled on the source index", RestStatus.BAD_REQUEST);
}
} }
} }
}
// ensure that the user would have the same level of access OR less on the target index // ensure that the user would have the same level of access OR less on the target index
final Automaton sourceIndexPermissions = userPermissions.indices().allowedActionsMatcher(request.getSourceIndex()); final Automaton sourceIndexPermissions = userPermissions.indices().allowedActionsMatcher(request.getSourceIndex());
final Automaton targetIndexPermissions = userPermissions.indices().allowedActionsMatcher(request.getTargetIndexRequest().index()); final Automaton targetIndexPermissions =
if (Operations.subsetOf(targetIndexPermissions, sourceIndexPermissions) == false) { userPermissions.indices().allowedActionsMatcher(request.getTargetIndexRequest().index());
// TODO we've already audited a access granted event so this is going to look ugly if (Operations.subsetOf(targetIndexPermissions, sourceIndexPermissions) == false) {
auditTrailService.accessDenied(authentication, action, request, userPermissions.names()); // TODO we've already audited a access granted event so this is going to look ugly
throw Exceptions.authorizationError("Resizing an index is not allowed when the target index " + auditTrailService.accessDenied(authentication, action, request, userPermissions.names());
throw Exceptions.authorizationError("Resizing an index is not allowed when the target index " +
"has more permissions than the source index"); "has more permissions than the source index");
}
} }
} }

View File

@ -42,7 +42,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void authenticationSuccess(String realm, User user, RestRequest request) { public void authenticationSuccess(String realm, User user, RestRequest request) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationSuccess(realm, user, request); auditTrail.authenticationSuccess(realm, user, request);
} }
@ -51,7 +51,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void authenticationSuccess(String realm, User user, String action, TransportMessage message) { public void authenticationSuccess(String realm, User user, String action, TransportMessage message) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationSuccess(realm, user, action, message); auditTrail.authenticationSuccess(realm, user, action, message);
} }
@ -60,7 +60,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void anonymousAccessDenied(String action, TransportMessage message) { public void anonymousAccessDenied(String action, TransportMessage message) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.anonymousAccessDenied(action, message); auditTrail.anonymousAccessDenied(action, message);
} }
@ -69,7 +69,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void anonymousAccessDenied(RestRequest request) { public void anonymousAccessDenied(RestRequest request) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.anonymousAccessDenied(request); auditTrail.anonymousAccessDenied(request);
} }
@ -78,7 +78,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void authenticationFailed(RestRequest request) { public void authenticationFailed(RestRequest request) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(request); auditTrail.authenticationFailed(request);
} }
@ -87,7 +87,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void authenticationFailed(String action, TransportMessage message) { public void authenticationFailed(String action, TransportMessage message) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(action, message); auditTrail.authenticationFailed(action, message);
} }
@ -96,7 +96,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void authenticationFailed(AuthenticationToken token, String action, TransportMessage message) { public void authenticationFailed(AuthenticationToken token, String action, TransportMessage message) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(token, action, message); auditTrail.authenticationFailed(token, action, message);
} }
@ -105,7 +105,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void authenticationFailed(String realm, AuthenticationToken token, String action, TransportMessage message) { public void authenticationFailed(String realm, AuthenticationToken token, String action, TransportMessage message) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(realm, token, action, message); auditTrail.authenticationFailed(realm, token, action, message);
} }
@ -114,7 +114,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void authenticationFailed(AuthenticationToken token, RestRequest request) { public void authenticationFailed(AuthenticationToken token, RestRequest request) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(token, request); auditTrail.authenticationFailed(token, request);
} }
@ -123,7 +123,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void authenticationFailed(String realm, AuthenticationToken token, RestRequest request) { public void authenticationFailed(String realm, AuthenticationToken token, RestRequest request) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(realm, token, request); auditTrail.authenticationFailed(realm, token, request);
} }
@ -132,7 +132,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void accessGranted(Authentication authentication, String action, TransportMessage message, String[] roleNames) { public void accessGranted(Authentication authentication, String action, TransportMessage message, String[] roleNames) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.accessGranted(authentication, action, message, roleNames); auditTrail.accessGranted(authentication, action, message, roleNames);
} }
@ -141,7 +141,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void accessDenied(Authentication authentication, String action, TransportMessage message, String[] roleNames) { public void accessDenied(Authentication authentication, String action, TransportMessage message, String[] roleNames) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.accessDenied(authentication, action, message, roleNames); auditTrail.accessDenied(authentication, action, message, roleNames);
} }
@ -150,7 +150,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void tamperedRequest(RestRequest request) { public void tamperedRequest(RestRequest request) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.tamperedRequest(request); auditTrail.tamperedRequest(request);
} }
@ -159,7 +159,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void tamperedRequest(String action, TransportMessage message) { public void tamperedRequest(String action, TransportMessage message) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.tamperedRequest(action, message); auditTrail.tamperedRequest(action, message);
} }
@ -168,7 +168,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void tamperedRequest(User user, String action, TransportMessage request) { public void tamperedRequest(User user, String action, TransportMessage request) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.tamperedRequest(user, action, request); auditTrail.tamperedRequest(user, action, request);
} }
@ -177,7 +177,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void connectionGranted(InetAddress inetAddress, String profile, SecurityIpFilterRule rule) { public void connectionGranted(InetAddress inetAddress, String profile, SecurityIpFilterRule rule) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.connectionGranted(inetAddress, profile, rule); auditTrail.connectionGranted(inetAddress, profile, rule);
} }
@ -186,7 +186,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void connectionDenied(InetAddress inetAddress, String profile, SecurityIpFilterRule rule) { public void connectionDenied(InetAddress inetAddress, String profile, SecurityIpFilterRule rule) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.connectionDenied(inetAddress, profile, rule); auditTrail.connectionDenied(inetAddress, profile, rule);
} }
@ -195,7 +195,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void runAsGranted(Authentication authentication, String action, TransportMessage message, String[] roleNames) { public void runAsGranted(Authentication authentication, String action, TransportMessage message, String[] roleNames) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.runAsGranted(authentication, action, message, roleNames); auditTrail.runAsGranted(authentication, action, message, roleNames);
} }
@ -204,7 +204,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void runAsDenied(Authentication authentication, String action, TransportMessage message, String[] roleNames) { public void runAsDenied(Authentication authentication, String action, TransportMessage message, String[] roleNames) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.runAsDenied(authentication, action, message, roleNames); auditTrail.runAsDenied(authentication, action, message, roleNames);
} }
@ -213,7 +213,7 @@ public class AuditTrailService extends AbstractComponent implements AuditTrail {
@Override @Override
public void runAsDenied(Authentication authentication, RestRequest request, String[] roleNames) { public void runAsDenied(Authentication authentication, RestRequest request, String[] roleNames) {
if (licenseState.isSecurityEnabled() && licenseState.isAuditingAllowed()) { if (licenseState.isAuditingAllowed()) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
auditTrail.runAsDenied(authentication, request, roleNames); auditTrail.runAsDenied(authentication, request, roleNames);
} }

View File

@ -98,7 +98,7 @@ public class Realms extends AbstractComponent implements Iterable<Realm> {
@Override @Override
public Iterator<Realm> iterator() { public Iterator<Realm> iterator() {
if (licenseState.isSecurityEnabled() == false || licenseState.isAuthAllowed() == false) { if (licenseState.isAuthAllowed() == false) {
return Collections.emptyIterator(); return Collections.emptyIterator();
} }
@ -120,7 +120,7 @@ public class Realms extends AbstractComponent implements Iterable<Realm> {
} }
public List<Realm> asList() { public List<Realm> asList() {
if (licenseState.isSecurityEnabled() == false || licenseState.isAuthAllowed() == false) { if (licenseState.isAuthAllowed() == false) {
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -45,7 +45,7 @@ public final class SecuritySearchOperationListener implements SearchOperationLis
*/ */
@Override @Override
public void onNewScrollContext(SearchContext searchContext) { public void onNewScrollContext(SearchContext searchContext) {
if (licenseState.isSecurityEnabled() && licenseState.isAuthAllowed()) { if (licenseState.isAuthAllowed()) {
searchContext.scrollContext().putInContext(AuthenticationField.AUTHENTICATION_KEY, searchContext.scrollContext().putInContext(AuthenticationField.AUTHENTICATION_KEY,
Authentication.getAuthentication(threadContext)); Authentication.getAuthentication(threadContext));
} }
@ -57,7 +57,7 @@ public final class SecuritySearchOperationListener implements SearchOperationLis
*/ */
@Override @Override
public void validateSearchContext(SearchContext searchContext, TransportRequest request) { public void validateSearchContext(SearchContext searchContext, TransportRequest request) {
if (licenseState.isSecurityEnabled() && licenseState.isAuthAllowed()) { if (licenseState.isAuthAllowed()) {
if (searchContext.scrollContext() != null) { if (searchContext.scrollContext() != null) {
final Authentication originalAuth = searchContext.scrollContext().getFromContext(AuthenticationField.AUTHENTICATION_KEY); final Authentication originalAuth = searchContext.scrollContext().getFromContext(AuthenticationField.AUTHENTICATION_KEY);
final Authentication current = Authentication.getAuthentication(threadContext); final Authentication current = Authentication.getAuthentication(threadContext);

View File

@ -59,8 +59,7 @@ public final class OptOutQueryCache extends AbstractIndexComponent implements Qu
@Override @Override
public Weight doCache(Weight weight, QueryCachingPolicy policy) { public Weight doCache(Weight weight, QueryCachingPolicy policy) {
// TODO: this is not concurrently safe since the license state can change between reads if (licenseState.isAuthAllowed() == false) {
if (licenseState.isSecurityEnabled() == false || licenseState.isAuthAllowed() == false) {
logger.debug("not opting out of the query cache; authorization is not allowed"); logger.debug("not opting out of the query cache; authorization is not allowed");
return indicesQueryCache.doCache(weight, policy); return indicesQueryCache.doCache(weight, policy);
} }

View File

@ -46,7 +46,7 @@ public class SecurityRestFilter implements RestHandler {
@Override @Override
public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception { public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {
if (licenseState.isSecurityEnabled() && licenseState.isAuthAllowed() && request.method() != Method.OPTIONS) { if (licenseState.isAuthAllowed() && request.method() != Method.OPTIONS) {
// CORS - allow for preflight unauthenticated OPTIONS request // CORS - allow for preflight unauthenticated OPTIONS request
if (extractClientCertificate) { if (extractClientCertificate) {
HttpChannel httpChannel = request.getHttpChannel(); HttpChannel httpChannel = request.getHttpChannel();

View File

@ -14,6 +14,7 @@ import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse; import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.xpack.core.XPackField; import org.elasticsearch.xpack.core.XPackField;
import org.elasticsearch.xpack.core.XPackSettings;
import java.io.IOException; import java.io.IOException;
@ -64,16 +65,14 @@ public abstract class SecurityBaseRestHandler extends BaseRestHandler {
* sent to the requestor * sent to the requestor
*/ */
protected Exception checkFeatureAvailable(RestRequest request) { protected Exception checkFeatureAvailable(RestRequest request) {
if (licenseState.isSecurityAvailable() == false) { if (XPackSettings.SECURITY_ENABLED.get(settings) == false) {
return new IllegalStateException("Security is not enabled but a security rest handler is registered");
} else if (licenseState.isSecurityAvailable() == false) {
return LicenseUtils.newComplianceException(XPackField.SECURITY); return LicenseUtils.newComplianceException(XPackField.SECURITY);
} else if (licenseState.isSecurityEnabled() == false) { } else if (licenseState.isSecurityDisabledByTrialLicense()) {
if (licenseState.isTrialLicense()) { return new ElasticsearchException("Security must be explicitly enabled when using a trial license. " +
return new ElasticsearchException("Security must be explicitly enabled when using a trial license. " + "Enable security by setting [xpack.security.enabled] to [true] in the elasticsearch.yml file " +
"Enable security by setting [xpack.security.enabled] to [true] in the elasticsearch.yml file " + "and restart the node.");
"and restart the node.");
} else {
return new IllegalStateException("Security is not enabled but a security rest handler is registered");
}
} else { } else {
return null; return null;
} }

View File

@ -107,7 +107,7 @@ public class SecurityServerTransportInterceptor extends AbstractComponent implem
// guarantee we use the same value wherever we would check the value for the state // guarantee we use the same value wherever we would check the value for the state
// being recovered // being recovered
final boolean stateNotRecovered = isStateNotRecovered; final boolean stateNotRecovered = isStateNotRecovered;
final boolean sendWithAuth = (licenseState.isSecurityEnabled() && licenseState.isAuthAllowed()) || stateNotRecovered; final boolean sendWithAuth = licenseState.isAuthAllowed() || stateNotRecovered;
if (sendWithAuth) { if (sendWithAuth) {
// the transport in core normally does this check, BUT since we are serializing to a string header we need to do it // the transport in core normally does this check, BUT since we are serializing to a string header we need to do it
// ourselves otherwise we wind up using a version newer than what we can actually send // ourselves otherwise we wind up using a version newer than what we can actually send
@ -266,7 +266,7 @@ public class SecurityServerTransportInterceptor extends AbstractComponent implem
public void messageReceived(T request, TransportChannel channel, Task task) throws Exception { public void messageReceived(T request, TransportChannel channel, Task task) throws Exception {
final AbstractRunnable receiveMessage = getReceiveRunnable(request, channel, task); final AbstractRunnable receiveMessage = getReceiveRunnable(request, channel, task);
try (ThreadContext.StoredContext ctx = threadContext.newStoredContext(true)) { try (ThreadContext.StoredContext ctx = threadContext.newStoredContext(true)) {
if (licenseState.isSecurityEnabled() && licenseState.isAuthAllowed()) { if (licenseState.isAuthAllowed()) {
String profile = channel.getProfileName(); String profile = channel.getProfileName();
ServerTransportFilter filter = profileFilters.get(profile); ServerTransportFilter filter = profileFilters.get(profile);

View File

@ -198,7 +198,7 @@ public class IPFilter {
} }
public boolean accept(String profile, InetSocketAddress peerAddress) { public boolean accept(String profile, InetSocketAddress peerAddress) {
if (licenseState.isSecurityEnabled() == false || licenseState.isIpFilteringAllowed() == false) { if (licenseState.isIpFilteringAllowed() == false) {
return true; return true;
} }

View File

@ -238,7 +238,7 @@ public class LicensingTests extends SecurityIntegTestCase {
License.OperationMode mode = randomFrom(License.OperationMode.GOLD, License.OperationMode.TRIAL, License.OperationMode mode = randomFrom(License.OperationMode.GOLD, License.OperationMode.TRIAL,
License.OperationMode.PLATINUM, License.OperationMode.STANDARD); License.OperationMode.PLATINUM, License.OperationMode.STANDARD);
enableLicensing(mode); enableLicensing(mode);
// security actions should not work! // security actions should work!
try (TransportClient client = new TestXPackTransportClient(settings, LocalStateSecurity.class)) { try (TransportClient client = new TestXPackTransportClient(settings, LocalStateSecurity.class)) {
client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress());
GetUsersResponse response = new SecurityClient(client).prepareGetUsers().get(); GetUsersResponse response = new SecurityClient(client).prepareGetUsers().get();

View File

@ -55,7 +55,6 @@ public class SecurityFeatureSetTests extends ESTestCase {
public void init() throws Exception { public void init() throws Exception {
settings = Settings.builder().put("path.home", createTempDir()).build(); settings = Settings.builder().put("path.home", createTempDir()).build();
licenseState = mock(XPackLicenseState.class); licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true);
realms = mock(Realms.class); realms = mock(Realms.class);
ipFilter = mock(IPFilter.class); ipFilter = mock(IPFilter.class);
rolesStore = mock(CompositeRolesStore.class); rolesStore = mock(CompositeRolesStore.class);
@ -77,7 +76,7 @@ public class SecurityFeatureSetTests extends ESTestCase {
rolesStore, roleMappingStore, ipFilter); rolesStore, roleMappingStore, ipFilter);
assertThat(featureSet.enabled(), is(true)); assertThat(featureSet.enabled(), is(true));
when(licenseState.isSecurityEnabled()).thenReturn(false); when(licenseState.isSecurityDisabledByTrialLicense()).thenReturn(true);
featureSet = new SecurityFeatureSet(settings, licenseState, realms, featureSet = new SecurityFeatureSet(settings, licenseState, realms,
rolesStore, roleMappingStore, ipFilter); rolesStore, roleMappingStore, ipFilter);
assertThat(featureSet.enabled(), is(false)); assertThat(featureSet.enabled(), is(false));
@ -90,7 +89,7 @@ public class SecurityFeatureSetTests extends ESTestCase {
Settings.Builder settings = Settings.builder().put(this.settings); Settings.Builder settings = Settings.builder().put(this.settings);
boolean enabled = randomBoolean(); boolean enabled = randomBoolean();
when(licenseState.isSecurityEnabled()).thenReturn(enabled); settings.put(XPackSettings.SECURITY_ENABLED.getKey(), enabled);
final boolean httpSSLEnabled = randomBoolean(); final boolean httpSSLEnabled = randomBoolean();
settings.put("xpack.security.http.ssl.enabled", httpSSLEnabled); settings.put("xpack.security.http.ssl.enabled", httpSSLEnabled);

View File

@ -67,7 +67,6 @@ public class SecurityActionFilterTests extends ESTestCase {
licenseState = mock(XPackLicenseState.class); licenseState = mock(XPackLicenseState.class);
when(licenseState.isAuthAllowed()).thenReturn(true); when(licenseState.isAuthAllowed()).thenReturn(true);
when(licenseState.isStatsAndHealthAllowed()).thenReturn(true); when(licenseState.isStatsAndHealthAllowed()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(true);
ThreadPool threadPool = mock(ThreadPool.class); ThreadPool threadPool = mock(ThreadPool.class);
threadContext = new ThreadContext(Settings.EMPTY); threadContext = new ThreadContext(Settings.EMPTY);
when(threadPool.getThreadContext()).thenReturn(threadContext); when(threadPool.getThreadContext()).thenReturn(threadContext);

View File

@ -35,7 +35,8 @@ public class IndicesAliasesRequestInterceptorTests extends ESTestCase {
public void testInterceptorThrowsWhenFLSDLSEnabled() { public void testInterceptorThrowsWhenFLSDLSEnabled() {
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true); when(licenseState.copyCurrentLicenseState()).thenReturn(licenseState);
when(licenseState.isAuthAllowed()).thenReturn(true);
when(licenseState.isAuditingAllowed()).thenReturn(true); when(licenseState.isAuditingAllowed()).thenReturn(true);
when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true); when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true);
ThreadContext threadContext = new ThreadContext(Settings.EMPTY); ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
@ -81,7 +82,8 @@ public class IndicesAliasesRequestInterceptorTests extends ESTestCase {
public void testInterceptorThrowsWhenTargetHasGreaterPermissions() throws Exception { public void testInterceptorThrowsWhenTargetHasGreaterPermissions() throws Exception {
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true); when(licenseState.copyCurrentLicenseState()).thenReturn(licenseState);
when(licenseState.isAuthAllowed()).thenReturn(true);
when(licenseState.isAuditingAllowed()).thenReturn(true); when(licenseState.isAuditingAllowed()).thenReturn(true);
when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true); when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true);
ThreadContext threadContext = new ThreadContext(Settings.EMPTY); ThreadContext threadContext = new ThreadContext(Settings.EMPTY);

View File

@ -37,7 +37,8 @@ public class ResizeRequestInterceptorTests extends ESTestCase {
public void testResizeRequestInterceptorThrowsWhenFLSDLSEnabled() { public void testResizeRequestInterceptorThrowsWhenFLSDLSEnabled() {
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true); when(licenseState.copyCurrentLicenseState()).thenReturn(licenseState);
when(licenseState.isAuthAllowed()).thenReturn(true);
when(licenseState.isAuditingAllowed()).thenReturn(true); when(licenseState.isAuditingAllowed()).thenReturn(true);
when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true); when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true);
ThreadPool threadPool = mock(ThreadPool.class); ThreadPool threadPool = mock(ThreadPool.class);
@ -76,7 +77,8 @@ public class ResizeRequestInterceptorTests extends ESTestCase {
public void testResizeRequestInterceptorThrowsWhenTargetHasGreaterPermissions() throws Exception { public void testResizeRequestInterceptorThrowsWhenTargetHasGreaterPermissions() throws Exception {
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true); when(licenseState.copyCurrentLicenseState()).thenReturn(licenseState);
when(licenseState.isAuthAllowed()).thenReturn(true);
when(licenseState.isAuditingAllowed()).thenReturn(true); when(licenseState.isAuditingAllowed()).thenReturn(true);
when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true); when(licenseState.isDocumentAndFieldLevelSecurityAllowed()).thenReturn(true);
ThreadPool threadPool = mock(ThreadPool.class); ThreadPool threadPool = mock(ThreadPool.class);

View File

@ -48,7 +48,6 @@ public class AuditTrailServiceTests extends ESTestCase {
licenseState = mock(XPackLicenseState.class); licenseState = mock(XPackLicenseState.class);
service = new AuditTrailService(Settings.EMPTY, auditTrails, licenseState); service = new AuditTrailService(Settings.EMPTY, auditTrails, licenseState);
isAuditingAllowed = randomBoolean(); isAuditingAllowed = randomBoolean();
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.isAuditingAllowed()).thenReturn(isAuditingAllowed); when(licenseState.isAuditingAllowed()).thenReturn(isAuditingAllowed);
token = mock(AuthenticationToken.class); token = mock(AuthenticationToken.class);
message = mock(TransportMessage.class); message = mock(TransportMessage.class);
@ -58,7 +57,6 @@ public class AuditTrailServiceTests extends ESTestCase {
public void testAuthenticationFailed() throws Exception { public void testAuthenticationFailed() throws Exception {
service.authenticationFailed(token, "_action", message); service.authenticationFailed(token, "_action", message);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).authenticationFailed(token, "_action", message); verify(auditTrail).authenticationFailed(token, "_action", message);
@ -71,7 +69,6 @@ public class AuditTrailServiceTests extends ESTestCase {
public void testAuthenticationFailedNoToken() throws Exception { public void testAuthenticationFailedNoToken() throws Exception {
service.authenticationFailed("_action", message); service.authenticationFailed("_action", message);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).authenticationFailed("_action", message); verify(auditTrail).authenticationFailed("_action", message);
@ -84,7 +81,6 @@ public class AuditTrailServiceTests extends ESTestCase {
public void testAuthenticationFailedRestNoToken() throws Exception { public void testAuthenticationFailedRestNoToken() throws Exception {
service.authenticationFailed(restRequest); service.authenticationFailed(restRequest);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).authenticationFailed(restRequest); verify(auditTrail).authenticationFailed(restRequest);
@ -97,7 +93,6 @@ public class AuditTrailServiceTests extends ESTestCase {
public void testAuthenticationFailedRest() throws Exception { public void testAuthenticationFailedRest() throws Exception {
service.authenticationFailed(token, restRequest); service.authenticationFailed(token, restRequest);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).authenticationFailed(token, restRequest); verify(auditTrail).authenticationFailed(token, restRequest);
@ -110,7 +105,6 @@ public class AuditTrailServiceTests extends ESTestCase {
public void testAuthenticationFailedRealm() throws Exception { public void testAuthenticationFailedRealm() throws Exception {
service.authenticationFailed("_realm", token, "_action", message); service.authenticationFailed("_realm", token, "_action", message);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).authenticationFailed("_realm", token, "_action", message); verify(auditTrail).authenticationFailed("_realm", token, "_action", message);
@ -123,7 +117,6 @@ public class AuditTrailServiceTests extends ESTestCase {
public void testAuthenticationFailedRestRealm() throws Exception { public void testAuthenticationFailedRestRealm() throws Exception {
service.authenticationFailed("_realm", token, restRequest); service.authenticationFailed("_realm", token, restRequest);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).authenticationFailed("_realm", token, restRequest); verify(auditTrail).authenticationFailed("_realm", token, restRequest);
@ -136,7 +129,6 @@ public class AuditTrailServiceTests extends ESTestCase {
public void testAnonymousAccess() throws Exception { public void testAnonymousAccess() throws Exception {
service.anonymousAccessDenied("_action", message); service.anonymousAccessDenied("_action", message);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).anonymousAccessDenied("_action", message); verify(auditTrail).anonymousAccessDenied("_action", message);
@ -152,7 +144,6 @@ public class AuditTrailServiceTests extends ESTestCase {
String[] roles = new String[] { randomAlphaOfLengthBetween(1, 6) }; String[] roles = new String[] { randomAlphaOfLengthBetween(1, 6) };
service.accessGranted(authentication, "_action", message, roles); service.accessGranted(authentication, "_action", message, roles);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).accessGranted(authentication, "_action", message, roles); verify(auditTrail).accessGranted(authentication, "_action", message, roles);
@ -168,7 +159,6 @@ public class AuditTrailServiceTests extends ESTestCase {
String[] roles = new String[] { randomAlphaOfLengthBetween(1, 6) }; String[] roles = new String[] { randomAlphaOfLengthBetween(1, 6) };
service.accessDenied(authentication, "_action", message, roles); service.accessDenied(authentication, "_action", message, roles);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).accessDenied(authentication, "_action", message, roles); verify(auditTrail).accessDenied(authentication, "_action", message, roles);
@ -183,7 +173,6 @@ public class AuditTrailServiceTests extends ESTestCase {
SecurityIpFilterRule rule = randomBoolean() ? SecurityIpFilterRule.ACCEPT_ALL : IPFilter.DEFAULT_PROFILE_ACCEPT_ALL; SecurityIpFilterRule rule = randomBoolean() ? SecurityIpFilterRule.ACCEPT_ALL : IPFilter.DEFAULT_PROFILE_ACCEPT_ALL;
service.connectionGranted(inetAddress, "client", rule); service.connectionGranted(inetAddress, "client", rule);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).connectionGranted(inetAddress, "client", rule); verify(auditTrail).connectionGranted(inetAddress, "client", rule);
@ -198,7 +187,6 @@ public class AuditTrailServiceTests extends ESTestCase {
SecurityIpFilterRule rule = new SecurityIpFilterRule(false, "_all"); SecurityIpFilterRule rule = new SecurityIpFilterRule(false, "_all");
service.connectionDenied(inetAddress, "client", rule); service.connectionDenied(inetAddress, "client", rule);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).connectionDenied(inetAddress, "client", rule); verify(auditTrail).connectionDenied(inetAddress, "client", rule);
@ -213,7 +201,6 @@ public class AuditTrailServiceTests extends ESTestCase {
String realm = "_realm"; String realm = "_realm";
service.authenticationSuccess(realm, user, restRequest); service.authenticationSuccess(realm, user, restRequest);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).authenticationSuccess(realm, user, restRequest); verify(auditTrail).authenticationSuccess(realm, user, restRequest);
@ -228,7 +215,6 @@ public class AuditTrailServiceTests extends ESTestCase {
String realm = "_realm"; String realm = "_realm";
service.authenticationSuccess(realm, user, "_action", message); service.authenticationSuccess(realm, user, "_action", message);
verify(licenseState).isAuditingAllowed(); verify(licenseState).isAuditingAllowed();
verify(licenseState).isSecurityEnabled();
if (isAuditingAllowed) { if (isAuditingAllowed) {
for (AuditTrail auditTrail : auditTrails) { for (AuditTrail auditTrail : auditTrails) {
verify(auditTrail).authenticationSuccess(realm, user, "_action", message); verify(auditTrail).authenticationSuccess(realm, user, "_action", message);

View File

@ -154,7 +154,6 @@ public class AuthenticationServiceTests extends ESTestCase {
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.allowedRealmType()).thenReturn(XPackLicenseState.AllowedRealmType.ALL); when(licenseState.allowedRealmType()).thenReturn(XPackLicenseState.AllowedRealmType.ALL);
when(licenseState.isAuthAllowed()).thenReturn(true); when(licenseState.isAuthAllowed()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(true);
realms = new TestRealms(Settings.EMPTY, TestEnvironment.newEnvironment(settings), Collections.<String, Realm.Factory>emptyMap(), realms = new TestRealms(Settings.EMPTY, TestEnvironment.newEnvironment(settings), Collections.<String, Realm.Factory>emptyMap(),
licenseState, threadContext, mock(ReservedRealm.class), Arrays.asList(firstRealm, secondRealm), licenseState, threadContext, mock(ReservedRealm.class), Arrays.asList(firstRealm, secondRealm),
Collections.singletonList(firstRealm)); Collections.singletonList(firstRealm));

View File

@ -69,7 +69,6 @@ public class RealmsTests extends ESTestCase {
threadContext = new ThreadContext(Settings.EMPTY); threadContext = new ThreadContext(Settings.EMPTY);
reservedRealm = mock(ReservedRealm.class); reservedRealm = mock(ReservedRealm.class);
when(licenseState.isAuthAllowed()).thenReturn(true); when(licenseState.isAuthAllowed()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.allowedRealmType()).thenReturn(AllowedRealmType.ALL); when(licenseState.allowedRealmType()).thenReturn(AllowedRealmType.ALL);
when(reservedRealm.type()).thenReturn(ReservedRealm.TYPE); when(reservedRealm.type()).thenReturn(ReservedRealm.TYPE);
} }

View File

@ -39,7 +39,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
public void testUnlicensed() { public void testUnlicensed() {
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.isAuthAllowed()).thenReturn(false); when(licenseState.isAuthAllowed()).thenReturn(false);
ThreadContext threadContext = new ThreadContext(Settings.EMPTY); ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
AuditTrailService auditTrailService = mock(AuditTrailService.class); AuditTrailService auditTrailService = mock(AuditTrailService.class);
@ -49,7 +48,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
SecuritySearchOperationListener listener = new SecuritySearchOperationListener(threadContext, licenseState, auditTrailService); SecuritySearchOperationListener listener = new SecuritySearchOperationListener(threadContext, licenseState, auditTrailService);
listener.onNewScrollContext(searchContext); listener.onNewScrollContext(searchContext);
listener.validateSearchContext(searchContext, Empty.INSTANCE); listener.validateSearchContext(searchContext, Empty.INSTANCE);
verify(licenseState, times(2)).isSecurityEnabled();
verify(licenseState, times(2)).isAuthAllowed(); verify(licenseState, times(2)).isAuthAllowed();
verifyZeroInteractions(auditTrailService, searchContext); verifyZeroInteractions(auditTrailService, searchContext);
} }
@ -60,7 +58,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
final Scroll scroll = new Scroll(TimeValue.timeValueSeconds(2L)); final Scroll scroll = new Scroll(TimeValue.timeValueSeconds(2L));
testSearchContext.scrollContext().scroll = scroll; testSearchContext.scrollContext().scroll = scroll;
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.isAuthAllowed()).thenReturn(true); when(licenseState.isAuthAllowed()).thenReturn(true);
ThreadContext threadContext = new ThreadContext(Settings.EMPTY); ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
AuditTrailService auditTrailService = mock(AuditTrailService.class); AuditTrailService auditTrailService = mock(AuditTrailService.class);
@ -75,7 +72,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
assertEquals(scroll, testSearchContext.scrollContext().scroll); assertEquals(scroll, testSearchContext.scrollContext().scroll);
verify(licenseState).isAuthAllowed(); verify(licenseState).isAuthAllowed();
verify(licenseState).isSecurityEnabled();
verifyZeroInteractions(auditTrailService); verifyZeroInteractions(auditTrailService);
} }
@ -86,7 +82,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
new Authentication(new User("test", "role"), new RealmRef("realm", "file", "node"), null)); new Authentication(new User("test", "role"), new RealmRef("realm", "file", "node"), null));
testSearchContext.scrollContext().scroll = new Scroll(TimeValue.timeValueSeconds(2L)); testSearchContext.scrollContext().scroll = new Scroll(TimeValue.timeValueSeconds(2L));
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.isAuthAllowed()).thenReturn(true); when(licenseState.isAuthAllowed()).thenReturn(true);
ThreadContext threadContext = new ThreadContext(Settings.EMPTY); ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
AuditTrailService auditTrailService = mock(AuditTrailService.class); AuditTrailService auditTrailService = mock(AuditTrailService.class);
@ -97,7 +92,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
authentication.writeToContext(threadContext); authentication.writeToContext(threadContext);
listener.validateSearchContext(testSearchContext, Empty.INSTANCE); listener.validateSearchContext(testSearchContext, Empty.INSTANCE);
verify(licenseState).isAuthAllowed(); verify(licenseState).isAuthAllowed();
verify(licenseState).isSecurityEnabled();
verifyZeroInteractions(auditTrailService); verifyZeroInteractions(auditTrailService);
} }
@ -108,7 +102,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
authentication.writeToContext(threadContext); authentication.writeToContext(threadContext);
listener.validateSearchContext(testSearchContext, Empty.INSTANCE); listener.validateSearchContext(testSearchContext, Empty.INSTANCE);
verify(licenseState, times(2)).isAuthAllowed(); verify(licenseState, times(2)).isAuthAllowed();
verify(licenseState, times(2)).isSecurityEnabled();
verifyZeroInteractions(auditTrailService); verifyZeroInteractions(auditTrailService);
} }
@ -125,7 +118,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
expectThrows(SearchContextMissingException.class, () -> listener.validateSearchContext(testSearchContext, request)); expectThrows(SearchContextMissingException.class, () -> listener.validateSearchContext(testSearchContext, request));
assertEquals(testSearchContext.id(), expected.id()); assertEquals(testSearchContext.id(), expected.id());
verify(licenseState, times(3)).isAuthAllowed(); verify(licenseState, times(3)).isAuthAllowed();
verify(licenseState, times(3)).isSecurityEnabled();
verify(auditTrailService).accessDenied(authentication, "action", request, authentication.getUser().roles()); verify(auditTrailService).accessDenied(authentication, "action", request, authentication.getUser().roles());
} }
@ -142,7 +134,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
final InternalScrollSearchRequest request = new InternalScrollSearchRequest(); final InternalScrollSearchRequest request = new InternalScrollSearchRequest();
listener.validateSearchContext(testSearchContext, request); listener.validateSearchContext(testSearchContext, request);
verify(licenseState, times(4)).isAuthAllowed(); verify(licenseState, times(4)).isAuthAllowed();
verify(licenseState, times(4)).isSecurityEnabled();
verifyNoMoreInteractions(auditTrailService); verifyNoMoreInteractions(auditTrailService);
} }
@ -161,7 +152,6 @@ public class SecuritySearchOperationListenerTests extends ESTestCase {
expectThrows(SearchContextMissingException.class, () -> listener.validateSearchContext(testSearchContext, request)); expectThrows(SearchContextMissingException.class, () -> listener.validateSearchContext(testSearchContext, request));
assertEquals(testSearchContext.id(), expected.id()); assertEquals(testSearchContext.id(), expected.id());
verify(licenseState, times(5)).isAuthAllowed(); verify(licenseState, times(5)).isAuthAllowed();
verify(licenseState, times(5)).isSecurityEnabled();
verify(auditTrailService).accessDenied(authentication, "action", request, authentication.getUser().roles()); verify(auditTrailService).accessDenied(authentication, "action", request, authentication.getUser().roles());
} }
} }

View File

@ -48,7 +48,7 @@ public class OptOutQueryCacheTests extends ESTestCase {
DirectoryReader reader; DirectoryReader reader;
@Before @Before
void initLuceneStuff() throws IOException { public void initLuceneStuff() throws IOException {
dir = newDirectory(); dir = newDirectory();
w = new RandomIndexWriter(random(), dir); w = new RandomIndexWriter(random(), dir);
reader = w.getReader(); reader = w.getReader();
@ -56,11 +56,12 @@ public class OptOutQueryCacheTests extends ESTestCase {
} }
@After @After
void closeLuceneStuff() throws IOException { public void closeLuceneStuff() throws IOException {
w.close(); w.close();
dir.close(); dir.close();
reader.close(); reader.close();
} }
public void testOptOutQueryCacheSafetyCheck() throws IOException { public void testOptOutQueryCacheSafetyCheck() throws IOException {
BooleanQuery.Builder builder = new BooleanQuery.Builder(); BooleanQuery.Builder builder = new BooleanQuery.Builder();
@ -123,25 +124,6 @@ public class OptOutQueryCacheTests extends ESTestCase {
assertFalse(OptOutQueryCache.cachingIsSafe(weight, permissions)); assertFalse(OptOutQueryCache.cachingIsSafe(weight, permissions));
} }
public void testOptOutQueryCacheSecurityIsNotEnabled() {
final Settings.Builder settings = Settings.builder()
.put("index.version.created", Version.CURRENT)
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0);
final IndexMetaData indexMetaData = IndexMetaData.builder("index").settings(settings).build();
final IndexSettings indexSettings = new IndexSettings(indexMetaData, Settings.EMPTY);
final IndicesQueryCache indicesQueryCache = mock(IndicesQueryCache.class);
final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
final XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(false);
when(licenseState.isAuthAllowed()).thenReturn(randomBoolean());
final OptOutQueryCache cache = new OptOutQueryCache(indexSettings, indicesQueryCache, threadContext, licenseState);
final Weight weight = mock(Weight.class);
final QueryCachingPolicy policy = mock(QueryCachingPolicy.class);
cache.doCache(weight, policy);
verify(indicesQueryCache).doCache(same(weight), same(policy));
}
public void testOptOutQueryCacheAuthIsNotAllowed() { public void testOptOutQueryCacheAuthIsNotAllowed() {
final Settings.Builder settings = Settings.builder() final Settings.Builder settings = Settings.builder()
.put("index.version.created", Version.CURRENT) .put("index.version.created", Version.CURRENT)
@ -152,7 +134,6 @@ public class OptOutQueryCacheTests extends ESTestCase {
final IndicesQueryCache indicesQueryCache = mock(IndicesQueryCache.class); final IndicesQueryCache indicesQueryCache = mock(IndicesQueryCache.class);
final ThreadContext threadContext = new ThreadContext(Settings.EMPTY); final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
final XPackLicenseState licenseState = mock(XPackLicenseState.class); final XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(randomBoolean());
when(licenseState.isAuthAllowed()).thenReturn(false); when(licenseState.isAuthAllowed()).thenReturn(false);
final OptOutQueryCache cache = new OptOutQueryCache(indexSettings, indicesQueryCache, threadContext, licenseState); final OptOutQueryCache cache = new OptOutQueryCache(indexSettings, indicesQueryCache, threadContext, licenseState);
final Weight weight = mock(Weight.class); final Weight weight = mock(Weight.class);
@ -171,7 +152,6 @@ public class OptOutQueryCacheTests extends ESTestCase {
final IndicesQueryCache indicesQueryCache = mock(IndicesQueryCache.class); final IndicesQueryCache indicesQueryCache = mock(IndicesQueryCache.class);
final ThreadContext threadContext = new ThreadContext(Settings.EMPTY); final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
final XPackLicenseState licenseState = mock(XPackLicenseState.class); final XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.isAuthAllowed()).thenReturn(true); when(licenseState.isAuthAllowed()).thenReturn(true);
final OptOutQueryCache cache = new OptOutQueryCache(indexSettings, indicesQueryCache, threadContext, licenseState); final OptOutQueryCache cache = new OptOutQueryCache(indexSettings, indicesQueryCache, threadContext, licenseState);
final Weight weight = mock(Weight.class); final Weight weight = mock(Weight.class);
@ -196,7 +176,6 @@ public class OptOutQueryCacheTests extends ESTestCase {
when(indicesAccessControl.getIndexPermissions("index")).thenReturn(indexAccessControl); when(indicesAccessControl.getIndexPermissions("index")).thenReturn(indexAccessControl);
threadContext.putTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY, indicesAccessControl); threadContext.putTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY, indicesAccessControl);
final XPackLicenseState licenseState = mock(XPackLicenseState.class); final XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.isAuthAllowed()).thenReturn(true); when(licenseState.isAuthAllowed()).thenReturn(true);
final OptOutQueryCache cache = new OptOutQueryCache(indexSettings, indicesQueryCache, threadContext, licenseState); final OptOutQueryCache cache = new OptOutQueryCache(indexSettings, indicesQueryCache, threadContext, licenseState);
final Weight weight = mock(Weight.class); final Weight weight = mock(Weight.class);

View File

@ -60,7 +60,6 @@ public class SecurityRestFilterTests extends ESTestCase {
channel = mock(RestChannel.class); channel = mock(RestChannel.class);
licenseState = mock(XPackLicenseState.class); licenseState = mock(XPackLicenseState.class);
when(licenseState.isAuthAllowed()).thenReturn(true); when(licenseState.isAuthAllowed()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(true);
restHandler = mock(RestHandler.class); restHandler = mock(RestHandler.class);
filter = new SecurityRestFilter(licenseState, filter = new SecurityRestFilter(licenseState,
new ThreadContext(Settings.EMPTY), authcService, restHandler, false); new ThreadContext(Settings.EMPTY), authcService, restHandler, false);

View File

@ -24,11 +24,11 @@ import static org.mockito.Mockito.when;
public class SecurityBaseRestHandlerTests extends ESTestCase { public class SecurityBaseRestHandlerTests extends ESTestCase {
public void testSecurityBaseRestHandlerChecksLicenseState() throws Exception { public void testSecurityBaseRestHandlerChecksLicenseState() throws Exception {
final boolean securityEnabled = randomBoolean(); final boolean securityDisabledByTrial = randomBoolean();
final AtomicBoolean consumerCalled = new AtomicBoolean(false); final AtomicBoolean consumerCalled = new AtomicBoolean(false);
final XPackLicenseState licenseState = mock(XPackLicenseState.class); final XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isSecurityAvailable()).thenReturn(true); when(licenseState.isSecurityAvailable()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(securityEnabled); when(licenseState.isSecurityDisabledByTrialLicense()).thenReturn(securityDisabledByTrial);
SecurityBaseRestHandler handler = new SecurityBaseRestHandler(Settings.EMPTY, licenseState) { SecurityBaseRestHandler handler = new SecurityBaseRestHandler(Settings.EMPTY, licenseState) {
@Override @Override
@ -46,7 +46,7 @@ public class SecurityBaseRestHandlerTests extends ESTestCase {
} }
}; };
FakeRestRequest fakeRestRequest = new FakeRestRequest(); FakeRestRequest fakeRestRequest = new FakeRestRequest();
FakeRestChannel fakeRestChannel = new FakeRestChannel(fakeRestRequest, randomBoolean(), securityEnabled ? 0 : 1); FakeRestChannel fakeRestChannel = new FakeRestChannel(fakeRestRequest, randomBoolean(), securityDisabledByTrial ? 1 : 0);
NodeClient client = mock(NodeClient.class); NodeClient client = mock(NodeClient.class);
assertFalse(consumerCalled.get()); assertFalse(consumerCalled.get());
@ -54,8 +54,7 @@ public class SecurityBaseRestHandlerTests extends ESTestCase {
handler.handleRequest(fakeRestRequest, fakeRestChannel, client); handler.handleRequest(fakeRestRequest, fakeRestChannel, client);
verify(licenseState).isSecurityAvailable(); verify(licenseState).isSecurityAvailable();
verify(licenseState).isSecurityEnabled(); if (securityDisabledByTrial == false) {
if (securityEnabled) {
assertTrue(consumerCalled.get()); assertTrue(consumerCalled.get());
assertEquals(0, fakeRestChannel.responses().get()); assertEquals(0, fakeRestChannel.responses().get());
assertEquals(0, fakeRestChannel.errors().get()); assertEquals(0, fakeRestChannel.errors().get());

View File

@ -73,7 +73,6 @@ public class SecurityServerTransportInterceptorTests extends ESTestCase {
securityContext = spy(new SecurityContext(settings, threadPool.getThreadContext())); securityContext = spy(new SecurityContext(settings, threadPool.getThreadContext()));
xPackLicenseState = mock(XPackLicenseState.class); xPackLicenseState = mock(XPackLicenseState.class);
when(xPackLicenseState.isAuthAllowed()).thenReturn(true); when(xPackLicenseState.isAuthAllowed()).thenReturn(true);
when(xPackLicenseState.isSecurityEnabled()).thenReturn(true);
} }
@After @After
@ -102,7 +101,6 @@ public class SecurityServerTransportInterceptorTests extends ESTestCase {
sender.sendRequest(null, null, null, null, null); sender.sendRequest(null, null, null, null, null);
assertTrue(calledWrappedSender.get()); assertTrue(calledWrappedSender.get());
verify(xPackLicenseState).isAuthAllowed(); verify(xPackLicenseState).isAuthAllowed();
verify(xPackLicenseState).isSecurityEnabled();
verifyNoMoreInteractions(xPackLicenseState); verifyNoMoreInteractions(xPackLicenseState);
verifyZeroInteractions(securityContext); verifyZeroInteractions(securityContext);
} }
@ -112,10 +110,8 @@ public class SecurityServerTransportInterceptorTests extends ESTestCase {
mock(AuthenticationService.class), mock(AuthorizationService.class), xPackLicenseState, mock(SSLService.class), mock(AuthenticationService.class), mock(AuthorizationService.class), xPackLicenseState, mock(SSLService.class),
securityContext, new DestructiveOperations(Settings.EMPTY, new ClusterSettings(Settings.EMPTY, securityContext, new DestructiveOperations(Settings.EMPTY, new ClusterSettings(Settings.EMPTY,
Collections.singleton(DestructiveOperations.REQUIRES_NAME_SETTING))), clusterService); Collections.singleton(DestructiveOperations.REQUIRES_NAME_SETTING))), clusterService);
final boolean securityEnabled = randomBoolean(); final boolean authAllowed = randomBoolean();
final boolean authAllowed = securityEnabled && randomBoolean();
when(xPackLicenseState.isAuthAllowed()).thenReturn(authAllowed); when(xPackLicenseState.isAuthAllowed()).thenReturn(authAllowed);
when(xPackLicenseState.isSecurityEnabled()).thenReturn(securityEnabled);
ClusterState notRecovered = ClusterState.builder(clusterService.state()) ClusterState notRecovered = ClusterState.builder(clusterService.state())
.blocks(ClusterBlocks.builder().addGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK).build()) .blocks(ClusterBlocks.builder().addGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK).build())
.build(); .build();
@ -139,10 +135,7 @@ public class SecurityServerTransportInterceptorTests extends ESTestCase {
sender.sendRequest(connection, "internal:foo", null, null, null); sender.sendRequest(connection, "internal:foo", null, null, null);
assertTrue(calledWrappedSender.get()); assertTrue(calledWrappedSender.get());
assertEquals(SystemUser.INSTANCE, sendingUser.get()); assertEquals(SystemUser.INSTANCE, sendingUser.get());
verify(xPackLicenseState).isSecurityEnabled(); verify(xPackLicenseState).isAuthAllowed();
if (securityEnabled) {
verify(xPackLicenseState).isAuthAllowed();
}
verify(securityContext).executeAsUser(any(User.class), any(Consumer.class), eq(Version.CURRENT)); verify(securityContext).executeAsUser(any(User.class), any(Consumer.class), eq(Version.CURRENT));
verifyNoMoreInteractions(xPackLicenseState); verifyNoMoreInteractions(xPackLicenseState);
} }
@ -177,7 +170,6 @@ public class SecurityServerTransportInterceptorTests extends ESTestCase {
assertEquals(user, sendingUser.get()); assertEquals(user, sendingUser.get());
assertEquals(user, securityContext.getUser()); assertEquals(user, securityContext.getUser());
verify(xPackLicenseState).isAuthAllowed(); verify(xPackLicenseState).isAuthAllowed();
verify(xPackLicenseState).isSecurityEnabled();
verify(securityContext, never()).executeAsUser(any(User.class), any(Consumer.class), any(Version.class)); verify(securityContext, never()).executeAsUser(any(User.class), any(Consumer.class), any(Version.class));
verifyNoMoreInteractions(xPackLicenseState); verifyNoMoreInteractions(xPackLicenseState);
} }
@ -215,7 +207,6 @@ public class SecurityServerTransportInterceptorTests extends ESTestCase {
assertEquals(SystemUser.INSTANCE, sendingUser.get()); assertEquals(SystemUser.INSTANCE, sendingUser.get());
assertEquals(user, securityContext.getUser()); assertEquals(user, securityContext.getUser());
verify(xPackLicenseState).isAuthAllowed(); verify(xPackLicenseState).isAuthAllowed();
verify(xPackLicenseState).isSecurityEnabled();
verify(securityContext).executeAsUser(any(User.class), any(Consumer.class), eq(Version.CURRENT)); verify(securityContext).executeAsUser(any(User.class), any(Consumer.class), eq(Version.CURRENT));
verifyNoMoreInteractions(xPackLicenseState); verifyNoMoreInteractions(xPackLicenseState);
} }
@ -246,7 +237,6 @@ public class SecurityServerTransportInterceptorTests extends ESTestCase {
assertEquals("there should always be a user when sending a message for action [indices:foo]", e.getMessage()); assertEquals("there should always be a user when sending a message for action [indices:foo]", e.getMessage());
assertNull(securityContext.getUser()); assertNull(securityContext.getUser());
verify(xPackLicenseState).isAuthAllowed(); verify(xPackLicenseState).isAuthAllowed();
verify(xPackLicenseState).isSecurityEnabled();
verify(securityContext, never()).executeAsUser(any(User.class), any(Consumer.class), any(Version.class)); verify(securityContext, never()).executeAsUser(any(User.class), any(Consumer.class), any(Version.class));
verifyNoMoreInteractions(xPackLicenseState); verifyNoMoreInteractions(xPackLicenseState);
} }

View File

@ -53,7 +53,6 @@ public class IPFilterTests extends ESTestCase {
public void init() { public void init() {
licenseState = mock(XPackLicenseState.class); licenseState = mock(XPackLicenseState.class);
when(licenseState.isIpFilteringAllowed()).thenReturn(true); when(licenseState.isIpFilteringAllowed()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(true);
auditTrail = mock(AuditTrailService.class); auditTrail = mock(AuditTrailService.class);
clusterSettings = new ClusterSettings(Settings.EMPTY, new HashSet<>(Arrays.asList( clusterSettings = new ClusterSettings(Settings.EMPTY, new HashSet<>(Arrays.asList(
IPFilter.HTTP_FILTER_ALLOW_SETTING, IPFilter.HTTP_FILTER_ALLOW_SETTING,

View File

@ -57,7 +57,6 @@ public class IpFilterRemoteAddressFilterTests extends ESTestCase {
IPFilter.PROFILE_FILTER_DENY_SETTING))); IPFilter.PROFILE_FILTER_DENY_SETTING)));
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isIpFilteringAllowed()).thenReturn(true); when(licenseState.isIpFilteringAllowed()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(true);
AuditTrailService auditTrailService = new AuditTrailService(settings, Collections.emptyList(), licenseState); AuditTrailService auditTrailService = new AuditTrailService(settings, Collections.emptyList(), licenseState);
IPFilter ipFilter = new IPFilter(settings, auditTrailService, clusterSettings, licenseState); IPFilter ipFilter = new IPFilter(settings, auditTrailService, clusterSettings, licenseState);
ipFilter.setBoundTransportAddress(transport.boundAddress(), transport.profileBoundAddresses()); ipFilter.setBoundTransportAddress(transport.boundAddress(), transport.profileBoundAddresses());

View File

@ -58,7 +58,6 @@ public class NioIPFilterTests extends ESTestCase {
IPFilter.PROFILE_FILTER_DENY_SETTING))); IPFilter.PROFILE_FILTER_DENY_SETTING)));
XPackLicenseState licenseState = mock(XPackLicenseState.class); XPackLicenseState licenseState = mock(XPackLicenseState.class);
when(licenseState.isIpFilteringAllowed()).thenReturn(true); when(licenseState.isIpFilteringAllowed()).thenReturn(true);
when(licenseState.isSecurityEnabled()).thenReturn(true);
AuditTrailService auditTrailService = new AuditTrailService(settings, Collections.emptyList(), licenseState); AuditTrailService auditTrailService = new AuditTrailService(settings, Collections.emptyList(), licenseState);
IPFilter ipFilter = new IPFilter(settings, auditTrailService, clusterSettings, licenseState); IPFilter ipFilter = new IPFilter(settings, auditTrailService, clusterSettings, licenseState);
ipFilter.setBoundTransportAddress(transport.boundAddress(), transport.profileBoundAddresses()); ipFilter.setBoundTransportAddress(transport.boundAddress(), transport.profileBoundAddresses());