Apache Solr open-source search software
SOLR-16024: Enable spotless on hadoop-auth module
Kevin Risden9669cb47f09a
diff --git a/gradle/validation/spotless.gradle b/gradle/validation/spotless.gradleindex d93e7f28656..3322a6dd378 100644--- a/gradle/validation/spotless.gradle+++ b/gradle/validation/spotless.gradle@@ -44,7 +44,6 @@ configure(project(":solr").subprojects) { prj ->// Exclude certain files (generated ones, mostly).switch (project.path) {- case ":solr:modules:hadoop-auth":case ":solr:modules:hdfs":case ":solr:modules:sql":case ":solr:core":diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/AttributeOnlyServletContext.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/AttributeOnlyServletContext.javaindex 27831c51f66..d4f10ab1ee7 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/AttributeOnlyServletContext.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/AttributeOnlyServletContext.java@@ -19,16 +19,15 @@ package org.apache.solr.security.hadoop;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;-import java.util.Collections;import java.util.Enumeration;import java.util.EventListener;import java.util.HashMap;import java.util.Map;import java.util.Set;-import javax.servlet.Filter;import javax.servlet.FilterRegistration;+import javax.servlet.FilterRegistration.Dynamic;import javax.servlet.RequestDispatcher;import javax.servlet.Servlet;import javax.servlet.ServletContext;@@ -36,12 +35,9 @@ import javax.servlet.ServletException;import javax.servlet.ServletRegistration;import javax.servlet.SessionCookieConfig;import javax.servlet.SessionTrackingMode;-import javax.servlet.FilterRegistration.Dynamic;import javax.servlet.descriptor.JspConfigDescriptor;-/**- * A concrete implementation of {@linkplain ServletContext} which support only attributes.- */+/** A concrete implementation of {@linkplain ServletContext} which support only attributes. */class AttributeOnlyServletContext implements ServletContext {private Map<String, Object> attributes = new HashMap<String, Object>();@@ -88,7 +84,7 @@ class AttributeOnlyServletContext implements ServletContext {}@Override- public Map<String,? extends ServletRegistration> getServletRegistrations() {+ public Map<String, ? extends ServletRegistration> getServletRegistrations() {return null;}@@ -178,7 +174,7 @@ class AttributeOnlyServletContext implements ServletContext {}@Override- public Map<String,? extends FilterRegistration> getFilterRegistrations() {+ public Map<String, ? extends FilterRegistration> getFilterRegistrations() {return null;}@@ -251,7 +247,8 @@ class AttributeOnlyServletContext implements ServletContext {}@Override- public javax.servlet.ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {+ public javax.servlet.ServletRegistration.Dynamic addServlet(+ String servletName, Class<? extends Servlet> servletClass) {return null;}@@ -261,7 +258,8 @@ class AttributeOnlyServletContext implements ServletContext {}@Override- public javax.servlet.ServletRegistration.Dynamic addServlet(String servletName, String className) {+ public javax.servlet.ServletRegistration.Dynamic addServlet(+ String servletName, String className) {return null;}diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/ConfigurableInternodeAuthHadoopPlugin.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/ConfigurableInternodeAuthHadoopPlugin.javaindex ca1bffb420d..35f59105012 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/ConfigurableInternodeAuthHadoopPlugin.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/ConfigurableInternodeAuthHadoopPlugin.java@@ -16,6 +16,13 @@*/package org.apache.solr.security.hadoop;+import java.io.IOException;+import java.lang.invoke.MethodHandles;+import java.net.URISyntaxException;+import java.util.Map;+import java.util.Objects;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.function.BiConsumer;import org.apache.http.HttpRequest;import org.apache.http.client.methods.HttpRequestWrapper;import org.apache.http.client.utils.URIBuilder;@@ -31,19 +38,12 @@ import org.eclipse.jetty.client.api.Request;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import java.io.IOException;-import java.lang.invoke.MethodHandles;-import java.net.URISyntaxException;-import java.util.Map;-import java.util.Objects;-import java.util.concurrent.atomic.AtomicBoolean;-import java.util.function.BiConsumer;-/**- * This class extends {@linkplain HadoopAuthPlugin} by enabling configuration of- * authentication mechanism for Solr internal communication.- **/-public class ConfigurableInternodeAuthHadoopPlugin extends HadoopAuthPlugin implements HttpClientBuilderPlugin {+ * This class extends {@linkplain HadoopAuthPlugin} by enabling configuration of authentication+ * mechanism for Solr internal communication.+ */+public class ConfigurableInternodeAuthHadoopPlugin extends HadoopAuthPlugin+ implements HttpClientBuilderPlugin {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());/**@@ -64,9 +64,15 @@ public class ConfigurableInternodeAuthHadoopPlugin extends HadoopAuthPlugin implpublic void init(Map<String, Object> pluginConfig) {super.init(pluginConfig);- String httpClientBuilderFactory = (String) Objects.requireNonNull(pluginConfig.get(HTTPCLIENT_BUILDER_FACTORY),- "Please specify clientBuilderFactory to be used for Solr internal communication.");- factory = this.coreContainer.getResourceLoader().newInstance(httpClientBuilderFactory, HttpClientBuilderFactory.class);+ String httpClientBuilderFactory =+ (String)+ Objects.requireNonNull(+ pluginConfig.get(HTTPCLIENT_BUILDER_FACTORY),+ "Please specify clientBuilderFactory to be used for Solr internal communication.");+ factory =+ this.coreContainer+ .getResourceLoader()+ .newInstance(httpClientBuilderFactory, HttpClientBuilderFactory.class);}@Override@@ -90,22 +96,24 @@ public class ConfigurableInternodeAuthHadoopPlugin extends HadoopAuthPlugin impl@Overridepublic boolean interceptInternodeRequest(HttpRequest httpRequest, HttpContext httpContext) {- if (! (httpRequest instanceof HttpRequestWrapper)) {+ if (!(httpRequest instanceof HttpRequestWrapper)) {log.warn("Unable to add doAs to forwarded/distributed request - unknown request type");return false;}AtomicBoolean success = new AtomicBoolean(false);- return intercept((key, value) -> {- HttpRequestWrapper request = (HttpRequestWrapper) httpRequest;- URIBuilder uriBuilder = new URIBuilder(request.getURI());- uriBuilder.setParameter(key, value);- try {- request.setURI(uriBuilder.build());- success.set(true);- } catch (URISyntaxException e) {- log.warn("Unable to add doAs to forwarded/distributed request - bad URI");- }- }) && success.get();+ return intercept(+ (key, value) -> {+ HttpRequestWrapper request = (HttpRequestWrapper) httpRequest;+ URIBuilder uriBuilder = new URIBuilder(request.getURI());+ uriBuilder.setParameter(key, value);+ try {+ request.setURI(uriBuilder.build());+ success.set(true);+ } catch (URISyntaxException e) {+ log.warn("Unable to add doAs to forwarded/distributed request - bad URI");+ }+ })+ && success.get();}@Override@@ -115,8 +123,9 @@ public class ConfigurableInternodeAuthHadoopPlugin extends HadoopAuthPlugin implprivate boolean intercept(BiConsumer<String, String> setParam) {SolrRequestInfo info = SolrRequestInfo.getRequestInfo();- if (info != null && (info.getAction() == SolrDispatchFilter.Action.FORWARD ||- info.getAction() == SolrDispatchFilter.Action.REMOTEQUERY)) {+ if (info != null+ && (info.getAction() == SolrDispatchFilter.Action.FORWARD+ || info.getAction() == SolrDispatchFilter.Action.REMOTEQUERY)) {if (info.getUserPrincipal() != null) {String name = info.getUserPrincipal().getName();log.debug("Setting doAs={} to forwarded/remote request", name);diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/DelegationTokenKerberosFilter.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/DelegationTokenKerberosFilter.javaindex 2ca03f26544..d6f2bf931dc 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/DelegationTokenKerberosFilter.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/DelegationTokenKerberosFilter.java@@ -20,21 +20,18 @@ import java.io.IOException;import java.util.Enumeration;import java.util.LinkedList;import java.util.List;-import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;-import org.apache.curator.RetryPolicy;import org.apache.curator.framework.AuthInfo;import org.apache.curator.framework.CuratorFramework;import org.apache.curator.framework.CuratorFrameworkFactory;import org.apache.curator.framework.api.ACLProvider;import org.apache.curator.retry.ExponentialBackoffRetry;-import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.security.UserGroupInformation;import org.apache.hadoop.security.authentication.server.AuthenticationHandler;@@ -50,8 +47,8 @@ import org.apache.zookeeper.data.ACL;/*** This is an authentication filter based on Hadoop's {@link DelegationTokenAuthenticationFilter}.- * The Kerberos plugin can be configured to use delegation tokens, which allow an- * application to reuse the authentication of an end-user or another application.+ * The Kerberos plugin can be configured to use delegation tokens, which allow an application to+ * reuse the authentication of an end-user or another application.*/public class DelegationTokenKerberosFilter extends DelegationTokenAuthenticationFilter {private CuratorFramework curatorFramework;@@ -60,10 +57,12 @@ public class DelegationTokenKerberosFilter extends DelegationTokenAuthenticationpublic void init(FilterConfig conf) throws ServletException {if (conf != null && "zookeeper".equals(conf.getInitParameter("signer.secret.provider"))) {SolrZkClient zkClient =- (SolrZkClient)conf.getServletContext().getAttribute(KerberosPlugin.DELEGATION_TOKEN_ZK_CLIENT);+ (SolrZkClient)+ conf.getServletContext().getAttribute(KerberosPlugin.DELEGATION_TOKEN_ZK_CLIENT);try {- conf.getServletContext().setAttribute("signer.secret.provider.zookeeper.curator.client",- getCuratorClient(zkClient));+ conf.getServletContext()+ .setAttribute(+ "signer.secret.provider.zookeeper.curator.client", getCuratorClient(zkClient));} catch (InterruptedException | KeeperException e) {throw new ServletException(e);}@@ -72,7 +71,7 @@ public class DelegationTokenKerberosFilter extends DelegationTokenAuthentication}/**- * Return the ProxyUser Configuration. FilterConfig properties beginning with+ * Return the ProxyUser Configuration. FilterConfig properties beginning with* "solr.impersonator.user.name" will be added to the configuration.*/@Override@@ -84,7 +83,9 @@ public class DelegationTokenKerberosFilter extends DelegationTokenAuthenticationString name = names.nextElement();if (name.startsWith(KerberosPlugin.IMPERSONATOR_PREFIX)) {String value = filterConf.getInitParameter(name);- conf.set(PROXYUSER_PREFIX + "." + name.substring(KerberosPlugin.IMPERSONATOR_PREFIX.length()), value);+ conf.set(+ PROXYUSER_PREFIX + "." + name.substring(KerberosPlugin.IMPERSONATOR_PREFIX.length()),+ value);conf.set(name, value);}}@@ -92,25 +93,29 @@ public class DelegationTokenKerberosFilter extends DelegationTokenAuthentication}@Override- public void doFilter(ServletRequest request, ServletResponse response,- FilterChain filterChain) throws IOException, ServletException {+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)+ throws IOException, ServletException {// include Impersonator User Name in case someone (e.g. logger) wants it- FilterChain filterChainWrapper = new FilterChain() {- @Override- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)- throws IOException, ServletException {- HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;-- UserGroupInformation ugi = HttpUserGroupInformation.get();- if (ugi != null && ugi.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY) {- UserGroupInformation realUserUgi = ugi.getRealUser();- if (realUserUgi != null) {- httpRequest.setAttribute(KerberosPlugin.IMPERSONATOR_USER_NAME, realUserUgi.getShortUserName());+ FilterChain filterChainWrapper =+ new FilterChain() {+ @Override+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)+ throws IOException, ServletException {+ HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;++ UserGroupInformation ugi = HttpUserGroupInformation.get();+ if (ugi != null+ && ugi.getAuthenticationMethod()+ == UserGroupInformation.AuthenticationMethod.PROXY) {+ UserGroupInformation realUserUgi = ugi.getRealUser();+ if (realUserUgi != null) {+ httpRequest.setAttribute(+ KerberosPlugin.IMPERSONATOR_USER_NAME, realUserUgi.getShortUserName());+ }+ }+ filterChain.doFilter(servletRequest, servletResponse);}- }- filterChain.doFilter(servletRequest, servletResponse);- }- };+ };super.doFilter(request, response, filterChainWrapper);}@@ -123,55 +128,60 @@ public class DelegationTokenKerberosFilter extends DelegationTokenAuthentication}@Override- protected void initializeAuthHandler(String authHandlerClassName,- FilterConfig filterConfig) throws ServletException {- // set the internal authentication handler in order to record whether the request should continue+ protected void initializeAuthHandler(String authHandlerClassName, FilterConfig filterConfig)+ throws ServletException {+ // set the internal authentication handler in order to record whether the request should+ // continuesuper.initializeAuthHandler(authHandlerClassName, filterConfig);AuthenticationHandler authHandler = getAuthenticationHandler();- super.initializeAuthHandler(RequestContinuesRecorderAuthenticationHandler.class.getName(), filterConfig);+ super.initializeAuthHandler(+ RequestContinuesRecorderAuthenticationHandler.class.getName(), filterConfig);RequestContinuesRecorderAuthenticationHandler newAuthHandler =- (RequestContinuesRecorderAuthenticationHandler)getAuthenticationHandler();+ (RequestContinuesRecorderAuthenticationHandler) getAuthenticationHandler();newAuthHandler.setAuthHandler(authHandler);}- protected CuratorFramework getCuratorClient(SolrZkClient zkClient) throws InterruptedException, KeeperException {+ protected CuratorFramework getCuratorClient(SolrZkClient zkClient)+ throws InterruptedException, KeeperException {// should we try to build a RetryPolicy off of the ZkController?RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);if (zkClient == null) {throw new IllegalArgumentException("zkClient required");}String zkHost = zkClient.getZkServerAddress();- String zkChroot = zkHost.contains("/")? zkHost.substring(zkHost.indexOf("/")): "";+ String zkChroot = zkHost.contains("/") ? zkHost.substring(zkHost.indexOf("/")) : "";String zkNamespace = zkChroot + SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH;zkNamespace = zkNamespace.startsWith("/") ? zkNamespace.substring(1) : zkNamespace;- String zkConnectionString = zkHost.contains("/")? zkHost.substring(0, zkHost.indexOf("/")): zkHost;+ String zkConnectionString =+ zkHost.contains("/") ? zkHost.substring(0, zkHost.indexOf("/")) : zkHost;SolrZkToCuratorCredentialsACLs curatorToSolrZk = new SolrZkToCuratorCredentialsACLs(zkClient);final int connectionTimeoutMs = 30000; // this value is currently hard coded, see SOLR-7561.- // Create /security znode upfront. Without this, the curator framework creates this directory path+ // Create /security znode upfront. Without this, the curator framework creates this directory+ // path// without the appropriate ACL configuration. This issue is possibly related to HADOOP-11973try {- zkClient.makePath(SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH, CreateMode.PERSISTENT, true);+ zkClient.makePath(+ SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH, CreateMode.PERSISTENT, true);} catch (KeeperException.NodeExistsException ex) {// ignore?}- curatorFramework = CuratorFrameworkFactory.builder()- .namespace(zkNamespace)- .connectString(zkConnectionString)- .retryPolicy(retryPolicy)- .aclProvider(curatorToSolrZk.getACLProvider())- .authorization(curatorToSolrZk.getAuthInfos())- .sessionTimeoutMs(zkClient.getZkClientTimeout())- .connectionTimeoutMs(connectionTimeoutMs)- .build();+ curatorFramework =+ CuratorFrameworkFactory.builder()+ .namespace(zkNamespace)+ .connectString(zkConnectionString)+ .retryPolicy(retryPolicy)+ .aclProvider(curatorToSolrZk.getACLProvider())+ .authorization(curatorToSolrZk.getAuthInfos())+ .sessionTimeoutMs(zkClient.getZkClientTimeout())+ .connectionTimeoutMs(connectionTimeoutMs)+ .build();curatorFramework.start();return curatorFramework;}- /**- * Convert Solr Zk Credentials/ACLs to Curator versions- */+ /** Convert Solr Zk Credentials/ACLs to Curator versions */protected static class SolrZkToCuratorCredentialsACLs {private final String zkChroot;private final ACLProvider aclProvider;@@ -181,11 +191,16 @@ public class DelegationTokenKerberosFilter extends DelegationTokenAuthenticationthis.aclProvider = createACLProvider(zkClient);this.authInfos = createAuthInfo(zkClient);String zkHost = zkClient.getZkServerAddress();- this.zkChroot = zkHost.contains("/")? zkHost.substring(zkHost.indexOf("/")): null;+ this.zkChroot = zkHost.contains("/") ? zkHost.substring(zkHost.indexOf("/")) : null;}- public ACLProvider getACLProvider() { return aclProvider; }- public List<AuthInfo> getAuthInfos() { return authInfos; }+ public ACLProvider getACLProvider() {+ return aclProvider;+ }++ public List<AuthInfo> getAuthInfos() {+ return authInfos;+ }private ACLProvider createACLProvider(SolrZkClient zkClient) {final ZkACLProvider zkACLProvider = zkClient.getZkACLProvider();@@ -220,8 +235,9 @@ public class DelegationTokenKerberosFilter extends DelegationTokenAuthentication// In theory the credentials to add could change here if zookeeper hasn't been initializedZkCredentialsProvider credentialsProvider =- zkClient.getZkClientConnectionStrategy().getZkCredentialsToAddAutomatically();- for (ZkCredentialsProvider.ZkCredentials zkCredentials : credentialsProvider.getCredentials()) {+ zkClient.getZkClientConnectionStrategy().getZkCredentialsToAddAutomatically();+ for (ZkCredentialsProvider.ZkCredentials zkCredentials :+ credentialsProvider.getCredentials()) {ret.add(new AuthInfo(zkCredentials.getScheme(), zkCredentials.getAuth()));}return ret;diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/HadoopAuthFilter.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/HadoopAuthFilter.javaindex 779bbafa71c..74bf5f98c11 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/HadoopAuthFilter.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/HadoopAuthFilter.java@@ -19,21 +19,18 @@ package org.apache.solr.security.hadoop;import java.io.IOException;import java.util.LinkedList;import java.util.List;-import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;-import org.apache.curator.RetryPolicy;import org.apache.curator.framework.AuthInfo;import org.apache.curator.framework.CuratorFramework;import org.apache.curator.framework.CuratorFrameworkFactory;import org.apache.curator.framework.api.ACLProvider;import org.apache.curator.retry.ExponentialBackoffRetry;-import org.apache.hadoop.security.UserGroupInformation;import org.apache.hadoop.security.authentication.server.AuthenticationHandler;import org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticationFilter;@@ -51,8 +48,8 @@ import org.apache.zookeeper.data.ACL;*/public class HadoopAuthFilter extends DelegationTokenAuthenticationFilter {/**- * This property defines the configuration parameter storing the Solr zookeeper client ref- * in the servlet filter config.+ * This property defines the configuration parameter storing the Solr zookeeper client ref in the+ * servlet filter config.*/static final String DELEGATION_TOKEN_ZK_CLIENT = "solr.kerberos.delegation.token.zk.client";@@ -62,10 +59,11 @@ public class HadoopAuthFilter extends DelegationTokenAuthenticationFilter {public void init(FilterConfig conf) throws ServletException {if (conf != null && "zookeeper".equals(conf.getInitParameter("signer.secret.provider"))) {SolrZkClient zkClient =- (SolrZkClient)conf.getServletContext().getAttribute(DELEGATION_TOKEN_ZK_CLIENT);+ (SolrZkClient) conf.getServletContext().getAttribute(DELEGATION_TOKEN_ZK_CLIENT);try {- conf.getServletContext().setAttribute("signer.secret.provider.zookeeper.curator.client",- getCuratorClient(zkClient));+ conf.getServletContext()+ .setAttribute(+ "signer.secret.provider.zookeeper.curator.client", getCuratorClient(zkClient));} catch (KeeperException | InterruptedException e) {throw new ServletException(e);}@@ -74,25 +72,29 @@ public class HadoopAuthFilter extends DelegationTokenAuthenticationFilter {}@Override- public void doFilter(ServletRequest request, ServletResponse response,- FilterChain filterChain) throws IOException, ServletException {+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)+ throws IOException, ServletException {// include Impersonator User Name in case someone (e.g. logger) wants it- FilterChain filterChainWrapper = new FilterChain() {- @Override- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)- throws IOException, ServletException {- HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;-- UserGroupInformation ugi = HttpUserGroupInformation.get();- if (ugi != null && ugi.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY) {- UserGroupInformation realUserUgi = ugi.getRealUser();- if (realUserUgi != null) {- httpRequest.setAttribute(KerberosPlugin.IMPERSONATOR_USER_NAME, realUserUgi.getShortUserName());+ FilterChain filterChainWrapper =+ new FilterChain() {+ @Override+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)+ throws IOException, ServletException {+ HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;++ UserGroupInformation ugi = HttpUserGroupInformation.get();+ if (ugi != null+ && ugi.getAuthenticationMethod()+ == UserGroupInformation.AuthenticationMethod.PROXY) {+ UserGroupInformation realUserUgi = ugi.getRealUser();+ if (realUserUgi != null) {+ httpRequest.setAttribute(+ KerberosPlugin.IMPERSONATOR_USER_NAME, realUserUgi.getShortUserName());+ }+ }+ filterChain.doFilter(servletRequest, servletResponse);}- }- filterChain.doFilter(servletRequest, servletResponse);- }- };+ };super.doFilter(request, response, filterChainWrapper);}@@ -107,35 +109,41 @@ public class HadoopAuthFilter extends DelegationTokenAuthenticationFilter {}@Override- protected void initializeAuthHandler(String authHandlerClassName,- FilterConfig filterConfig) throws ServletException {- // set the internal authentication handler in order to record whether the request should continue+ protected void initializeAuthHandler(String authHandlerClassName, FilterConfig filterConfig)+ throws ServletException {+ // set the internal authentication handler in order to record whether the request should+ // continuesuper.initializeAuthHandler(authHandlerClassName, filterConfig);AuthenticationHandler authHandler = getAuthenticationHandler();- super.initializeAuthHandler(RequestContinuesRecorderAuthenticationHandler.class.getName(), filterConfig);+ super.initializeAuthHandler(+ RequestContinuesRecorderAuthenticationHandler.class.getName(), filterConfig);RequestContinuesRecorderAuthenticationHandler newAuthHandler =- (RequestContinuesRecorderAuthenticationHandler)getAuthenticationHandler();+ (RequestContinuesRecorderAuthenticationHandler) getAuthenticationHandler();newAuthHandler.setAuthHandler(authHandler);}- protected CuratorFramework getCuratorClient(SolrZkClient zkClient) throws KeeperException, InterruptedException {+ protected CuratorFramework getCuratorClient(SolrZkClient zkClient)+ throws KeeperException, InterruptedException {// should we try to build a RetryPolicy off of the ZkController?RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);if (zkClient == null) {throw new IllegalArgumentException("zkClient required");}String zkHost = zkClient.getZkServerAddress();- String zkChroot = zkHost.contains("/")? zkHost.substring(zkHost.indexOf("/")): "";+ String zkChroot = zkHost.contains("/") ? zkHost.substring(zkHost.indexOf("/")) : "";String zkNamespace = zkChroot + SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH;zkNamespace = zkNamespace.startsWith("/") ? zkNamespace.substring(1) : zkNamespace;- String zkConnectionString = zkHost.contains("/")? zkHost.substring(0, zkHost.indexOf("/")): zkHost;+ String zkConnectionString =+ zkHost.contains("/") ? zkHost.substring(0, zkHost.indexOf("/")) : zkHost;SolrZkToCuratorCredentialsACLs curatorToSolrZk = new SolrZkToCuratorCredentialsACLs(zkClient);final int connectionTimeoutMs = 30000; // this value is currently hard coded, see SOLR-7561.- // Create /security znode upfront. Without this, the curator framework creates this directory path+ // Create /security znode upfront. Without this, the curator framework creates this directory+ // path// without the appropriate ACL configuration. This issue is possibly related to HADOOP-11973try {- zkClient.makePath(SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH, CreateMode.PERSISTENT, true);+ zkClient.makePath(+ SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH, CreateMode.PERSISTENT, true);} catch (KeeperException ex) {if (ex.code() != KeeperException.Code.NODEEXISTS) {@@ -143,22 +151,21 @@ public class HadoopAuthFilter extends DelegationTokenAuthenticationFilter {}}- curatorFramework = CuratorFrameworkFactory.builder()- .namespace(zkNamespace)- .connectString(zkConnectionString)- .retryPolicy(retryPolicy)- .aclProvider(curatorToSolrZk.getACLProvider())- .authorization(curatorToSolrZk.getAuthInfos())- .sessionTimeoutMs(zkClient.getZkClientTimeout())- .connectionTimeoutMs(connectionTimeoutMs)- .build();+ curatorFramework =+ CuratorFrameworkFactory.builder()+ .namespace(zkNamespace)+ .connectString(zkConnectionString)+ .retryPolicy(retryPolicy)+ .aclProvider(curatorToSolrZk.getACLProvider())+ .authorization(curatorToSolrZk.getAuthInfos())+ .sessionTimeoutMs(zkClient.getZkClientTimeout())+ .connectionTimeoutMs(connectionTimeoutMs)+ .build();curatorFramework.start();return curatorFramework;}- /**- * Convert Solr Zk Credentials/ACLs to Curator versions- */+ /** Convert Solr Zk Credentials/ACLs to Curator versions */protected static class SolrZkToCuratorCredentialsACLs {private final String zkChroot;private final ACLProvider aclProvider;@@ -168,11 +175,16 @@ public class HadoopAuthFilter extends DelegationTokenAuthenticationFilter {this.aclProvider = createACLProvider(zkClient);this.authInfos = createAuthInfo(zkClient);String zkHost = zkClient.getZkServerAddress();- this.zkChroot = zkHost.contains("/")? zkHost.substring(zkHost.indexOf("/")): null;+ this.zkChroot = zkHost.contains("/") ? zkHost.substring(zkHost.indexOf("/")) : null;}- public ACLProvider getACLProvider() { return aclProvider; }- public List<AuthInfo> getAuthInfos() { return authInfos; }+ public ACLProvider getACLProvider() {+ return aclProvider;+ }++ public List<AuthInfo> getAuthInfos() {+ return authInfos;+ }private ACLProvider createACLProvider(SolrZkClient zkClient) {final ZkACLProvider zkACLProvider = zkClient.getZkACLProvider();@@ -207,8 +219,9 @@ public class HadoopAuthFilter extends DelegationTokenAuthenticationFilter {// In theory the credentials to add could change here if zookeeper hasn't been initializedZkCredentialsProvider credentialsProvider =- zkClient.getZkClientConnectionStrategy().getZkCredentialsToAddAutomatically();- for (ZkCredentialsProvider.ZkCredentials zkCredentials : credentialsProvider.getCredentials()) {+ zkClient.getZkClientConnectionStrategy().getZkCredentialsToAddAutomatically();+ for (ZkCredentialsProvider.ZkCredentials zkCredentials :+ credentialsProvider.getCredentials()) {ret.add(new AuthInfo(zkCredentials.getScheme(), zkCredentials.getAuth()));}return ret;diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/HadoopAuthPlugin.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/HadoopAuthPlugin.javaindex bb50424f447..3e9d904d6f9 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/HadoopAuthPlugin.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/HadoopAuthPlugin.java@@ -16,9 +16,10 @@*/package org.apache.solr.security.hadoop;-import static org.apache.solr.security.hadoop.RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR;import static org.apache.solr.security.hadoop.HadoopAuthFilter.DELEGATION_TOKEN_ZK_CLIENT;+import static org.apache.solr.security.hadoop.RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR;+import com.fasterxml.jackson.core.JsonGenerator;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.util.Collection;@@ -33,8 +34,6 @@ import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;--import com.fasterxml.jackson.core.JsonGenerator;import org.apache.hadoop.security.authentication.server.AuthenticationFilter;import org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticationHandler;import org.apache.solr.client.solrj.impl.Krb5HttpClientBuilder;@@ -47,37 +46,34 @@ import org.slf4j.Logger;import org.slf4j.LoggerFactory;/**- * This class implements a generic plugin which can use authentication schemes exposed by the- * Hadoop framework. This plugin supports following features- * - integration with authentication mechanisms (e.g. kerberos)- * - Delegation token support- * - Proxy users (or secure impersonation) support+ * This class implements a generic plugin which can use authentication schemes exposed by the Hadoop+ * framework. This plugin supports following features - integration with authentication mechanisms+ * (e.g. kerberos) - Delegation token support - Proxy users (or secure impersonation) support*- * This plugin enables defining configuration parameters required by the underlying Hadoop authentication- * mechanism. These configuration parameters can either be specified as a Java system property or the default- * value can be specified as part of the plugin configuration.+ * <p>This plugin enables defining configuration parameters required by the underlying Hadoop+ * authentication mechanism. These configuration parameters can either be specified as a Java system+ * property or the default value can be specified as part of the plugin configuration.*- * The proxy users are configured by specifying relevant Hadoop configuration parameters. Please note that- * the delegation token support must be enabled for using the proxy users support.+ * <p>The proxy users are configured by specifying relevant Hadoop configuration parameters. Please+ * note that the delegation token support must be enabled for using the proxy users support.*- * Note - this class does not support configuring authentication mechanism for Solr internal communication.- * For this purpose {@linkplain ConfigurableInternodeAuthHadoopPlugin} should be used. If this plugin is used in the- * SolrCloud mode, it will use PKI based authentication mechanism for Solr internal communication.- **/+ * <p>Note - this class does not support configuring authentication mechanism for Solr internal+ * communication. For this purpose {@linkplain ConfigurableInternodeAuthHadoopPlugin} should be+ * used. If this plugin is used in the SolrCloud mode, it will use PKI based authentication+ * mechanism for Solr internal communication.+ */public class HadoopAuthPlugin extends AuthenticationPlugin {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- /**- * A property specifying the type of authentication scheme to be configured.- */+ /** A property specifying the type of authentication scheme to be configured. */private static final String HADOOP_AUTH_TYPE = "type";/**- * A property specifies the value of the prefix to be used to define Java system property- * for configuring the authentication mechanism. The name of the Java system property is- * defined by appending the configuration parmeter namne to this prefix value e.g. if prefix- * is 'solr' then the Java system property 'solr.kerberos.principal' defines the value of- * configuration parameter 'kerberos.principal'.+ * A property specifies the value of the prefix to be used to define Java system property for+ * configuring the authentication mechanism. The name of the Java system property is defined by+ * appending the configuration parmeter namne to this prefix value e.g. if prefix is 'solr' then+ * the Java system property 'solr.kerberos.principal' defines the value of configuration parameter+ * 'kerberos.principal'.*/private static final String SYSPROP_PREFIX_PROPERTY = "sysPropPrefix";@@ -94,25 +90,22 @@ public class HadoopAuthPlugin extends AuthenticationPlugin {*/private static final String DEFAULT_AUTH_CONFIGS_PROPERTY = "defaultConfigs";- /**- * A property which enable (or disable) the delegation tokens functionality.- */+ /** A property which enable (or disable) the delegation tokens functionality. */private static final String DELEGATION_TOKEN_ENABLED_PROPERTY = "enableDelegationToken";- /**- * A property which enables initialization of kerberos before connecting to Zookeeper.- */+ /** A property which enables initialization of kerberos before connecting to Zookeeper. */private static final String INIT_KERBEROS_ZK = "initKerberosZk";/*** A property which configures proxy users for the underlying Hadoop authentication mechanism.- * This configuration is expressed as a collection of key-value pairs (i.e. property-name : value).+ * This configuration is expressed as a collection of key-value pairs (i.e. property-name :+ * value).*/public static final String PROXY_USER_CONFIGS = "proxyUserConfigs";/**- * This parameter is used to debug the authentication related issues during development.- * This should not be used in production.+ * This parameter is used to debug the authentication related issues during development. This+ * should not be used in production.*/private static final boolean TRACE_HTTP = Boolean.getBoolean("hadoopauth.tracehttp");@@ -125,13 +118,15 @@ public class HadoopAuthPlugin extends AuthenticationPlugin {}@Override- public void init(Map<String,Object> pluginConfig) {+ public void init(Map<String, Object> pluginConfig) {try {- delegationTokenEnabled = Boolean.parseBoolean((String) pluginConfig.get(DELEGATION_TOKEN_ENABLED_PROPERTY));+ delegationTokenEnabled =+ Boolean.parseBoolean((String) pluginConfig.get(DELEGATION_TOKEN_ENABLED_PROPERTY));authFilter = delegationTokenEnabled ? new HadoopAuthFilter() : new AuthenticationFilter();// Initialize kerberos before initializing curator instance.- boolean initKerberosZk = Boolean.parseBoolean((String)pluginConfig.getOrDefault(INIT_KERBEROS_ZK, "false"));+ boolean initKerberosZk =+ Boolean.parseBoolean((String) pluginConfig.getOrDefault(INIT_KERBEROS_ZK, "false"));if (initKerberosZk) {(new Krb5HttpClientBuilder()).getBuilder();}@@ -141,7 +136,8 @@ public class HadoopAuthPlugin extends AuthenticationPlugin {} catch (ServletException e) {log.error("Error initializing {}", getClass().getSimpleName(), e);- throw new SolrException(ErrorCode.SERVER_ERROR, "Error initializing " + getClass().getName() + ": "+e);+ throw new SolrException(+ ErrorCode.SERVER_ERROR, "Error initializing " + getClass().getName() + ": " + e);}}@@ -153,14 +149,16 @@ public class HadoopAuthPlugin extends AuthenticationPlugin {params.put(HADOOP_AUTH_TYPE, type);String sysPropPrefix = (String) pluginConfig.getOrDefault(SYSPROP_PREFIX_PROPERTY, "solr.");- Collection<String> authConfigNames = (Collection<String>) pluginConfig.- getOrDefault(AUTH_CONFIG_NAMES_PROPERTY, Collections.emptyList());- Map<String,String> authConfigDefaults = (Map<String,String>) pluginConfig- .getOrDefault(DEFAULT_AUTH_CONFIGS_PROPERTY, Collections.emptyMap());- Map<String,String> proxyUserConfigs = (Map<String,String>) pluginConfig- .getOrDefault(PROXY_USER_CONFIGS, Collections.emptyMap());-- for ( String configName : authConfigNames) {+ Collection<String> authConfigNames =+ (Collection<String>)+ pluginConfig.getOrDefault(AUTH_CONFIG_NAMES_PROPERTY, Collections.emptyList());+ Map<String, String> authConfigDefaults =+ (Map<String, String>)+ pluginConfig.getOrDefault(DEFAULT_AUTH_CONFIGS_PROPERTY, Collections.emptyMap());+ Map<String, String> proxyUserConfigs =+ (Map<String, String>) pluginConfig.getOrDefault(PROXY_USER_CONFIGS, Collections.emptyMap());++ for (String configName : authConfigNames) {String systemProperty = sysPropPrefix + configName;String defaultConfigVal = authConfigDefaults.get(configName);String configVal = System.getProperty(systemProperty, defaultConfigVal);@@ -170,14 +168,17 @@ public class HadoopAuthPlugin extends AuthenticationPlugin {}if (delegationTokenEnabled) {// This is the only kind we support right now anyway- params.putIfAbsent("delegation-token.token-kind", KerberosPlugin.DELEGATION_TOKEN_TYPE_DEFAULT);+ params.putIfAbsent(+ "delegation-token.token-kind", KerberosPlugin.DELEGATION_TOKEN_TYPE_DEFAULT);}// Configure proxy user settings.params.putAll(proxyUserConfigs);// Needed to work around HADOOP-13346- params.put(DelegationTokenAuthenticationHandler.JSON_MAPPER_PREFIX + JsonGenerator.Feature.AUTO_CLOSE_TARGET,+ params.put(+ DelegationTokenAuthenticationHandler.JSON_MAPPER_PREFIX+ + JsonGenerator.Feature.AUTO_CLOSE_TARGET,"false");final ServletContext servletContext = new AttributeOnlyServletContext();@@ -190,33 +191,35 @@ public class HadoopAuthPlugin extends AuthenticationPlugin {servletContext.setAttribute(DELEGATION_TOKEN_ZK_CLIENT, controller.getZkClient());}- FilterConfig conf = new FilterConfig() {- @Override- public ServletContext getServletContext() {- return servletContext;- }+ FilterConfig conf =+ new FilterConfig() {+ @Override+ public ServletContext getServletContext() {+ return servletContext;+ }- @Override- public Enumeration<String> getInitParameterNames() {- return Collections.enumeration(params.keySet());- }+ @Override+ public Enumeration<String> getInitParameterNames() {+ return Collections.enumeration(params.keySet());+ }- @Override- public String getInitParameter(String param) {- return params.get(param);- }+ @Override+ public String getInitParameter(String param) {+ return params.get(param);+ }- @Override- public String getFilterName() {- return "HadoopAuthFilter";- }- };+ @Override+ public String getFilterName() {+ return "HadoopAuthFilter";+ }+ };return conf;}@Override- public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)+ public boolean doAuthenticate(+ HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws Exception {if (TRACE_HTTP) {log.info("----------HTTP Request---------");@@ -257,7 +260,7 @@ public class HadoopAuthPlugin extends AuthenticationPlugin {numErrors.mark();}}-+if (TRACE_HTTP) {log.info("----------HTTP Response---------");if (log.isInfoEnabled()) {@@ -272,9 +275,8 @@ public class HadoopAuthPlugin extends AuthenticationPlugin {log.info("-------------------------------");}-if (authFilter instanceof HadoopAuthFilter) { // delegation token mgmt.- String requestContinuesAttr = (String)request.getAttribute(REQUEST_CONTINUES_ATTR);+ String requestContinuesAttr = (String) request.getAttribute(REQUEST_CONTINUES_ATTR);if (requestContinuesAttr == null) {log.warn("Could not find {}", REQUEST_CONTINUES_ATTR);return false;diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/KerberosFilter.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/KerberosFilter.javaindex 94b8fa1bb93..436342bd484 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/KerberosFilter.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/KerberosFilter.java@@ -19,14 +19,12 @@ package org.apache.solr.security.hadoop;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.security.Principal;-import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;-import org.apache.hadoop.security.authentication.server.AuthenticationFilter;import org.apache.hadoop.security.authentication.server.AuthenticationHandler;import org.apache.solr.core.CoreContainer;@@ -49,35 +47,37 @@ public class KerberosFilter extends AuthenticationFilter {}@Override- protected void initializeAuthHandler(String authHandlerClassName,- FilterConfig filterConfig) throws ServletException {- // set the internal authentication handler in order to record whether the request should continue+ protected void initializeAuthHandler(String authHandlerClassName, FilterConfig filterConfig)+ throws ServletException {+ // set the internal authentication handler in order to record whether the request should+ // continuesuper.initializeAuthHandler(authHandlerClassName, filterConfig);AuthenticationHandler authHandler = getAuthenticationHandler();super.initializeAuthHandler(RequestContinuesRecorderAuthenticationHandler.class.getName(), filterConfig);RequestContinuesRecorderAuthenticationHandler newAuthHandler =- (RequestContinuesRecorderAuthenticationHandler)getAuthenticationHandler();+ (RequestContinuesRecorderAuthenticationHandler) getAuthenticationHandler();newAuthHandler.setAuthHandler(authHandler);}private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());@Override- protected void doFilter(FilterChain filterChain, HttpServletRequest request,- HttpServletResponse response) throws IOException, ServletException {+ protected void doFilter(+ FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)+ throws IOException, ServletException {request = substituteOriginalUserRequest(request);super.doFilter(filterChain, request, response);}/**- * If principal is an admin user, i.e. has ALL permissions (e.g. request coming from Solr- * node), and "originalUserPrincipal" is specified, then set originalUserPrincipal- * as the principal. This is the case in forwarded/remote requests- * through KerberosPlugin. This is needed because the original node that received- * this request did not perform any authorization, and hence we are the first ones- * to authorize the request (and we need the original user principal to do so).+ * If principal is an admin user, i.e. has ALL permissions (e.g. request coming from Solr node),+ * and "originalUserPrincipal" is specified, then set originalUserPrincipal as the principal. This+ * is the case in forwarded/remote requests through KerberosPlugin. This is needed because the+ * original node that received this request did not perform any authorization, and hence we are+ * the first ones to authorize the request (and we need the original user principal to do so).+ ** @return Substituted request, if applicable, or the original request*/private HttpServletRequest substituteOriginalUserRequest(HttpServletRequest request) {@@ -85,27 +85,34 @@ public class KerberosFilter extends AuthenticationFilter {AuthorizationPlugin authzPlugin = coreContainer.getAuthorizationPlugin();if (authzPlugin instanceof RuleBasedAuthorizationPlugin) {RuleBasedAuthorizationPlugin ruleBased = (RuleBasedAuthorizationPlugin) authzPlugin;- if (request.getHeader(KerberosPlugin.ORIGINAL_USER_PRINCIPAL_HEADER) != null &&- ruleBased.doesUserHavePermission(request.getUserPrincipal(), PermissionNameProvider.Name.ALL)) {- request = new HttpServletRequestWrapper(request) {- @Override- public Principal getUserPrincipal() {- String originalUserPrincipal = originalRequest.getHeader(KerberosPlugin.ORIGINAL_USER_PRINCIPAL_HEADER);- if (log.isInfoEnabled()) {- log.info("Substituting user principal from {} to {}.", originalRequest.getUserPrincipal(), originalUserPrincipal);- }- return new Principal() {+ if (request.getHeader(KerberosPlugin.ORIGINAL_USER_PRINCIPAL_HEADER) != null+ && ruleBased.doesUserHavePermission(+ request.getUserPrincipal(), PermissionNameProvider.Name.ALL)) {+ request =+ new HttpServletRequestWrapper(request) {@Override- public String getName() {- return originalUserPrincipal;- }- @Override- public String toString() {- return originalUserPrincipal;+ public Principal getUserPrincipal() {+ String originalUserPrincipal =+ originalRequest.getHeader(KerberosPlugin.ORIGINAL_USER_PRINCIPAL_HEADER);+ if (log.isInfoEnabled()) {+ log.info(+ "Substituting user principal from {} to {}.",+ originalRequest.getUserPrincipal(),+ originalUserPrincipal);+ }+ return new Principal() {+ @Override+ public String getName() {+ return originalUserPrincipal;+ }++ @Override+ public String toString() {+ return originalUserPrincipal;+ }+ };}};- }- };}}return request;diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/KerberosPlugin.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/KerberosPlugin.javaindex 5d6827e314c..946d97320ab 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/KerberosPlugin.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/KerberosPlugin.java@@ -16,13 +16,14 @@*/package org.apache.solr.security.hadoop;+import com.fasterxml.jackson.core.JsonGenerator;+import com.google.common.annotations.VisibleForTesting;import java.lang.invoke.MethodHandles;import java.util.Collections;import java.util.Enumeration;import java.util.HashMap;import java.util.Map;import java.util.function.BiConsumer;-import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;@@ -30,9 +31,6 @@ import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;--import com.fasterxml.jackson.core.JsonGenerator;-import com.google.common.annotations.VisibleForTesting;import org.apache.hadoop.security.authentication.util.KerberosName;import org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticationHandler;import org.apache.http.HttpRequest;@@ -59,7 +57,7 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBuKrb5HttpClientBuilder kerberosBuilder = new Krb5HttpClientBuilder();private Filter kerberosFilter;-+public static final String NAME_RULES_PARAM = "solr.kerberos.name.rules";public static final String NAME_RULES_MECHANISM_PARAM = "solr.kerberos.name.rules.mechanism";public static final String COOKIE_DOMAIN_PARAM = "solr.kerberos.cookie.domain";@@ -72,7 +70,8 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBupublic static final String DELEGATION_TOKEN_ENABLED = "solr.kerberos.delegation.token.enabled";public static final String DELEGATION_TOKEN_KIND = "solr.kerberos.delegation.token.kind";public static final String DELEGATION_TOKEN_VALIDITY = "solr.kerberos.delegation.token.validity";- public static final String DELEGATION_TOKEN_SECRET_PROVIDER = "solr.kerberos.delegation.token.signer.secret.provider";+ public static final String DELEGATION_TOKEN_SECRET_PROVIDER =+ "solr.kerberos.delegation.token.signer.secret.provider";public static final String DELEGATION_TOKEN_SECRET_PROVIDER_ZK_PATH ="solr.kerberos.delegation.token.signer.secret.provider.zookeper.path";public static final String DELEGATION_TOKEN_SECRET_MANAGER_ZNODE_WORKING_PATH =@@ -84,8 +83,7 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBupublic static final String ORIGINAL_USER_PRINCIPAL_HEADER = "originalUserPrincipal";- static final String DELEGATION_TOKEN_ZK_CLIENT =- "solr.kerberos.delegation.token.zk.client";+ static final String DELEGATION_TOKEN_ZK_CLIENT = "solr.kerberos.delegation.token.zk.client";private final CoreContainer coreContainer;@@ -99,17 +97,22 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBuFilterConfig conf = getInitFilterConfig(pluginConfig, false);kerberosFilter.init(conf);} catch (ServletException e) {- throw new SolrException(ErrorCode.SERVER_ERROR, "Error initializing kerberos authentication plugin: "+e);+ throw new SolrException(+ ErrorCode.SERVER_ERROR, "Error initializing kerberos authentication plugin: " + e);}}-@VisibleForTesting- protected FilterConfig getInitFilterConfig(Map<String, Object> pluginConfig, boolean skipKerberosChecking) {+ protected FilterConfig getInitFilterConfig(+ Map<String, Object> pluginConfig, boolean skipKerberosChecking) {Map<String, String> params = new HashMap<>();params.put("type", "kerberos");putParam(params, "kerberos.name.rules", NAME_RULES_PARAM, "DEFAULT");- putParam(params, "kerberos.name.rules.mechanism", NAME_RULES_MECHANISM_PARAM, KerberosName.DEFAULT_MECHANISM);+ putParam(+ params,+ "kerberos.name.rules.mechanism",+ NAME_RULES_MECHANISM_PARAM,+ KerberosName.DEFAULT_MECHANISM);putParam(params, "token.valid", TOKEN_VALID_PARAM, "30");putParam(params, "cookie.path", COOKIE_PATH_PARAM, "/");if (!skipKerberosChecking) {@@ -124,7 +127,11 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBuZkController controller = coreContainer.getZkController();if (delegationTokenEnabled) {- putParam(params, "delegation-token.token-kind", DELEGATION_TOKEN_KIND, DELEGATION_TOKEN_TYPE_DEFAULT);+ putParam(+ params,+ "delegation-token.token-kind",+ DELEGATION_TOKEN_KIND,+ DELEGATION_TOKEN_TYPE_DEFAULT);if (coreContainer.isZooKeeperAware()) {putParam(params, "signer.secret.provider", DELEGATION_TOKEN_SECRET_PROVIDER, "zookeeper");if ("zookeeper".equals(params.get("signer.secret.provider"))) {@@ -132,19 +139,28 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBuputParam(params, "token.validity", DELEGATION_TOKEN_VALIDITY, "36000");params.put("zk-dt-secret-manager.enable", "true");- String chrootPath = zkHost.contains("/")? zkHost.substring(zkHost.indexOf("/")): "";- String znodeWorkingPath = chrootPath + SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH + "/zkdtsm";+ String chrootPath = zkHost.contains("/") ? zkHost.substring(zkHost.indexOf("/")) : "";+ String znodeWorkingPath =+ chrootPath + SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH + "/zkdtsm";// Note - Curator complains if the znodeWorkingPath starts with /- znodeWorkingPath = znodeWorkingPath.startsWith("/")? znodeWorkingPath.substring(1): znodeWorkingPath;- putParam(params, "zk-dt-secret-manager.znodeWorkingPath",- DELEGATION_TOKEN_SECRET_MANAGER_ZNODE_WORKING_PATH, znodeWorkingPath);- putParam(params, "signer.secret.provider.zookeeper.path",- DELEGATION_TOKEN_SECRET_PROVIDER_ZK_PATH, "/token");+ znodeWorkingPath =+ znodeWorkingPath.startsWith("/") ? znodeWorkingPath.substring(1) : znodeWorkingPath;+ putParam(+ params,+ "zk-dt-secret-manager.znodeWorkingPath",+ DELEGATION_TOKEN_SECRET_MANAGER_ZNODE_WORKING_PATH,+ znodeWorkingPath);+ putParam(+ params,+ "signer.secret.provider.zookeeper.path",+ DELEGATION_TOKEN_SECRET_PROVIDER_ZK_PATH,+ "/token");// ensure krb5 is setup properly before running curatorgetHttpClientBuilder(SolrHttpClientBuilder.create());}} else {- log.info("CoreContainer is not ZooKeeperAware, not setting ZK-related delegation token properties");+ log.info(+ "CoreContainer is not ZooKeeperAware, not setting ZK-related delegation token properties");}}@@ -152,25 +168,27 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBu// appended to the domain. Useful for situations where multiple solr nodes are// on the same host.String usePortStr = System.getProperty(COOKIE_PORT_AWARE_PARAM, null);- boolean needPortAwareCookies = (usePortStr == null) ? false: Boolean.parseBoolean(usePortStr);+ boolean needPortAwareCookies = (usePortStr == null) ? false : Boolean.parseBoolean(usePortStr);if (!needPortAwareCookies || !coreContainer.isZooKeeperAware()) {putParam(params, "cookie.domain", COOKIE_DOMAIN_PARAM, null);} else { // we need port aware cookies and we are in SolrCloud mode.String host = System.getProperty(COOKIE_DOMAIN_PARAM, null);- if (host==null) {- throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required parameter '"+COOKIE_DOMAIN_PARAM+"'.");+ if (host == null) {+ throw new SolrException(+ ErrorCode.SERVER_ERROR, "Missing required parameter '" + COOKIE_DOMAIN_PARAM + "'.");}int port = controller.getHostPort();params.put("cookie.domain", host + ":" + port);}// check impersonator config- for (Enumeration<?> e = System.getProperties().propertyNames(); e.hasMoreElements();) {+ for (Enumeration<?> e = System.getProperties().propertyNames(); e.hasMoreElements(); ) {String key = e.nextElement().toString();if (key.startsWith(IMPERSONATOR_PREFIX)) {if (!delegationTokenEnabled) {- throw new SolrException(ErrorCode.SERVER_ERROR,+ throw new SolrException(+ ErrorCode.SERVER_ERROR,"Impersonator configuration requires delegation tokens to be enabled: " + key);}params.put(key, System.getProperty(key));@@ -178,7 +196,9 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBu}// Needed to work around HADOOP-13346- params.put(DelegationTokenAuthenticationHandler.JSON_MAPPER_PREFIX + JsonGenerator.Feature.AUTO_CLOSE_TARGET,+ params.put(+ DelegationTokenAuthenticationHandler.JSON_MAPPER_PREFIX+ + JsonGenerator.Feature.AUTO_CLOSE_TARGET,"false");final ServletContext servletContext = new AttributeOnlyServletContext();@@ -194,55 +214,66 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBu}log.info("Params: {}", params);- FilterConfig conf = new FilterConfig() {- @Override- public ServletContext getServletContext() {- return servletContext;- }-- @Override- public Enumeration<String> getInitParameterNames() {- return Collections.enumeration(params.keySet());- }-- @Override- public String getInitParameter(String param) {- return params.get(param);- }-- @Override- public String getFilterName() {- return "KerberosFilter";- }- };+ FilterConfig conf =+ new FilterConfig() {+ @Override+ public ServletContext getServletContext() {+ return servletContext;+ }++ @Override+ public Enumeration<String> getInitParameterNames() {+ return Collections.enumeration(params.keySet());+ }++ @Override+ public String getInitParameter(String param) {+ return params.get(param);+ }++ @Override+ public String getFilterName() {+ return "KerberosFilter";+ }+ };return conf;}- private void putParam(Map<String, String> params, String internalParamName, String externalParamName, String defaultValue) {+ private void putParam(+ Map<String, String> params,+ String internalParamName,+ String externalParamName,+ String defaultValue) {String value = System.getProperty(externalParamName, defaultValue);- if (value==null) {- throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required parameter '"+externalParamName+"'.");+ if (value == null) {+ throw new SolrException(+ ErrorCode.SERVER_ERROR, "Missing required parameter '" + externalParamName + "'.");}params.put(internalParamName, value);}- private void putParamOptional(Map<String, String> params, String internalParamName, String externalParamName) {+ private void putParamOptional(+ Map<String, String> params, String internalParamName, String externalParamName) {String value = System.getProperty(externalParamName);- if (value!=null) {+ if (value != null) {params.put(internalParamName, value);}}@Override- public boolean doAuthenticate(HttpServletRequest req, HttpServletResponse rsp,- FilterChain chain) throws Exception {+ public boolean doAuthenticate(HttpServletRequest req, HttpServletResponse rsp, FilterChain chain)+ throws Exception {log.debug("Request to authenticate using kerberos: {}", req);kerberosFilter.doFilter(req, rsp, chain);- String requestContinuesAttr = (String)req.getAttribute(RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR);+ String requestContinuesAttr =+ (String)+ req.getAttribute(RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR);if (requestContinuesAttr == null) {- log.warn("Could not find {}", RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR);+ log.warn(+ "Could not find {}",+ RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR);return false;} else {return Boolean.parseBoolean(requestContinuesAttr);@@ -261,8 +292,9 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBuprivate boolean intercept(BiConsumer<String, String> header) {SolrRequestInfo info = SolrRequestInfo.getRequestInfo();- if (info != null && (info.getAction() == SolrDispatchFilter.Action.FORWARD ||- info.getAction() == SolrDispatchFilter.Action.REMOTEQUERY)) {+ if (info != null+ && (info.getAction() == SolrDispatchFilter.Action.FORWARD+ || info.getAction() == SolrDispatchFilter.Action.REMOTEQUERY)) {if (info.getUserPrincipal() != null) {if (log.isInfoEnabled()) {log.info("Setting original user principal: {}", info.getUserPrincipal().getName());@@ -281,12 +313,13 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBu@Overridepublic void setup(Http2SolrClient client) {- final HttpListenerFactory.RequestResponseListener listener = new HttpListenerFactory.RequestResponseListener() {- @Override- public void onQueued(Request request) {- interceptInternodeRequest(request);- }- };+ final HttpListenerFactory.RequestResponseListener listener =+ new HttpListenerFactory.RequestResponseListener() {+ @Override+ public void onQueued(Request request) {+ interceptInternodeRequest(request);+ }+ };client.addListenerFactory(() -> listener);kerberosBuilder.setup(client);@@ -298,7 +331,11 @@ public class KerberosPlugin extends AuthenticationPlugin implements HttpClientBukerberosBuilder.close();}- protected Filter getKerberosFilter() { return kerberosFilter; }+ protected Filter getKerberosFilter() {+ return kerberosFilter;+ }- protected void setKerberosFilter(Filter kerberosFilter) { this.kerberosFilter = kerberosFilter; }+ protected void setKerberosFilter(Filter kerberosFilter) {+ this.kerberosFilter = kerberosFilter;+ }}diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/RequestContinuesRecorderAuthenticationHandler.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/RequestContinuesRecorderAuthenticationHandler.javaindex 10d4998572e..eb166a7b58a 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/RequestContinuesRecorderAuthenticationHandler.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/RequestContinuesRecorderAuthenticationHandler.java@@ -18,11 +18,9 @@ package org.apache.solr.security.hadoop;import java.io.IOException;import java.util.Properties;-import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;-import org.apache.hadoop.security.authentication.client.AuthenticationException;import org.apache.hadoop.security.authentication.server.AuthenticationHandler;import org.apache.hadoop.security.authentication.server.AuthenticationToken;@@ -55,12 +53,13 @@ public class RequestContinuesRecorderAuthenticationHandler implements AuthenticaauthHandler.destroy();}- public boolean managementOperation(AuthenticationToken token,- HttpServletRequest request,- HttpServletResponse response)+ public boolean managementOperation(+ AuthenticationToken token, HttpServletRequest request, HttpServletResponse response)throws IOException, AuthenticationException {boolean result = authHandler.managementOperation(token, request, response);- request.setAttribute(RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR, Boolean.toString(result));+ request.setAttribute(+ RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR,+ Boolean.toString(result));return result;}diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/package-info.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/package-info.javaindex 65cdfbe41e4..cfe322e9b26 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/package-info.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/security/hadoop/package-info.java@@ -15,8 +15,5 @@* limitations under the License.*/-/**- * Commonly used classes for Solr security framework.- */+/** Commonly used classes for Solr security framework. */package org.apache.solr.security.hadoop;-diff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/util/configuration/providers/hadoop/HadoopSSLCredentialProvider.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/util/configuration/providers/hadoop/HadoopSSLCredentialProvider.javaindex 77aa6e746a6..1b51d558134 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/util/configuration/providers/hadoop/HadoopSSLCredentialProvider.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/util/configuration/providers/hadoop/HadoopSSLCredentialProvider.java@@ -17,21 +17,18 @@package org.apache.solr.util.configuration.providers.hadoop;+import static org.apache.hadoop.security.alias.CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH;+import java.io.IOException;import java.lang.invoke.MethodHandles;import java.util.EnumMap;-import org.apache.hadoop.conf.Configuration;import org.apache.solr.common.StringUtils;import org.apache.solr.util.configuration.providers.AbstractSSLCredentialProvider;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import static org.apache.hadoop.security.alias.CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH;--/**- * System property based SSL configuration provider- */+/** System property based SSL configuration provider */public class HadoopSSLCredentialProvider extends AbstractSSLCredentialProvider {private Configuration hadoopConfigurationProvider;@@ -44,10 +41,14 @@ public class HadoopSSLCredentialProvider extends AbstractSSLCredentialProvider {public HadoopSSLCredentialProvider(Configuration hadoopConfigurationProvider) {if (StringUtils.isEmpty(System.getProperty(CREDENTIAL_PROVIDER_PATH))) {- throw new RuntimeException("Cannot initialize Hadoop configuration provider without credential provider path. Use " + CREDENTIAL_PROVIDER_PATH + " system property to configure.");+ throw new RuntimeException(+ "Cannot initialize Hadoop configuration provider without credential provider path. Use "+ + CREDENTIAL_PROVIDER_PATH+ + " system property to configure.");}this.hadoopConfigurationProvider = hadoopConfigurationProvider;- hadoopConfigurationProvider.set(CREDENTIAL_PROVIDER_PATH, System.getProperty(CREDENTIAL_PROVIDER_PATH));+ hadoopConfigurationProvider.set(+ CREDENTIAL_PROVIDER_PATH, System.getProperty(CREDENTIAL_PROVIDER_PATH));}@Overridediff --git a/solr/modules/hadoop-auth/src/java/org/apache/solr/util/configuration/providers/hadoop/package-info.java b/solr/modules/hadoop-auth/src/java/org/apache/solr/util/configuration/providers/hadoop/package-info.javaindex 0c11f9087e5..07a5a223d42 100644--- a/solr/modules/hadoop-auth/src/java/org/apache/solr/util/configuration/providers/hadoop/package-info.java+++ b/solr/modules/hadoop-auth/src/java/org/apache/solr/util/configuration/providers/hadoop/package-info.java@@ -15,8 +15,5 @@* limitations under the License.*/-/**- * Commonly used classes for Solr security framework.- */+/** Commonly used classes for Solr security framework. */package org.apache.solr.util.configuration.providers.hadoop;-diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/client/solrj/impl/Krb5HttpClientUtils.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/client/solrj/impl/Krb5HttpClientUtils.javaindex d2917b7d0e0..7a7733fc039 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/client/solrj/impl/Krb5HttpClientUtils.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/client/solrj/impl/Krb5HttpClientUtils.java@@ -16,17 +16,16 @@*/package org.apache.solr.client.solrj.impl;+import java.lang.invoke.MethodHandles;+import java.net.URI;+import javax.security.auth.login.AppConfigurationEntry;+import javax.security.auth.login.Configuration;import org.eclipse.jetty.client.HttpAuthenticationStore;import org.eclipse.jetty.client.WWWAuthenticationProtocolHandler;import org.eclipse.jetty.client.util.SPNEGOAuthentication;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import javax.security.auth.login.AppConfigurationEntry;-import javax.security.auth.login.Configuration;-import java.lang.invoke.MethodHandles;-import java.net.URI;-/*** All of this is a clone of Krb5HttpClientBuilder to hardcode the user-principal for a unit test*/@@ -34,25 +33,29 @@ public class Krb5HttpClientUtils {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());private static Configuration jaasConfig = new Krb5HttpClientBuilder.SolrJaasConfiguration();-public static void setup(Http2SolrClient http2Client, String principalName) {HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore();authenticationStore.addAuthentication(createSPNEGOAuthentication(principalName));http2Client.getHttpClient().setAuthenticationStore(authenticationStore);- http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient()));+ http2Client+ .getProtocolHandlers()+ .put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient()));}private static SPNEGOAuthentication createSPNEGOAuthentication(String principalName) {- SPNEGOAuthentication authentication = new SPNEGOAuthentication(null){+ SPNEGOAuthentication authentication =+ new SPNEGOAuthentication(null) {- public boolean matches(String type, URI uri, String realm) {- return this.getType().equals(type);- }- };+ public boolean matches(String type, URI uri, String realm) {+ return this.getType().equals(type);+ }+ };String clientAppName = System.getProperty("solr.kerberos.jaas.appname", "Client");AppConfigurationEntry[] entries = jaasConfig.getAppConfigurationEntry(clientAppName);if (entries == null) {- log.warn("Could not find login configuration entry for {}. SPNego authentication may not be successful.", (Object)clientAppName);+ log.warn(+ "Could not find login configuration entry for {}. SPNego authentication may not be successful.",+ (Object) clientAppName);return authentication;}if (entries.length != 1) {@@ -60,7 +63,8 @@ public class Krb5HttpClientUtils {return authentication;}- Krb5HttpClientBuilder.setAuthenticationOptions(authentication, entries[0].getOptions(), principalName);+ Krb5HttpClientBuilder.setAuthenticationOptions(+ authentication, entries[0].getOptions(), principalName);return authentication;}}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HadoopAuthFakeGroupMapping.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HadoopAuthFakeGroupMapping.javaindex b77a7232d14..053f3e55061 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HadoopAuthFakeGroupMapping.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HadoopAuthFakeGroupMapping.java@@ -18,12 +18,9 @@ package org.apache.solr.security.hadoop;import java.util.Collections;import java.util.List;-import org.apache.hadoop.security.GroupMappingServiceProvider;-/**- * Fake mapping for Hadoop to prevent falling back to Shell group provider- */+/** Fake mapping for Hadoop to prevent falling back to Shell group provider */public class HadoopAuthFakeGroupMapping implements GroupMappingServiceProvider {@Overridepublic List<String> getGroups(String user) {@@ -31,10 +28,8 @@ public class HadoopAuthFakeGroupMapping implements GroupMappingServiceProvider {}@Override- public void cacheGroupsRefresh() {- }+ public void cacheGroupsRefresh() {}@Override- public void cacheGroupsAdd(List<String> groups) {- }+ public void cacheGroupsAdd(List<String> groups) {}}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HadoopTestUtil.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HadoopTestUtil.javaindex f8a7222f942..78e0d3f0ffc 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HadoopTestUtil.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HadoopTestUtil.java@@ -19,7 +19,6 @@ package org.apache.solr.security.hadoop;import java.lang.invoke.MethodHandles;import org.apache.hadoop.io.nativeio.NativeIO;-import org.apache.lucene.util.Constants;import org.apache.solr.SolrTestCase;import org.slf4j.Logger;@@ -35,9 +34,9 @@ public class HadoopTestUtil {/*** If Hadoop home is set via environment variable HADOOP_HOME or Java system property- * hadoop.home.dir, the behavior of test is undefined. Ensure that these are not set- * before starting. It is not possible to easily unset environment variables so better- * to bail out early instead of trying to test.+ * hadoop.home.dir, the behavior of test is undefined. Ensure that these are not set before+ * starting. It is not possible to easily unset environment variables so better to bail out early+ * instead of trying to test.*/protected static void ensureHadoopHomeNotSet() {if (System.getenv("HADOOP_HOME") != null) {@@ -48,11 +47,10 @@ public class HadoopTestUtil {}}- /**- * Hadoop integration tests fail on Windows without Hadoop NativeIO- */+ /** Hadoop integration tests fail on Windows without Hadoop NativeIO */protected static void checkHadoopWindows() {- SolrTestCase.assumeTrue("Hadoop does not work on Windows without Hadoop NativeIO",+ SolrTestCase.assumeTrue(+ "Hadoop does not work on Windows without Hadoop NativeIO",!Constants.WINDOWS || NativeIO.isAvailable());}}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HttpParamDelegationTokenPlugin.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HttpParamDelegationTokenPlugin.javaindex 27e353aed20..d4624a52db4 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HttpParamDelegationTokenPlugin.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/HttpParamDelegationTokenPlugin.java@@ -26,7 +26,6 @@ import java.util.List;import java.util.Map;import java.util.Optional;import java.util.Properties;-import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;@@ -37,13 +36,11 @@ import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;-import org.apache.hadoop.security.authentication.client.AuthenticationException;import org.apache.hadoop.security.authentication.server.AuthenticationFilter;import org.apache.hadoop.security.authentication.server.AuthenticationHandler;import org.apache.hadoop.security.authentication.server.AuthenticationToken;import org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticationHandler;-import org.apache.http.HttpException;import org.apache.http.HttpRequest;import org.apache.http.HttpRequestInterceptor;@@ -61,25 +58,30 @@ import org.apache.solr.request.SolrRequestInfo;import org.eclipse.jetty.client.api.Request;/**- * AuthenticationHandler that supports delegation tokens and simple- * authentication via the "user" http parameter+ * AuthenticationHandler that supports delegation tokens and simple authentication via the "user"+ * http parameter*/public class HttpParamDelegationTokenPlugin extends KerberosPlugin {public static final String USER_PARAM = "user"; // http parameter for user authentication- public static final String REMOTE_HOST_PARAM = "remoteHost"; // http parameter for indicating remote host- public static final String REMOTE_ADDRESS_PARAM = "remoteAddress"; // http parameter for indicating remote address- public static final String INTERNAL_REQUEST_HEADER = "internalRequest"; // http header for indicating internal request+ public static final String REMOTE_HOST_PARAM =+ "remoteHost"; // http parameter for indicating remote host+ public static final String REMOTE_ADDRESS_PARAM =+ "remoteAddress"; // http parameter for indicating remote address+ public static final String INTERNAL_REQUEST_HEADER =+ "internalRequest"; // http header for indicating internal requestboolean isSolrThread() {return ExecutorUtil.isSolrServerThread();}- private final HttpRequestInterceptor interceptor = new HttpRequestInterceptor() {- @Override- public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {- getPrincipal().ifPresent(usr -> httpRequest.setHeader(INTERNAL_REQUEST_HEADER, usr));- }- };+ private final HttpRequestInterceptor interceptor =+ new HttpRequestInterceptor() {+ @Override+ public void process(HttpRequest httpRequest, HttpContext httpContext)+ throws HttpException, IOException {+ getPrincipal().ifPresent(usr -> httpRequest.setHeader(INTERNAL_REQUEST_HEADER, usr));+ }+ };public HttpParamDelegationTokenPlugin(CoreContainer coreContainer) {super(coreContainer);@@ -90,36 +92,38 @@ public class HttpParamDelegationTokenPlugin extends KerberosPlugin {try {final FilterConfig initConf = getInitFilterConfig(pluginConfig, true);- FilterConfig conf = new FilterConfig() {- @Override- public ServletContext getServletContext() {- return initConf.getServletContext();- }+ FilterConfig conf =+ new FilterConfig() {+ @Override+ public ServletContext getServletContext() {+ return initConf.getServletContext();+ }- @Override- public Enumeration<String> getInitParameterNames() {- return initConf.getInitParameterNames();- }+ @Override+ public Enumeration<String> getInitParameterNames() {+ return initConf.getInitParameterNames();+ }- @Override- public String getInitParameter(String param) {- if (AuthenticationFilter.AUTH_TYPE.equals(param)) {- return HttpParamDelegationTokenAuthenticationHandler.class.getName();- }- return initConf.getInitParameter(param);- }+ @Override+ public String getInitParameter(String param) {+ if (AuthenticationFilter.AUTH_TYPE.equals(param)) {+ return HttpParamDelegationTokenAuthenticationHandler.class.getName();+ }+ return initConf.getInitParameter(param);+ }- @Override- public String getFilterName() {- return "HttpParamFilter";- }- };+ @Override+ public String getFilterName() {+ return "HttpParamFilter";+ }+ };Filter kerberosFilter = new HttpParamToRequestFilter();kerberosFilter.init(conf);setKerberosFilter(kerberosFilter);} catch (ServletException e) {- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,- "Error initializing kerberos authentication plugin: "+e);+ throw new SolrException(+ SolrException.ErrorCode.SERVER_ERROR,+ "Error initializing kerberos authentication plugin: " + e);}}@@ -129,32 +133,33 @@ public class HttpParamDelegationTokenPlugin extends KerberosPlugin {if (reqInfo != null) {Principal principal = reqInfo.getUserPrincipal();if (principal == null) {- //this had a request but not authenticated- //so we don't not need to set a principal+ // this had a request but not authenticated+ // so we don't not need to set a principalreturn Optional.empty();} else {usr = principal.getName();}} else {if (!isSolrThread()) {- //if this is not running inside a Solr threadpool (as in testcases)+ // if this is not running inside a Solr threadpool (as in testcases)// then no need to add any headerreturn Optional.empty();}- //this request seems to be originated from Solr itself- usr = "$"; //special name to denote the user is the node itself+ // this request seems to be originated from Solr itself+ usr = "$"; // special name to denote the user is the node itself}return Optional.of(usr);}@Overridepublic void setup(Http2SolrClient client) {- final HttpListenerFactory.RequestResponseListener listener = new HttpListenerFactory.RequestResponseListener() {- @Override- public void onQueued(Request request) {- getPrincipal().ifPresent(usr -> request.header(INTERNAL_REQUEST_HEADER, usr));- }- };+ final HttpListenerFactory.RequestResponseListener listener =+ new HttpListenerFactory.RequestResponseListener() {+ @Override+ public void onQueued(Request request) {+ getPrincipal().ifPresent(usr -> request.header(INTERNAL_REQUEST_HEADER, usr));+ }+ };client.addListenerFactory(() -> listener);}@@ -172,7 +177,8 @@ public class HttpParamDelegationTokenPlugin extends KerberosPlugin {}private static String getHttpParam(HttpServletRequest request, String param) {- List<NameValuePair> pairs = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));+ List<NameValuePair> pairs =+ URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));for (NameValuePair nvp : pairs) {if (param.equals(nvp.getName())) {return nvp.getValue();@@ -181,8 +187,8 @@ public class HttpParamDelegationTokenPlugin extends KerberosPlugin {return null;}- public static class HttpParamDelegationTokenAuthenticationHandler extends- DelegationTokenAuthenticationHandler {+ public static class HttpParamDelegationTokenAuthenticationHandler+ extends DelegationTokenAuthenticationHandler {public HttpParamDelegationTokenAuthenticationHandler() {super(new HttpParamAuthenticationHandler());@@ -205,28 +211,26 @@ public class HttpParamDelegationTokenPlugin extends KerberosPlugin {}@Override- public void init(Properties config) throws ServletException {- }+ public void init(Properties config) throws ServletException {}@Override- public void destroy() {- }+ public void destroy() {}@Override- public boolean managementOperation(AuthenticationToken token,- HttpServletRequest request, HttpServletResponse response)+ public boolean managementOperation(+ AuthenticationToken token, HttpServletRequest request, HttpServletResponse response)throws IOException, AuthenticationException {return false;}@Override- public AuthenticationToken authenticate(HttpServletRequest request,- HttpServletResponse response)+ public AuthenticationToken authenticate(+ HttpServletRequest request, HttpServletResponse response)throws IOException, AuthenticationException {AuthenticationToken token = null;String userName = getHttpParam(request, USER_PARAM);if (userName == null) {- //check if this is an internal request+ // check if this is an internal requestuserName = request.getHeader(INTERNAL_REQUEST_HEADER);}if (userName != null) {@@ -240,52 +244,54 @@ public class HttpParamDelegationTokenPlugin extends KerberosPlugin {}}- /**- * Filter that converts http params to HttpServletRequest params- */+ /** Filter that converts http params to HttpServletRequest params */private static class HttpParamToRequestFilter extends DelegationTokenKerberosFilter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {final HttpServletRequest httpRequest = (HttpServletRequest) request;- final HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(httpRequest) {- @Override- public String getRemoteHost() {- String param = getHttpParam(httpRequest, REMOTE_HOST_PARAM);- return param != null ? param : httpRequest.getRemoteHost();- }+ final HttpServletRequestWrapper requestWrapper =+ new HttpServletRequestWrapper(httpRequest) {+ @Override+ public String getRemoteHost() {+ String param = getHttpParam(httpRequest, REMOTE_HOST_PARAM);+ return param != null ? param : httpRequest.getRemoteHost();+ }- @Override- public String getRemoteAddr() {- String param = getHttpParam(httpRequest, REMOTE_ADDRESS_PARAM);- return param != null ? param : httpRequest.getRemoteAddr();- }- };+ @Override+ public String getRemoteAddr() {+ String param = getHttpParam(httpRequest, REMOTE_ADDRESS_PARAM);+ return param != null ? param : httpRequest.getRemoteAddr();+ }+ };super.doFilter(requestWrapper, response, chain);}@Override- protected void doFilter(FilterChain filterChain, HttpServletRequest request,- HttpServletResponse response) throws IOException, ServletException {- // remove the filter-specific authentication information, so it doesn't get accidentally forwarded.+ protected void doFilter(+ FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)+ throws IOException, ServletException {+ // remove the filter-specific authentication information, so it doesn't get accidentally+ // forwarded.List<NameValuePair> newPairs = new LinkedList<NameValuePair>();- List<NameValuePair> pairs = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));+ List<NameValuePair> pairs =+ URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));for (NameValuePair nvp : pairs) {if (!USER_PARAM.equals(nvp.getName())) {newPairs.add(nvp);- }- else {+ } else {request.setAttribute(USER_PARAM, nvp.getValue());}}final String queryStringNoUser = URLEncodedUtils.format(newPairs, StandardCharsets.UTF_8);- HttpServletRequest requestWrapper = new HttpServletRequestWrapper(request) {- @Override- public String getQueryString() {- return queryStringNoUser;- }- };+ HttpServletRequest requestWrapper =+ new HttpServletRequestWrapper(request) {+ @Override+ public String getQueryString() {+ return queryStringNoUser;+ }+ };super.doFilter(filterChain, requestWrapper, response);}}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/ImpersonationUtil.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/ImpersonationUtil.javaindex 1d2c189bba9..d8cb4c99f7c 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/ImpersonationUtil.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/ImpersonationUtil.java@@ -17,7 +17,6 @@package org.apache.solr.security.hadoop;import java.util.List;-import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.security.authentication.client.PseudoAuthenticator;import org.apache.lucene.util.Constants;@@ -28,7 +27,8 @@ import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.params.SolrParams;/**- * This class implements utility functions required to test the secure impersonation feature for {@linkplain HadoopAuthPlugin}+ * This class implements utility functions required to test the secure impersonation feature for+ * {@linkplain HadoopAuthPlugin}*/public class ImpersonationUtil {@@ -68,5 +68,4 @@ public class ImpersonationUtil {static String getExpectedHostExMsg(String user) {return "Unauthorized connection for super-user: " + user;}-}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/ImpersonatorCollectionsHandler.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/ImpersonatorCollectionsHandler.javaindex 51bbb16126c..4295b2f2d96 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/ImpersonatorCollectionsHandler.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/ImpersonatorCollectionsHandler.java@@ -17,9 +17,7 @@package org.apache.solr.security.hadoop;import java.util.concurrent.atomic.AtomicBoolean;-import javax.servlet.http.HttpServletRequest;-import org.apache.hadoop.security.authentication.client.PseudoAuthenticator;import org.apache.solr.core.CoreContainer;import org.apache.solr.handler.admin.CollectionsHandler;@@ -28,8 +26,8 @@ import org.apache.solr.response.SolrQueryResponse;import org.junit.Assert;/**- * This class extends {@linkplain CollectionsHandler} and implements extra validations- * for verifying proxy users support in {@linkplain HadoopAuthPlugin}+ * This class extends {@linkplain CollectionsHandler} and implements extra validations for verifying+ * proxy users support in {@linkplain HadoopAuthPlugin}*/public class ImpersonatorCollectionsHandler extends CollectionsHandler {static AtomicBoolean called = new AtomicBoolean(false);@@ -48,7 +46,7 @@ public class ImpersonatorCollectionsHandler extends CollectionsHandler {super.handleRequestBody(req, rsp);String doAs = req.getParams().get(KerberosPlugin.IMPERSONATOR_DO_AS_HTTP_PARAM);if (doAs != null) {- HttpServletRequest httpRequest = (HttpServletRequest)req.getContext().get("httpRequest");+ HttpServletRequest httpRequest = (HttpServletRequest) req.getContext().get("httpRequest");Assert.assertNotNull(httpRequest);String user = req.getParams().get(PseudoAuthenticator.USER_NAME);Assert.assertNotNull(user);diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/KerberosTestServices.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/KerberosTestServices.javaindex 3e619cd17ca..f66fea53f2d 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/KerberosTestServices.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/KerberosTestServices.java@@ -16,8 +16,6 @@*/package org.apache.solr.security.hadoop;-import javax.security.auth.login.AppConfigurationEntry;-import javax.security.auth.login.Configuration;import java.io.File;import java.lang.invoke.MethodHandles;import java.net.BindException;@@ -28,7 +26,8 @@ import java.util.Locale;import java.util.Map;import java.util.Objects;import java.util.Properties;-+import javax.security.auth.login.AppConfigurationEntry;+import javax.security.auth.login.Configuration;import org.apache.commons.io.FileUtils;import org.apache.hadoop.minikdc.MiniKdc;import org.apache.solr.client.solrj.impl.Krb5HttpClientBuilder;@@ -37,7 +36,7 @@ import org.slf4j.LoggerFactory;public class KerberosTestServices {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());-+private volatile MiniKdc kdc;private final JaasConfiguration jaasConfiguration;private final Configuration savedConfig;@@ -46,10 +45,8 @@ public class KerberosTestServices {private final File workDir;- private KerberosTestServices(File workDir,- JaasConfiguration jaasConfiguration,- Configuration savedConfig,- boolean debug) {+ private KerberosTestServices(+ File workDir, JaasConfiguration jaasConfiguration, Configuration savedConfig, boolean debug) {this.jaasConfiguration = jaasConfiguration;this.savedConfig = savedConfig;this.workDir = workDir;@@ -104,8 +101,8 @@ public class KerberosTestServices {}/**- * Returns a MiniKdc that can be used for creating kerberos principals- * and keytabs. Caller is responsible for starting/stopping the kdc.+ * Returns a MiniKdc that can be used for creating kerberos principals and keytabs. Caller is+ * responsible for starting/stopping the kdc.*/private static MiniKdc getKdc(File workDir, boolean debug) throws Exception {Properties conf = MiniKdc.createConf();@@ -115,8 +112,8 @@ public class KerberosTestServices {}/**- * Programmatic version of a jaas.conf file suitable for connecting- * to a SASL-configured zookeeper.+ * Programmatic version of a jaas.conf file suitable for connecting to a SASL-configured+ * zookeeper.*/private static class JaasConfiguration extends Configuration {@@ -125,16 +122,16 @@ public class KerberosTestServices {private String clientAppName = "Client", serverAppName = "Server";/**- * Add an entry to the jaas configuration with the passed in name,- * principal, and keytab. The other necessary options will be set for you.+ * Add an entry to the jaas configuration with the passed in name, principal, and keytab. The+ * other necessary options will be set for you.** @param clientPrincipal The principal of the client* @param clientKeytab The location of the keytab with the clientPrincipal* @param serverPrincipal The principal of the server* @param serverKeytab The location of the keytab with the serverPrincipal*/- public JaasConfiguration(String clientPrincipal, File clientKeytab,- String serverPrincipal, File serverKeytab) {+ public JaasConfiguration(+ String clientPrincipal, File clientKeytab, String serverPrincipal, File serverKeytab) {Map<String, String> clientOptions = new HashMap<>();clientOptions.put("principal", clientPrincipal);clientOptions.put("keyTab", clientKeytab.getAbsolutePath());@@ -146,24 +143,30 @@ public class KerberosTestServices {if (jaasProp != null && "true".equalsIgnoreCase(jaasProp)) {clientOptions.put("debug", "true");}- clientEntry = new AppConfigurationEntry[]{- new AppConfigurationEntry(krb5LoginModuleName,- AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,- clientOptions)};- if(serverPrincipal!=null && serverKeytab!=null) {+ clientEntry =+ new AppConfigurationEntry[] {+ new AppConfigurationEntry(+ krb5LoginModuleName,+ AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,+ clientOptions)+ };+ if (serverPrincipal != null && serverKeytab != null) {Map<String, String> serverOptions = new HashMap<>(clientOptions);serverOptions.put("principal", serverPrincipal);serverOptions.put("keytab", serverKeytab.getAbsolutePath());- serverEntry = new AppConfigurationEntry[]{- new AppConfigurationEntry(krb5LoginModuleName,- AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,- serverOptions)};+ serverEntry =+ new AppConfigurationEntry[] {+ new AppConfigurationEntry(+ krb5LoginModuleName,+ AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,+ serverOptions)+ };}}/**- * Add an entry to the jaas configuration with the passed in principal and keytab,- * along with the app name.+ * Add an entry to the jaas configuration with the passed in principal and keytab, along with+ * the app name.** @param principal The principal* @param keytab The keytab containing credentials for the principal@@ -186,17 +189,19 @@ public class KerberosTestServices {}}- public final static String krb5LoginModuleName =- System.getProperty("java.vendor").contains("IBM") ?- "com.ibm.security.auth.module.Krb5LoginModule" :- "com.sun.security.auth.module.Krb5LoginModule";+ public static final String krb5LoginModuleName =+ System.getProperty("java.vendor").contains("IBM")+ ? "com.ibm.security.auth.module.Krb5LoginModule"+ : "com.sun.security.auth.module.Krb5LoginModule";/**- * These Locales don't generate dates that are compatible with Hadoop MiniKdc.- * See LocaleTest.java and https://issues.apache.org/jira/browse/DIRKRB-753+ * These Locales don't generate dates that are compatible with Hadoop MiniKdc. See LocaleTest.java+ * and https://issues.apache.org/jira/browse/DIRKRB-753*/- private final static List<String> incompatibleLanguagesWithMiniKdc = Arrays.asList(- "mzn", "ps", "mr", "uz", "ks", "bn", "my", "sd", "pa", "ar", "th", "dz", "ja", "ne", "ckb", "fa", "lrc", "ur", "ig");+ private static final List<String> incompatibleLanguagesWithMiniKdc =+ Arrays.asList(+ "mzn", "ps", "mr", "uz", "ks", "bn", "my", "sd", "pa", "ar", "th", "dz", "ja", "ne",+ "ckb", "fa", "lrc", "ur", "ig");public static class Builder {private File kdcWorkDir;@@ -207,7 +212,7 @@ public class KerberosTestServices {private String appName;private boolean debug = false;- public Builder() { }+ public Builder() {}public Builder withKdc(File kdcWorkDir) {this.kdcWorkDir = kdcWorkDir;@@ -219,8 +224,8 @@ public class KerberosTestServices {return this;}- public Builder withJaasConfiguration(String clientPrincipal, File clientKeytab,- String serverPrincipal, File serverKeytab) {+ public Builder withJaasConfiguration(+ String clientPrincipal, File clientKeytab, String serverPrincipal, File serverKeytab) {this.clientPrincipal = Objects.requireNonNull(clientPrincipal);this.clientKeytab = Objects.requireNonNull(clientKeytab);this.serverPrincipal = serverPrincipal;@@ -239,12 +244,15 @@ public class KerberosTestServices {}public KerberosTestServices build() throws Exception {- final Configuration oldConfig = clientPrincipal != null ? Configuration.getConfiguration() : null;+ final Configuration oldConfig =+ clientPrincipal != null ? Configuration.getConfiguration() : null;JaasConfiguration jaasConfiguration = null;if (clientPrincipal != null) {- jaasConfiguration = (appName == null) ?- new JaasConfiguration(clientPrincipal, clientKeytab, serverPrincipal, serverKeytab) :- new JaasConfiguration(clientPrincipal, clientKeytab, appName);+ jaasConfiguration =+ (appName == null)+ ? new JaasConfiguration(+ clientPrincipal, clientKeytab, serverPrincipal, serverKeytab)+ : new JaasConfiguration(clientPrincipal, clientKeytab, appName);}return new KerberosTestServices(kdcWorkDir, jaasConfiguration, oldConfig, debug);}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/KerberosUtils.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/KerberosUtils.javaindex 1db7c5bc8ee..e7e39d117f2 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/KerberosUtils.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/KerberosUtils.java@@ -20,13 +20,11 @@ import java.io.File;import java.nio.file.Files;import java.nio.file.Path;-/**- * A utility class which provides common functionality required to test kerberos integration.- */+/** A utility class which provides common functionality required to test kerberos integration. */public class KerberosUtils {/**- * This method sets up Hadoop mini-kdc along with relevant Kerberos configuration files- * (e.g. jaas.conf) as well as system properties.+ * This method sets up Hadoop mini-kdc along with relevant Kerberos configuration files (e.g.+ * jaas.conf) as well as system properties.** @param baseDir The directory path which should be used by the Hadoop mini-kdc* @return An instance of {@link KerberosTestServices}@@ -36,26 +34,36 @@ public class KerberosUtils {System.setProperty("solr.jaas.debug", "true");Path kdcDir = baseDir.resolve("minikdc");String solrClientPrincipal = "solr";- String solrAltClientPrincipal = "solr_alt"; // An alternate principal that can be handled differently by authz tests+ String solrAltClientPrincipal =+ "solr_alt"; // An alternate principal that can be handled differently by authz testsFile keytabFile = kdcDir.resolve("keytabs").toFile();- KerberosTestServices tmp = KerberosTestServices.builder()+ KerberosTestServices tmp =+ KerberosTestServices.builder().withKdc(kdcDir.toFile()).withJaasConfiguration(solrClientPrincipal, keytabFile, "SolrClient").build();String solrServerPrincipal = "HTTP/127.0.0.1";tmp.start();- tmp.getKdc().createPrincipal(keytabFile, solrServerPrincipal, solrAltClientPrincipal, solrClientPrincipal);+ tmp.getKdc()+ .createPrincipal(+ keytabFile, solrServerPrincipal, solrAltClientPrincipal, solrClientPrincipal);String appName = "SolrClient";- String jaas = appName + " {\n"+ String jaas =+ appName+ + " {\n"+ " com.sun.security.auth.module.Krb5LoginModule required\n"+ " useKeyTab=true\n"- + " keyTab=\"" + keytabFile.getAbsolutePath() + "\"\n"+ + " keyTab=\""+ + keytabFile.getAbsolutePath()+ + "\"\n"+ " storeKey=true\n"+ " useTicketCache=false\n"+ " doNotPrompt=true\n"+ " debug=true\n"- + " principal=\"" + solrClientPrincipal + "\";\n"+ + " principal=\""+ + solrClientPrincipal+ + "\";\n"+ "};";Path jaasFile = kdcDir.resolve("jaas-client.conf");@@ -66,16 +74,18 @@ public class KerberosUtils {System.setProperty("solr.kerberos.principal", solrServerPrincipal);System.setProperty("solr.kerberos.keytab", keytabFile.getAbsolutePath());// Extracts 127.0.0.1 from HTTP/[email protected]- System.setProperty("solr.kerberos.name.rules", "RULE:[1:$1@$0](.*EXAMPLE.COM)s/@.*//"+ System.setProperty(+ "solr.kerberos.name.rules",+ "RULE:[1:$1@$0](.*EXAMPLE.COM)s/@.*//"+ "\nRULE:[2:$2@$0](.*EXAMPLE.COM)s/@.*//"- + "\nDEFAULT"- );+ + "\nDEFAULT");return tmp;}/**- * This method stops the Hadoop mini-kdc instance as well as cleanup relevant Java system properties.+ * This method stops the Hadoop mini-kdc instance as well as cleanup relevant Java system+ * properties.** @param kerberosTestServices An instance of Hadoop mini-kdc*/diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/LocaleTest.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/LocaleTest.javaindex 20f3caba3ad..cb29a1ab4fd 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/LocaleTest.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/LocaleTest.java@@ -16,18 +16,6 @@*/package org.apache.solr.security.hadoop;-import org.apache.hadoop.minikdc.MiniKdc;-import org.apache.lucene.util.LuceneTestCase;-import org.apache.solr.SolrTestCase;-import org.apache.solr.util.LogLevel;-import org.junit.Test;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import javax.security.auth.login.AppConfigurationEntry;-import javax.security.auth.login.Configuration;-import javax.security.auth.login.LoginContext;-import javax.security.auth.login.LoginException;import java.io.File;import java.lang.invoke.MethodHandles;import java.nio.file.Path;@@ -37,6 +25,17 @@ import java.util.Locale;import java.util.Map;import java.util.Properties;import java.util.stream.Collectors;+import javax.security.auth.login.AppConfigurationEntry;+import javax.security.auth.login.Configuration;+import javax.security.auth.login.LoginContext;+import javax.security.auth.login.LoginException;+import org.apache.hadoop.minikdc.MiniKdc;+import org.apache.lucene.util.LuceneTestCase;+import org.apache.solr.SolrTestCase;+import org.apache.solr.util.LogLevel;+import org.junit.Test;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;@LuceneTestCase.SuppressSysoutChecks(bugUrl = "https://issues.apache.org/jira/browse/DIRKRB-753")@LogLevel("org.apache.kerby=WARN")@@ -56,23 +55,32 @@ public class LocaleTest extends SolrTestCase {kdc.start();kdc.createPrincipal(keytabFile, principal);- AppConfigurationEntry appConfigEntry = new AppConfigurationEntry(- KerberosTestServices.krb5LoginModuleName,- AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,- Map.of("principal", principal,- "storeKey", "true",- "useKeyTab", "true",- "useTicketCache", "false",- "refreshKrb5Config", "true",- "keyTab", keytabFile.getAbsolutePath(),- "keytab", keytabFile.getAbsolutePath())- );- Configuration configuration = new Configuration() {- @Override- public AppConfigurationEntry[] getAppConfigurationEntry(String name) {- return new AppConfigurationEntry[]{appConfigEntry};- }- };+ AppConfigurationEntry appConfigEntry =+ new AppConfigurationEntry(+ KerberosTestServices.krb5LoginModuleName,+ AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,+ Map.of(+ "principal",+ principal,+ "storeKey",+ "true",+ "useKeyTab",+ "true",+ "useTicketCache",+ "false",+ "refreshKrb5Config",+ "true",+ "keyTab",+ keytabFile.getAbsolutePath(),+ "keytab",+ keytabFile.getAbsolutePath()));+ Configuration configuration =+ new Configuration() {+ @Override+ public AppConfigurationEntry[] getAppConfigurationEntry(String name) {+ return new AppConfigurationEntry[] {appConfigEntry};+ }+ };List<Locale> locales = new ArrayList<>();for (Locale locale : Locale.getAvailableLocales()) {@@ -83,7 +91,9 @@ public class LocaleTest extends SolrTestCase {locales.add(locale);}}- log.error("Could not login with locales {}", locales.stream().collect(Collectors.groupingBy(Locale::getLanguage)));+ log.error(+ "Could not login with locales {}",+ locales.stream().collect(Collectors.groupingBy(Locale::getLanguage)));kdc.stop();}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/SaslZkACLProviderTest.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/SaslZkACLProviderTest.javaindex 1dbe2b00d78..530aab2914e 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/SaslZkACLProviderTest.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/SaslZkACLProviderTest.java@@ -16,13 +16,13 @@*/package org.apache.solr.security.hadoop;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.nio.file.Path;-import org.apache.lucene.util.Constants;import org.apache.lucene.util.QuickPatchThreadsFilter;import org.apache.solr.SolrIgnoredThreadsFilter;@@ -45,13 +45,13 @@ import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;--@ThreadLeakFilters(defaultFilters = true, filters = {- SolrIgnoredThreadsFilter.class,- QuickPatchThreadsFilter.class,- BadZookeeperThreadsFilter.class-})+@ThreadLeakFilters(+ defaultFilters = true,+ filters = {+ SolrIgnoredThreadsFilter.class,+ QuickPatchThreadsFilter.class,+ BadZookeeperThreadsFilter.class+ })public class SaslZkACLProviderTest extends SolrTestCaseJ4 {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());@@ -62,12 +62,12 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() {- assumeFalse("FIXME: SOLR-7040: This test fails under IBM J9",- Constants.JAVA_VENDOR.startsWith("IBM"));+ assumeFalse(+ "FIXME: SOLR-7040: This test fails under IBM J9", Constants.JAVA_VENDOR.startsWith("IBM"));System.setProperty("solrcloud.skip.autorecovery", "true");System.setProperty("hostName", "localhost");}-+@AfterClasspublic static void afterClass() {System.clearProperty("solrcloud.skip.autorecovery");@@ -89,8 +89,10 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {System.setProperty("zkHost", zkServer.getZkAddress());- try (SolrZkClient zkClient = new SolrZkClientWithACLs(zkServer.getZkHost(), AbstractZkTestCase.TIMEOUT)) {- ZooKeeperSaslClient saslClient = zkClient.getSolrZooKeeper().getConnection().zooKeeperSaslClient;+ try (SolrZkClient zkClient =+ new SolrZkClientWithACLs(zkServer.getZkHost(), AbstractZkTestCase.TIMEOUT)) {+ ZooKeeperSaslClient saslClient =+ zkClient.getSolrZooKeeper().getConnection().zooKeeperSaslClient;assumeFalse("Could not set up ZK with SASL", saslClient.isFailed());zkClient.makePath("/solr", false, true);} catch (KeeperException e) {@@ -105,19 +107,37 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {}protected void setupZNodes() throws Exception {- SolrZkClient zkClient = new SolrZkClientWithACLs(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);+ SolrZkClient zkClient =+ new SolrZkClientWithACLs(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);try {- zkClient.create("/protectedCreateNode", "content".getBytes(DATA_ENCODING), CreateMode.PERSISTENT, false);- zkClient.makePath("/protectedMakePathNode", "content".getBytes(DATA_ENCODING), CreateMode.PERSISTENT, false);- zkClient.create(SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH, "content".getBytes(DATA_ENCODING), CreateMode.PERSISTENT, false);+ zkClient.create(+ "/protectedCreateNode", "content".getBytes(DATA_ENCODING), CreateMode.PERSISTENT, false);+ zkClient.makePath(+ "/protectedMakePathNode",+ "content".getBytes(DATA_ENCODING),+ CreateMode.PERSISTENT,+ false);+ zkClient.create(+ SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH,+ "content".getBytes(DATA_ENCODING),+ CreateMode.PERSISTENT,+ false);} finally {zkClient.close();}zkClient = new SolrZkClientNoACLs(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);try {- zkClient.create("/unprotectedCreateNode", "content".getBytes(DATA_ENCODING), CreateMode.PERSISTENT, false);- zkClient.makePath("/unprotectedMakePathNode", "content".getBytes(DATA_ENCODING), CreateMode.PERSISTENT, false);+ zkClient.create(+ "/unprotectedCreateNode",+ "content".getBytes(DATA_ENCODING),+ CreateMode.PERSISTENT,+ false);+ zkClient.makePath(+ "/unprotectedMakePathNode",+ "content".getBytes(DATA_ENCODING),+ CreateMode.PERSISTENT,+ false);} finally {zkClient.close();}@@ -133,12 +153,12 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {@Testpublic void testSaslZkACLProvider() throws Exception {// Test with Sasl enabled- SolrZkClient zkClient = new SolrZkClientWithACLs(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);+ SolrZkClient zkClient =+ new SolrZkClientWithACLs(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);try {- AbstractVMParamsZkACLAndCredentialsProvidersTestBase.doTest(zkClient,- true, true, true, true, true,- true, true, true, true, true);- } finally {+ AbstractVMParamsZkACLAndCredentialsProvidersTestBase.doTest(+ zkClient, true, true, true, true, true, true, true, true, true, true);+ } finally {zkClient.close();}@@ -147,18 +167,15 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {System.setProperty("zookeeper.sasl.client", "false");zkClient = new SolrZkClientNoACLs(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);try {- AbstractVMParamsZkACLAndCredentialsProvidersTestBase.doTest(zkClient,- true, true, false, false, false,- false, false, false, false, false);+ AbstractVMParamsZkACLAndCredentialsProvidersTestBase.doTest(+ zkClient, true, true, false, false, false, false, false, false, false, false);} finally {zkClient.close();System.clearProperty("zookeeper.sasl.client");}}- /**- * A SolrZKClient that adds Sasl ACLs- */+ /** A SolrZKClient that adds Sasl ACLs */private static class SolrZkClientWithACLs extends SolrZkClient {public SolrZkClientWithACLs(String zkServerAddress, int zkClientTimeout) {@@ -171,9 +188,7 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {}}- /**- * A SolrZKClient that doesn't add ACLs- */+ /** A SolrZKClient that doesn't add ACLs */private static class SolrZkClientNoACLs extends SolrZkClient {public SolrZkClientNoACLs(String zkServerAddress, int zkClientTimeout) {@@ -186,9 +201,7 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {}}- /**- * A ZkTestServer with Sasl support- */+ /** A ZkTestServer with Sasl support */public static class SaslZkTestServer extends ZkTestServer {private final Path kdcDir;private KerberosTestServices kerberosTestServices;@@ -209,14 +222,17 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {String zkClientPrincipal = "solr";String zkServerPrincipal = "zookeeper/localhost";- kerberosTestServices = KerberosTestServices.builder()- .withKdc(kdcDir.toFile())- .withDebug() // SOLR-15366- .withJaasConfiguration(zkClientPrincipal, keytabFile, zkServerPrincipal, keytabFile)- .build();+ kerberosTestServices =+ KerberosTestServices.builder()+ .withKdc(kdcDir.toFile())+ .withDebug() // SOLR-15366+ .withJaasConfiguration(zkClientPrincipal, keytabFile, zkServerPrincipal, keytabFile)+ .build();kerberosTestServices.start();- kerberosTestServices.getKdc().createPrincipal(keytabFile, zkClientPrincipal, zkServerPrincipal);+ kerberosTestServices+ .getKdc()+ .createPrincipal(keytabFile, zkClientPrincipal, zkServerPrincipal);} catch (Exception ex) {throw new RuntimeException(ex);}@@ -229,8 +245,7 @@ public class SaslZkACLProviderTest extends SolrTestCaseJ4 {System.clearProperty("zookeeper.kerberos.removeRealmFromPrincipal");System.clearProperty("zookeeper.kerberos.removeHostFromPrincipal");super.shutdown();- if (kerberosTestServices != null)- kerberosTestServices.stop();+ if (kerberosTestServices != null) kerberosTestServices.stop();}}}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestDelegationWithHadoopAuth.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestDelegationWithHadoopAuth.javaindex 86737bbb3f3..46c1bd68c48 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestDelegationWithHadoopAuth.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestDelegationWithHadoopAuth.java@@ -20,7 +20,6 @@ import java.util.Collections;import java.util.HashSet;import java.util.Optional;import java.util.Set;-import org.apache.hadoop.security.authentication.client.PseudoAuthenticator;import org.apache.hadoop.util.Time;import org.apache.http.HttpStatus;@@ -55,18 +54,16 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {public static void setupClass() throws Exception {HadoopTestUtil.checkAssumptions();- configureCluster(NUM_SERVERS)// nodes- .withSecurityJson(TEST_PATH().resolve("security").resolve("hadoop_simple_auth_with_delegation.json"))+ configureCluster(NUM_SERVERS) // nodes+ .withSecurityJson(+ TEST_PATH().resolve("security").resolve("hadoop_simple_auth_with_delegation.json")).configure();JettySolrRunner runnerPrimary = cluster.getJettySolrRunners().get(0);- primarySolrClient =- new HttpSolrClient.Builder(runnerPrimary.getBaseUrl().toString())- .build();+ primarySolrClient = new HttpSolrClient.Builder(runnerPrimary.getBaseUrl().toString()).build();JettySolrRunner runnerSecondary = cluster.getJettySolrRunners().get(1);secondarySolrClient =- new HttpSolrClient.Builder(runnerSecondary.getBaseUrl().toString())- .build();+ new HttpSolrClient.Builder(runnerSecondary.getBaseUrl().toString()).build();}@AfterClass@@ -82,36 +79,40 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}}- private String getDelegationToken(final String renewer, final String user, HttpSolrClient solrClient) throws Exception {- DelegationTokenRequest.Get get = new DelegationTokenRequest.Get(renewer) {- @Override- public SolrParams getParams() {- ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());- params.set(PseudoAuthenticator.USER_NAME, user);- return params;- }- };+ private String getDelegationToken(+ final String renewer, final String user, HttpSolrClient solrClient) throws Exception {+ DelegationTokenRequest.Get get =+ new DelegationTokenRequest.Get(renewer) {+ @Override+ public SolrParams getParams() {+ ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());+ params.set(PseudoAuthenticator.USER_NAME, user);+ return params;+ }+ };DelegationTokenResponse.Get getResponse = get.process(solrClient);return getResponse.getDelegationToken();}- private long renewDelegationToken(final String token, final int expectedStatusCode,- final String user, HttpSolrClient client) throws Exception {- DelegationTokenRequest.Renew renew = new DelegationTokenRequest.Renew(token) {- @Override- public SolrParams getParams() {- ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());- params.set(PseudoAuthenticator.USER_NAME, user);- return params;- }-- @Override- public Set<String> getQueryParams() {- Set<String> queryParams = super.getQueryParams();- queryParams.add(PseudoAuthenticator.USER_NAME);- return queryParams;- }- };+ private long renewDelegationToken(+ final String token, final int expectedStatusCode, final String user, HttpSolrClient client)+ throws Exception {+ DelegationTokenRequest.Renew renew =+ new DelegationTokenRequest.Renew(token) {+ @Override+ public SolrParams getParams() {+ ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());+ params.set(PseudoAuthenticator.USER_NAME, user);+ return params;+ }++ @Override+ public Set<String> getQueryParams() {+ Set<String> queryParams = super.getQueryParams();+ queryParams.add(PseudoAuthenticator.USER_NAME);+ return queryParams;+ }+ };try {DelegationTokenResponse.Renew renewResponse = renew.process(client);assertEquals(HttpStatus.SC_OK, expectedStatusCode);@@ -123,7 +124,7 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}private void cancelDelegationToken(String token, int expectedStatusCode, HttpSolrClient client)- throws Exception {+ throws Exception {DelegationTokenRequest.Cancel cancel = new DelegationTokenRequest.Cancel(token);try {cancel.process(client);@@ -134,12 +135,12 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}private void doSolrRequest(String token, int expectedStatusCode, HttpSolrClient client)- throws Exception {+ throws Exception {doSolrRequest(token, expectedStatusCode, client, 1);}- private void doSolrRequest(String token, int expectedStatusCode, HttpSolrClient client, int trials)- throws Exception {+ private void doSolrRequest(+ String token, int expectedStatusCode, HttpSolrClient client, int trials) throws Exception {int lastStatusCode = 0;for (int i = 0; i < trials; ++i) {lastStatusCode = getStatusCode(token, null, null, client);@@ -163,21 +164,26 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}private int getStatusCode(String token, final String user, final String op, HttpSolrClient client)- throws Exception {+ throws Exception {SolrClient delegationTokenClient;- if (random().nextBoolean()) delegationTokenClient = new HttpSolrClient.Builder(client.getBaseURL().toString())- .withKerberosDelegationToken(token)- .withResponseParser(client.getParser())- .build();- else delegationTokenClient = new CloudSolrClient.Builder(Collections.singletonList(cluster.getZkServer().getZkAddress()), Optional.empty())- .withLBHttpSolrClientBuilder(new LBHttpSolrClient.Builder()- .withResponseParser(client.getParser())- .withSocketTimeout(30000).withConnectionTimeout(15000)- .withHttpSolrClientBuilder(- new HttpSolrClient.Builder()- .withKerberosDelegationToken(token)- ))- .build();+ if (random().nextBoolean())+ delegationTokenClient =+ new HttpSolrClient.Builder(client.getBaseURL().toString())+ .withKerberosDelegationToken(token)+ .withResponseParser(client.getParser())+ .build();+ else+ delegationTokenClient =+ new CloudSolrClient.Builder(+ Collections.singletonList(cluster.getZkServer().getZkAddress()), Optional.empty())+ .withLBHttpSolrClientBuilder(+ new LBHttpSolrClient.Builder()+ .withResponseParser(client.getParser())+ .withSocketTimeout(30000)+ .withConnectionTimeout(15000)+ .withHttpSolrClientBuilder(+ new HttpSolrClient.Builder().withKerberosDelegationToken(token)))+ .build();try {ModifiableSolrParams p = new ModifiableSolrParams();if (user != null) p.set(PseudoAuthenticator.USER_NAME, user);@@ -200,9 +206,8 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}}- private void doSolrRequest(SolrClient client,- SolrRequest<?> request,- int expectedStatusCode) throws Exception {+ private void doSolrRequest(SolrClient client, SolrRequest<?> request, int expectedStatusCode)+ throws Exception {try {client.request(request);assertEquals(HttpStatus.SC_OK, expectedStatusCode);@@ -212,7 +217,7 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}private void verifyTokenValid(String token) throws Exception {- // pass with token+ // pass with tokendoSolrRequest(token, HttpStatus.SC_OK, primarySolrClient);// fail without token@@ -225,9 +230,7 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {doSolrRequest(null, ErrorCode.UNAUTHORIZED.code, secondarySolrClient);}- /**- * Test basic Delegation Token get/verify- */+ /** Test basic Delegation Token get/verify */@Testpublic void testDelegationTokenVerify() throws Exception {// Get token@@ -294,8 +297,7 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}}- private void verifyDelegationTokenRenew(String renewer, String user)- throws Exception {+ private void verifyDelegationTokenRenew(String renewer, String user) throws Exception {{// renew on same serverString token = getDelegationToken(renewer, user, primarySolrClient);@@ -316,7 +318,9 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}@Test-// commented 4-Sep-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 2-Aug-2018+ // commented 4-Sep-2018+ // @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") //+ // 2-Aug-2018public void testDelegationTokenRenew() throws Exception {// test with specifying renewerverifyDelegationTokenRenew(USER_1, USER_1);@@ -340,12 +344,11 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {renewDelegationToken(token, ErrorCode.FORBIDDEN.code, "notRenewUser", secondarySolrClient);}- /**- * Test that a non-delegation-token "op" http param is handled correctly- */+ /** Test that a non-delegation-token "op" http param is handled correctly */@Testpublic void testDelegationOtherOp() throws Exception {- assertEquals(HttpStatus.SC_OK, getStatusCode(null, USER_1, "someSolrOperation", primarySolrClient));+ assertEquals(+ HttpStatus.SC_OK, getStatusCode(null, USER_1, "someSolrOperation", primarySolrClient));}@Test@@ -360,9 +363,7 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {}}- /**- * Test HttpSolrServer's delegation token support- */+ /** Test HttpSolrServer's delegation token support */@Testpublic void testDelegationTokenSolrClient() throws Exception {// Get token@@ -382,17 +383,20 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {ss.close();}- try (HttpSolrClient client = new HttpSolrClient.Builder(primarySolrClient.getBaseURL())- .withKerberosDelegationToken(token)- .withResponseParser(primarySolrClient.getParser())- .build()) {+ try (HttpSolrClient client =+ new HttpSolrClient.Builder(primarySolrClient.getBaseURL())+ .withKerberosDelegationToken(token)+ .withResponseParser(primarySolrClient.getParser())+ .build()) {// test with token via propertydoSolrRequest(client, request, HttpStatus.SC_OK);// test with param -- should throw an exceptionModifiableSolrParams tokenParam = new ModifiableSolrParams();tokenParam.set("delegation", "invalidToken");- expectThrows(IllegalArgumentException.class, () -> doSolrRequest(client, getAdminRequest(tokenParam), ErrorCode.FORBIDDEN.code));+ expectThrows(+ IllegalArgumentException.class,+ () -> doSolrRequest(client, getAdminRequest(tokenParam), ErrorCode.FORBIDDEN.code));}}}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestImpersonationWithHadoopAuth.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestImpersonationWithHadoopAuth.javaindex 91db855974e..61964e1a9c6 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestImpersonationWithHadoopAuth.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestImpersonationWithHadoopAuth.java@@ -16,13 +16,17 @@*/package org.apache.solr.security.hadoop;+import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.USER_PARAM;+import static org.apache.solr.security.hadoop.ImpersonationUtil.getExpectedGroupExMsg;+import static org.apache.solr.security.hadoop.ImpersonationUtil.getExpectedHostExMsg;+import static org.apache.solr.security.hadoop.ImpersonationUtil.getProxyRequest;+import java.net.InetAddress;import java.nio.charset.Charset;import java.nio.file.Files;import java.nio.file.Path;import java.util.HashMap;import java.util.Map;-import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.embedded.JettySolrRunner;import org.apache.solr.client.solrj.impl.BaseHttpSolrClient;@@ -36,12 +40,7 @@ import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;-import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.USER_PARAM;-import static org.apache.solr.security.hadoop.ImpersonationUtil.getExpectedGroupExMsg;-import static org.apache.solr.security.hadoop.ImpersonationUtil.getExpectedHostExMsg;-import static org.apache.solr.security.hadoop.ImpersonationUtil.getProxyRequest;--public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {+public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {protected static final int NUM_SERVERS = 2;private static final boolean defaultAddRequestHeadersToContext =SolrRequestParsers.DEFAULT.isAddRequestHeadersToContext();@@ -52,25 +51,34 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {HadoopTestUtil.checkAssumptions();InetAddress loopback = InetAddress.getLoopbackAddress();- Path securityJsonPath = TEST_PATH().resolve("security").resolve("hadoop_simple_auth_with_delegation.json");- String securityJson = new String(Files.readAllBytes(securityJsonPath), Charset.defaultCharset());-- Map<String, Object> securityConfig = (Map<String, Object>)Utils.fromJSONString(securityJson);- Map<String, Object> authConfig = (Map<String, Object>)securityConfig.get("authentication");- Map<String,String> proxyUserConfigs = (Map<String,String>) authConfig- .getOrDefault(HadoopAuthPlugin.PROXY_USER_CONFIGS, new HashMap<>());+ Path securityJsonPath =+ TEST_PATH().resolve("security").resolve("hadoop_simple_auth_with_delegation.json");+ String securityJson =+ new String(Files.readAllBytes(securityJsonPath), Charset.defaultCharset());++ Map<String, Object> securityConfig = (Map<String, Object>) Utils.fromJSONString(securityJson);+ Map<String, Object> authConfig = (Map<String, Object>) securityConfig.get("authentication");+ Map<String, String> proxyUserConfigs =+ (Map<String, String>)+ authConfig.getOrDefault(HadoopAuthPlugin.PROXY_USER_CONFIGS, new HashMap<>());proxyUserConfigs.put("proxyuser.noGroups.hosts", "*");proxyUserConfigs.put("proxyuser.anyHostAnyUser.hosts", "*");proxyUserConfigs.put("proxyuser.anyHostAnyUser.groups", "*");proxyUserConfigs.put("proxyuser.wrongHost.hosts", DEAD_HOST_1);proxyUserConfigs.put("proxyuser.wrongHost.groups", "*");proxyUserConfigs.put("proxyuser.noHosts.groups", "*");- proxyUserConfigs.put("proxyuser.localHostAnyGroup.hosts",- loopback.getCanonicalHostName() + "," + loopback.getHostName() + "," + loopback.getHostAddress());+ proxyUserConfigs.put(+ "proxyuser.localHostAnyGroup.hosts",+ loopback.getCanonicalHostName()+ + ","+ + loopback.getHostName()+ + ","+ + loopback.getHostAddress());proxyUserConfigs.put("proxyuser.localHostAnyGroup.groups", "*");proxyUserConfigs.put("proxyuser.bogusGroup.hosts", "*");proxyUserConfigs.put("proxyuser.bogusGroup.groups", "__some_bogus_group");- proxyUserConfigs.put("proxyuser.anyHostUsersGroup.groups", ImpersonationUtil.getUsersFirstGroup());+ proxyUserConfigs.put(+ "proxyuser.anyHostUsersGroup.groups", ImpersonationUtil.getUsersFirstGroup());proxyUserConfigs.put("proxyuser.anyHostUsersGroup.hosts", "*");authConfig.put(HadoopAuthPlugin.PROXY_USER_CONFIGS, proxyUserConfigs);@@ -78,9 +86,10 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {SolrRequestParsers.DEFAULT.setAddRequestHeadersToContext(true);System.setProperty("collectionsHandler", ImpersonatorCollectionsHandler.class.getName());- configureCluster(NUM_SERVERS)// nodes+ configureCluster(NUM_SERVERS) // nodes.withSecurityJson(Utils.toJSONString(securityConfig))- .addConfig("conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf"))+ .addConfig(+ "conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf")).configure();}@@ -91,24 +100,30 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {}private SolrClient newSolrClient() {- return new HttpSolrClient.Builder(- cluster.getJettySolrRunner(0).getBaseUrl().toString()).build();+ return new HttpSolrClient.Builder(cluster.getJettySolrRunner(0).getBaseUrl().toString())+ .build();}@Testpublic void testProxyNoConfigGroups() throws Exception {try (SolrClient solrClient = newSolrClient()) {- BaseHttpSolrClient.RemoteSolrException ex = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("noGroups","bar")));- assertTrue(ex.getLocalizedMessage(), ex.getMessage().contains(getExpectedGroupExMsg("noGroups", "bar")));+ BaseHttpSolrClient.RemoteSolrException ex =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("noGroups", "bar")));+ assertTrue(+ ex.getLocalizedMessage(),+ ex.getMessage().contains(getExpectedGroupExMsg("noGroups", "bar")));}}@Testpublic void testProxyWrongHost() throws Exception {try (SolrClient solrClient = newSolrClient()) {- BaseHttpSolrClient.RemoteSolrException ex = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("wrongHost","bar")));+ BaseHttpSolrClient.RemoteSolrException ex =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("wrongHost", "bar")));assertTrue(ex.getMessage().contains(getExpectedHostExMsg("wrongHost")));}}@@ -116,8 +131,10 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {@Testpublic void testProxyNoConfigHosts() throws Exception {try (SolrClient solrClient = newSolrClient()) {- BaseHttpSolrClient.RemoteSolrException ex = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("noHosts","bar")));+ BaseHttpSolrClient.RemoteSolrException ex =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("noHosts", "bar")));assertTrue(ex.getMessage().contains(getExpectedHostExMsg("noHosts")));}}@@ -134,8 +151,10 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {public void testProxyInvalidProxyUser() throws Exception {try (SolrClient solrClient = newSolrClient()) {// wrong direction, should fail- BaseHttpSolrClient.RemoteSolrException ex = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("bar","anyHostAnyUser")));+ BaseHttpSolrClient.RemoteSolrException ex =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("bar", "anyHostAnyUser")));assertTrue(ex.getMessage().contains(getExpectedGroupExMsg("bar", "anyHostAnyUser")));}}@@ -159,8 +178,10 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {@Testpublic void testProxyInvalidGroup() throws Exception {try (SolrClient solrClient = newSolrClient()) {- BaseHttpSolrClient.RemoteSolrException ex = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("bogusGroup","bar")));+ BaseHttpSolrClient.RemoteSolrException ex =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("bogusGroup", "bar")));assertTrue(ex.getMessage().contains(getExpectedGroupExMsg("bogusGroup", "bar")));}}@@ -168,18 +189,20 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {@Testpublic void testProxyNullProxyUser() throws Exception {try (SolrClient solrClient = newSolrClient()) {- expectThrows(BaseHttpSolrClient.RemoteSolrException.class, () -> solrClient.request(getProxyRequest("","bar")));+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("", "bar")));}}@Test- @AwaitsFix(bugUrl="https://issues.apache.org/jira/browse/HADOOP-9893")+ @AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/HADOOP-9893")public void testForwarding() throws Exception {String collectionName = "forwardingCollection";// create collection- CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection(collectionName, "conf1",- 1, 1);+ CollectionAdminRequest.Create create =+ CollectionAdminRequest.createCollection(collectionName, "conf1", 1, 1);try (SolrClient solrClient = newSolrClient()) {create.process(solrClient);}@@ -187,7 +210,8 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {// try a command to each node, one of them must be forwardedfor (JettySolrRunner jetty : cluster.getJettySolrRunners()) {try (HttpSolrClient client =- new HttpSolrClient.Builder(jetty.getBaseUrl().toString() + "/" + collectionName).build()) {+ new HttpSolrClient.Builder(jetty.getBaseUrl().toString() + "/" + collectionName)+ .build()) {ModifiableSolrParams params = new ModifiableSolrParams();params.set("q", "*:*");params.set(USER_PARAM, "user");@@ -195,5 +219,4 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {}}}-}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestRuleBasedAuthorizationWithKerberos.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestRuleBasedAuthorizationWithKerberos.javaindex ec3a6134662..72c64e32bf4 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestRuleBasedAuthorizationWithKerberos.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestRuleBasedAuthorizationWithKerberos.java@@ -36,84 +36,90 @@ import org.junit.Test;@LogLevel("org.apache.solr.security=DEBUG")public class TestRuleBasedAuthorizationWithKerberos extends SolrCloudTestCase {- protected static final int NUM_SERVERS = 2;- protected static final int NUM_SHARDS = 1;- protected static final int REPLICATION_FACTOR = 1;- private static KerberosTestServices kerberosTestServices;-- private String collectionName;-- @BeforeClass- public static void setupClass() throws Exception {- assumeFalse("Hadoop does not work on Windows", Constants.WINDOWS);-- kerberosTestServices = KerberosUtils.setupMiniKdc(createTempDir());-- configureCluster(NUM_SERVERS)// nodes- .withSecurityJson(TEST_PATH().resolve("security").resolve("hadoop_kerberos_authz_config.json"))- .addConfig("conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf"))- .configure();- }-- @AfterClass- public static void tearDownClass() {- KerberosUtils.cleanupMiniKdc(kerberosTestServices);- kerberosTestServices = null;- }-- @Before- @Override- public void setUp() throws Exception {- super.setUp();- collectionName = getSaferTestName();-- // create collection- CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection(collectionName, "conf1",- NUM_SHARDS, REPLICATION_FACTOR);- create.process(cluster.getSolrClient());- cluster.waitForActiveCollection(collectionName, 1, 1);- }-- @Test- public void testReadsAltUser() throws Exception {- String authorizedColl = "public";-- // create collection- CollectionAdminRequest.createCollection(authorizedColl, "conf1", NUM_SHARDS, REPLICATION_FACTOR)- .process(cluster.getSolrClient());- cluster.waitForActiveCollection(authorizedColl, 1, 1);-- final SolrQuery q = new SolrQuery("*:*");-- for (JettySolrRunner jsr : cluster.getJettySolrRunners()) {- final String baseUrl = jsr.getBaseUrl().toString();- try (Http2SolrClient client = new Http2SolrClient.Builder(baseUrl).build()) {- Krb5HttpClientUtils.setup(client, "solr_alt");- assertEquals(0, client.query(authorizedColl, q).getStatus());- BaseHttpSolrClient.RemoteSolrException e = assertThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> client.query(collectionName, q));- assertEquals(403, e.code());- }- }- }-- @Test- public void testCollectionCreateSearchDelete() throws Exception {- CloudSolrClient solrClient = cluster.getSolrClient();-- SolrInputDocument doc = new SolrInputDocument();- doc.setField("id", "1");- solrClient.add(collectionName, doc);- solrClient.commit(collectionName);-- SolrQuery query = new SolrQuery();- query.setQuery("*:*");- QueryResponse rsp = solrClient.query(collectionName, query);- assertEquals(1, rsp.getResults().getNumFound());-- CollectionAdminRequest.Delete deleteReq = CollectionAdminRequest.deleteCollection(collectionName);- deleteReq.process(solrClient);- AbstractDistribZkTestBase.waitForCollectionToDisappear(collectionName,- solrClient.getZkStateReader(), true, 330);+ protected static final int NUM_SERVERS = 2;+ protected static final int NUM_SHARDS = 1;+ protected static final int REPLICATION_FACTOR = 1;+ private static KerberosTestServices kerberosTestServices;++ private String collectionName;++ @BeforeClass+ public static void setupClass() throws Exception {+ assumeFalse("Hadoop does not work on Windows", Constants.WINDOWS);++ kerberosTestServices = KerberosUtils.setupMiniKdc(createTempDir());++ configureCluster(NUM_SERVERS) // nodes+ .withSecurityJson(+ TEST_PATH().resolve("security").resolve("hadoop_kerberos_authz_config.json"))+ .addConfig(+ "conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf"))+ .configure();+ }++ @AfterClass+ public static void tearDownClass() {+ KerberosUtils.cleanupMiniKdc(kerberosTestServices);+ kerberosTestServices = null;+ }++ @Before+ @Override+ public void setUp() throws Exception {+ super.setUp();+ collectionName = getSaferTestName();++ // create collection+ CollectionAdminRequest.Create create =+ CollectionAdminRequest.createCollection(+ collectionName, "conf1", NUM_SHARDS, REPLICATION_FACTOR);+ create.process(cluster.getSolrClient());+ cluster.waitForActiveCollection(collectionName, 1, 1);+ }++ @Test+ public void testReadsAltUser() throws Exception {+ String authorizedColl = "public";++ // create collection+ CollectionAdminRequest.createCollection(authorizedColl, "conf1", NUM_SHARDS, REPLICATION_FACTOR)+ .process(cluster.getSolrClient());+ cluster.waitForActiveCollection(authorizedColl, 1, 1);++ final SolrQuery q = new SolrQuery("*:*");++ for (JettySolrRunner jsr : cluster.getJettySolrRunners()) {+ final String baseUrl = jsr.getBaseUrl().toString();+ try (Http2SolrClient client = new Http2SolrClient.Builder(baseUrl).build()) {+ Krb5HttpClientUtils.setup(client, "solr_alt");+ assertEquals(0, client.query(authorizedColl, q).getStatus());+ BaseHttpSolrClient.RemoteSolrException e =+ assertThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> client.query(collectionName, q));+ assertEquals(403, e.code());+ }}+ }++ @Test+ public void testCollectionCreateSearchDelete() throws Exception {+ CloudSolrClient solrClient = cluster.getSolrClient();++ SolrInputDocument doc = new SolrInputDocument();+ doc.setField("id", "1");+ solrClient.add(collectionName, doc);+ solrClient.commit(collectionName);++ SolrQuery query = new SolrQuery();+ query.setQuery("*:*");+ QueryResponse rsp = solrClient.query(collectionName, query);+ assertEquals(1, rsp.getResults().getNumFound());++ CollectionAdminRequest.Delete deleteReq =+ CollectionAdminRequest.deleteCollection(collectionName);+ deleteReq.process(solrClient);+ AbstractDistribZkTestBase.waitForCollectionToDisappear(+ collectionName, solrClient.getZkStateReader(), true, 330);+ }}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithDelegationTokens.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithDelegationTokens.javaindex 02c1df879b9..796beb9072e 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithDelegationTokens.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithDelegationTokens.java@@ -16,12 +16,13 @@*/package org.apache.solr.security.hadoop;+import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.USER_PARAM;+import java.lang.invoke.MethodHandles;import java.util.Collections;import java.util.HashSet;import java.util.Optional;import java.util.Set;-import org.apache.hadoop.util.Time;import org.apache.http.HttpStatus;import org.apache.lucene.util.LuceneTestCase;@@ -52,11 +53,7 @@ import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.USER_PARAM;--/**- * Test the delegation token support in the {@link KerberosPlugin}.- */+/** Test the delegation token support in the {@link KerberosPlugin}. */@LuceneTestCase.Slowpublic class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());@@ -73,13 +70,10 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {miniCluster = new MiniSolrCloudCluster(NUM_SERVERS, createTempDir(), buildJettyConfig("/solr"));JettySolrRunner runnerPrimary = miniCluster.getJettySolrRunners().get(0);- solrClientPrimary =- new HttpSolrClient.Builder(runnerPrimary.getBaseUrl().toString())- .build();+ solrClientPrimary = new HttpSolrClient.Builder(runnerPrimary.getBaseUrl().toString()).build();JettySolrRunner runnerSecondary = miniCluster.getJettySolrRunners().get(1);solrClientSecondary =- new HttpSolrClient.Builder(runnerSecondary.getBaseUrl().toString())- .build();+ new HttpSolrClient.Builder(runnerSecondary.getBaseUrl().toString()).build();}@AfterClass@@ -101,36 +95,40 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {System.clearProperty("solr.kerberos.cookie.domain");}- private String getDelegationToken(final String renewer, final String user, HttpSolrClient solrClient) throws Exception {- DelegationTokenRequest.Get get = new DelegationTokenRequest.Get(renewer) {- @Override- public SolrParams getParams() {- ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());- params.set(USER_PARAM, user);- return params;- }- };+ private String getDelegationToken(+ final String renewer, final String user, HttpSolrClient solrClient) throws Exception {+ DelegationTokenRequest.Get get =+ new DelegationTokenRequest.Get(renewer) {+ @Override+ public SolrParams getParams() {+ ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());+ params.set(USER_PARAM, user);+ return params;+ }+ };DelegationTokenResponse.Get getResponse = get.process(solrClient);return getResponse.getDelegationToken();}- private long renewDelegationToken(final String token, final int expectedStatusCode,- final String user, HttpSolrClient client) throws Exception {- DelegationTokenRequest.Renew renew = new DelegationTokenRequest.Renew(token) {- @Override- public SolrParams getParams() {- ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());- params.set(USER_PARAM, user);- return params;- }-- @Override- public Set<String> getQueryParams() {- Set<String> queryParams = super.getQueryParams();- queryParams.add(USER_PARAM);- return queryParams;- }- };+ private long renewDelegationToken(+ final String token, final int expectedStatusCode, final String user, HttpSolrClient client)+ throws Exception {+ DelegationTokenRequest.Renew renew =+ new DelegationTokenRequest.Renew(token) {+ @Override+ public SolrParams getParams() {+ ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());+ params.set(USER_PARAM, user);+ return params;+ }++ @Override+ public Set<String> getQueryParams() {+ Set<String> queryParams = super.getQueryParams();+ queryParams.add(USER_PARAM);+ return queryParams;+ }+ };try {DelegationTokenResponse.Renew renewResponse = renew.process(client);assertEquals(HttpStatus.SC_OK, expectedStatusCode);@@ -142,7 +140,7 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}private void cancelDelegationToken(String token, int expectedStatusCode, HttpSolrClient client)- throws Exception {+ throws Exception {DelegationTokenRequest.Cancel cancel = new DelegationTokenRequest.Cancel(token);try {cancel.process(client);@@ -153,12 +151,12 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}private void doSolrRequest(String token, int expectedStatusCode, HttpSolrClient client)- throws Exception {+ throws Exception {doSolrRequest(token, expectedStatusCode, client, 1);}- private void doSolrRequest(String token, int expectedStatusCode, HttpSolrClient client, int trials)- throws Exception {+ private void doSolrRequest(+ String token, int expectedStatusCode, HttpSolrClient client, int trials) throws Exception {int lastStatusCode = 0;for (int i = 0; i < trials; ++i) {lastStatusCode = getStatusCode(token, null, null, client);@@ -180,6 +178,7 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}};}+private SolrRequest<UpdateResponse> getUpdateRequest(boolean commit) {UpdateRequest request = new UpdateRequest();if (commit) {@@ -192,21 +191,27 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}private int getStatusCode(String token, final String user, final String op, HttpSolrClient client)- throws Exception {+ throws Exception {SolrClient delegationTokenClient;- if (random().nextBoolean()) delegationTokenClient = new HttpSolrClient.Builder(client.getBaseURL().toString())- .withKerberosDelegationToken(token)- .withResponseParser(client.getParser())- .build();- else delegationTokenClient = new CloudSolrClient.Builder(Collections.singletonList(miniCluster.getZkServer().getZkAddress()), Optional.empty())- .withLBHttpSolrClientBuilder(new LBHttpSolrClient.Builder()- .withSocketTimeout(30000).withConnectionTimeout(15000)- .withResponseParser(client.getParser())- .withHttpSolrClientBuilder(- new HttpSolrClient.Builder()- .withKerberosDelegationToken(token)- ))- .build();+ if (random().nextBoolean())+ delegationTokenClient =+ new HttpSolrClient.Builder(client.getBaseURL().toString())+ .withKerberosDelegationToken(token)+ .withResponseParser(client.getParser())+ .build();+ else+ delegationTokenClient =+ new CloudSolrClient.Builder(+ Collections.singletonList(miniCluster.getZkServer().getZkAddress()),+ Optional.empty())+ .withLBHttpSolrClientBuilder(+ new LBHttpSolrClient.Builder()+ .withSocketTimeout(30000)+ .withConnectionTimeout(15000)+ .withResponseParser(client.getParser())+ .withHttpSolrClientBuilder(+ new HttpSolrClient.Builder().withKerberosDelegationToken(token)))+ .build();try {ModifiableSolrParams p = new ModifiableSolrParams();if (user != null) p.set(USER_PARAM, user);@@ -229,9 +234,8 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}}- private void doSolrRequest(HttpSolrClient client,- SolrRequest<?> request,- int expectedStatusCode) throws Exception {+ private void doSolrRequest(HttpSolrClient client, SolrRequest<?> request, int expectedStatusCode)+ throws Exception {try {client.request(request);assertEquals(HttpStatus.SC_OK, expectedStatusCode);@@ -240,9 +244,9 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}}- private void doSolrRequest(HttpSolrClient client,- SolrRequest<?> request, String collectionName,- int expectedStatusCode) throws Exception {+ private void doSolrRequest(+ HttpSolrClient client, SolrRequest<?> request, String collectionName, int expectedStatusCode)+ throws Exception {try {client.request(request, collectionName);assertEquals(HttpStatus.SC_OK, expectedStatusCode);@@ -252,7 +256,7 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}private void verifyTokenValid(String token) throws Exception {- // pass with token+ // pass with tokendoSolrRequest(token, HttpStatus.SC_OK, solrClientPrimary);// fail without token@@ -265,9 +269,7 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {doSolrRequest(null, ErrorCode.UNAUTHORIZED.code, solrClientSecondary);}- /**- * Test basic Delegation Token get/verify- */+ /** Test basic Delegation Token get/verify */@Testpublic void testDelegationTokenVerify() throws Exception {final String user = "bar";@@ -336,8 +338,7 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}}- private void verifyDelegationTokenRenew(String renewer, String user)- throws Exception {+ private void verifyDelegationTokenRenew(String renewer, String user) throws Exception {{// renew on same serverString token = getDelegationToken(renewer, user, solrClientPrimary);@@ -358,7 +359,8 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}@Test- //commented 20-Sep-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 23-Aug-2018+ // commented 20-Sep-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") //+ // added 23-Aug-2018public void testDelegationTokenRenew() throws Exception {// test with specifying renewerverifyDelegationTokenRenew("bar", "bar");@@ -382,12 +384,11 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {renewDelegationToken(token, ErrorCode.FORBIDDEN.code, "notRenewUser", solrClientSecondary);}- /**- * Test that a non-delegation-token "op" http param is handled correctly- */+ /** Test that a non-delegation-token "op" http param is handled correctly */@Testpublic void testDelegationOtherOp() throws Exception {- assertEquals(HttpStatus.SC_OK, getStatusCode(null, "bar", "someSolrOperation", solrClientPrimary));+ assertEquals(+ HttpStatus.SC_OK, getStatusCode(null, "bar", "someSolrOperation", solrClientPrimary));}@Test@@ -402,9 +403,7 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {}}- /**- * Test HttpSolrServer's delegation token support- */+ /** Test HttpSolrServer's delegation token support */@Testpublic void testDelegationTokenSolrClient() throws Exception {// Get token@@ -415,19 +414,20 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {// test without tokenfinal HttpSolrClient ssWoToken =- new HttpSolrClient.Builder(solrClientPrimary.getBaseURL().toString())- .withResponseParser(solrClientPrimary.getParser())- .build();+ new HttpSolrClient.Builder(solrClientPrimary.getBaseURL().toString())+ .withResponseParser(solrClientPrimary.getParser())+ .build();try {doSolrRequest(ssWoToken, request, ErrorCode.UNAUTHORIZED.code);} finally {ssWoToken.close();}- final HttpSolrClient ssWToken = new HttpSolrClient.Builder(solrClientPrimary.getBaseURL().toString())- .withKerberosDelegationToken(token)- .withResponseParser(solrClientPrimary.getParser())- .build();+ final HttpSolrClient ssWToken =+ new HttpSolrClient.Builder(solrClientPrimary.getBaseURL().toString())+ .withKerberosDelegationToken(token)+ .withResponseParser(solrClientPrimary.getParser())+ .build();try {// test with token via propertydoSolrRequest(ssWToken, request, HttpStatus.SC_OK);@@ -435,16 +435,15 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {// test with param -- should throw an exceptionModifiableSolrParams tokenParam = new ModifiableSolrParams();tokenParam.set("delegation", "invalidToken");- expectThrows(IllegalArgumentException.class,+ expectThrows(+ IllegalArgumentException.class,() -> doSolrRequest(ssWToken, getAdminRequest(tokenParam), ErrorCode.FORBIDDEN.code));} finally {ssWToken.close();}}- /**- * Test HttpSolrServer's delegation token support for Update Requests- */+ /** Test HttpSolrServer's delegation token support for Update Requests */@Testpublic void testDelegationTokenSolrClientWithUpdateRequests() throws Exception {String collectionName = "testDelegationTokensWithUpdate";@@ -454,16 +453,20 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {assertNotNull(token);// Tests with update request.- // Before SOLR-13921, the request without commit will fail with a NullpointerException in DelegationTokenHttpSolrClient.createMethod- // due to a missing null check in the createMethod. (When requesting a commit, the setAction method will call setParams on the+ // Before SOLR-13921, the request without commit will fail with a NullpointerException in+ // DelegationTokenHttpSolrClient.createMethod+ // due to a missing null check in the createMethod. (When requesting a commit, the setAction+ // method will call setParams on the// request so there is no NPE in the createMethod.)- final HttpSolrClient scUpdateWToken = new HttpSolrClient.Builder(solrClientPrimary.getBaseURL().toString())- .withKerberosDelegationToken(token)- .withResponseParser(solrClientPrimary.getParser())- .build();+ final HttpSolrClient scUpdateWToken =+ new HttpSolrClient.Builder(solrClientPrimary.getBaseURL().toString())+ .withKerberosDelegationToken(token)+ .withResponseParser(solrClientPrimary.getParser())+ .build();// Create collection- CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection(collectionName, 1, 1);+ CollectionAdminRequest.Create create =+ CollectionAdminRequest.createCollection(collectionName, 1, 1);create.process(scUpdateWToken);try {@@ -479,5 +482,4 @@ public class TestSolrCloudWithDelegationTokens extends SolrTestCaseJ4 {scUpdateWToken.close();}}-}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.javaindex 1030aed6d22..009f3ddd06d 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.java@@ -39,9 +39,10 @@ public class TestSolrCloudWithHadoopAuthPlugin extends SolrCloudAuthTestCase {kerberosTestServices = KerberosUtils.setupMiniKdc(createTempDir());- configureCluster(NUM_SERVERS)// nodes+ configureCluster(NUM_SERVERS) // nodes.withSecurityJson(TEST_PATH().resolve("security").resolve("hadoop_kerberos_config.json"))- .addConfig("conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf"))+ .addConfig(+ "conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf")).withDefaultClusterProperty("useLegacyReplicaAssignment", "false").configure();}@@ -64,10 +65,11 @@ public class TestSolrCloudWithHadoopAuthPlugin extends SolrCloudAuthTestCase {String collectionName = "testkerberoscollection";// create collection- CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection(collectionName, "conf1",- NUM_SHARDS, REPLICATION_FACTOR);+ CollectionAdminRequest.Create create =+ CollectionAdminRequest.createCollection(+ collectionName, "conf1", NUM_SHARDS, REPLICATION_FACTOR);create.process(solrClient);- // The metrics counter for wrong credentials here really just means+ // The metrics counter for wrong credentials here really just meansassertAuthMetricsMinimums(2, 1, 0, 1, 0, 0);SolrInputDocument doc = new SolrInputDocument();@@ -81,10 +83,11 @@ public class TestSolrCloudWithHadoopAuthPlugin extends SolrCloudAuthTestCase {QueryResponse rsp = solrClient.query(collectionName, query);assertEquals(1, rsp.getResults().getNumFound());- CollectionAdminRequest.Delete deleteReq = CollectionAdminRequest.deleteCollection(collectionName);+ CollectionAdminRequest.Delete deleteReq =+ CollectionAdminRequest.deleteCollection(collectionName);deleteReq.process(solrClient);- AbstractDistribZkTestBase.waitForCollectionToDisappear(collectionName,- solrClient.getZkStateReader(), true, 330);+ AbstractDistribZkTestBase.waitForCollectionToDisappear(+ collectionName, solrClient.getZkStateReader(), true, 330);// cookie was used to avoid re-authenticationassertAuthMetricsMinimums(6, 4, 0, 2, 0, 0);}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithKerberosAlt.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithKerberosAlt.javaindex 698d8a6f633..1a84589bd72 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithKerberosAlt.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithKerberosAlt.java@@ -16,13 +16,11 @@*/package org.apache.solr.security.hadoop;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;import java.io.File;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;--import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;-import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;-import org.apache.commons.io.FileUtils;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.QuickPatchThreadsFilter;@@ -39,15 +37,14 @@ import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-/**- * Test 5 nodes Solr cluster with Kerberos plugin enabled.- */-@ThreadLeakFilters(defaultFilters = true, filters = {- SolrIgnoredThreadsFilter.class,- QuickPatchThreadsFilter.class,- BadZookeeperThreadsFilter.class // Zookeeper login leaks TGT renewal threads-})-+/** Test 5 nodes Solr cluster with Kerberos plugin enabled. */+@ThreadLeakFilters(+ defaultFilters = true,+ filters = {+ SolrIgnoredThreadsFilter.class,+ QuickPatchThreadsFilter.class,+ BadZookeeperThreadsFilter.class // Zookeeper login leaks TGT renewal threads+ })@LuceneTestCase.Slow@ThreadLeakLingering(linger = 10000) // minikdc has some lingering threadspublic class TestSolrCloudWithKerberosAlt extends SolrCloudTestCase {@@ -56,10 +53,10 @@ public class TestSolrCloudWithKerberosAlt extends SolrCloudTestCase {private static final int numShards = 1;private static final int numReplicas = 1;- private static final int nodeCount = numShards*numReplicas;+ private static final int nodeCount = numShards * numReplicas;private static final String configName = "solrCloudCollectionConfig";private static final String collectionName = "testkerberoscollection";-+private KerberosTestServices kerberosTestServices;@Override@@ -71,32 +68,41 @@ public class TestSolrCloudWithKerberosAlt extends SolrCloudTestCase {private void setupMiniKdc() throws Exception {System.setProperty("solr.jaas.debug", "true");- String kdcDir = createTempDir()+File.separator+"minikdc";+ String kdcDir = createTempDir() + File.separator + "minikdc";String solrClientPrincipal = "solr";File keytabFile = new File(kdcDir, "keytabs");- kerberosTestServices = KerberosTestServices.builder()- .withKdc(new File(kdcDir))- .withJaasConfiguration(solrClientPrincipal, keytabFile, "SolrClient")- .build();+ kerberosTestServices =+ KerberosTestServices.builder()+ .withKdc(new File(kdcDir))+ .withJaasConfiguration(solrClientPrincipal, keytabFile, "SolrClient")+ .build();String solrServerPrincipal = "HTTP/127.0.0.1";kerberosTestServices.start();- kerberosTestServices.getKdc().createPrincipal(keytabFile, solrServerPrincipal, solrClientPrincipal);-- String jaas = "SolrClient {\n"- + " com.sun.security.auth.module.Krb5LoginModule required\n"- + " useKeyTab=true\n"- + " keyTab=\"" + keytabFile.getAbsolutePath() + "\"\n"- + " storeKey=true\n"- + " useTicketCache=false\n"- + " doNotPrompt=true\n"- + " debug=true\n"- + " principal=\"" + solrClientPrincipal + "\";\n"- + "};";-- String jaasFilePath = kdcDir+File.separator+"jaas-client.conf";+ kerberosTestServices+ .getKdc()+ .createPrincipal(keytabFile, solrServerPrincipal, solrClientPrincipal);++ String jaas =+ "SolrClient {\n"+ + " com.sun.security.auth.module.Krb5LoginModule required\n"+ + " useKeyTab=true\n"+ + " keyTab=\""+ + keytabFile.getAbsolutePath()+ + "\"\n"+ + " storeKey=true\n"+ + " useTicketCache=false\n"+ + " doNotPrompt=true\n"+ + " debug=true\n"+ + " principal=\""+ + solrClientPrincipal+ + "\";\n"+ + "};";++ String jaasFilePath = kdcDir + File.separator + "jaas-client.conf";FileUtils.write(new File(jaasFilePath), jaas, StandardCharsets.UTF_8);System.setProperty("java.security.auth.login.config", jaasFilePath);- System.setProperty("solr.kerberos.jaas.appname", "SolrClient"); // Get this app name from the jaas file+ System.setProperty(+ "solr.kerberos.jaas.appname", "SolrClient"); // Get this app name from the jaas fileSystem.setProperty("solr.kerberos.cookie.domain", "127.0.0.1");System.setProperty("solr.kerberos.principal", solrServerPrincipal);System.setProperty("solr.kerberos.keytab", keytabFile.getAbsolutePath());@@ -105,10 +111,11 @@ public class TestSolrCloudWithKerberosAlt extends SolrCloudTestCase {log.info("Enable delegation token: {}", enableDt);System.setProperty("solr.kerberos.delegation.token.enabled", Boolean.toString(enableDt));// Extracts 127.0.0.1 from HTTP/[email protected]- System.setProperty("solr.kerberos.name.rules", "RULE:[1:$1@$0](.*EXAMPLE.COM)s/@.*//"- + "\nRULE:[2:$2@$0](.*EXAMPLE.COM)s/@.*//"- + "\nDEFAULT"- );+ System.setProperty(+ "solr.kerberos.name.rules",+ "RULE:[1:$1@$0](.*EXAMPLE.COM)s/@.*//"+ + "\nRULE:[2:$2@$0](.*EXAMPLE.COM)s/@.*//"+ + "\nDEFAULT");// more debugging, if needed// System.setProperty("sun.security.jgss.debug", "true");@@ -116,7 +123,7 @@ public class TestSolrCloudWithKerberosAlt extends SolrCloudTestCase {// System.setProperty("sun.security.jgss.debug", "true");// System.setProperty("java.security.debug", "logincontext,policy,scl,gssloginconfig");}-+@Testpublic void testBasics() throws Exception {testCollectionCreateSearchDelete();@@ -135,12 +142,12 @@ public class TestSolrCloudWithKerberosAlt extends SolrCloudTestCase {new UpdateRequest().add("id", "1").commit(client, collectionName);QueryResponse rsp = client.query(collectionName, new SolrQuery("*:*"));assertEquals(1, rsp.getResults().getNumFound());-+// delete the collection we created earlierCollectionAdminRequest.deleteCollection(collectionName).process(client);-- AbstractDistribZkTestBase.waitForCollectionToDisappear- (collectionName, client.getZkStateReader(), true, 330);++ AbstractDistribZkTestBase.waitForCollectionToDisappear(+ collectionName, client.getZkStateReader(), true, 330);}@Override@@ -154,7 +161,7 @@ public class TestSolrCloudWithKerberosAlt extends SolrCloudTestCase {System.clearProperty("authenticationPlugin");System.clearProperty("solr.kerberos.delegation.token.enabled");System.clearProperty("solr.kerberos.name.rules");-+// more debugging, if needed// System.clearProperty("sun.security.jgss.debug");// System.clearProperty("sun.security.krb5.debug");diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithSecureImpersonation.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithSecureImpersonation.javaindex 22a9f68e267..0801b2d506b 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithSecureImpersonation.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithSecureImpersonation.java@@ -16,13 +16,16 @@*/package org.apache.solr.security.hadoop;-import javax.servlet.http.HttpServletRequest;+import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.REMOTE_ADDRESS_PARAM;+import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.REMOTE_HOST_PARAM;+import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.USER_PARAM;+import java.net.InetAddress;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.concurrent.atomic.AtomicBoolean;-+import javax.servlet.http.HttpServletRequest;import org.apache.hadoop.conf.Configuration;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.SolrClient;@@ -46,10 +49,6 @@ import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;-import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.REMOTE_ADDRESS_PARAM;-import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.REMOTE_HOST_PARAM;-import static org.apache.solr.security.hadoop.HttpParamDelegationTokenPlugin.USER_PARAM;-public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {private static final int NUM_SERVERS = 2;private static MiniSolrCloudCluster miniCluster;@@ -80,9 +79,15 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {filterProps.put(KerberosPlugin.IMPERSONATOR_PREFIX + "noHosts.groups", "*");filterProps.put(KerberosPlugin.IMPERSONATOR_PREFIX + "localHostAnyGroup.groups", "*");InetAddress loopback = InetAddress.getLoopbackAddress();- filterProps.put(KerberosPlugin.IMPERSONATOR_PREFIX + "localHostAnyGroup.hosts",- loopback.getCanonicalHostName() + "," + loopback.getHostName() + "," + loopback.getHostAddress());- filterProps.put(KerberosPlugin.IMPERSONATOR_PREFIX + "anyHostUsersGroup.groups", getUsersFirstGroup());+ filterProps.put(+ KerberosPlugin.IMPERSONATOR_PREFIX + "localHostAnyGroup.hosts",+ loopback.getCanonicalHostName()+ + ","+ + loopback.getHostName()+ + ","+ + loopback.getHostAddress());+ filterProps.put(+ KerberosPlugin.IMPERSONATOR_PREFIX + "anyHostUsersGroup.groups", getUsersFirstGroup());filterProps.put(KerberosPlugin.IMPERSONATOR_PREFIX + "anyHostUsersGroup.hosts", "*");filterProps.put(KerberosPlugin.IMPERSONATOR_PREFIX + "bogusGroup.groups", "__some_bogus_group");filterProps.put(KerberosPlugin.IMPERSONATOR_PREFIX + "bogusGroup.hosts", "*");@@ -92,7 +97,7 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {@BeforeClasspublic static void startup() throws Exception {HadoopTestUtil.checkAssumptions();-+System.setProperty("authenticationPlugin", HttpParamDelegationTokenPlugin.class.getName());System.setProperty(KerberosPlugin.DELEGATION_TOKEN_ENABLED, "true");@@ -112,13 +117,13 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {solrClient = new HttpSolrClient.Builder(runner.getBaseUrl().toString()).build();}- /**- * Verify that impersonator info is preserved in the request- */+ /** Verify that impersonator info is preserved in the request */public static class ImpersonatorCollectionsHandler extends CollectionsHandler {public static AtomicBoolean called = new AtomicBoolean(false);- public ImpersonatorCollectionsHandler() { super(); }+ public ImpersonatorCollectionsHandler() {+ super();+ }public ImpersonatorCollectionsHandler(final CoreContainer coreContainer) {super(coreContainer);@@ -130,9 +135,9 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {super.handleRequestBody(req, rsp);String doAs = req.getParams().get(KerberosPlugin.IMPERSONATOR_DO_AS_HTTP_PARAM);if (doAs != null) {- HttpServletRequest httpRequest = (HttpServletRequest)req.getContext().get("httpRequest");+ HttpServletRequest httpRequest = (HttpServletRequest) req.getContext().get("httpRequest");assertNotNull(httpRequest);- String user = (String)httpRequest.getAttribute(USER_PARAM);+ String user = (String) httpRequest.getAttribute(USER_PARAM);assertNotNull(user);assertEquals(user, httpRequest.getAttribute(KerberosPlugin.IMPERSONATOR_USER_NAME));}@@ -171,20 +176,22 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {}}- private void create1ShardCollection(String name, String config, MiniSolrCloudCluster solrCluster) throws Exception {+ private void create1ShardCollection(String name, String config, MiniSolrCloudCluster solrCluster)+ throws Exception {CollectionAdminResponse response;- CollectionAdminRequest.Create create = new CollectionAdminRequest.Create(name,config,1,1,0,0) {- @Override- public SolrParams getParams() {- ModifiableSolrParams msp = new ModifiableSolrParams(super.getParams());- msp.set(USER_PARAM, "user");- return msp;- }- };+ CollectionAdminRequest.Create create =+ new CollectionAdminRequest.Create(name, config, 1, 1, 0, 0) {+ @Override+ public SolrParams getParams() {+ ModifiableSolrParams msp = new ModifiableSolrParams(super.getParams());+ msp.set(USER_PARAM, "user");+ return msp;+ }+ };response = create.process(solrCluster.getSolrClient());miniCluster.waitForActiveCollection(name, 1, 1);-+if (response.getStatus() != 0 || response.getErrorMessages() != null) {fail("Could not create collection. Response" + response.toString());}@@ -198,7 +205,8 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {return getProxyRequest(user, doAs, remoteHost, null);}- private SolrRequest<?> getProxyRequest(String user, String doAs, String remoteHost, String remoteAddress) {+ private SolrRequest<?> getProxyRequest(+ String user, String doAs, String remoteHost, String remoteAddress) {return new CollectionAdminRequest.List() {@Overridepublic SolrParams getParams() {@@ -222,25 +230,28 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {@Testpublic void testProxyNoConfigGroups() {- BaseHttpSolrClient.RemoteSolrException e = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("noGroups","bar"))- );+ BaseHttpSolrClient.RemoteSolrException e =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("noGroups", "bar")));assertTrue(e.getMessage().contains(getExpectedGroupExMsg("noGroups", "bar")));}@Testpublic void testProxyWrongHost() {- BaseHttpSolrClient.RemoteSolrException e = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("wrongHost","bar"))- );+ BaseHttpSolrClient.RemoteSolrException e =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("wrongHost", "bar")));assertTrue(e.getMessage().contains(getExpectedHostExMsg("wrongHost")));}@Testpublic void testProxyNoConfigHosts() {- BaseHttpSolrClient.RemoteSolrException e = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("noHosts","bar"))- );+ BaseHttpSolrClient.RemoteSolrException e =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("noHosts", "bar")));assertTrue(e.getMessage().contains(getExpectedHostExMsg("noHosts")));}@@ -253,9 +264,10 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {@Testpublic void testProxyInvalidProxyUser() {// wrong direction, should fail- BaseHttpSolrClient.RemoteSolrException e = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("bar","anyHostAnyUser"))- );+ BaseHttpSolrClient.RemoteSolrException e =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("bar", "anyHostAnyUser")));assertTrue(e.getMessage().contains(getExpectedGroupExMsg("bar", "anyHostAnyUser")));}@@ -265,8 +277,6 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {assertTrue(ImpersonatorCollectionsHandler.called.get());}--@Testpublic void testProxyValidateGroup() throws Exception {solrClient.request(getProxyRequest("anyHostUsersGroup", System.getProperty("user.name"), null));@@ -275,37 +285,48 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {@Testpublic void testProxyUnknownRemote() {- BaseHttpSolrClient.RemoteSolrException e = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> {- // Use a reserved ip address- String nonProxyUserConfiguredIpAddress = "255.255.255.255";- solrClient.request(getProxyRequest("localHostAnyGroup", "bar", "unknownhost.bar.foo", nonProxyUserConfiguredIpAddress));- });+ BaseHttpSolrClient.RemoteSolrException e =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> {+ // Use a reserved ip address+ String nonProxyUserConfiguredIpAddress = "255.255.255.255";+ solrClient.request(+ getProxyRequest(+ "localHostAnyGroup",+ "bar",+ "unknownhost.bar.foo",+ nonProxyUserConfiguredIpAddress));+ });assertTrue(e.getMessage().contains(getExpectedHostExMsg("localHostAnyGroup")));}@Testpublic void testProxyInvalidRemote() {- BaseHttpSolrClient.RemoteSolrException e = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> {- solrClient.request(getProxyRequest("localHostAnyGroup","bar", "[ff01::114]", "[::1]"));- });+ BaseHttpSolrClient.RemoteSolrException e =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> {+ solrClient.request(+ getProxyRequest("localHostAnyGroup", "bar", "[ff01::114]", "[::1]"));+ });assertTrue(e.getMessage().contains(getExpectedHostExMsg("localHostAnyGroup")));}@Testpublic void testProxyInvalidGroup() {- BaseHttpSolrClient.RemoteSolrException e = expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("bogusGroup","bar", null))- );+ BaseHttpSolrClient.RemoteSolrException e =+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("bogusGroup", "bar", null)));assertTrue(e.getMessage().contains(getExpectedGroupExMsg("bogusGroup", "bar")));}@Testpublic void testProxyNullProxyUser() {- expectThrows(BaseHttpSolrClient.RemoteSolrException.class,- () -> solrClient.request(getProxyRequest("","bar"))- );+ expectThrows(+ BaseHttpSolrClient.RemoteSolrException.class,+ () -> solrClient.request(getProxyRequest("", "bar")));}@Test@@ -316,8 +337,9 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {// try a command to each node, one of them must be forwardedfor (JettySolrRunner jetty : miniCluster.getJettySolrRunners()) {- try (HttpSolrClient client = new HttpSolrClient.Builder(- jetty.getBaseUrl().toString() + "/" + collectionName).build()) {+ try (HttpSolrClient client =+ new HttpSolrClient.Builder(jetty.getBaseUrl().toString() + "/" + collectionName)+ .build()) {ModifiableSolrParams params = new ModifiableSolrParams();params.set("q", "*:*");params.set(USER_PARAM, "user");diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestZkAclsWithHadoopAuth.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestZkAclsWithHadoopAuth.javaindex 26e2a6a8711..95a7c69a253 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestZkAclsWithHadoopAuth.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestZkAclsWithHadoopAuth.java@@ -26,7 +26,6 @@ import java.security.NoSuchAlgorithmException;import java.util.List;import java.util.Locale;import java.util.concurrent.TimeUnit;-import org.apache.solr.cloud.MiniSolrCloudCluster;import org.apache.solr.cloud.SolrCloudTestCase;import org.apache.solr.common.cloud.SecurityAwareZkACLProvider;@@ -49,26 +48,30 @@ public class TestZkAclsWithHadoopAuth extends SolrCloudTestCase {protected static final int REPLICATION_FACTOR = 1;private static final String SOLR_PASSWD = "solr";private static final String FOO_PASSWD = "foo";- private static final Id SOLR_ZK_ID = new Id("digest", digest ("solr", SOLR_PASSWD));- private static final Id FOO_ZK_ID = new Id("digest", digest ("foo", FOO_PASSWD));+ private static final Id SOLR_ZK_ID = new Id("digest", digest("solr", SOLR_PASSWD));+ private static final Id FOO_ZK_ID = new Id("digest", digest("foo", FOO_PASSWD));@BeforeClasspublic static void setupClass() throws Exception {HadoopTestUtil.checkAssumptions();- System.setProperty(SolrZkClient.ZK_ACL_PROVIDER_CLASS_NAME_VM_PARAM_NAME,+ System.setProperty(+ SolrZkClient.ZK_ACL_PROVIDER_CLASS_NAME_VM_PARAM_NAME,VMParamsAllAndReadonlyDigestZkACLProvider.class.getName());- System.setProperty(SolrZkClient.ZK_CRED_PROVIDER_CLASS_NAME_VM_PARAM_NAME,+ System.setProperty(+ SolrZkClient.ZK_CRED_PROVIDER_CLASS_NAME_VM_PARAM_NAME,VMParamsSingleSetCredentialsDigestZkCredentialsProvider.class.getName());System.setProperty(DEFAULT_DIGEST_USERNAME_VM_PARAM_NAME, "solr");System.setProperty(DEFAULT_DIGEST_PASSWORD_VM_PARAM_NAME, SOLR_PASSWD);System.setProperty(DEFAULT_DIGEST_READONLY_USERNAME_VM_PARAM_NAME, "foo");System.setProperty(DEFAULT_DIGEST_READONLY_PASSWORD_VM_PARAM_NAME, FOO_PASSWD);- configureCluster(NUM_SERVERS)// nodes+ configureCluster(NUM_SERVERS) // nodes.withSolrXml(MiniSolrCloudCluster.DEFAULT_CLOUD_SOLR_XML)- .withSecurityJson(TEST_PATH().resolve("security").resolve("hadoop_simple_auth_with_delegation.json"))- .addConfig("conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf"))+ .withSecurityJson(+ TEST_PATH().resolve("security").resolve("hadoop_simple_auth_with_delegation.json"))+ .addConfig(+ "conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf")).configure();}@@ -85,8 +88,13 @@ public class TestZkAclsWithHadoopAuth extends SolrCloudTestCase {@Test@SuppressWarnings({"try"})public void testZkAcls() throws Exception {- try (ZooKeeper keeper = new ZooKeeper(cluster.getZkServer().getZkAddress(),- (int) TimeUnit.MINUTES.toMillis(1), arg0 -> {/* Do nothing */})) {+ try (ZooKeeper keeper =+ new ZooKeeper(+ cluster.getZkServer().getZkAddress(),+ (int) TimeUnit.MINUTES.toMillis(1),+ arg0 -> {+ /* Do nothing */+ })) {keeper.addAuthInfo("digest", ("solr:" + SOLR_PASSWD).getBytes(StandardCharsets.UTF_8));// Test well known paths.@@ -101,7 +109,7 @@ public class TestZkAclsWithHadoopAuth extends SolrCloudTestCase {}}- private void walkZkTree (ZooKeeper keeper, String zkChroot, String path) throws Exception {+ private void walkZkTree(ZooKeeper keeper, String zkChroot, String path) throws Exception {if (isSecurityZNode(zkChroot, path)) {checkSecurityACLs(keeper, path);} else {@@ -130,7 +138,7 @@ public class TestZkAclsWithHadoopAuth extends SolrCloudTestCase {assertTrue(message, acls.contains(new ACL(ZooDefs.Perms.ALL, SOLR_ZK_ID)));}- private void checkNonSecurityACLs(ZooKeeper keeper, String path) throws Exception {+ private void checkNonSecurityACLs(ZooKeeper keeper, String path) throws Exception {List<ACL> acls = keeper.getACL(path, new Stat());String message = String.format(Locale.ROOT, "Path %s ACLs found %s", path, acls);assertEquals(message, 2, acls.size());@@ -138,9 +146,9 @@ public class TestZkAclsWithHadoopAuth extends SolrCloudTestCase {assertTrue(message, acls.contains(new ACL(ZooDefs.Perms.READ, FOO_ZK_ID)));}- private static String digest (String userName, String passwd) {+ private static String digest(String userName, String passwd) {try {- return DigestAuthenticationProvider.generateDigest(userName+":"+passwd);+ return DigestAuthenticationProvider.generateDigest(userName + ":" + passwd);} catch (NoSuchAlgorithmException ex) {throw new RuntimeException(ex);}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/util/configuration/SSLConfigurationsTest.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/util/configuration/SSLConfigurationsTest.javaindex 4e096910eb0..dc174330b36 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/util/configuration/SSLConfigurationsTest.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/util/configuration/SSLConfigurationsTest.java@@ -26,13 +26,12 @@ import java.io.IOException;import java.util.Arrays;import java.util.HashMap;import java.util.Map;-import org.apache.hadoop.conf.Configuration;import org.apache.lucene.util.TestRuleRestoreSystemProperties;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.util.configuration.providers.EnvSSLCredentialProvider;-import org.apache.solr.util.configuration.providers.hadoop.HadoopSSLCredentialProvider;import org.apache.solr.util.configuration.providers.SysPropSSLCredentialProvider;+import org.apache.solr.util.configuration.providers.hadoop.HadoopSSLCredentialProvider;import org.junit.Before;import org.junit.Rule;import org.junit.Test;@@ -47,14 +46,15 @@ public class SSLConfigurationsTest {public static final String SAMPLE_PW2 = "pw456";public static final String SAMPLE_PW3 = "pw789";public static final String KEY_STORE_PASSWORD = SSLConfigurations.SysProps.SSL_KEY_STORE_PASSWORD;- public static final String CLIENT_KEY_STORE_PASSWORD = SSLConfigurations.SysProps.SSL_CLIENT_KEY_STORE_PASSWORD;+ public static final String CLIENT_KEY_STORE_PASSWORD =+ SSLConfigurations.SysProps.SSL_CLIENT_KEY_STORE_PASSWORD;@Rule- public TestRule syspropRestore = new TestRuleRestoreSystemProperties(- SSLConfigurations.SysProps.SSL_KEY_STORE_PASSWORD,- SSLConfigurations.SysProps.SSL_CLIENT_KEY_STORE_PASSWORD,- CREDENTIAL_PROVIDER_PATH- );+ public TestRule syspropRestore =+ new TestRuleRestoreSystemProperties(+ SSLConfigurations.SysProps.SSL_KEY_STORE_PASSWORD,+ SSLConfigurations.SysProps.SSL_CLIENT_KEY_STORE_PASSWORD,+ CREDENTIAL_PROVIDER_PATH);@Beforepublic void setUp() {@@ -64,62 +64,78 @@ public class SSLConfigurationsTest {private SSLConfigurations createSut(Configuration mockHadoopConfiguration) {EnvSSLCredentialProvider envSSLCredentialProvider = new EnvSSLCredentialProvider();envSSLCredentialProvider.setEnvVars(envs);- sut = new SSLConfigurations(Arrays.asList(- new HadoopSSLCredentialProvider(mockHadoopConfiguration),- envSSLCredentialProvider,- new SysPropSSLCredentialProvider())- );+ sut =+ new SSLConfigurations(+ Arrays.asList(+ new HadoopSSLCredentialProvider(mockHadoopConfiguration),+ envSSLCredentialProvider,+ new SysPropSSLCredentialProvider()));return sut;}@Testpublic void testSslConfigKeystorePwFromKeystoreHadoopCredentialProvider() throws IOException {- getSutWithMockedHadoopCredentialProvider(SSLConfigurations.SysProps.SSL_KEY_STORE_PASSWORD, SAMPLE_PW1)+ getSutWithMockedHadoopCredentialProvider(+ SSLConfigurations.SysProps.SSL_KEY_STORE_PASSWORD, SAMPLE_PW1).init();assertThat(System.getProperty(CLIENT_KEY_STORE_PASSWORD), is(SAMPLE_PW1));}@Test- public void testSslConfigKeystorePwFromClientKeystoreHadoopCredentialProvider() throws IOException {- getSutWithMockedHadoopCredentialProvider(SSLConfigurations.SysProps.SSL_CLIENT_KEY_STORE_PASSWORD, SAMPLE_PW2)+ public void testSslConfigKeystorePwFromClientKeystoreHadoopCredentialProvider()+ throws IOException {+ getSutWithMockedHadoopCredentialProvider(+ SSLConfigurations.SysProps.SSL_CLIENT_KEY_STORE_PASSWORD, SAMPLE_PW2).init();assertThat(System.getProperty(CLIENT_KEY_STORE_PASSWORD), is(SAMPLE_PW2));}@Testpublic void testGetKeyStorePasswordFromHadoopCredentialProvider() throws IOException {- SSLConfigurations sut = getSutWithMockedHadoopCredentialProvider(SSLConfigurations.SysProps.SSL_KEY_STORE_PASSWORD, SAMPLE_PW3);+ SSLConfigurations sut =+ getSutWithMockedHadoopCredentialProvider(+ SSLConfigurations.SysProps.SSL_KEY_STORE_PASSWORD, SAMPLE_PW3);assertThat(sut.getKeyStorePassword(), is(SAMPLE_PW3));}@Testpublic void testGetTruststorePasswordFromHadoopCredentialProvider() throws IOException {- SSLConfigurations sut = getSutWithMockedHadoopCredentialProvider(SSLConfigurations.SysProps.SSL_TRUST_STORE_PASSWORD, SAMPLE_PW3);+ SSLConfigurations sut =+ getSutWithMockedHadoopCredentialProvider(+ SSLConfigurations.SysProps.SSL_TRUST_STORE_PASSWORD, SAMPLE_PW3);assertThat(sut.getTrustStorePassword(), is(SAMPLE_PW3));}@Testpublic void testGetClientKeyStorePasswordFromHadoopCredentialProvider() throws IOException {- SSLConfigurations sut = getSutWithMockedHadoopCredentialProvider(SSLConfigurations.SysProps.SSL_CLIENT_KEY_STORE_PASSWORD, SAMPLE_PW3);+ SSLConfigurations sut =+ getSutWithMockedHadoopCredentialProvider(+ SSLConfigurations.SysProps.SSL_CLIENT_KEY_STORE_PASSWORD, SAMPLE_PW3);assertThat(sut.getClientKeyStorePassword(), is(SAMPLE_PW3));}@Testpublic void testGetClientTruststorePasswordFromHadoopCredentialProvider() throws IOException {- SSLConfigurations sut = getSutWithMockedHadoopCredentialProvider(SSLConfigurations.SysProps.SSL_CLIENT_TRUST_STORE_PASSWORD, SAMPLE_PW3);+ SSLConfigurations sut =+ getSutWithMockedHadoopCredentialProvider(+ SSLConfigurations.SysProps.SSL_CLIENT_TRUST_STORE_PASSWORD, SAMPLE_PW3);assertThat(sut.getClientTrustStorePassword(), is(SAMPLE_PW3));}@Testpublic void testHadoopCredentialProviderPrioritySysPropAndEnvVars() throws IOException {- SSLConfigurations sut = getSutWithMockedHadoopCredentialProvider(KEY_STORE_PASSWORD, SAMPLE_PW3);+ SSLConfigurations sut =+ getSutWithMockedHadoopCredentialProvider(KEY_STORE_PASSWORD, SAMPLE_PW3);assertThat(sut.getKeyStorePassword(), is(SAMPLE_PW3));}- private SSLConfigurations getSutWithMockedHadoopCredentialProvider(String key, String pw) throws IOException {+ private SSLConfigurations getSutWithMockedHadoopCredentialProvider(String key, String pw)+ throws IOException {Configuration mockHadoopConfiguration = getMockHadoopConfiguration();when(mockHadoopConfiguration.getPassword(key))- .then(invocationOnMock -> invocationOnMock.getArguments()[0].equals(key) ? pw.toCharArray() : null);+ .then(+ invocationOnMock ->+ invocationOnMock.getArguments()[0].equals(key) ? pw.toCharArray() : null);System.setProperty(CREDENTIAL_PROVIDER_PATH, "/some/path"); // enables HCPreturn createSut(mockHadoopConfiguration);}diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/util/configuration/providers/hadoop/HadoopSSLCredentialProviderTest.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/util/configuration/providers/hadoop/HadoopSSLCredentialProviderTest.javaindex e1d60ab749f..951c712d00b 100644--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/util/configuration/providers/hadoop/HadoopSSLCredentialProviderTest.java+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/util/configuration/providers/hadoop/HadoopSSLCredentialProviderTest.java@@ -17,9 +17,13 @@package org.apache.solr.util.configuration.providers.hadoop;+import static org.apache.hadoop.security.alias.CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH;+import static org.apache.solr.util.configuration.providers.AbstractSSLCredentialProvider.DEFAULT_CREDENTIAL_KEY_MAP;+import static org.hamcrest.core.Is.is;+import static org.junit.Assert.assertThat;+import java.io.IOException;import java.util.Map;-import org.apache.hadoop.conf.Configuration;import org.apache.lucene.util.TestRuleRestoreSystemProperties;import org.apache.solr.SolrTestCaseJ4;@@ -29,19 +33,11 @@ import org.junit.Test;import org.junit.rules.TestRule;import org.mockito.Mockito;-import static org.apache.hadoop.security.alias.CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH;-import static org.apache.solr.util.configuration.providers.AbstractSSLCredentialProvider.DEFAULT_CREDENTIAL_KEY_MAP;-import static org.hamcrest.core.Is.is;-import static org.junit.Assert.assertThat;--/**- */+/** */public class HadoopSSLCredentialProviderTest {@Rule- public TestRule syspropRestore = new TestRuleRestoreSystemProperties(- CREDENTIAL_PROVIDER_PATH- );+ public TestRule syspropRestore = new TestRuleRestoreSystemProperties(CREDENTIAL_PROVIDER_PATH);@Test(expected = RuntimeException.class)public void testConstructorRequiresCredPath() {@@ -51,17 +47,22 @@ public class HadoopSSLCredentialProviderTest {@Testpublic void testGetCredentials() throws Exception {int cnt = 0;- for (Map.Entry<SSLCredentialProvider.CredentialType, String> set : DEFAULT_CREDENTIAL_KEY_MAP.entrySet()) {+ for (Map.Entry<SSLCredentialProvider.CredentialType, String> set :+ DEFAULT_CREDENTIAL_KEY_MAP.entrySet()) {String pw = "pw" + ++cnt;- HadoopSSLCredentialProvider sut = new HadoopSSLCredentialProvider(getMockedHadoopCredentialProvider(set.getValue(), pw));+ HadoopSSLCredentialProvider sut =+ new HadoopSSLCredentialProvider(getMockedHadoopCredentialProvider(set.getValue(), pw));assertThat(sut.getCredential(set.getKey()), is(pw));}}- private Configuration getMockedHadoopCredentialProvider(String key, String pw) throws IOException {+ private Configuration getMockedHadoopCredentialProvider(String key, String pw)+ throws IOException {Configuration mockHadoopConfiguration = getMockHadoopConfiguration();Mockito.when(mockHadoopConfiguration.getPassword(key))- .then(invocationOnMock -> invocationOnMock.getArguments()[0].equals(key) ? pw.toCharArray() : null);+ .then(+ invocationOnMock ->+ invocationOnMock.getArguments()[0].equals(key) ? pw.toCharArray() : null);System.setProperty(CREDENTIAL_PROVIDER_PATH, "/some/path"); // enables HCPreturn mockHadoopConfiguration;}