cleanup the exceptions used by Shield to only the ones in core

Original commit: elastic/x-pack-elasticsearch@5424fe68fa
This commit is contained in:
jaymode 2015-07-02 07:59:28 -04:00 committed by uboness
parent 792359103d
commit a3a04a7d1d
57 changed files with 242 additions and 442 deletions

View File

@ -1,24 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.shield;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.collect.Tuple;
/**
*
*/
public class ShieldException extends ElasticsearchException.WithRestHeadersException {
public ShieldException(String msg, Tuple... headers) {
super(msg, headers);
}
public ShieldException(String msg, Throwable cause, Tuple... headers) {
super(msg, headers);
initCause(cause);
}
}

View File

@ -98,7 +98,7 @@ public class ShieldPlugin extends AbstractPlugin {
}
int i = userSetting.indexOf(":");
if (i < 0 || i == userSetting.length() - 1) {
throw new ShieldSettingsException("invalid [shield.user] settings. must be in the form of \"<username>:<password>\"");
throw new IllegalArgumentException("invalid [shield.user] setting. must be in the form of \"<username>:<password>\"");
}
String username = userSetting.substring(0, i);
String password = userSetting.substring(i + 1);

View File

@ -1,21 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.shield;
/**
*
*/
public class ShieldSettingsException extends ShieldException {
public ShieldSettingsException(String msg) {
super(msg);
}
public ShieldSettingsException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@ -5,6 +5,7 @@
*/
package org.elasticsearch.shield;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
@ -39,7 +40,7 @@ public abstract class User {
if (input.readBoolean()) {
String name = input.readString();
if (!System.NAME.equals(name)) {
throw new ShieldException("invalid system user");
throw new ElasticsearchException("invalid system user");
}
return SYSTEM;
}

View File

@ -25,7 +25,6 @@ import org.elasticsearch.shield.authz.AuthorizationException;
import org.elasticsearch.shield.authz.AuthorizationService;
import org.elasticsearch.shield.authz.Privilege;
import org.elasticsearch.shield.crypto.CryptoService;
import org.elasticsearch.shield.crypto.SignatureException;
import org.elasticsearch.shield.license.LicenseEventsNotifier;
import org.elasticsearch.shield.license.LicenseService;
@ -142,9 +141,9 @@ public class ShieldActionFilter extends AbstractComponent implements ActionFilte
return request;
} catch (SignatureException se) {
} catch (IllegalArgumentException|IllegalStateException e) {
auditTrail.tamperedRequest(user, action, request);
throw new AuthorizationException("invalid request: " + se.getMessage());
throw new AuthorizationException("invalid request: " + e.getMessage());
}
}

View File

@ -14,7 +14,6 @@ import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.authc.Realm;
import org.elasticsearch.shield.authc.RealmMissingException;
import org.elasticsearch.shield.authc.Realms;
import org.elasticsearch.shield.authc.support.CachingUsernamePasswordRealm;
import org.elasticsearch.threadpool.ThreadPool;
@ -73,7 +72,7 @@ public class TransportClearRealmCacheAction extends TransportNodesAction<ClearRe
for (String realmName : nodeRequest.realms) {
Realm realm = realms.realm(realmName);
if (realm == null) {
throw new RealmMissingException("could not find active realm [" + realmName + "]");
throw new IllegalArgumentException("could not find active realm [" + realmName + "]");
}
clearCache(realm, nodeRequest.usernames);
}

View File

@ -1,22 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.shield.audit;
import org.elasticsearch.shield.ShieldException;
/**
*
*/
public class AuditException extends ShieldException {
public AuditException(String msg) {
super(msg);
}
public AuditException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.shield.audit.index;
import org.elasticsearch.shield.ShieldException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Locale;
@ -55,7 +53,7 @@ public enum IndexAuditLevel {
enumSet.add(SYSTEM_ACCESS_GRANTED);
break;
default:
throw new ShieldException("invalid event name specified [" + level + "]");
throw new IllegalArgumentException("invalid event name specified [" + level + "]");
}
}
return enumSet;

View File

@ -39,7 +39,6 @@ import org.elasticsearch.env.Environment;
import org.elasticsearch.gateway.GatewayService;
import org.elasticsearch.plugins.PluginsService;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.ShieldPlugin;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.audit.AuditTrail;
@ -152,7 +151,7 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail {
String[] excludedEvents = settings.getAsArray("shield.audit.index.events.exclude");
try {
events = parse(includedEvents, excludedEvents);
} catch (ShieldException e) {
} catch (IllegalArgumentException e) {
logger.warn("invalid event type specified, using default for audit index output. include events [{}], exclude events [{}]", e, includedEvents, excludedEvents);
events = parse(DEFAULT_EVENT_INCLUDES, Strings.EMPTY_ARRAY);
}
@ -542,7 +541,7 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail {
if (currentState != State.STOPPING && currentState != State.STOPPED) {
boolean accepted = eventQueue.offer(message);
if (!accepted) {
throw new ShieldException("queue is full, bulk processor may have stopped indexing");
throw new IllegalStateException("queue is full, bulk processor may have stopped indexing");
}
}
}
@ -638,11 +637,11 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail {
assert !Thread.currentThread().isInterrupted() : "current thread has been interrupted before putting index template!!!";
PutIndexTemplateResponse response = client.admin().indices().putTemplate(request).actionGet();
if (!response.isAcknowledged()) {
throw new ShieldException("failed to put index template for audit logging");
throw new IllegalStateException("failed to put index template for audit logging");
}
} catch (Exception e) {
logger.debug("unexpected exception while putting index template", e);
throw new ShieldException("failed to load [" + INDEX_TEMPLATE_NAME + ".json]", e);
throw new IllegalStateException("failed to load [" + INDEX_TEMPLATE_NAME + ".json]", e);
}
}

View File

@ -5,24 +5,24 @@
*/
package org.elasticsearch.shield.authc;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.ShieldPlugin;
/**
*
*/
public class AuthenticationException extends ShieldException {
import java.util.Collections;
import java.util.List;
import java.util.Map;
public static final Tuple<String, String[]> BASIC_AUTH_HEADER = Tuple.tuple("WWW-Authenticate", new String[]{"Basic realm=\"" + ShieldPlugin.NAME + "\""});
public class AuthenticationException extends ElasticsearchException.WithRestHeadersException {
public static final Map<String, List<String>> HEADERS = Collections.singletonMap("WWW-Authenticate", Collections.singletonList("Basic realm=\"" + ShieldPlugin.NAME + "\""));
public AuthenticationException(String msg) {
super(msg, BASIC_AUTH_HEADER);
this(msg, null);
}
public AuthenticationException(String msg, Throwable cause) {
super(msg, cause, BASIC_AUTH_HEADER);
super(msg, cause, HEADERS);
}
@Override

View File

@ -1,24 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.shield.authc;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.shield.ShieldException;
/**
*
*/
public class RealmMissingException extends ShieldException {
public RealmMissingException(String msg) {
super(msg);
}
@Override
public RestStatus status() {
return RestStatus.NOT_FOUND;
}
}

View File

@ -12,7 +12,6 @@ import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.ShieldSettingsFilter;
import org.elasticsearch.shield.authc.esusers.ESUsersRealm;
@ -75,11 +74,11 @@ public class Realms extends AbstractLifecycleComponent<Realms> implements Iterab
Settings realmSettings = realmsSettings.getAsSettings(name);
String type = realmSettings.get("type");
if (type == null) {
throw new ShieldSettingsException("missing realm type for [" + name + "] realm");
throw new IllegalArgumentException("missing realm type for [" + name + "] realm");
}
Realm.Factory factory = factories.get(type);
if (factory == null) {
throw new ShieldSettingsException("unknown realm type [" + type + "] set for realm [" + name + "]");
throw new IllegalArgumentException("unknown realm type [" + type + "] set for realm [" + name + "]");
}
factory.filterOutSensitiveSettings(name, settingsFilter);
RealmConfig config = new RealmConfig(name, realmSettings, settings, env);
@ -93,7 +92,7 @@ public class Realms extends AbstractLifecycleComponent<Realms> implements Iterab
// this is an internal realm factory, let's make sure we didn't already registered one
// (there can only be one instance of an internal realm)
if (internalTypes.contains(type)) {
throw new ShieldSettingsException("multiple [" + type + "] realms are configured. [" + type +
throw new IllegalArgumentException("multiple [" + type + "] realms are configured. [" + type +
"] is an internal realm and therefore there can only be one such realm configured");
}
internalTypes.add(type);
@ -124,11 +123,11 @@ public class Realms extends AbstractLifecycleComponent<Realms> implements Iterab
Settings realmSettings = realmsSettings.getAsSettings(name);
String type = realmSettings.get("type");
if (type == null) {
throw new ShieldSettingsException("missing realm type for [" + name + "] realm");
throw new IllegalArgumentException("missing realm type for [" + name + "] realm");
}
if (type.equals(realmType)) {
if (result != null) {
throw new ShieldSettingsException("multiple [" + realmType + "] realms are configured. only one [" + realmType + "] may be configured");
throw new IllegalArgumentException("multiple [" + realmType + "] realms are configured. only one [" + realmType + "] may be configured");
}
result = realmSettings;
}

View File

@ -1,31 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.shield.authc.activedirectory;
import org.elasticsearch.shield.ShieldException;
/**
* ActiveDirectoryExceptions typically wrap {@link com.unboundid.ldap.sdk.LDAPException}, and have an additional
* parameter of DN attached to each message.
*/
public class ActiveDirectoryException extends ShieldException {
public ActiveDirectoryException(String msg){
super(msg);
}
public ActiveDirectoryException(String msg, Throwable cause){
super(msg, cause);
}
public ActiveDirectoryException(String msg, String dn) {
this(msg, dn, null);
}
public ActiveDirectoryException(String msg, String dn, Throwable cause) {
super( msg + "; DN=[" + dn + "]", cause);
}
}

View File

@ -12,6 +12,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.shield.authc.ldap.support.LdapSession.GroupsResolver;
@ -43,7 +44,8 @@ public class ActiveDirectoryGroupsResolver implements GroupsResolver {
try {
results = search(connection, searchRequest, logger);
} catch (LDAPException e) {
throw new ActiveDirectoryException("failed to fetch AD groups", userDn, e);
// TODO parameterize
throw new AuthenticationException("failed to fetch AD groups for DN [" + userDn + "]", e);
}
ImmutableList.Builder<String> groups = ImmutableList.builder();
@ -70,7 +72,7 @@ public class ActiveDirectoryGroupsResolver implements GroupsResolver {
}
return Filter.createORFilter(orFilters);
} catch (LDAPException e) {
throw new ActiveDirectoryException("failed to fetch AD groups", userDn, e);
throw new AuthenticationException("failed to fetch AD groups for DN [" + userDn + "]", e);
}
}

View File

@ -9,8 +9,8 @@ import com.google.common.primitives.Ints;
import com.unboundid.ldap.sdk.*;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.ShieldSettingsFilter;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.shield.authc.ldap.support.LdapSession;
@ -21,6 +21,8 @@ import org.elasticsearch.shield.ssl.ClientSSLService;
import javax.net.SocketFactory;
import java.io.IOException;
import static org.elasticsearch.shield.authc.ldap.support.LdapUtils.createFilter;
import static org.elasticsearch.shield.authc.ldap.support.LdapUtils.search;
@ -52,7 +54,7 @@ public class ActiveDirectorySessionFactory extends SessionFactory {
Settings settings = config.settings();
domainName = settings.get(AD_DOMAIN_NAME_SETTING);
if (domainName == null) {
throw new ShieldSettingsException("missing [" + AD_DOMAIN_NAME_SETTING + "] setting for active directory");
throw new IllegalArgumentException("missing [" + AD_DOMAIN_NAME_SETTING + "] setting for active directory");
}
String domainDN = buildDnFromDomain(domainName);
userSearchDN = settings.get(AD_USER_SEARCH_BASEDN_SETTING, domainDN);
@ -93,13 +95,13 @@ public class ActiveDirectorySessionFactory extends SessionFactory {
* @return An authenticated
*/
@Override
public LdapSession session(String userName, SecuredString password) {
public LdapSession session(String userName, SecuredString password) throws Exception {
LDAPConnection connection;
try {
connection = ldapServerSet.getConnection();
} catch (LDAPException e) {
throw new ActiveDirectoryException("failed to connect to any active directory servers", e);
throw new IOException("failed to connect to any active directory servers", e);
}
String userPrincipal = userName + "@" + domainName;
@ -110,15 +112,16 @@ public class ActiveDirectorySessionFactory extends SessionFactory {
SearchResult results = search(connection, searchRequest, logger);
int numResults = results.getEntryCount();
if (numResults > 1) {
throw new ActiveDirectoryException("search for user [" + userName + "] by principle name yielded multiple results");
throw new IllegalStateException("search for user [" + userName + "] by principle name yielded multiple results");
} else if (numResults < 1) {
throw new ActiveDirectoryException("search for user [" + userName + "] by principle name yielded no results");
throw new IllegalStateException("search for user [" + userName + "] by principle name yielded no results");
}
String dn = results.getSearchEntries().get(0).getDN();
return new LdapSession(connectionLogger, connection, dn, groupResolver, timeout);
} catch (LDAPException e) {
connection.close();
throw new ActiveDirectoryException("unable to authenticate user [" + userName + "] to active directory domain [" + domainName + "]", e);
// TODO think more about this exception...
throw new AuthenticationException("unable to authenticate user [" + userName + "] to active directory domain [" + domainName + "]", e);
}
}

View File

@ -12,7 +12,6 @@ import org.elasticsearch.common.inject.internal.Nullable;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.ShieldPlugin;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.support.Hasher;
@ -129,7 +128,7 @@ public class FileUserPasswdStore {
try {
lines = Files.readAllLines(path, Charsets.UTF_8);
} catch (IOException ioe) {
throw new ShieldException("could not read users file [" + path.toAbsolutePath() + "]", ioe);
throw new IllegalStateException("could not read users file [" + path.toAbsolutePath() + "]", ioe);
}
ImmutableMap.Builder<String, char[]> users = ImmutableMap.builder();

View File

@ -8,7 +8,6 @@ package org.elasticsearch.shield.authc.ldap;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.ShieldSettingsFilter;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.ldap.support.AbstractLdapRealm;
@ -56,7 +55,7 @@ public class LdapRealm extends AbstractLdapRealm {
Settings searchSettings = config.settings().getAsSettings("user_search");
if (!searchSettings.names().isEmpty()) {
if (config.settings().getAsArray(LdapSessionFactory.USER_DN_TEMPLATES_SETTING).length > 0) {
throw new ShieldSettingsException("settings were found for both user search and user template modes of operation. Please remove the settings for the\n"
throw new IllegalArgumentException("settings were found for both user search and user template modes of operation. Please remove the settings for the\n"
+ "mode you do not wish to use. For more details refer to the ldap authentication section of the Shield guide.");
}
return new LdapUserSearchSessionFactory(config, clientSSLService);

View File

@ -7,7 +7,7 @@ package org.elasticsearch.shield.authc.ldap;
import com.unboundid.ldap.sdk.*;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.ldap.support.LdapSession;
import org.elasticsearch.shield.authc.ldap.support.LdapSession.GroupsResolver;
@ -16,6 +16,7 @@ import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.ssl.ClientSSLService;
import javax.net.SocketFactory;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
@ -40,7 +41,7 @@ public class LdapSessionFactory extends SessionFactory {
Settings settings = config.settings();
userDnTemplates = settings.getAsArray(USER_DN_TEMPLATES_SETTING);
if (userDnTemplates == null) {
throw new ShieldSettingsException("missing required LDAP setting [" + USER_DN_TEMPLATES_SETTING + "]");
throw new IllegalArgumentException("missing required LDAP setting [" + USER_DN_TEMPLATES_SETTING + "]");
}
this.ldapServerSet = serverSet(config.settings(), sslService);
groupResolver = groupResolver(settings);
@ -50,7 +51,7 @@ public class LdapSessionFactory extends SessionFactory {
// Parse LDAP urls
String[] ldapUrls = settings.getAsArray(URLS_SETTING);
if (ldapUrls == null || ldapUrls.length == 0) {
throw new ShieldSettingsException("missing required LDAP setting [" + URLS_SETTING + "]");
throw new IllegalArgumentException("missing required LDAP setting [" + URLS_SETTING + "]");
}
LDAPServers servers = new LDAPServers(ldapUrls);
LDAPConnectionOptions options = connectionOptions(settings);
@ -78,13 +79,13 @@ public class LdapSessionFactory extends SessionFactory {
* @return authenticated exception
*/
@Override
public LdapSession session(String username, SecuredString password) {
public LdapSession session(String username, SecuredString password) throws Exception {
LDAPConnection connection;
try {
connection = ldapServerSet.getConnection();
} catch (LDAPException e) {
throw new ShieldLdapException("failed to connect to any LDAP servers", e);
throw new IOException("failed to connect to any LDAP servers", e);
}
LDAPException lastException = null;
@ -106,7 +107,7 @@ public class LdapSessionFactory extends SessionFactory {
}
connection.close();
throw new ShieldLdapException("failed LDAP authentication", lastException);
throw new AuthenticationException("failed LDAP authentication", lastException);
}
/**

View File

@ -7,11 +7,12 @@ package org.elasticsearch.shield.authc.ldap;
import com.google.common.primitives.Ints;
import com.unboundid.ldap.sdk.*;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.ShieldSettingsFilter;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.shield.authc.ldap.support.LdapSession;
@ -21,6 +22,7 @@ import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.ssl.ClientSSLService;
import javax.net.SocketFactory;
import java.io.IOException;
import java.util.Locale;
import static com.unboundid.ldap.sdk.Filter.createEqualityFilter;
@ -46,7 +48,7 @@ public class LdapUserSearchSessionFactory extends SessionFactory {
Settings settings = config.settings();
userSearchBaseDn = settings.get("user_search.base_dn");
if (userSearchBaseDn == null) {
throw new ShieldSettingsException("user_search base_dn must be specified");
throw new IllegalArgumentException("user_search base_dn must be specified");
}
scope = LdapSearchScope.resolve(settings.get("user_search.scope"), LdapSearchScope.SUB_TREE);
userAttribute = settings.get("user_search.attribute", DEFAULT_USERNAME_ATTRIBUTE);
@ -74,7 +76,7 @@ public class LdapUserSearchSessionFactory extends SessionFactory {
String entryDn = settings.get("user_search.pool.health_check.dn", (bindRequest == null) ? null : bindRequest.getBindDN());
if (entryDn == null) {
pool.close();
throw new ShieldSettingsException("[bind_dn] has not been specified so a value must be specified for [user_search.pool.health_check.dn] or [user_search.pool.health_check.enabled] must be set to false");
throw new IllegalArgumentException("[bind_dn] has not been specified so a value must be specified for [user_search.pool.health_check.dn] or [user_search.pool.health_check.enabled] must be set to false");
}
long healthCheckInterval = settings.getAsTime("user_search.pool.health_check.interval", DEFAULT_HEALTH_CHECK_INTERVAL).millis();
// Checks the status of the LDAP connection at a specified interval in the background. We do not check on
@ -86,7 +88,7 @@ public class LdapUserSearchSessionFactory extends SessionFactory {
}
return pool;
} catch (LDAPException e) {
throw new ShieldLdapException("unable to connect to any LDAP servers", e);
throw new ElasticsearchException("unable to connect to any LDAP servers", e);
}
}
@ -103,7 +105,7 @@ public class LdapUserSearchSessionFactory extends SessionFactory {
// Parse LDAP urls
String[] ldapUrls = settings.getAsArray(URLS_SETTING);
if (ldapUrls == null || ldapUrls.length == 0) {
throw new ShieldSettingsException("missing required LDAP setting [" + URLS_SETTING + "]");
throw new IllegalArgumentException("missing required LDAP setting [" + URLS_SETTING + "]");
}
LDAPServers servers = new LDAPServers(ldapUrls);
LDAPConnectionOptions options = connectionOptions(settings);
@ -124,34 +126,34 @@ public class LdapUserSearchSessionFactory extends SessionFactory {
}
@Override
public LdapSession session(String user, SecuredString password) {
public LdapSession session(String user, SecuredString password) throws Exception {
SearchRequest request = new SearchRequest(userSearchBaseDn, scope.scope(), createEqualityFilter(userAttribute, encodeValue(user)), Strings.EMPTY_ARRAY);
request.setTimeLimitSeconds(Ints.checkedCast(timeout.seconds()));
try {
SearchResultEntry entry = searchForEntry(connectionPool, request, logger);
if (entry == null) {
throw new ShieldLdapException("failed to find user [" + user + "] with search base [" + userSearchBaseDn + "] scope [" + scope.toString().toLowerCase(Locale.ENGLISH) +"]");
throw new AuthenticationException("failed to find user [" + user + "] with search base [" + userSearchBaseDn + "] scope [" + scope.toString().toLowerCase(Locale.ENGLISH) +"]");
}
String dn = entry.getDN();
tryBind(dn, password);
return new LdapSession(logger, connectionPool, dn, groupResolver, timeout);
} catch (LDAPException e) {
throw new ShieldLdapException("failed to authenticate user [" + user + "]", e);
throw new AuthenticationException("failed to authenticate user [" + user + "]", e);
}
}
private void tryBind(String dn, SecuredString password) {
private void tryBind(String dn, SecuredString password) throws IOException {
LDAPConnection bindConnection;
try {
bindConnection = serverSet.getConnection();
} catch (LDAPException e) {
throw new ShieldLdapException("unable to connect to any LDAP servers for bind", e);
throw new IOException("unable to connect to any LDAP servers for bind", e);
}
try {
bindConnection.bind(dn, new String(password.internalChars()));
} catch (LDAPException e) {
throw new ShieldLdapException("failed LDAP authentication", dn, e);
throw new AuthenticationException("failed LDAP authentication for DN [" + dn + "]", e);
} finally {
bindConnection.close();
}

View File

@ -11,7 +11,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.shield.authc.ldap.support.LdapSession.GroupsResolver;
@ -37,7 +37,7 @@ class SearchGroupsResolver implements GroupsResolver {
public SearchGroupsResolver(Settings settings) {
baseDn = settings.get("base_dn");
if (baseDn == null) {
throw new ShieldSettingsException("base_dn must be specified");
throw new IllegalArgumentException("base_dn must be specified");
}
filter = settings.get("filter", GROUP_SEARCH_DEFAULT_FILTER);
userAttribute = settings.get("user_attribute");
@ -57,7 +57,7 @@ class SearchGroupsResolver implements GroupsResolver {
groups.add(entry.getDN());
}
} catch (LDAPException e) {
throw new ShieldLdapException("could not search for LDAP groups", userDn, e);
throw new AuthenticationException("could not search for LDAP groups for DN [" + userDn + "]", e);
}
return groups;
@ -70,11 +70,11 @@ class SearchGroupsResolver implements GroupsResolver {
SearchResultEntry results = searchForEntry(connection, request, logger);
Attribute attribute = results.getAttribute(userAttribute);
if (attribute == null) {
throw new ShieldLdapException("no results returned for attribute [" + userAttribute + "]", userDn);
throw new AuthenticationException("no results returned for DN [" + userDn + "] attribute [" + userAttribute + "]");
}
return attribute.getValue();
} catch (LDAPException e) {
throw new ShieldLdapException("could not retrieve attribute [" + userAttribute + "]", userDn, e);
throw new AuthenticationException("could not retrieve attribute [" + userAttribute + "] for DN [" + userDn + "]", e);
}
}
}

View File

@ -1,31 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.shield.authc.ldap;
import org.elasticsearch.shield.ShieldException;
/**
* LdapExceptions typically wrap {@link com.unboundid.ldap.sdk.LDAPException}, and have an additional
* parameter of DN attached to each message.
*/
public class ShieldLdapException extends ShieldException {
public ShieldLdapException(String msg){
super(msg);
}
public ShieldLdapException(String msg, Throwable cause){
super(msg, cause);
}
public ShieldLdapException(String msg, String dn) {
this(msg, dn, null);
}
public ShieldLdapException(String msg, String dn, Throwable cause) {
super( msg + "; LDAP DN=[" + dn + "]", cause);
}
}

View File

@ -7,6 +7,7 @@ package org.elasticsearch.shield.authc.ldap;
import com.google.common.primitives.Ints;
import com.unboundid.ldap.sdk.*;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
@ -47,7 +48,7 @@ class UserAttributeGroupsResolver implements GroupsResolver {
String[] values = attributeReturned.getValues();
return Arrays.asList(values);
} catch (LDAPException e) {
throw new ShieldLdapException("could not look up group attributes for user", userDn, e);
throw new ElasticsearchException("could not look up group attributes for DN [{}]", e, userDn);
}
}
}

View File

@ -6,7 +6,6 @@
package org.elasticsearch.shield.authc.ldap.support;
import com.unboundid.ldap.sdk.SearchScope;
import org.elasticsearch.shield.authc.ldap.ShieldLdapException;
import java.util.Locale;
@ -39,7 +38,7 @@ public enum LdapSearchScope {
case "one_level" : return ONE_LEVEL;
case "sub_tree" : return SUB_TREE;
default:
throw new ShieldLdapException("Unknown search scope [" + scope + "]");
throw new IllegalArgumentException("Unknown search scope [" + scope + "]");
}
}
}

View File

@ -7,7 +7,6 @@ package org.elasticsearch.shield.authc.ldap.support;
import com.unboundid.ldap.sdk.*;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.shield.authc.ldap.ShieldLdapException;
import javax.naming.ldap.Rdn;
import java.text.MessageFormat;
@ -24,7 +23,7 @@ public final class LdapUtils {
try {
return new DN(dn);
} catch (LDAPException e) {
throw new ShieldLdapException("invalid DN [" + dn + "]", e);
throw new IllegalArgumentException("invalid DN [" + dn + "]", e);
}
}

View File

@ -14,7 +14,6 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.support.SecuredString;
@ -71,8 +70,10 @@ public abstract class SessionFactory {
*
* @param user The name of the user to authenticate the connection with.
* @param password The password of the user
* @return LdapSession representing a connection to LDAP as the provided user
* @throws Exception if an error occurred when creating the session
*/
public abstract LdapSession session(String user, SecuredString password);
public abstract LdapSession session(String user, SecuredString password) throws Exception;
protected static LDAPConnectionOptions connectionOptions(Settings settings) {
LDAPConnectionOptions options = new LDAPConnectionOptions();
@ -103,7 +104,7 @@ public abstract class SessionFactory {
addresses[i] = url.getHost();
ports[i] = url.getPort();
} catch (LDAPException e) {
throw new ShieldSettingsException("unable to parse configured LDAP url [" + urls[i] +"]", e);
throw new IllegalArgumentException("unable to parse configured LDAP url [" + urls[i] +"]", e);
}
}
}
@ -133,7 +134,7 @@ public abstract class SessionFactory {
if (!allSecure && !allClear) {
//No mixing is allowed because we use the same socketfactory
throw new ShieldSettingsException("configured LDAP protocols are not all equal " +
throw new IllegalArgumentException("configured LDAP protocols are not all equal " +
"(ldaps://.. and ldap://..): [" + Strings.arrayToCommaDelimitedString(ldapUrls) + "]");
}

View File

@ -11,7 +11,6 @@ import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.ShieldSettingsFilter;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.authc.AuthenticationToken;
@ -144,7 +143,7 @@ public class PkiRealm extends Realm<X509AuthenticationToken> {
String password = settings.get("truststore.password");
if (password == null) {
throw new ShieldSettingsException("no truststore password configured");
throw new IllegalArgumentException("no truststore password configured");
}
String trustStoreAlgorithm = settings.get("truststore.algorithm", System.getProperty("ssl.TrustManagerFactory.algorithm", TrustManagerFactory.getDefaultAlgorithm()));
@ -159,7 +158,7 @@ public class PkiRealm extends Realm<X509AuthenticationToken> {
trustFactory.init(ks);
trustManagers = trustFactory.getTrustManagers();
} catch (Exception e) {
throw new ShieldSettingsException("failed to load specified truststore", e);
throw new IllegalArgumentException("failed to load specified truststore", e);
}
List<X509TrustManager> trustManagerList = new ArrayList<>();
@ -170,7 +169,7 @@ public class PkiRealm extends Realm<X509AuthenticationToken> {
}
if (trustManagerList.isEmpty()) {
throw new ShieldSettingsException("no valid certificates found in truststore");
throw new IllegalArgumentException("no valid certificates found in truststore");
}
return trustManagerList.toArray(new X509TrustManager[trustManagerList.size()]);

View File

@ -14,7 +14,6 @@ import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldPlugin;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.watcher.FileChangesListener;
import org.elasticsearch.watcher.FileWatcher;
@ -135,7 +134,7 @@ public class DnRoleMapper {
return ImmutableMap.copyOf(dnToRoles);
} catch (IOException e) {
throw new ShieldSettingsException("could not read realm [" + realmType + "/" + realmName + "] role mappings file [" + path.toAbsolutePath() + "]", e);
throw new ElasticsearchException("could not read realm [" + realmType + "/" + realmName + "] role mappings file [" + path.toAbsolutePath() + "]", e);
}
}

View File

@ -7,8 +7,6 @@ package org.elasticsearch.shield.authc.support;
import com.google.common.base.Charsets;
import org.elasticsearch.common.Base64;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.ShieldSettingsException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@ -261,7 +259,7 @@ public enum Hasher {
public static Hasher resolve(String name) {
Hasher hasher = resolve(name, null);
if (hasher == null) {
throw new ShieldSettingsException("unknown hash function [" + name + "]");
throw new IllegalArgumentException("unknown hash function [" + name + "]");
}
return hasher;
}
@ -278,7 +276,7 @@ public enum Hasher {
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new ShieldException("unsupported digest algorithm [MD5]. Please verify you are running on Java 7 or above", e);
throw new IllegalStateException("unsupported digest algorithm [MD5]. Please verify you are running on Java 7 or above", e);
}
}
@ -288,7 +286,7 @@ public enum Hasher {
md5.reset();
return md5;
} catch (CloneNotSupportedException e) {
throw new ShieldException("could not create MD5 digest", e);
throw new IllegalStateException("could not create MD5 digest", e);
}
}
}
@ -301,7 +299,7 @@ public enum Hasher {
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new ShieldException("unsupported digest algorithm [SHA-1]", e);
throw new IllegalStateException("unsupported digest algorithm [SHA-1]", e);
}
}
@ -311,7 +309,7 @@ public enum Hasher {
sha1.reset();
return sha1;
} catch (CloneNotSupportedException e) {
throw new ShieldException("could not create SHA-1 digest", e);
throw new IllegalStateException("could not create SHA-1 digest", e);
}
}
}
@ -324,7 +322,7 @@ public enum Hasher {
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new ShieldException("unsupported digest algorithm [SHA-256]. Please verify you are running on Java 7 or above", e);
throw new IllegalStateException("unsupported digest algorithm [SHA-256]. Please verify you are running on Java 7 or above", e);
}
}
@ -334,7 +332,7 @@ public enum Hasher {
sha.reset();
return sha;
} catch (CloneNotSupportedException e) {
throw new ShieldException("could not create [SHA-256] digest", e);
throw new IllegalStateException("could not create [SHA-256] digest", e);
}
}
}

View File

@ -5,13 +5,11 @@
*/
package org.elasticsearch.shield.authz;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.shield.ShieldException;
/**
*
*/
public class AuthorizationException extends ShieldException {
// FIXME move this class to core and change package...
public class AuthorizationException extends ElasticsearchException {
public AuthorizationException(String msg) {
super(msg);

View File

@ -22,7 +22,6 @@ import org.elasticsearch.action.search.MultiSearchAction;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.suggest.SuggestAction;
import org.elasticsearch.common.Strings;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.support.AutomatonPredicate;
import org.elasticsearch.shield.support.Automatons;
@ -208,12 +207,12 @@ public abstract class Privilege<P extends Privilege<P>> {
public static void addCustom(String name, String... actionPatterns) {
for (String pattern : actionPatterns) {
if (!Index.ACTION_MATCHER.apply(pattern)) {
throw new ShieldException("cannot register custom index privilege [" + name + "]. index action must follow the 'indices:*' format");
throw new IllegalArgumentException("cannot register custom index privilege [" + name + "]. index action must follow the 'indices:*' format");
}
}
Index custom = new Index(name, actionPatterns);
if (values.contains(custom)) {
throw new ShieldException("cannot register custom index privilege [" + name + "] as it already exists.");
throw new IllegalArgumentException("cannot register custom index privilege [" + name + "] as it already exists.");
}
values.add(custom);
}
@ -316,12 +315,12 @@ public abstract class Privilege<P extends Privilege<P>> {
public static void addCustom(String name, String... actionPatterns) {
for (String pattern : actionPatterns) {
if (!Cluster.ACTION_MATCHER.apply(pattern)) {
throw new ShieldException("cannot register custom cluster privilege [" + name + "]. cluster aciton must follow the 'cluster:*' format");
throw new IllegalArgumentException("cannot register custom cluster privilege [" + name + "]. cluster aciton must follow the 'cluster:*' format");
}
}
Cluster custom = new Cluster(name, actionPatterns);
if (values.contains(custom)) {
throw new ShieldException("cannot register custom cluster privilege [" + name + "] as it already exists.");
throw new IllegalArgumentException("cannot register custom cluster privilege [" + name + "] as it already exists.");
}
values.add(custom);
}

View File

@ -12,9 +12,7 @@ import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.ShieldPlugin;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.authc.support.CharArrays;
import org.elasticsearch.watcher.FileChangesListener;
import org.elasticsearch.watcher.FileWatcher;
@ -82,15 +80,16 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
this.listeners = new CopyOnWriteArrayList<>(listeners);
this.encryptionAlgorithm = settings.get("shield.encryption.algorithm", DEFAULT_ENCRYPTION_ALGORITHM);
this.keyLength = settings.getAsInt("shield.encryption_key.length", DEFAULT_KEY_LENGTH);
if (keyLength % 8 != 0) {
throw new ShieldSettingsException("invalid key length [" + keyLength + "]. value must be a multiple of 8");
}
this.ivLength = keyLength / 8;
this.keyAlgorithm = settings.get("shield.encryption_key.algorithm", DEFAULT_KEY_ALGORITH);
}
@Override
protected void doStart() throws ElasticsearchException {
if (keyLength % 8 != 0) {
throw new IllegalArgumentException("invalid key length [" + keyLength + "]. value must be a multiple of 8");
}
keyFile = resolveSystemKey(settings, env);
systemKey = readSystemKey(keyFile);
encryptionKey = encryptionKey(systemKey, keyLength, keyAlgorithm);
@ -131,7 +130,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
byte[] bytes = Files.readAllBytes(file);
return new SecretKeySpec(bytes, KEY_ALGO);
} catch (IOException e) {
throw new ShieldException("could not read secret key", e);
throw new ElasticsearchException("could not read secret key", e);
}
}
@ -161,7 +160,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
}
if (!signedText.startsWith("$$") || signedText.length() < 2) {
throw new SignatureException("tampered signed text");
throw new IllegalArgumentException("tampered signed text");
}
String text;
@ -174,7 +173,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
text = signedText.substring(i + 2 + length);
} catch (Throwable t) {
logger.error("error occurred while parsing signed text", t);
throw new SignatureException("tampered signed text");
throw new IllegalArgumentException("tampered signed text");
}
try {
@ -184,10 +183,10 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
}
} catch (Throwable t) {
logger.error("error occurred while verifying signed text", t);
throw new SignatureException("error while verifying the signed text");
throw new IllegalStateException("error while verifying the signed text");
}
throw new SignatureException("tampered signed text");
throw new IllegalArgumentException("tampered signed text");
}
@Override
@ -243,7 +242,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
try {
bytes = Base64.decode(encrypted);
} catch (IOException e) {
throw new ShieldException("unable to decode encrypted data", e);
throw new ElasticsearchException("unable to decode encrypted data", e);
}
byte[] decrypted = decryptInternal(bytes, key);
@ -299,15 +298,15 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
System.arraycopy(iv, 0, output, 0, iv.length);
System.arraycopy(encrypted, 0, output, iv.length, encrypted.length);
return output;
} catch (BadPaddingException |IllegalBlockSizeException e) {
throw new ShieldException("error encrypting data", e);
} catch (BadPaddingException|IllegalBlockSizeException e) {
throw new ElasticsearchException("error encrypting data", e);
}
}
private byte[] decryptInternal(byte[] bytes, SecretKey key) {
if (bytes.length < ivLength) {
logger.error("received data for decryption with size [{}] that is less than IV length [{}]", bytes.length, ivLength);
throw new ShieldException("invalid data to decrypt");
throw new ElasticsearchException("invalid data to decrypt");
}
byte[] iv = new byte[ivLength];
@ -319,7 +318,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
try {
return cipher.doFinal(data);
} catch (BadPaddingException|IllegalBlockSizeException e) {
throw new ShieldException("error decrypting data", e);
throw new ElasticsearchException("error decrypting data", e);
}
}
@ -339,7 +338,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
try {
return Base64.encodeBytes(sig, 0, sig.length, Base64.URL_SAFE);
} catch (IOException e) {
throw new SignatureException("unable to encode signed data", e);
throw new IllegalArgumentException("unable to encode signed data", e);
}
}
@ -350,7 +349,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
cipher.init(mode, key, new IvParameterSpec(initializationVector));
return cipher;
} catch (Exception e) {
throw new ShieldException("error creating cipher", e);
throw new ElasticsearchException("error creating cipher", e);
}
}
@ -362,7 +361,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
try {
byte[] bytes = systemKey.getEncoded();
if ((bytes.length * 8) < keyLength) {
throw new ShieldException("at least " + keyLength +" bits should be provided as key data");
throw new IllegalArgumentException("at least " + keyLength +" bits should be provided as key data");
}
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
@ -370,13 +369,13 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
assert digest.length == (256 / 8);
if ((digest.length * 8) < keyLength) {
throw new ShieldException("requested key length is too large");
throw new IllegalArgumentException("requested key length is too large");
}
byte[] truncatedDigest = Arrays.copyOfRange(digest, 0, (keyLength / 8));
return new SecretKeySpec(truncatedDigest, algorithm);
} catch (NoSuchAlgorithmException e) {
throw new ShieldException("error getting encryption key", e);
throw new ElasticsearchException("error getting encryption key", e);
}
}

View File

@ -1,22 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.shield.crypto;
import org.elasticsearch.shield.authz.AuthorizationException;
/**
*
*/
public class SignatureException extends AuthorizationException {
public SignatureException(String msg) {
super(msg);
}
public SignatureException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@ -17,7 +17,6 @@ import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldSettingsException;
import javax.net.ssl.*;
import java.io.IOException;
@ -95,10 +94,10 @@ public abstract class AbstractSSLService extends AbstractComponent {
return sslContexts.getUnchecked(sslSettings);
} catch (UncheckedExecutionException e) {
// Unwrap ElasticsearchSSLException
if (e.getCause() instanceof ElasticsearchSSLException) {
throw (ElasticsearchSSLException) e.getCause();
if (e.getCause() instanceof ElasticsearchException) {
throw (ElasticsearchException) e.getCause();
} else {
throw new ElasticsearchSSLException("failed to load SSLContext", e);
throw new ElasticsearchException("failed to load SSLContext", e);
}
}
}
@ -132,13 +131,13 @@ public abstract class AbstractSSLService extends AbstractComponent {
} catch (ElasticsearchException e) {
throw e;
} catch (Throwable t) {
throw new ElasticsearchSSLException("failed loading cipher suites [" + Arrays.asList(ciphers) + "]", t);
throw new IllegalArgumentException("failed loading cipher suites [" + Arrays.asList(ciphers) + "]", t);
}
try {
sslEngine.setEnabledProtocols(supportedProtocols);
} catch (IllegalArgumentException e) {
throw new ElasticsearchSSLException("failed setting supported protocols [" + Arrays.asList(supportedProtocols) + "]", e);
throw new IllegalArgumentException("failed setting supported protocols [" + Arrays.asList(supportedProtocols) + "]", e);
}
return sslEngine;
}
@ -163,7 +162,7 @@ public abstract class AbstractSSLService extends AbstractComponent {
}
if (requestedCiphersList.isEmpty()) {
throw new ShieldSettingsException("none of the ciphers [" + Arrays.asList(requestedCiphers) + "] are supported by this JVM");
throw new IllegalArgumentException("none of the ciphers [" + Arrays.asList(requestedCiphers) + "] are supported by this JVM");
}
if (!unsupportedCiphers.isEmpty()) {
@ -204,7 +203,7 @@ public abstract class AbstractSSLService extends AbstractComponent {
kmf.init(ks, keyPassword.toCharArray());
return kmf.getKeyManagers();
} catch (Exception e) {
throw new ElasticsearchSSLException("failed to initialize a KeyManagerFactory", e);
throw new ElasticsearchException("failed to initialize a KeyManagerFactory", e);
}
}
@ -217,7 +216,7 @@ public abstract class AbstractSSLService extends AbstractComponent {
sslContext.getServerSessionContext().setSessionTimeout(Ints.checkedCast(sessionCacheTimeout.seconds()));
return sslContext;
} catch (Exception e) {
throw new ElasticsearchSSLException("failed to initialize the SSLContext", e);
throw new ElasticsearchException("failed to initialize the SSLContext", e);
}
}
@ -234,7 +233,7 @@ public abstract class AbstractSSLService extends AbstractComponent {
trustFactory.init(ks);
return trustFactory.getTrustManagers();
} catch (Exception e) {
throw new ElasticsearchSSLException("failed to initialize a TrustManagerFactory", e);
throw new ElasticsearchException("failed to initialize a TrustManagerFactory", e);
}
}

View File

@ -8,7 +8,6 @@ package org.elasticsearch.shield.ssl;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldSettingsException;
public class ClientSSLService extends AbstractSSLService {
@ -23,13 +22,13 @@ public class ClientSSLService extends AbstractSSLService {
if (sslSettings.keyStorePath != null) {
if (sslSettings.keyStorePassword == null) {
throw new ShieldSettingsException("no keystore password configured");
throw new IllegalArgumentException("no keystore password configured");
}
}
if (sslSettings.trustStorePath != null) {
if (sslSettings.trustStorePassword == null) {
throw new ShieldSettingsException("no truststore password configured");
throw new IllegalArgumentException("no truststore password configured");
}
}

View File

@ -1,29 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.shield.ssl;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.rest.RestStatus;
/**
*
*/
public class ElasticsearchSSLException extends ElasticsearchException {
public ElasticsearchSSLException(String msg) {
super(msg);
}
public ElasticsearchSSLException(String msg, Throwable cause) {
super(msg, cause);
}
@Override
public RestStatus status() {
return RestStatus.BAD_REQUEST;
}
}

View File

@ -8,7 +8,6 @@ package org.elasticsearch.shield.ssl;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.ShieldSettingsFilter;
public class ServerSSLService extends AbstractSSLService {
@ -27,15 +26,15 @@ public class ServerSSLService extends AbstractSSLService {
SSLSettings sslSettings = new SSLSettings(customSettings, settings);
if (sslSettings.keyStorePath == null) {
throw new ShieldSettingsException("no keystore configured");
throw new IllegalArgumentException("no keystore configured");
}
if (sslSettings.keyStorePassword == null) {
throw new ShieldSettingsException("no keystore password configured");
throw new IllegalArgumentException("no keystore password configured");
}
assert sslSettings.trustStorePath != null;
if (sslSettings.trustStorePassword == null) {
throw new ShieldSettingsException("no truststore password configured");
throw new IllegalArgumentException("no truststore password configured");
}
return sslSettings;
}

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.shield.transport;
import org.elasticsearch.shield.ssl.ElasticsearchSSLException;
import javax.net.ssl.SSLEngine;
import java.util.Locale;
@ -62,7 +60,7 @@ public enum SSLClientAuth {
case "true":
return REQUIRED;
default:
throw new ElasticsearchSSLException("could not resolve ssl client auth auth. unknown ssl client auth value [" + value + "]");
throw new IllegalArgumentException("could not resolve ssl client auth auth. unknown ssl client auth value [" + value + "]");
}
}
}

View File

@ -9,7 +9,6 @@ import com.google.common.collect.Maps;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.action.ShieldActionMapper;
import org.elasticsearch.shield.authc.AuthenticationService;
import org.elasticsearch.shield.authz.AuthorizationService;
@ -128,7 +127,7 @@ public class ShieldServerTransportService extends TransportService {
// apply the default filter to local requests. We never know what the request is or who sent it...
filter = profileFilters.get("default");
} else {
throw new ShieldException("transport profile [" + profile + "] is not associated with a transport filter");
throw new IllegalStateException("transport profile [" + profile + "] is not associated with a transport filter");
}
}
assert filter != null;

View File

@ -6,7 +6,7 @@
package org.elasticsearch.shield.transport.filter;
import com.google.common.net.InetAddresses;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.ElasticsearchException;
import org.jboss.netty.handler.ipfilter.IpFilterRule;
import org.jboss.netty.handler.ipfilter.IpSubnetFilterRule;
import org.jboss.netty.handler.ipfilter.PatternRule;
@ -99,7 +99,7 @@ public class ShieldIpFilterRule implements IpFilterRule {
try {
return new IpSubnetFilterRule(isAllowRule, value);
} catch (UnknownHostException e) {
throw new ShieldException("unable to create shield filter for rule [" + (isAllowRule ? "allow " : "deny ") + value + "]", e);
throw new ElasticsearchException("unable to create shield filter for rule [" + (isAllowRule ? "allow " : "deny ") + value + "]", e);
}
}

View File

@ -16,7 +16,6 @@ import org.elasticsearch.shield.authc.AuthenticationService;
import org.elasticsearch.shield.authz.AuthorizationException;
import org.elasticsearch.shield.authz.AuthorizationService;
import org.elasticsearch.shield.crypto.CryptoService;
import org.elasticsearch.shield.crypto.SignatureException;
import org.elasticsearch.shield.license.LicenseEventsNotifier;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Before;
@ -96,7 +95,7 @@ public class ShieldActionFilterTests extends ElasticsearchTestCase {
SearchScrollRequest request = new SearchScrollRequest("scroll_id");
ActionListener listener = mock(ActionListener.class);
ActionFilterChain chain = mock(ActionFilterChain.class);
SignatureException sigException = new SignatureException("bad bad boy");
IllegalArgumentException sigException = new IllegalArgumentException("bad bad boy");
User user = mock(User.class);
when(authcService.authenticate("_action", request, User.SYSTEM)).thenReturn(user);
when(cryptoService.signed("scroll_id")).thenReturn(true);

View File

@ -8,7 +8,6 @@ package org.elasticsearch.shield.authc;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.ShieldSettingsFilter;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.authc.esusers.ESUsersRealm;
@ -70,7 +69,7 @@ public class RealmsTests extends ElasticsearchTestCase {
}
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testWithSettings_WithMultipleInternalRealmsOfSameType() throws Exception {
Settings settings = Settings.builder()
.put("shield.authc.realms.realm_1.type", ESUsersRealm.TYPE)

View File

@ -7,9 +7,9 @@ package org.elasticsearch.shield.authc.activedirectory;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.ldap.LdapSessionFactory;
import org.elasticsearch.shield.authc.ldap.ShieldLdapException;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.shield.authc.ldap.support.LdapSession;
import org.elasticsearch.shield.authc.ldap.support.LdapTest;
@ -21,6 +21,7 @@ import org.elasticsearch.test.junit.annotations.Network;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
@ -54,7 +55,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test @SuppressWarnings("unchecked")
public void testAdAuth() {
public void testAdAuth() throws Exception {
RealmConfig config = new RealmConfig("ad-test", buildAdSettings(AD_LDAP_URL, AD_DOMAIN, false), globalSettings);
ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService);
@ -76,7 +77,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
@Test
@AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch-shield/issues/499")
public void testTcpReadTimeout() {
public void testTcpReadTimeout() throws Exception {
Settings settings = Settings.builder()
.put(buildAdSettings(AD_LDAP_URL, AD_DOMAIN, false))
.put(SessionFactory.HOSTNAME_VERIFICATION_SETTING, false)
@ -89,13 +90,13 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
// In certain cases we may have a successful bind, but a search should take longer and cause a timeout
ldap.groups();
fail("The TCP connection should timeout before getting groups back");
} catch (ActiveDirectoryException e) {
} catch (AuthenticationException e) {
assertThat(e.getCause().getMessage(), containsString("A client-side timeout was encountered while waiting"));
}
}
@Test
public void testAdAuth_avengers() {
public void testAdAuth_avengers() throws Exception {
RealmConfig config = new RealmConfig("ad-test", buildAdSettings(AD_LDAP_URL, AD_DOMAIN, false), globalSettings);
ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService);
@ -108,7 +109,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test @SuppressWarnings("unchecked")
public void testAuthenticate() {
public void testAuthenticate() throws Exception {
Settings settings = buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.ONE_LEVEL, false);
RealmConfig config = new RealmConfig("ad-test", settings, globalSettings);
ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService);
@ -129,7 +130,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test @SuppressWarnings("unchecked")
public void testAuthenticate_baseUserSearch() {
public void testAuthenticate_baseUserSearch() throws Exception {
Settings settings = buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Bruce Banner, CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.BASE, false);
RealmConfig config = new RealmConfig("ad-test", settings, globalSettings);
ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService);
@ -150,7 +151,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test @SuppressWarnings("unchecked")
public void testAuthenticate_baseGroupSearch() {
public void testAuthenticate_baseGroupSearch() throws Exception {
Settings settings = Settings.builder()
.put(buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.ONE_LEVEL, false))
.put(ActiveDirectorySessionFactory.AD_GROUP_SEARCH_BASEDN_SETTING, "CN=Avengers,CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com")
@ -168,7 +169,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test @SuppressWarnings("unchecked")
public void testAuthenticateWithUserPrincipalName() {
public void testAuthenticateWithUserPrincipalName() throws Exception {
Settings settings = buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.ONE_LEVEL, false);
RealmConfig config = new RealmConfig("ad-test", settings, globalSettings);
ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService);
@ -186,7 +187,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test
public void testAuthenticateWithSAMAccountName() {
public void testAuthenticateWithSAMAccountName() throws Exception {
Settings settings = buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.ONE_LEVEL, false);
RealmConfig config = new RealmConfig("ad-test", settings, globalSettings);
ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService);
@ -205,7 +206,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test @SuppressWarnings("unchecked")
public void testCustomUserFilter() {
public void testCustomUserFilter() throws Exception {
Settings settings = Settings.builder()
.put(buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.SUB_TREE, false))
.put(ActiveDirectorySessionFactory.AD_USER_SEARCH_FILTER_SETTING, "(&(objectclass=user)(userPrincipalName={0}@ad.test.elasticsearch.com))")
@ -225,7 +226,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
@Test @SuppressWarnings("unchecked")
public void testStandardLdapConnection(){
public void testStandardLdapConnection() throws Exception {
String groupSearchBase = "DC=ad,DC=test,DC=elasticsearch,DC=com";
String userTemplate = "CN={0},CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com";
Settings settings = LdapTest.buildLdapSettings(AD_LDAP_URL, userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE);
@ -245,7 +246,7 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test @SuppressWarnings("unchecked")
public void testStandardLdapWithAttributeGroups(){
public void testStandardLdapWithAttributeGroups() throws Exception {
String userTemplate = "CN={0},CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com";
Settings settings = LdapTest.buildLdapSettings(AD_LDAP_URL, userTemplate, false);
RealmConfig config = new RealmConfig("ad-as-ldap-test", settings, globalSettings);
@ -264,20 +265,19 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
}
@Test
public void testAdAuthWithHostnameVerification() {
public void testAdAuthWithHostnameVerification() throws Exception {
RealmConfig config = new RealmConfig("ad-test", buildAdSettings(AD_LDAP_URL, AD_DOMAIN, true), globalSettings);
ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService);
String userName = "ironman";
try (LdapSession ldap = sessionFactory.session(userName, SecuredStringTests.build(PASSWORD))) {
fail("Test active directory certificate does not have proper hostname/ip address for hostname verification");
} catch (ActiveDirectoryException e) {
} catch (IOException e) {
assertThat(e.getMessage(), containsString("failed to connect to any active directory servers"));
}
}
@Test(expected = ShieldLdapException.class)
public void testStandardLdapHostnameVerification(){
public void testStandardLdapHostnameVerification() throws Exception {
String groupSearchBase = "DC=ad,DC=test,DC=elasticsearch,DC=com";
String userTemplate = "CN={0},CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com";
Settings settings = Settings.builder()
@ -290,6 +290,8 @@ public class ActiveDirectorySessionFactoryTests extends ElasticsearchTestCase {
String user = "Bruce Banner";
try (LdapSession ldap = sessionFactory.session(user, SecuredStringTests.build(PASSWORD))) {
fail("Test active directory certificate does not have proper hostname/ip address for hostname verification");
} catch (IOException e) {
assertThat(e.getMessage(), containsString("failed to connect to any LDAP servers"));
}
}

View File

@ -12,7 +12,6 @@ import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.audit.logfile.CapturingLogger;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.support.Hasher;
@ -204,7 +203,7 @@ public class FileUserPasswdStoreTests extends ElasticsearchTestCase {
try {
FileUserPasswdStore.parseFile(file, logger);
fail("expected a parse failure");
} catch (ShieldException se) {
} catch (IllegalStateException se) {
this.logger.info("expected", se);
}
}

View File

@ -7,7 +7,6 @@ package org.elasticsearch.shield.authc.ldap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
@ -210,7 +209,7 @@ public class LdapRealmTests extends LdapTest {
try {
LdapRealm.Factory.sessionFactory(config, null);
fail("an exception should have been thrown because both user template and user search settings were specified");
} catch (ShieldSettingsException e) {
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("settings were found for both user search and user template"));
}
}

View File

@ -6,6 +6,7 @@
package org.elasticsearch.shield.authc.ldap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.shield.authc.ldap.support.LdapSession;
@ -17,6 +18,7 @@ import org.elasticsearch.test.junit.annotations.Network;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.Matchers.*;
@ -52,7 +54,7 @@ public class LdapSessionFactoryTests extends LdapTest {
try (LdapSession session = sessionFactory.session(user, userPass)) {
fail("expected connection timeout error here");
} catch (Throwable t) {
assertThat(t, instanceOf(ShieldLdapException.class));
assertThat(t, instanceOf(AuthenticationException.class));
assertThat(t.getCause().getMessage(), containsString("A client-side timeout was encountered while waiting "));
} finally {
ldapServer.setProcessingDelayMillis(0L);
@ -85,7 +87,7 @@ public class LdapSessionFactoryTests extends LdapTest {
} catch (Throwable t) {
long time = System.currentTimeMillis() - start;
assertThat(time, lessThan(10000l));
assertThat(t, instanceOf(ShieldLdapException.class));
assertThat(t, instanceOf(IOException.class));
assertThat(t.getCause().getCause().getMessage(), containsString("within the configured timeout of"));
}
}
@ -112,7 +114,7 @@ public class LdapSessionFactoryTests extends LdapTest {
}
@Test(expected = ShieldLdapException.class)
@Test(expected = AuthenticationException.class)
public void testBindWithBogusTemplates() throws Exception {
String groupSearchBase = "o=sevenSeas";
String[] userTemplates = new String[] {

View File

@ -10,7 +10,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.activedirectory.ActiveDirectorySessionFactoryTests;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
@ -100,7 +100,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTest {
try (LdapSession ldap = sessionFactory.session(user, userPass)) {
fail("the user should not have been found");
} catch (ShieldLdapException e) {
} catch (AuthenticationException e) {
assertThat(e.getMessage(), containsString("failed to find user [William Bush] with search base [o=sevenSeas] scope [base]"));
} finally {
sessionFactory.shutdown();
@ -155,7 +155,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTest {
try (LdapSession ldap = sessionFactory.session(user, userPass)) {
fail("the user should not have been found");
} catch (ShieldLdapException e) {
} catch (AuthenticationException e) {
assertThat(e.getMessage(), containsString("failed to find user [William Bush] with search base [o=sevenSeas] scope [one_level]"));
} finally {
sessionFactory.shutdown();
@ -209,7 +209,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTest {
try (LdapSession ldap = sessionFactory.session(user, userPass)) {
fail("the user should not have been found");
} catch (ShieldLdapException e) {
} catch (AuthenticationException e) {
assertThat(e.getMessage(), containsString("failed to find user [William Bush] with search base [o=sevenSeas] scope [sub_tree]"));
} finally {
sessionFactory.shutdown();
@ -242,7 +242,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTest {
}
@Test @Network
public void testUserSearchWithActiveDirectory() {
public void testUserSearchWithActiveDirectory() throws Exception {
String groupSearchBase = "DC=ad,DC=test,DC=elasticsearch,DC=com";
String userSearchBase = "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com";
Settings settings = settingsBuilder()
@ -270,7 +270,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTest {
}
@Test @Network
public void testUserSearchwithBindUserOpenLDAP() {
public void testUserSearchwithBindUserOpenLDAP() throws Exception {
String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
String userSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
RealmConfig config = new RealmConfig("oldap-test", settingsBuilder()
@ -344,7 +344,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTest {
}
@Test
public void testThatEmptyBindDNThrowsExceptionWithHealthCheckEnabled() throws Exception{
public void testThatEmptyBindDNThrowsExceptionWithHealthCheckEnabled() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
RealmConfig config = new RealmConfig("ldap_realm", settingsBuilder()
@ -355,7 +355,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTest {
try {
new LdapUserSearchSessionFactory(config, null);
} catch (ShieldSettingsException e) {
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("[bind_dn] has not been specified so a value must be specified for [user_search.pool.health_check.dn] or [user_search.pool.health_check.enabled] must be set to false"));
}
}

View File

@ -5,6 +5,7 @@
*/
package org.elasticsearch.shield.authc.ldap;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.authc.RealmConfig;
@ -19,6 +20,7 @@ import org.elasticsearch.test.junit.annotations.Network;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Path;
import static org.hamcrest.Matchers.containsString;
@ -51,7 +53,7 @@ public class OpenLdapTests extends ElasticsearchTestCase {
}
@Test
public void testConnect() {
public void testConnect() throws Exception {
//openldap does not use cn as naming attributes by default
String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
String userTemplate = "uid={0},ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
@ -67,7 +69,7 @@ public class OpenLdapTests extends ElasticsearchTestCase {
}
@Test
public void testGroupSearchScopeBase() {
public void testGroupSearchScopeBase() throws Exception {
//base search on a groups means that the user can be in just one group
String groupSearchBase = "cn=Avengers,ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
@ -84,7 +86,7 @@ public class OpenLdapTests extends ElasticsearchTestCase {
}
@Test
public void testCustomFilter() {
public void testCustomFilter() throws Exception {
String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
String userTemplate = "uid={0},ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
Settings settings = Settings.builder()
@ -102,7 +104,7 @@ public class OpenLdapTests extends ElasticsearchTestCase {
@Test
@AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch-shield/issues/499")
public void testTcpTimeout() {
public void testTcpTimeout() throws Exception {
String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
String userTemplate = "uid={0},ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
Settings settings = Settings.builder()
@ -117,13 +119,13 @@ public class OpenLdapTests extends ElasticsearchTestCase {
// In certain cases we may have a successful bind, but a search should take longer and cause a timeout
ldap.groups();
fail("The TCP connection should timeout before getting groups back");
} catch (ShieldLdapException e) {
} catch (ElasticsearchException e) {
assertThat(e.getCause().getMessage(), containsString("A client-side timeout was encountered while waiting"));
}
}
@Test
public void testStandardLdapConnectionHostnameVerification() {
public void testStandardLdapConnectionHostnameVerification() throws Exception {
//openldap does not use cn as naming attributes by default
String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
String userTemplate = "uid={0},ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com";
@ -138,7 +140,7 @@ public class OpenLdapTests extends ElasticsearchTestCase {
String user = "blackwidow";
try (LdapSession ldap = sessionFactory.session(user, SecuredStringTests.build(PASSWORD))) {
fail("OpenLDAP certificate does not contain the correct hostname/ip so hostname verification should fail on open");
} catch (ShieldLdapException e) {
} catch (IOException e) {
assertThat(e.getMessage(), containsString("failed to connect to any LDAP servers"));
}
}

View File

@ -12,7 +12,7 @@ import com.unboundid.ldap.sdk.LDAPURL;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.authc.AuthenticationException;
import org.elasticsearch.shield.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.shield.authc.ldap.support.SessionFactory;
import org.elasticsearch.shield.ssl.ClientSSLService;
@ -126,7 +126,7 @@ public class SearchGroupsResolverTests extends ElasticsearchTestCase {
try {
new SearchGroupsResolver(settings);
fail("base_dn must be specified and an exception should have been thrown");
} catch (ShieldSettingsException e) {
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("base_dn must be specified"));
}
}
@ -160,7 +160,7 @@ public class SearchGroupsResolverTests extends ElasticsearchTestCase {
try {
resolver.readUserAttribute(ldapConnection, BRUCE_BANNER_DN, TimeValue.timeValueSeconds(5), NoOpLogger.INSTANCE);
fail("searching for a non-existing attribute should throw an LdapException");
} catch (ShieldLdapException e) {
} catch (AuthenticationException e) {
assertThat(e.getMessage(), containsString("no results returned"));
}
}

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.shield.authc.ldap.support;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test;
@ -54,14 +53,14 @@ public class LDAPServersTests extends ElasticsearchTestCase {
assertThat(servers.ssl(), is(equalTo(false)));
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testConfigure_1ldaps_1ldap() {
String[] urls = new String[] { "LDAPS://primary.example.com:636", "ldap://secondary.example.com:392" };
new SessionFactory.LDAPServers(urls);
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testConfigure_1ldap_1ldaps() {
String[] urls = new String[] { "ldap://primary.example.com:392", "ldaps://secondary.example.com:636" };

View File

@ -7,7 +7,6 @@ package org.elasticsearch.shield.authc.pki;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.authc.RealmConfig;
import org.elasticsearch.shield.authc.support.DnRoleMapper;
@ -158,7 +157,7 @@ public class PkiRealmTests extends ElasticsearchTestCase {
try {
new PkiRealm(new RealmConfig("", settings, globalSettings), mock(DnRoleMapper.class));
fail("exception should have been thrown");
} catch (ShieldSettingsException e) {
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("no truststore password configured"));
}
}

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.shield.authc.support;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test;
@ -64,7 +63,7 @@ public class HasherTests extends ElasticsearchTestCase {
try {
Hasher.resolve("unknown_hasher");
fail("expected a shield setting error when trying to resolve an unknown hasher");
} catch (ShieldSettingsException sse) {
} catch (IllegalArgumentException e) {
// expected
}
Hasher hasher = randomFrom(Hasher.values());

View File

@ -11,7 +11,6 @@ import org.elasticsearch.action.get.MultiGetAction;
import org.elasticsearch.action.search.MultiSearchAction;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.suggest.SuggestAction;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.support.AutomatonPredicate;
import org.elasticsearch.shield.support.Automatons;
import org.elasticsearch.test.ElasticsearchTestCase;
@ -128,12 +127,12 @@ public class PrivilegeTests extends ElasticsearchTestCase {
assertThat(cluster.predicate().apply("cluster:bar"), is(true));
}
@Test(expected = ShieldException.class)
@Test(expected = IllegalArgumentException.class)
public void testCluster_AddCustom_InvalidPattern() throws Exception {
Privilege.Cluster.addCustom("foo", "bar");
}
@Test(expected = ShieldException.class)
@Test(expected = IllegalArgumentException.class)
public void testCluster_AddCustom_AlreadyExists() throws Exception {
Privilege.Cluster.addCustom("all", "bar");
}
@ -215,12 +214,12 @@ public class PrivilegeTests extends ElasticsearchTestCase {
assertThat(index.predicate().apply("indices:bar"), is(true));
}
@Test(expected = ShieldException.class)
@Test(expected = IllegalArgumentException.class)
public void testIndex_AddCustom_InvalidPattern() throws Exception {
Privilege.Index.addCustom("foo", "bar");
}
@Test(expected = ShieldException.class)
@Test(expected = IllegalArgumentException.class)
public void testIndex_AddCustom_AlreadyExists() throws Exception {
Privilege.Index.addCustom("all", "bar");
}

View File

@ -99,7 +99,7 @@ public class InternalCryptoServiceTests extends ElasticsearchTestCase {
try {
service.unsignAndVerify(fakeSignedText);
} catch (SignatureException e) {
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is(equalTo("tampered signed text")));
assertThat(e.getCause(), is(nullValue()));
}
@ -119,7 +119,7 @@ public class InternalCryptoServiceTests extends ElasticsearchTestCase {
try {
service.unsignAndVerify(fakeSignedText);
} catch (SignatureException e) {
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is(equalTo("tampered signed text")));
assertThat(e.getCause(), is(nullValue()));
}
@ -139,7 +139,7 @@ public class InternalCryptoServiceTests extends ElasticsearchTestCase {
try {
service.unsignAndVerify(fakeSignedText);
} catch (SignatureException e) {
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is(equalTo("tampered signed text")));
}
@ -147,7 +147,7 @@ public class InternalCryptoServiceTests extends ElasticsearchTestCase {
fakeSignedText = "$$" + randomIntBetween(length + 1, Integer.MAX_VALUE) + "$$" + fakeSignature + signed.substring(i + 2 + length);
try {
service.unsignAndVerify(fakeSignedText);
} catch (SignatureException e) {
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is(equalTo("tampered signed text")));
assertThat(e.getCause(), is(nullValue()));
}

View File

@ -8,10 +8,10 @@ package org.elasticsearch.shield.ssl;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.elasticsearch.test.junit.annotations.Network;
import org.junit.Before;
@ -37,15 +37,20 @@ public class ClientSSLServiceTests extends ElasticsearchTestCase {
env = new Environment(settingsBuilder().put("path.home", createTempDir()).build());
}
@Test(expected = ElasticsearchSSLException.class)
@Test
public void testThatInvalidProtocolThrowsException() throws Exception {
new ClientSSLService(settingsBuilder()
.put("shield.ssl.protocol", "non-existing")
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("shield.ssl.truststore.path", testclientStore)
.put("shield.ssl.truststore.password", "testclient")
.build(), env).createSSLEngine();
try {
new ClientSSLService(settingsBuilder()
.put("shield.ssl.protocol", "non-existing")
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("shield.ssl.truststore.path", testclientStore)
.put("shield.ssl.truststore.password", "testclient")
.build(), env).createSSLEngine();
fail("expected an exception");
} catch (ElasticsearchException e) {
assertThat(e.getMessage(), containsString("failed to initialize the SSLContext"));
}
}
@Test
@ -91,13 +96,18 @@ public class ClientSSLServiceTests extends ElasticsearchTestCase {
.build(), env).createSSLEngine();
}
@Test(expected = ElasticsearchSSLException.class)
@Test
public void testIncorrectKeyPasswordThrowsException() throws Exception {
Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks");
new ClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", differentPasswordsStore)
.put("shield.ssl.keystore.password", "testnode")
.build(), env).createSSLEngine();
try {
new ClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", differentPasswordsStore)
.put("shield.ssl.keystore.password", "testnode")
.build(), env).createSSLEngine();
fail("expected an exception");
} catch (ElasticsearchException e) {
assertThat(e.getMessage(), containsString("failed to initialize a KeyManagerFactory"));
}
}
@Test
@ -193,7 +203,7 @@ public class ClientSSLServiceTests extends ElasticsearchTestCase {
}
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testThatTruststorePasswordIsRequired() throws Exception {
ClientSSLService sslService = new ClientSSLService(settingsBuilder()
.put("shield.ssl.truststore.path", testclientStore)
@ -201,7 +211,7 @@ public class ClientSSLServiceTests extends ElasticsearchTestCase {
sslService.sslContext();
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testThatKeystorePasswordIsRequired() throws Exception {
ClientSSLService sslService = new ClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
@ -223,7 +233,7 @@ public class ClientSSLServiceTests extends ElasticsearchTestCase {
assertThat(Arrays.asList(enabledCiphers), not(contains("foo", "bar")));
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void invalidCiphersOnlyThrowsException() throws Exception {
ClientSSLService sslService = new ClientSSLService(settingsBuilder()
.putArray("shield.ssl.ciphers", new String[] { "foo", "bar" })

View File

@ -5,10 +5,10 @@
*/
package org.elasticsearch.shield.ssl;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldSettingsException;
import org.elasticsearch.shield.ShieldSettingsFilter;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Before;
@ -37,7 +37,7 @@ public class ServerSSLServiceTests extends ElasticsearchTestCase {
env = new Environment(settingsBuilder().put("path.home", createTempDir()).build());
}
@Test(expected = ElasticsearchSSLException.class)
@Test
public void testThatInvalidProtocolThrowsException() throws Exception {
Settings settings = settingsBuilder()
.put("shield.ssl.protocol", "non-existing")
@ -46,7 +46,12 @@ public class ServerSSLServiceTests extends ElasticsearchTestCase {
.put("shield.ssl.truststore.path", testnodeStore)
.put("shield.ssl.truststore.password", "testnode")
.build();
new ServerSSLService(settings, settingsFilter, env).createSSLEngine();
try {
new ServerSSLService(settings, settingsFilter, env).createSSLEngine();
fail("expected an exception");
} catch (ElasticsearchException e) {
assertThat(e.getMessage(), containsString("failed to initialize the SSLContext"));
}
}
@Test
@ -93,13 +98,18 @@ public class ServerSSLServiceTests extends ElasticsearchTestCase {
.build(), settingsFilter, env).createSSLEngine();
}
@Test(expected = ElasticsearchSSLException.class)
@Test
public void testIncorrectKeyPasswordThrowsException() throws Exception {
Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks");
new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", differentPasswordsStore)
.put("shield.ssl.keystore.password", "testnode")
.build(), settingsFilter, env).createSSLEngine();
try {
new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", differentPasswordsStore)
.put("shield.ssl.keystore.password", "testnode")
.build(), settingsFilter, env).createSSLEngine();
fail("expected an exception");
} catch (ElasticsearchException e) {
assertThat(e.getMessage(), containsString("failed to initialize a KeyManagerFactory"));
}
}
@Test
@ -136,13 +146,13 @@ public class ServerSSLServiceTests extends ElasticsearchTestCase {
assertThat(context.getSessionTimeout(), equalTo(600));
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testThatCreateSSLEngineWithoutAnySettingsDoesNotWork() throws Exception {
ServerSSLService sslService = new ServerSSLService(Settings.EMPTY, settingsFilter, env);
sslService.createSSLEngine();
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testThatCreateSSLEngineWithOnlyTruststoreDoesNotWork() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.truststore.path", testnodeStore)
@ -152,7 +162,7 @@ public class ServerSSLServiceTests extends ElasticsearchTestCase {
assertThat(sslEngine, notNullValue());
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testThatTruststorePasswordIsRequired() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
@ -162,7 +172,7 @@ public class ServerSSLServiceTests extends ElasticsearchTestCase {
sslService.sslContext();
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void testThatKeystorePasswordIsRequired() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
@ -186,7 +196,7 @@ public class ServerSSLServiceTests extends ElasticsearchTestCase {
assertThat(Arrays.asList(enabledCiphers), not(contains("foo", "bar")));
}
@Test(expected = ShieldSettingsException.class)
@Test(expected = IllegalArgumentException.class)
public void invalidCiphersOnlyThrowsException() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)

View File

@ -17,6 +17,6 @@ public class ShieldAssertions {
assertThat(e.status(), is(RestStatus.UNAUTHORIZED));
assertThat(e.getHeaders(), hasKey("WWW-Authenticate"));
assertThat(e.getHeaders().get("WWW-Authenticate"), hasSize(1));
assertThat(e.getHeaders().get("WWW-Authenticate").get(0), is(AuthenticationException.BASIC_AUTH_HEADER.v2()[0]));
assertThat(e.getHeaders().get("WWW-Authenticate").get(0), is(AuthenticationException.HEADERS.entrySet().iterator().next().getValue().get(0)));
}
}

View File

@ -9,7 +9,6 @@ import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.ShieldException;
import org.elasticsearch.shield.ShieldSettingsFilter;
import org.elasticsearch.shield.ssl.ServerSSLService;
import org.elasticsearch.test.ElasticsearchTestCase;
@ -196,7 +195,7 @@ public class HandshakeWaitingHandlerTests extends ElasticsearchTestCase {
randomPort = randomIntBetween(49000, 65500);
}
if (tries >= maxTries) {
throw new ShieldException("Failed to start server bootstrap [" + tries + "] times, stopping", t);
throw new RuntimeException("Failed to start server bootstrap [" + tries + "] times, stopping", t);
}
tries++;
}