This is an automated email from the ASF dual-hosted git repository. dsmiley pushed a commit to branch branch_10x in repository https://gitbox.apache.org/repos/asf/solr.git
commit 8e6865f0c199663cc2c4b2a3a606ca281f24a3ef Author: Eric Pugh <[email protected]> AuthorDate: Wed Nov 11 11:31:34 2026 -0500 SOLR-18527: Provide a example of a secure Solr using bin/solr start -e secure (#5306) Co-authored-by: Claude Sonnet 5 <[email protected]> (cherry picked from commit 780653ba4e9e65052dc7eb7baf77113a6788bbb5) --- changelog/unreleased/SOLR-18527.yml | 10 + solr/bin/solr | 12 + .../java/org/apache/solr/cli/RunExampleTool.java | 689 ++++++++++++++++++--- .../org/apache/solr/cli/TestSolrCLIRunExample.java | 37 +- solr/example/README.md | 1 + solr/packaging/build.gradle | 12 +- solr/packaging/test/test_example.bats | 14 + solr/packaging/test/test_secure_example.bats | 140 +++++ .../deployment-guide/pages/enabling-ssl.adoc | 1 + .../pages/solr-control-script-reference.adoc | 7 +- .../getting-started/getting-started-nav.adoc | 1 + .../getting-started/pages/solr-tutorial.adoc | 3 +- .../getting-started/pages/tutorial-opennlp.adoc | 2 +- .../pages/tutorial-securing-solr.adoc | 512 +++++++++++++++ 14 files changed, 1340 insertions(+), 101 deletions(-) diff --git a/changelog/unreleased/SOLR-18527.yml b/changelog/unreleased/SOLR-18527.yml new file mode 100644 index 00000000000..5ebb97e2918 --- /dev/null +++ b/changelog/unreleased/SOLR-18527.yml @@ -0,0 +1,10 @@ +title: > + Add a step-by-step tutorial and a bin/solr start -e secure example for configuring + a two-node SolrCloud cluster with self-signed PKCS12 certificates, HTTPS, Basic Authentication, + and ZooKeeper digest accounts and ACLs. +type: added +authors: + - name: Eric Pugh +links: + - name: SOLR-18527 + url: https://issues.apache.org/jira/browse/SOLR-18527 diff --git a/solr/bin/solr b/solr/bin/solr index 92d7608c8fb..617ba4bab8b 100755 --- a/solr/bin/solr +++ b/solr/bin/solr @@ -420,6 +420,7 @@ function print_usage() { echo " -e/--example <name> Name of the example to run; available examples:" echo " cloud: SolrCloud example" echo " techproducts: Comprehensive example illustrating many of Solr's core capabilities" + echo " secure: Two-node HTTPS example with Basic Authentication and ZooKeeper ACLs" echo " schemaless: Schema-less example (schema is inferred from data during indexing)" echo " films: Example of starting with _default configset and adding explicit fields dynamically" echo "" @@ -636,6 +637,17 @@ fi # Everything below here is to support start, stop and restart. +if [[ "$SCRIPT_CMD" == "start" ]]; then + # This has to re-scan the raw args rather than reuse $EXAMPLE (set further below by the + # full option-parsing loop): the ulimit check right below this runs before that loop does. + for example_arg in "$@"; do + if [[ "$example_arg" == "-e" || "$example_arg" == "--example" ]]; then + export SOLR_ULIMIT_CHECKS=false + break + fi + done +fi + #Check current Ulimits for Open Files and Max Processes. Warn if they are below the recommended values. : "${SOLR_RECOMMENDED_MAX_PROCESSES:=65000}" diff --git a/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java b/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java index e40c7bd2366..ca1850e05d3 100644 --- a/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java +++ b/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java @@ -20,12 +20,16 @@ package org.apache.solr.cli; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.Socket; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.SecureRandom; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; @@ -49,6 +53,8 @@ import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.common.SolrException; import org.apache.solr.common.util.EnvUtils; +import org.apache.solr.common.util.TimeSource; +import org.apache.solr.util.TimeOut; import org.noggit.CharArr; import org.noggit.JSONWriter; @@ -121,7 +127,8 @@ public class RunExampleTool extends ToolBase { .hasArg() .argName("NAME") .required() - .desc("Name of the example to launch, one of: cloud, techproducts, schemaless, films.") + .desc( + "Name of the example to launch, one of: cloud, secure, techproducts, schemaless, films.") .get(); /** @@ -288,7 +295,7 @@ public class RunExampleTool extends ToolBase { String jvmOpts, boolean force, String credentials, - String extraArgs) {} + List<String> extraArgs) {} /** * Parameters for running a single-node example (techproducts, schemaless or films), independent @@ -332,7 +339,7 @@ public class RunExampleTool extends ToolBase { required = true, paramLabel = "NAME", description = - "Name of the example to launch, one of: cloud, techproducts, schemaless, films.") + "Name of the example to launch, one of: cloud, secure, techproducts, schemaless, films.") private String exampleOpt; @picocli.CommandLine.Option( @@ -499,13 +506,14 @@ public class RunExampleTool extends ToolBase { + script); if (!"cloud".equals(exampleType) + && !"secure".equals(exampleType) && !"techproducts".equals(exampleType) && !"schemaless".equals(exampleType) && !"films".equals(exampleType)) { throw new IllegalArgumentException( "Unsupported example " + exampleType - + "! Please choose one of: cloud, schemaless, techproducts, or films"); + + "! Please choose one of: cloud, secure, schemaless, techproducts, or films"); } StartSolrParams startParams = @@ -523,6 +531,7 @@ public class RunExampleTool extends ToolBase { Integer.parseInt( cli.getOptionValue( PORT_OPTION, System.getenv().getOrDefault("SOLR_PORT_LISTEN", "8983"))); + validatePort(port); if ("cloud".equals(exampleType)) { runCloudExample( @@ -532,12 +541,31 @@ public class RunExampleTool extends ToolBase { zkHost, port, startParams)); + } else if ("secure".equals(exampleType)) { + runSecureExample( + new CloudExampleParams( + cli.hasOption(NO_PROMPT_OPTION), + cli.getOptionValue(SCRIPT_INPUTS_OPTION), + zkHost, + port, + startParams), + cli.hasOption(USER_MANAGED_OPTION)); } else { runExample( new RunExampleParams(!cli.hasOption(USER_MANAGED_OPTION), zkHost, port, startParams)); } } + /** + * Rejects ports outside the range bin/solr's embedded ZooKeeper (port + 1000) can support, for + * every example type. + */ + private static void validatePort(int port) { + if (port < 1024 || port > 64535) { + throw new IllegalArgumentException("Choose a port between 1024 and 64535."); + } + } + /** * Resolves and validates the server, example and Solr home directories plus the bin/solr script * from the given raw values, seeding the corresponding tool state. @@ -549,6 +577,10 @@ public class RunExampleTool extends ToolBase { String solrHomeArg, String exampleType) throws Exception { + if ("secure".equals(exampleType) && CLIUtils.isWindows()) { + throw new IllegalArgumentException( + "The secure example requires Unix or macOS; Windows is not supported."); + } serverDir = Path.of(serverDirArg); if (!Files.isDirectory(serverDir)) throw new IllegalArgumentException( @@ -597,13 +629,14 @@ public class RunExampleTool extends ToolBase { String solrHomeProp = EnvUtils.getProperty("solr.home"); if (solrHomeProp != null && !solrHomeProp.isEmpty()) { solrHomeDir = Path.of(solrHomeProp); - } else if ("cloud".equals(exampleType)) { - solrHomeDir = exampleDir.resolve("cloud"); + } else if ("cloud".equals(exampleType) || "secure".equals(exampleType)) { + solrHomeDir = exampleDir.resolve(exampleType); if (!Files.isDirectory(solrHomeDir)) Files.createDirectory(solrHomeDir); } else { solrHomeDir = serverDir.resolve("solr"); } } + if ("secure".equals(exampleType)) Files.createDirectories(solrHomeDir); if (!Files.isDirectory(solrHomeDir)) throw new IllegalArgumentException( "Value of --solr-home option is invalid! " @@ -611,6 +644,513 @@ public class RunExampleTool extends ToolBase { + " is not a directory!"); } + /** Runs the equivalent steps of the Ref Guide security tutorial */ + void runSecureExample(CloudExampleParams params, boolean userManaged) throws Exception { + StartSolrParams start = params.start(); + if (userManaged || params.zkHost() != null) { + throw new IllegalArgumentException( + "The secure example requires its own embedded ZooKeeper in SolrCloud mode."); + } + if (start.host() != null + || start.jvmOpts() != null + || !start.extraArgs().isEmpty() + || params.scriptInputs() != null + || System.getenv("SOLR_DATA_HOME") != null) { + throw new IllegalArgumentException( + "Unsupported argument provided. 'secure' example currently only supports: --solr-home," + + " -p, --no-prompt, -m, or --force."); + } + int port = params.basePort(); + String password = generateSecureExamplePassword(); + Path home = solrHomeDir.toAbsolutePath().normalize(); + echo( + "Commands below use paths relative to " + + serverDir.getParent().toAbsolutePath().normalize()); + Path tls = home.resolve("tls"); + Path include = tls.resolve("solr.in.sh"); + String zkHost = "localhost:" + (port + 1000); + Map<String, String> environment = new HashMap<>(EnvironmentUtils.getProcEnvironment()); + environment.put("SOLR_INCLUDE", include.toString()); + environment.put("SOLR_ULIMIT_CHECKS", "false"); + environment.put("SOLR_PID_DIR", home.toString()); + environment.put("SOLR_HOME", tls.toString()); + environment.remove("SOLR_ZK_CREDS_AND_ACLS"); + environment.remove("ZK_HOST"); + echo( + "Generated password: " + + password + + " (used for the keystore and all basic-auth/ZooKeeper demonstration accounts below)."); + echo("ZooKeeper is protected by digest ACLs; its transport remains plaintext on loopback."); + if (!params.noPrompt()) { + prompt( + userInputScanner(), + "Press Enter to delete and recreate " + + secureExampleDisplayArgument(home.toString()) + + ", or Ctrl-C to cancel: ", + ""); + } + resetSecureExampleHome(home, environment); + Files.setPosixFilePermissions(home, PosixFilePermissions.fromString("rwx------")); + Files.createDirectories(tls); + Files.setPosixFilePermissions(tls, PosixFilePermissions.fromString("rwx------")); + for (String node : List.of("node1", "node2")) { + Path nodeHome = Files.createDirectories(home.resolve(node).resolve("solr")); + for (String file : List.of("solr.xml", "zoo.cfg")) { + Files.copy(serverDir.resolve("solr").resolve(file), nodeHome.resolve(file)); + } + } + writeSecureExampleFile( + include, + String.format( + Locale.ROOT, + """ + SOLR_ULIMIT_CHECKS=false + SOLR_HOST_BIND=127.0.0.1 + SOLR_HOST_ADVERTISE=127.0.0.1 + SOLR_PID_DIR=%s + SOLR_OPTS=%s + """, + secureExampleShellQuote(home.toString()), + secureExampleShellQuote("-Dsolr.security.allow.paths=" + home))); + boolean ready = false; + try { + echo("\n"); + echo("1. Start both nodes."); + startSecureNodes(params, home, environment, zkHost); + for (int nodePort : List.of(port, port + 1)) { + waitForSecureExample( + environment, tls, null, "http://localhost:" + nodePort + "/api/node/health"); + } + stopSecureNodes(port, environment); + + echo("\n"); + echo("2. Generate a self-signed certificate and PKCS12 key and trust stores."); + String keytool = Path.of(EnvUtils.getProperty("java.home"), "bin", "keytool").toString(); + runSecureCommand( + environment, + keytool, + "-genkeypair", + "-alias", + "solr-ssl", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-validity", + "365", + "-dname", + "CN=localhost", + "-ext", + "SAN=DNS:localhost,IP:127.0.0.1", + "-storetype", + "PKCS12", + "-keystore", + tls.resolve("solr-ssl.keystore.p12").toString(), + "-storepass", + password, + "-keypass", + password); + runSecureCommand( + environment, + keytool, + "-exportcert", + "-rfc", + "-alias", + "solr-ssl", + "-keystore", + tls.resolve("solr-ssl.keystore.p12").toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-file", + tls.resolve("cert.pem").toString()); + runSecureCommand( + environment, + keytool, + "-importcert", + "-noprompt", + "-alias", + "solr-ssl", + "-file", + tls.resolve("cert.pem").toString(), + "-storetype", + "PKCS12", + "-keystore", + tls.resolve("solr-ssl.truststore.p12").toString(), + "-storepass", + password); + runSecureCommand( + environment, + "openssl", + "x509", + "-in", + tls.resolve("cert.pem").toString(), + "-noout", + "-subject", + "-dates"); + Files.writeString( + include, + String.format( + Locale.ROOT, + """ + SOLR_SSL_ENABLED=true + SOLR_SSL_KEY_STORE=%s + SOLR_SSL_KEY_STORE_TYPE=PKCS12 + SOLR_SSL_KEY_STORE_PASSWORD=%s + SOLR_SSL_TRUST_STORE=%s + SOLR_SSL_TRUST_STORE_TYPE=PKCS12 + SOLR_SSL_TRUST_STORE_PASSWORD=%s + SOLR_SSL_CLIENT_TRUST_STORE=${SOLR_SSL_CLIENT_TRUST_STORE:-%s} + SOLR_SSL_CLIENT_TRUST_STORE_TYPE=PKCS12 + SOLR_SSL_CLIENT_TRUST_STORE_PASSWORD=%s + SOLR_SSL_NEED_CLIENT_AUTH=false + SOLR_SSL_WANT_CLIENT_AUTH=false + SOLR_SSL_CHECK_PEER_NAME=true + """, + secureExampleShellQuote(tls.resolve("solr-ssl.keystore.p12").toString()), + secureExampleShellQuote(password), + secureExampleShellQuote(tls.resolve("solr-ssl.truststore.p12").toString()), + secureExampleShellQuote(password), + secureExampleShellQuote(tls.resolve("solr-ssl.truststore.p12").toString()), + secureExampleShellQuote(password)), + StandardOpenOption.APPEND); + for (String file : List.of("solr-ssl.keystore.p12", "solr-ssl.truststore.p12")) { + Files.setPosixFilePermissions( + tls.resolve(file), PosixFilePermissions.fromString("rw-------")); + } + + echo("\n"); + echo("3. Restart both nodes with HTTPS and verify the certificate."); + startSecureNodes(params, home, environment, zkHost); + for (int nodePort : List.of(port, port + 1)) { + waitForSecureExample( + environment, + tls, + "admin:" + password, + "https://localhost:" + nodePort + "/api/node/health"); + } + echo("\n"); + echo("\n"); + echo( + "4. Enable Basic Authentication and configure administrator, indexing, and search accounts."); + runSecureCommand( + environment, + script, + "auth", + "enable", + "--type", + "basicAuth", + "--credentials", + "admin:" + password, + "--block-unknown", + "true", + "-z", + zkHost); + waitForSecureExample( + environment, tls, "admin:" + password, "https://localhost:" + port + "/api/node/health"); + secureExampleRequest( + environment, + tls, + port, + password, + "/api/cluster/security/authentication", + String.format( + Locale.ROOT, + """ + { + "set-user": { + "index": "%s", + "search": "%s" + } + } + """, + password, + password)); + secureExampleRequest( + environment, + tls, + port, + password, + "/api/cluster/security/authorization", + """ + { + "update-permission": {"index": 9, "role": ["admin", "search"]}, + "set-user-role": { + "admin": ["superadmin", "admin"], + "index": ["index", "search"], + "search": ["search"] + } + } + """); + + echo("\n"); + echo("\n"); + echo( + "5. Configure ZooKeeper digest accounts and migrate existing znodes to restricted ACLs."); + Path credentials = tls.resolve("zk-credentials.properties"); + writeSecureExampleFile( + credentials, + String.format( + Locale.ROOT, + """ + zkDigestUsername=zk-admin + zkDigestPassword=%s + zkDigestReadonlyUsername=zk-readonly + zkDigestReadonlyPassword=%s + """, + password, + password)); + String zkOptions = + "-DzkCredentialsInjector=org.apache.solr.common.cloud.VMParamsZkCredentialsInjector " + + "-DzkCredentialsProvider=org.apache.solr.common.cloud.DigestZkCredentialsProvider " + + "-DzkACLProvider=org.apache.solr.common.cloud.DigestZkACLProvider "; + String zkSettings = + String.format( + Locale.ROOT, + """ + + SOLR_ZK_CREDS_AND_ACLS=%s + SOLR_OPTS="$SOLR_OPTS $SOLR_ZK_CREDS_AND_ACLS" + """, + secureExampleShellQuote(zkOptions + "-DzkDigestCredentialsFile=" + credentials)); + Files.writeString(include, zkSettings, StandardOpenOption.APPEND); + echo("Added ZooKeeper settings to " + secureExampleDisplayArgument(include.toString()) + ":"); + echo(zkSettings.strip()); + stopSecureNodes(port, environment); + startSecureNodes(params, home, environment, zkHost); + for (int nodePort : List.of(port, port + 1)) { + waitForSecureExample( + environment, + tls, + "admin:" + password, + "https://localhost:" + nodePort + "/api/node/health"); + } + runSecureCommand(environment, script, "zk", "updateacls", "/", "-z", zkHost); + Map<String, String> adminEnvironment = new HashMap<>(environment); + adminEnvironment.put("SOLR_INCLUDE", "/dev/null"); + adminEnvironment.put( + "SOLR_ZK_CREDS_AND_ACLS", + zkOptions + "-DzkDigestUsername=zk-admin -DzkDigestPassword=" + password); + runSecureCommand( + adminEnvironment, script, "zk", "updateacls", "/security.json", "-z", zkHost); + + echo("\n"); + echo("6. Create one shard per node and index the techproducts documents over HTTPS."); + runSecureCommand( + environment, + script, + "create", + "-c", + "techproducts", + "--shards", + "2", + "--replication-factor", + "1", + "--conf-dir", + serverDir + .resolve("solr/configsets/sample_techproducts_configs/conf") + .toAbsolutePath() + .toString(), + "--solr-url", + "https://localhost:" + port, + "--credentials", + "admin:" + password); + runSecureCommand( + environment, + script, + "post", + "-c", + "techproducts", + "--credentials", + "index:" + password, + "--solr-url", + "https://localhost:" + port, + exampleDir.resolve("exampledocs/*.xml").toAbsolutePath().toString()); + ready = true; + } finally { + if (!ready) { + echo( + "Setup failed. See " + + home + + "/node{1,2}/logs/solr.log. Run the secure example again to reset it and retry."); + for (int nodePort : List.of(port + 1, port)) { + try { + runSecureCommand(environment, script, "stop", "-p", Integer.toString(nodePort)); + } catch (Exception ignored) { + // Preserve the setup failure if cleanup also fails. + } + } + } + } + for (int nodePort : List.of(port, port + 1)) { + waitForSecureExample( + environment, + tls, + "search:" + password, + "https://localhost:" + + nodePort + + "/api/collections/techproducts/select?q=*:*&rows=0&shards.tolerant=false"); + } + echo("\n\n"); + echo( + "Two-node secure example is ready: https://localhost:" + + port + + "/solr/ and https://localhost:" + + (port + 1) + + "/solr/"); + echo( + "HTTP accounts: admin (administration), index (indexing/search), search (search only)." + + " Password: " + + password + + "."); + echo( + "ZooKeeper accounts: zk-admin (all), zk-readonly (metadata read only). Password: " + + password + + "."); + echo("Configuration: " + secureExampleDisplayArgument(include.toString())); + echo( + "Check status: SOLR_INCLUDE='" + + secureExampleDisplayArgument(include.toString()) + + "' ./bin/solr status"); + echo("\n"); + echo( + "Stop nodes: SOLR_INCLUDE='" + + secureExampleDisplayArgument(include.toString()) + + "' ./bin/solr stop --all "); + echo("\n"); + echo( + "See the Securing Solr tutorial for the individual commands and inter-node trust exercise."); + } + + private void resetSecureExampleHome(Path home, Map<String, String> environment) + throws IOException { + echo("Resetting the secure example in " + secureExampleDisplayArgument(home.toString())); + Map<String, String> stopEnvironment = new HashMap<>(environment); + stopEnvironment.put("SOLR_INCLUDE", "/dev/null"); + runSecureCommand(stopEnvironment, script, "stop", "--all"); + PathUtils.deleteDirectory(home); + Files.createDirectories(home); + } + + private void startSecureNodes( + CloudExampleParams params, Path home, Map<String, String> environment, String zkHost) + throws IOException { + for (int node = 1; node <= 2; node++) { + Map<String, String> nodeEnvironment = new HashMap<>(environment); + nodeEnvironment.put("SOLR_LOGS_DIR", home.resolve("node" + node + "/logs").toString()); + List<String> command = + new ArrayList<>( + List.of( + script, + "start", + "--solr-home", + home.resolve("node" + node + "/solr").toString(), + "--server-dir", + serverDir.toAbsolutePath().toString(), + "-p", + Integer.toString(params.basePort() + node - 1))); + if (node == 2) command.addAll(List.of("-z", zkHost)); + if (params.start().force()) command.add("--force"); + if (params.start().memory() != null) command.addAll(List.of("-m", params.start().memory())); + runSecureCommand(nodeEnvironment, command.toArray(String[]::new)); + } + } + + private void stopSecureNodes(int port, Map<String, String> environment) throws IOException { + for (int nodePort : List.of(port + 1, port)) { + runSecureCommand(environment, script, "stop", "-p", Integer.toString(nodePort)); + } + } + + private static String secureExampleShellQuote(String value) { + return "'" + value.replace("'", "'\\''") + "'"; + } + + /** + * Generates a fresh password for the secure example's keystore and demonstration accounts, so + * every run gets its own secret instead of a hardcoded one. + */ + private static String generateSecureExamplePassword() { + final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + SecureRandom random = new SecureRandom(); + StringBuilder password = new StringBuilder(20); + for (int i = 0; i < 20; i++) { + password.append(alphabet.charAt(random.nextInt(alphabet.length()))); + } + return password.toString(); + } + + private void writeSecureExampleFile(Path file, String content) throws IOException { + if (!Files.exists(file)) + Files.createFile( + file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + Files.writeString(file, content); + } + + private void secureExampleRequest( + Map<String, String> environment, Path tls, int port, String password, String api, String json) + throws IOException { + runSecureCommand( + environment, + "curl", + "--silent", + "--show-error", + "--fail", + "--cacert", + tls.resolve("cert.pem").toString(), + "--user", + "admin:" + password, + "-H", + "Content-Type: application/json", + "--data-binary", + json, + "https://localhost:" + port + api); + } + + private void waitForSecureExample( + Map<String, String> environment, Path tls, String credentials, String url) throws Exception { + List<String> command = new ArrayList<>(List.of("curl", "--silent", "--show-error", "--fail")); + if (url.startsWith("https://")) { + command.addAll(List.of("--cacert", tls.resolve("cert.pem").toString())); + } + if (credentials != null) command.addAll(List.of("--user", credentials)); + command.add(url); + new TimeOut(60, TimeUnit.SECONDS, TimeSource.NANO_TIME) + .waitFor( + "Timed out waiting for " + url, + () -> { + try { + runSecureCommand(environment, command.toArray(String[]::new)); + return true; + } catch (ExecuteException e) { + return false; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + } + + private String secureExampleDisplayArgument(String argument) { + String installPrefix = serverDir.getParent().toAbsolutePath().normalize() + "/"; + return argument.startsWith(installPrefix) + ? "./" + argument.substring(installPrefix.length()) + : argument; + } + + private void runSecureCommand(Map<String, String> environment, String... arguments) + throws IOException { + var command = new org.apache.commons.exec.CommandLine(arguments[0]); + command.addArguments(Arrays.copyOfRange(arguments, 1, arguments.length), false); + echo( + "\n" + + String.join( + " ", Arrays.stream(arguments).map(this::secureExampleDisplayArgument).toList())); + int result = executor.execute(command, environment); + if (result != 0) + throw new ExecuteException("Secure example command failed: " + arguments[0], result); + } + void runExample(RunExampleParams params) throws Exception { String exampleName = params.start().example(); String collectionName = "schemaless".equals(exampleName) ? "gettingstarted" : exampleName; @@ -853,7 +1393,7 @@ public class RunExampleTool extends ToolBase { readInput.useDelimiter(","); prompt = true; // Enable prompting code path, but reading from script inputs instead of user } else if (prompt) { - readInput = new Scanner(userInput, StandardCharsets.UTF_8); + readInput = userInputScanner(); } if (prompt) { @@ -1004,21 +1544,9 @@ public class RunExampleTool extends ToolBase { int maxWaitSecs) throws Exception { - String extraArgs = params.extraArgs(); - String host = params.host(); String memory = params.memory(); - - String hostArg = (host != null && !"localhost".equals(host)) ? " --host " + host : ""; - String zkHostArg = (zkHost != null) ? " -z " + zkHost : ""; - String memArg = (memory != null) ? " -m " + memory : ""; - String cloudModeArg = cloudMode ? "" : "--user-managed"; - String forceArg = params.force() ? " --force" : ""; - String verboseArg = isVerbose() ? "--verbose" : ""; - String jvmOpts = params.jvmOpts(); - String jvmOptsArg = - (jvmOpts != null && !jvmOpts.isEmpty()) ? " --jvm-opts \"" + jvmOpts + "\"" : ""; Path cwd = Path.of(System.getProperty("user.dir")); Path binDir = Path.of(script).getParent(); @@ -1033,31 +1561,49 @@ public class RunExampleTool extends ToolBase { if (!isWindows && cwdPath.length() > 1 && solrHome.startsWith(cwdPath)) solrHome = solrHome.substring(cwdPath.length() + 1); - final var syspropArg = - ("techproducts".equals(params.example())) - ? "-Dsolr.modules=clustering,extraction,langid,ltr,scripting,sql -Dsolr.ltr.enabled=true -Dsolr.clustering.enabled=true" - : ""; - - String startCmdStr = - String.format( - Locale.ROOT, - "\"%s\" start %s -p %d --solr-home \"%s\" --server-dir \"%s\" %s %s %s %s %s %s %s", - callScript, - cloudModeArg, - port, - solrHome, - serverDir.toAbsolutePath(), - hostArg, - zkHostArg, - memArg, - forceArg, - verboseArg, - extraArgs, - syspropArg); - startCmdStr = startCmdStr.replaceAll("\\s+", " ").trim(); // for pretty printing + // Built as discrete arguments (never a single string later re-tokenized by + // CommandLine.parse()) so that values containing whitespace, such as a --solr-home path, + // survive intact. + List<String> command = new ArrayList<>(); + command.add(callScript); + command.add("start"); + if (!cloudMode) command.add("--user-managed"); + command.add("-p"); + command.add(Integer.toString(port)); + command.add("--solr-home"); + command.add(solrHome); + command.add("--server-dir"); + command.add(serverDir.toAbsolutePath().toString()); + if (host != null && !"localhost".equals(host)) { + command.add("--host"); + command.add(host); + } + if (zkHost != null) { + command.add("-z"); + command.add(zkHost); + } + if (memory != null) { + command.add("-m"); + command.add(memory); + } + if (params.force()) command.add("--force"); + if (isVerbose()) command.add("--verbose"); + command.addAll(params.extraArgs()); + if ("techproducts".equals(params.example())) { + command.addAll( + List.of( + "-Dsolr.modules=clustering,extraction,langid,ltr,scripting,sql", + "-Dsolr.ltr.enabled=true", + "-Dsolr.clustering.enabled=true")); + } + if (jvmOpts != null && !jvmOpts.isEmpty()) { + command.add("--jvm-opts"); + command.add(jvmOpts); + } + String cmdStr = String.join(" ", command); echo("\nStarting up Solr on port " + port + " using command:"); - echo(startCmdStr + jvmOptsArg + "\n"); + echo(cmdStr + "\n"); String solrUrl = String.format( @@ -1069,7 +1615,9 @@ public class RunExampleTool extends ToolBase { if (nodeStatus != null) return nodeStatus; // the server they are trying to start is already running - int code; + var startCmd = new org.apache.commons.exec.CommandLine(command.get(0)); + startCmd.addArguments(command.subList(1, command.size()).toArray(String[]::new), false); + if (isWindows) { // On Windows, the execution doesn't return, so we have to execute async // and when calling the script, it seems to be inheriting the environment that launched this @@ -1086,20 +1634,6 @@ public class RunExampleTool extends ToolBase { } } DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler(); - org.apache.commons.exec.CommandLine startCmd = - org.apache.commons.exec.CommandLine.parse(startCmdStr); - - if (!jvmOptsArg.isEmpty()) { - startCmd.addArgument("--jvm-opts"); - - /* CommandLine.parse() tends to strip off the quotes by default before sending to cmd.exe. - This may cause cmd to break up the argument value on certain characters in unintended ways - thereby passing incorrect value to start.cmd - (eg: for "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:18983", it - breaks apart the value at "-agentlib:jdwp" passing incorrect args to start.cmd ). - The 'false' here tells Exec: “don’t touch my quotes—this is one atomic argument” */ - startCmd.addArgument("\"" + jvmOpts + "\"", false); - } executor.execute(startCmd, startEnv, handler); // wait for execution. try { @@ -1109,24 +1643,19 @@ public class RunExampleTool extends ToolBase { // safe to ignore ... } if (handler.hasResult() && handler.getExitValue() != 0) { - startCmdStr += jvmOptsArg; throw new Exception( "Failed to start Solr using command: " - + startCmdStr + + cmdStr + " Exception : " + handler.getException()); } } else { - // Unlike Windows, special handling of jvmOpts is not required on linux. We can simply - // concatenate to form the complete command - startCmdStr += jvmOptsArg; try { - code = executor.execute(org.apache.commons.exec.CommandLine.parse(startCmdStr)); + int code = executor.execute(startCmd); + if (code != 0) throw new Exception("Failed to start Solr using command: " + cmdStr); } catch (ExecuteException e) { - throw new Exception( - "Failed to start Solr using command: " + startCmdStr + " Exception : " + e); + throw new Exception("Failed to start Solr using command: " + cmdStr + " Exception : " + e); } - if (code != 0) throw new Exception("Failed to start Solr using command: " + startCmdStr); } return getNodeStatus(solrUrl, params.credentials(), maxWaitSecs); @@ -1166,23 +1695,17 @@ public class RunExampleTool extends ToolBase { throw new IllegalStateException("Port " + port + " is already being used by another process."); } - protected String readExtraArgs(String[] extraArgsArr) { - String extraArgs = ""; - if (extraArgsArr != null && extraArgsArr.length > 0) { - StringBuilder sb = new StringBuilder(); - int app = 0; + protected List<String> readExtraArgs(String[] extraArgsArr) { + List<String> extraArgs = new ArrayList<>(); + if (extraArgsArr != null) { for (int e = 0; e < extraArgsArr.length; e++) { String arg = extraArgsArr[e]; if ("e".equals(arg) || "example".equals(arg)) { e++; // skip over the example arg continue; } - - if (app > 0) sb.append(" "); - sb.append(arg); - ++app; + extraArgs.add(arg); } - extraArgs = sb.toString().trim(); } return extraArgs; } @@ -1409,15 +1932,18 @@ public class RunExampleTool extends ToolBase { + script); if (!"cloud".equals(exampleType) + && !"secure".equals(exampleType) && !"techproducts".equals(exampleType) && !"schemaless".equals(exampleType) && !"films".equals(exampleType)) { throw new IllegalArgumentException( "Unsupported example " + exampleType - + "! Please choose one of: cloud, schemaless, techproducts, or films"); + + "! Please choose one of: cloud, secure, schemaless, techproducts, or films"); } + validatePort(port); + StartSolrParams startParams = new StartSolrParams( exampleType, hostOpt, memoryOpt, jvmOptsOpt, forceOpt, null, readExtraArgs(extraArgs)); @@ -1425,6 +1951,10 @@ public class RunExampleTool extends ToolBase { if ("cloud".equals(exampleType)) { runCloudExample( new CloudExampleParams(noPromptOpt, scriptInputsOpt, zkHost, port, startParams)); + } else if ("secure".equals(exampleType)) { + runSecureExample( + new CloudExampleParams(noPromptOpt, scriptInputsOpt, zkHost, port, startParams), + userManagedOpt); } else { runExample(new RunExampleParams(!userManagedOpt, zkHost, port, startParams)); } @@ -1511,6 +2041,11 @@ public class RunExampleTool extends ToolBase { return (inputAsInt != null) ? inputAsInt : defVal; } + /** A scanner reading from {@link #userInput}, for interactive (non-script-input) prompting. */ + private Scanner userInputScanner() { + return new Scanner(userInput, StandardCharsets.UTF_8); + } + protected String prompt(Scanner s, String prompt) { return prompt(s, prompt, null); } diff --git a/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java b/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java index 224c1b643ad..8c401bfd2af 100644 --- a/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java +++ b/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java @@ -327,10 +327,7 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 { for (int pass = 0; pass < 2; pass++) { // need a port to start the example server on - int bindPort; - try (ServerSocket socket = new ServerSocket(0)) { - bindPort = socket.getLocalPort(); - } + int bindPort = pickFreePort(); log.info("Selected port {} to start {} example Solr instance on ...", bindPort, exampleName); @@ -359,9 +356,7 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 { if (status == -1) { // maybe it's the port, try again - try (ServerSocket socket = new ServerSocket(0)) { - bindPort = socket.getLocalPort(); - } + bindPort = pickFreePort(); Thread.sleep(100); status = runTool(tool, toolArgs); } @@ -435,10 +430,7 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 { "--example-dir", solrExampleDir.toString() }; - int bindPort; - try (ServerSocket socket = new ServerSocket(0)) { - bindPort = socket.getLocalPort(); - } + int bindPort = pickFreePort(); String collectionName = "testCloudExamplePrompt"; @@ -539,10 +531,7 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 { Path solrExampleDir = createTempDir(); Path solrServerDir = solrHomeDir.getParent(); - int bindPort = -1; - try (ServerSocket socket = new ServerSocket(0)) { - bindPort = socket.getLocalPort(); - } + int bindPort = pickFreePort(); String collectionName = "testCloudExampleWithScriptInputs"; @@ -645,10 +634,7 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 { Path solrServerDir = solrHomeDir.getParent(); // need a port to start the example server on - int bindPort; - try (ServerSocket socket = new ServerSocket(0)) { - bindPort = socket.getLocalPort(); - } + int bindPort = pickFreePort(); Path toExecute = Path.of(solrExampleDir.toString(), "failExecuteScript"); try { @@ -762,7 +748,7 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 { assertEquals( "Unsupported example " + unsupportedExample - + "! Please choose one of: cloud, schemaless, techproducts, or films", + + "! Please choose one of: cloud, secure, schemaless, techproducts, or films", exception.getMessage()); } @@ -774,4 +760,15 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 { Files.createFile(solrScript); return serverDir; } + + /** Picks a free port, staying under 64536 so port + 1000 (embedded ZooKeeper) stays valid. */ + private static int pickFreePort() throws IOException { + int port; + do { + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + } while (port > 64535); + return port; + } } diff --git a/solr/example/README.md b/solr/example/README.md index f0c8e46a4be..a93a84306f5 100644 --- a/solr/example/README.md +++ b/solr/example/README.md @@ -27,6 +27,7 @@ separate directory. To run a specific example, do: cloud : SolrCloud example schemaless : Schema-less example (schema is inferred from data during indexing) techproducts : Kitchen sink example providing comprehensive examples of Solr features + secure : Two-node HTTPS example with Basic Authentication and ZooKeeper ACLs films : Example of starting with _default configset and defining explicit fields dynamically. ``` diff --git a/solr/packaging/build.gradle b/solr/packaging/build.gradle index 535063ecea4..a33f77ee12b 100644 --- a/solr/packaging/build.gradle +++ b/solr/packaging/build.gradle @@ -365,6 +365,15 @@ abstract class BatsTask extends Exec { @Optional String filterTags = null + // Whether testFiles was populated via the --tests CLI option, as opposed to being + // preconfigured by the build script (e.g. integrationTestsPicocli's curated list). + // Explicitly requesting tests by name means the nightly tag filter should not apply. + // TODO: once the commons-cli/picocli split goes away (integrationTestsPicocli and its + // hardcoded testFiles list are removed), this field is redundant with `!testFiles.empty` + // and can be deleted in favor of that simpler check. + @Input + boolean testsSelectedViaCli = false + /** Where to write the junit report. Defaults to the project's test-output directory. */ @Internal String reportDir = null @@ -372,6 +381,7 @@ abstract class BatsTask extends Exec { @Option(option = "tests", description = "Sets test cases to be included") public void setTestNamePatterns(List<String> tests) { // TODO: bats --filter <regex> + testsSelectedViaCli = true tests.each {testFiles << "$testDir/$it"} } @@ -384,7 +394,7 @@ abstract class BatsTask extends Exec { if (logger.isInfoEnabled()) { batsArgs << '--verbose-run' } - if (filterTags) { + if (filterTags && !testsSelectedViaCli) { batsArgs += ['--filter-tags', filterTags] } batsArgs += diff --git a/solr/packaging/test/test_example.bats b/solr/packaging/test/test_example.bats index a5b4108e549..2b99d6d4b6c 100644 --- a/solr/packaging/test/test_example.bats +++ b/solr/packaging/test/test_example.bats @@ -50,3 +50,17 @@ teardown() { run curl "http://localhost:${SOLR2_PORT}/solr/admin/info/properties" assert_output --partial 'helloworld' } + +@test "examples suppress resource limit warnings while ordinary starts retain them" { + run env SOLR_INCLUDE=/dev/null SOLR_ULIMIT_CHECKS=true SOLR_RECOMMENDED_OPEN_FILES=2147483647 \ + solr start --server-dir "$BATS_TEST_TMPDIR/missing-server" + assert_failure + assert_output --partial 'Your open file limit' + assert_output --partial 'not found' + + run env SOLR_INCLUDE=/dev/null SOLR_ULIMIT_CHECKS=true SOLR_RECOMMENDED_OPEN_FILES=2147483647 \ + solr start "-e" "films" --server-dir "$BATS_TEST_TMPDIR/missing-server" + assert_failure + assert_output --partial 'not found' + refute_output --partial 'set SOLR_ULIMIT_CHECKS to false' +} diff --git a/solr/packaging/test/test_secure_example.bats b/solr/packaging/test/test_secure_example.bats new file mode 100644 index 00000000000..c537304606b --- /dev/null +++ b/solr/packaging/test/test_secure_example.bats @@ -0,0 +1,140 @@ +#!/usr/bin/env bats + +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +load bats_helper + +# bats file_tags=nightly + +setup() { + common_clean_setup + command -v openssl >/dev/null 2>&1 || skip "OpenSSL is not available" + export SOLR_INCLUDE="$BATS_TEST_TMPDIR/global-solr.in.sh" + export SOLR_STOP_WAIT=15 + touch "$SOLR_INCLUDE" +} + +teardown() { + save_home_on_failure + solr stop --all >/dev/null 2>&1 || true +} + +@test "secure example starts two HTTPS nodes with authentication and ZooKeeper ACLs" { + mkdir -p "$SOLR_HOME/node1" + printf 'left over\n' > "$SOLR_HOME/node1/incomplete-file" + run env SOLR_ULIMIT_CHECKS=true solr start -e secure --no-prompt --solr-home "$SOLR_HOME" -p "$SOLR_PORT" + assert_success + assert_output --partial 'Two-node secure example is ready' + assert_output --partial "http://localhost:$SOLR_PORT/api/node/health" + assert_output --partial "http://localhost:$SOLR2_PORT/api/node/health" + refute_output --partial 'forcefully killing it now' + refute_output --partial 'set SOLR_ULIMIT_CHECKS to false' + assert_output --partial 'Check status: SOLR_INCLUDE=' + + password=$(echo "$output" | grep -o 'Generated password: [A-Za-z0-9]*' | awk '{print $NF}') + [ -n "$password" ] + + run ls -a "$SOLR_HOME" + assert_success + refute_output --partial '.secure-example' + run ls -a "$SOLR_HOME/node1" + assert_success + refute_output --partial 'incomplete-file' + + run cat "$SOLR_INCLUDE" + assert_output '' + + run curl --noproxy '*' --silent --show-error --fail --cacert "$SOLR_HOME/tls/cert.pem" \ + --user "admin:$password" "https://localhost:$SOLR_PORT/api/cluster/security/authentication" + assert_success + assert_output --partial '"admin"' + refute_output --partial '"solr"' + + for port in "$SOLR_PORT" "$SOLR2_PORT"; do + run curl --noproxy '*' --silent --show-error --fail --cacert "$SOLR_HOME/tls/cert.pem" \ + --user "search:$password" "https://localhost:$port/solr/techproducts/select?q=*:*&rows=0&shards.info=true" + assert_success + assert_output --partial '"numFound":31' + assert_output --partial "https://127.0.0.1:$SOLR_PORT/" + assert_output --partial "https://127.0.0.1:$SOLR2_PORT/" + refute_output --partial 'http://' + + run curl --noproxy '*' --silent --show-error --fail --max-time 5 "https://localhost:$port/api/node/health" + assert_failure + assert_output --partial 'certificate' + + run curl --noproxy '*' --silent --show-error --fail --cacert "$SOLR_HOME/tls/cert.pem" \ + "https://localhost:$port/api/node/health" + assert_failure + assert_output --partial '401' + + run curl --noproxy '*' --silent --show-error --fail --cacert "$SOLR_HOME/tls/cert.pem" \ + --user "solr:$password" "https://localhost:$port/api/node/health" + assert_failure + assert_output --partial '401' + + run curl --noproxy '*' --silent --show-error --fail --cacert "$SOLR_HOME/tls/cert.pem" \ + --user "admin:$password" "https://localhost:$port/solr/techproducts/select?q=*:*" + assert_failure + assert_output --partial '403' + + run curl --noproxy '*' --silent --show-error --fail --cacert "$SOLR_HOME/tls/cert.pem" \ + --user "admin:$password" -H 'Content-Type: application/json' --data-binary '[{"id":"forbidden-admin"}]' \ + "https://localhost:$port/solr/techproducts/update" + assert_failure + assert_output --partial '403' + + run curl --noproxy '*' --silent --show-error --fail --cacert "$SOLR_HOME/tls/cert.pem" \ + --user "search:$password" -H 'Content-Type: application/json' --data-binary '[{"id":"forbidden"}]' \ + "https://localhost:$port/solr/techproducts/update" + assert_failure + assert_output --partial '403' + + run curl --noproxy '*' --silent --show-error --fail --max-time 5 "http://localhost:$port/api/node/health" + assert_failure + done + + run env SOLR_INCLUDE="$SOLR_HOME/tls/solr.in.sh" solr zk ls / --zk-host "localhost:$ZK_PORT" + assert_success + assert_output --partial 'collections' + + run env SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS= solr zk ls / --zk-host "localhost:$ZK_PORT" + assert_failure + assert_output --partial 'NoAuth' + + local readonly_opts="-DzkCredentialsInjector=org.apache.solr.common.cloud.VMParamsZkCredentialsInjector -DzkCredentialsProvider=org.apache.solr.common.cloud.DigestZkCredentialsProvider -DzkDigestUsername=zk-readonly -DzkDigestPassword=$password" + run env SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS="$readonly_opts" \ + solr zk ls /collections --zk-host "localhost:$ZK_PORT" + assert_success + assert_output --partial 'techproducts' + run env SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS="$readonly_opts" \ + solr zk cp zk:/security.json "$BATS_TEST_TMPDIR/security.json" --zk-host "localhost:$ZK_PORT" + assert_failure + assert_output --partial 'NoAuth' + run env SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS="$readonly_opts" \ + solr zk mkroot /forbidden --zk-host "localhost:$ZK_PORT" + assert_failure + assert_output --partial 'NoAuth' +} + +@test "secure example rejects unsupported options" { + run solr start -e secure --no-prompt --solr-home "$SOLR_HOME" --host other-host + assert_failure + assert_output --partial 'host' + run solr start -e secure --no-prompt --solr-home "$SOLR_HOME" --user-managed + assert_failure + assert_output --partial 'requires its own embedded ZooKeeper' +} diff --git a/solr/solr-ref-guide/modules/deployment-guide/pages/enabling-ssl.adoc b/solr/solr-ref-guide/modules/deployment-guide/pages/enabling-ssl.adoc index e78db69d201..7a4ab361b41 100644 --- a/solr/solr-ref-guide/modules/deployment-guide/pages/enabling-ssl.adoc +++ b/solr/solr-ref-guide/modules/deployment-guide/pages/enabling-ssl.adoc @@ -20,6 +20,7 @@ Solr can encrypt communications to and from clients and between nodes in SolrCloud mode with Secure Sockets Layer encryption (SSL). This section describes enabling SSL using a self-signed certificate. +For a complete local exercise with two nodes, verified inter-node HTTPS, authentication, and ZooKeeper ACLs, see xref:getting-started:tutorial-securing-solr.adoc[]. For background on SSL certificates and keys, see http://www.tldp.org/HOWTO/SSL-Certificates-HOWTO/. diff --git a/solr/solr-ref-guide/modules/deployment-guide/pages/solr-control-script-reference.adoc b/solr/solr-ref-guide/modules/deployment-guide/pages/solr-control-script-reference.adoc index 296dfc809f8..dc28d62109c 100644 --- a/solr/solr-ref-guide/modules/deployment-guide/pages/solr-control-script-reference.adoc +++ b/solr/solr-ref-guide/modules/deployment-guide/pages/solr-control-script-reference.adoc @@ -177,7 +177,7 @@ Solr will create core directories under this directory. This allows you to run multiple Solr instances on the same host while reusing the same server directory set using the `--server-dir` parameter. If set, the specified directory should contain a solr.xml file, unless solr.xml exists in Zookeeper. + -This parameter is ignored when running examples (`-e`), as the `solr.solr.home` depends on which example is run. +This parameter is ignored when running examples (`-e`), except for `secure`, which uses it as the parent directory for both node homes and the TLS configuration. + The default value is `server/solr`. If passed relative dir, validation with current dir will be done, before trying default `server/<dir>`. @@ -264,6 +264,7 @@ These examples are provided to help you get started faster with Solr generally, The available options are: * `cloud`: SolrCloud example +* `secure`: Two-node SolrCloud example with HTTPS, Basic Authentication, and ZooKeeper ACLs (Bash only) * `techproducts`: Comprehensive example illustrating many of Solr's core capabilities * `schemaless`: Schema-less example (schema is inferred from data during indexing) * `films`: Example of starting with _default configset and adding explicit fields dynamically @@ -376,6 +377,10 @@ The configset used can be found in `$SOLR_TIP/server/solr/configsets/sample_tech + The data used can be found in `$SOLR_HOME/example/exampledocs/`. +* *secure*: This example starts two local SolrCloud nodes with PKCS12 certificates, Basic Authentication, and ZooKeeper digest ACLs. +It uses demonstration passwords and keeps ZooKeeper transport on loopback without TLS. +See xref:getting-started:tutorial-securing-solr.adoc[] for the equivalent manual steps. + * *schemaless*: This example starts a standalone Solr instance using a managed schema, as described in the section xref:configuration-guide:schema-factory.adoc[], and provides a very minimal pre-defined schema. Solr will run in xref:indexing-guide:schemaless-mode.adoc[] with this configuration, where Solr will create fields in the schema on the fly and will guess field types used in incoming documents. + diff --git a/solr/solr-ref-guide/modules/getting-started/getting-started-nav.adoc b/solr/solr-ref-guide/modules/getting-started/getting-started-nav.adoc index 562ba636558..8c5fbe292d6 100644 --- a/solr/solr-ref-guide/modules/getting-started/getting-started-nav.adoc +++ b/solr/solr-ref-guide/modules/getting-started/getting-started-nav.adoc @@ -34,6 +34,7 @@ ** xref:tutorial-paramsets.adoc[] ** xref:tutorial-vectors.adoc[] ** xref:tutorial-solrcloud.adoc[] +** xref:tutorial-securing-solr.adoc[] ** xref:tutorial-opennlp.adoc[] ** xref:tutorial-aws.adoc[] diff --git a/solr/solr-ref-guide/modules/getting-started/pages/solr-tutorial.adoc b/solr/solr-ref-guide/modules/getting-started/pages/solr-tutorial.adoc index 4b1659aabb6..2e687e8840c 100644 --- a/solr/solr-ref-guide/modules/getting-started/pages/solr-tutorial.adoc +++ b/solr/solr-ref-guide/modules/getting-started/pages/solr-tutorial.adoc @@ -29,7 +29,8 @@ The xref:tutorial-films.adoc[second exercise] works with a different set of data The xref:tutorial-diy.adoc[third exercise] encourages you to begin to work with your own data and start a plan for your implementation. The tutorial also includes other, more advanced, exercises that introduce you to xref:tutorial-paramsets.adoc[ParamSets], -xref:tutorial-vectors.adoc[vector search], xref:tutorial-opennlp.adoc[sentiment analysis with OpenNLP], xref:tutorial-solrcloud.adoc[SolrCloud], and xref:tutorial-aws.adoc[deploying Solr to AWS]. +xref:tutorial-vectors.adoc[vector search], xref:tutorial-opennlp.adoc[sentiment analysis with OpenNLP], xref:tutorial-solrcloud.adoc[SolrCloud], +xref:tutorial-securing-solr.adoc[securing a two-node cluster], and xref:tutorial-aws.adoc[deploying Solr to AWS]. Finally, we'll introduce <<Spatial Queries,spatial search>>, and show you how to get your Solr instance back into a clean state. diff --git a/solr/solr-ref-guide/modules/getting-started/pages/tutorial-opennlp.adoc b/solr/solr-ref-guide/modules/getting-started/pages/tutorial-opennlp.adoc index 1e58a41d058..ed6f5eca31a 100644 --- a/solr/solr-ref-guide/modules/getting-started/pages/tutorial-opennlp.adoc +++ b/solr/solr-ref-guide/modules/getting-started/pages/tutorial-opennlp.adoc @@ -1,4 +1,4 @@ -= Exercise 7: Sentiment Analysis with OpenNLP += Exercise 8: Sentiment Analysis with OpenNLP :experimental: :tabs-sync-option: // Licensed to the Apache Software Foundation (ASF) under one diff --git a/solr/solr-ref-guide/modules/getting-started/pages/tutorial-securing-solr.adoc b/solr/solr-ref-guide/modules/getting-started/pages/tutorial-securing-solr.adoc new file mode 100644 index 00000000000..911ebff15b7 --- /dev/null +++ b/solr/solr-ref-guide/modules/getting-started/pages/tutorial-securing-solr.adoc @@ -0,0 +1,512 @@ += Exercise 7: Securing Solr +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +This exercise starts a two node Solr cluster, enables HTTPS, assigns separate administration, indexing, and search accounts, and protects ZooKeeper data with access control lists (ACLs). +You will verify HTTPS for both client requests and requests between Solr nodes. +Each step uses the tools included in the Solr distribution, JDK `keytool`, OpenSSL, and `curl`. + +Use a fresh full Solr installation on Unix or macOS, with ports 8983, 8984, and 9983 available. +Run the commands in the same Bash-compatible shell, from the installation directory, using an installation path without spaces. +Do not run these commands against an existing cluster. + +IMPORTANT: This exact setup is not ready or appropriate for production use. +It is a local learning exercise with demonstration passwords and a shared self-signed certificate. +Keep the cluster on loopback. +ZooKeeper authentication and ACLs do not encrypt its connection; this exercise leaves ZooKeeper transport on loopback without TLS. +For deployment guidance, see xref:deployment-guide:securing-solr.adoc[], xref:deployment-guide:enabling-ssl.adoc[], and xref:deployment-guide:zookeeper-access-control.adoc[]. + +== Start Two Nodes + +Prepare two isolated Solr homes by copying the distribution's configuration files. +Then start the first node with the ordinary `bin/solr start` command: + +[source,bash] +---- +umask 077 # Makes new files and directories accessible only to your user +export TUTORIAL_HOME="$PWD/tutorial/secure" +mkdir -p "$TUTORIAL_HOME/node1/solr" "$TUTORIAL_HOME/node2/solr" "$TUTORIAL_HOME/tls" +for node in node1 node2; do + cp server/solr/solr.xml "$TUTORIAL_HOME/$node/solr/" + cp server/solr/zoo.cfg "$TUTORIAL_HOME/$node/solr/" +done +cat > "$TUTORIAL_HOME/tls/solr.in.sh" <<EOF +SOLR_ULIMIT_CHECKS=false +SOLR_HOST_BIND=127.0.0.1 +SOLR_HOST_ADVERTISE=127.0.0.1 +SOLR_PID_DIR="$TUTORIAL_HOME" +SOLR_OPTS="-Dsolr.security.allow.paths=$TUTORIAL_HOME" +EOF +export SOLR_INCLUDE="$TUTORIAL_HOME/tls/solr.in.sh" +SOLR_LOGS_DIR="$TUTORIAL_HOME/node1/logs" \ + bin/solr start --solr-home "$TUTORIAL_HOME/node1/solr" +---- + +`SOLR_ULIMIT_CHECKS=false` suppresses resource-limit warnings for this local exercise. + +`SOLR_LOGS_DIR` gives each node its own log directory. + +The first SolrCloud node listens on `localhost:8983` and starts embedded ZooKeeper on `localhost:9983`. +The embedded ZooKeeper is suitable for this exercise; production clusters should use an external ensemble. + +Check that it responds over HTTP, then start the second node: + +[source,bash] +---- +curl --fail 'http://localhost:8983/api/node/health' +SOLR_LOGS_DIR="$TUTORIAL_HOME/node2/logs" \ + bin/solr start -p 8984 --solr-home "$TUTORIAL_HOME/node2/solr" -z localhost:9983 +curl --fail 'http://localhost:8984/api/node/health' +curl --fail --silent --show-error \ + 'http://localhost:8983/api/cluster/nodes' +---- + +Wait for each health request to succeed before proceeding; repeat the corresponding `curl` command if the node is still initializing. +A listening TCP port alone does not mean Solr has finished starting. + +Both nodes use ZooKeeper's root namespace. +The first node runs embedded ZooKeeper; the second joins it with `-z localhost:9983`. +Each home starts with only configuration files and stores its own data. + +The response's `nodes` array must contain two nodes, with ports 8983 and 8984. +If only one node appears, repeat the `curl` command after the second node finishes initializing; continue when both are present. +Both nodes share the first node's ZooKeeper, rather than forming separate clusters. +The working directory holds both nodes' data, certificates, and a private configuration file. +Node logs are under `tutorial/secure/node1/logs` and `tutorial/secure/node2/logs`. + +== Create a Certificate and PKCS12 Stores + +Generate a private key and self-signed certificate directly in a PKCS12 keystore. +The `-ext 'SAN=...'` option below sets the certificate's subject alternative names, so the certificate is considered valid for both `localhost` and `127.0.0.1`, the two names used in this exercise: + +[source,bash] +---- +keytool -genkeypair -alias solr-ssl -keyalg RSA -keysize 2048 \ + -validity 365 -dname 'CN=localhost' \ + -ext 'SAN=DNS:localhost,IP:127.0.0.1' \ + -storetype PKCS12 -keystore "$TUTORIAL_HOME/tls/solr-ssl.keystore.p12" \ + -storepass SolrRocks -keypass SolrRocks +keytool -exportcert -alias solr-ssl -rfc \ + -keystore "$TUTORIAL_HOME/tls/solr-ssl.keystore.p12" -storetype PKCS12 \ + -storepass SolrRocks -file "$TUTORIAL_HOME/tls/cert.pem" +keytool -importcert -noprompt -alias solr-ssl \ + -file "$TUTORIAL_HOME/tls/cert.pem" \ + -keystore "$TUTORIAL_HOME/tls/solr-ssl.truststore.p12" -storetype PKCS12 \ + -storepass SolrRocks +openssl x509 -in "$TUTORIAL_HOME/tls/cert.pem" -noout -subject -dates -text +---- + +The keystore contains the private key and certificate presented by each server. +The truststore contains the certificate trusted by Solr's outbound HTTPS clients. +The PEM certificate lets `curl` verify the server without disabling certificate checks. +Using the same keystore on both nodes simplifies the exercise; real deployments should manage certificates and private keys separately for each node. + +== Enable HTTPS on Both Nodes + +Solr only applies include-file changes when a node starts, so this section rewrites the include file and then stops and restarts both nodes to pick up HTTPS. + +Write an include file used only for this exercise. +The unquoted heredoc expands the absolute working-directory path now; escaped dollar signs preserve variables for later launches: + +[source,bash] +---- +cat > "$TUTORIAL_HOME/tls/solr.in.sh" <<EOF +SOLR_ULIMIT_CHECKS=false +SOLR_HOST_BIND=127.0.0.1 +SOLR_HOST_ADVERTISE=127.0.0.1 +SOLR_PID_DIR="$TUTORIAL_HOME" +SOLR_OPTS="-Dsolr.security.allow.paths=$TUTORIAL_HOME" +SOLR_SSL_ENABLED=true +SOLR_SSL_KEY_STORE="$TUTORIAL_HOME/tls/solr-ssl.keystore.p12" +SOLR_SSL_KEY_STORE_PASSWORD=SolrRocks +SOLR_SSL_KEY_STORE_TYPE=PKCS12 +SOLR_SSL_TRUST_STORE="$TUTORIAL_HOME/tls/solr-ssl.truststore.p12" +SOLR_SSL_TRUST_STORE_PASSWORD=SolrRocks +SOLR_SSL_TRUST_STORE_TYPE=PKCS12 +SOLR_SSL_CLIENT_TRUST_STORE="\${SOLR_SSL_CLIENT_TRUST_STORE:-$TUTORIAL_HOME/tls/solr-ssl.truststore.p12}" +SOLR_SSL_CLIENT_TRUST_STORE_PASSWORD=SolrRocks +SOLR_SSL_CLIENT_TRUST_STORE_TYPE=PKCS12 +SOLR_SSL_NEED_CLIENT_AUTH=false +SOLR_SSL_WANT_CLIENT_AUTH=false +SOLR_SSL_CHECK_PEER_NAME=true +EOF +chmod 600 "$TUTORIAL_HOME/tls/solr.in.sh" +---- + +The server's truststore and the outbound client's truststore are explicit. +Nodes advertise the IPv4 loopback address `127.0.0.1`; client URLs can also use `localhost`, because the certificate covers both. +Hostname verification remains enabled. +Client certificates are not required; later steps authenticate users with Basic Authentication over HTTPS. + +Stop the second node before stopping the first node and its embedded ZooKeeper, then restart both with the updated include file: + +[source,bash] +---- +bin/solr stop -p 8984 +bin/solr stop -p 8983 +export SOLR_INCLUDE="$TUTORIAL_HOME/tls/solr.in.sh" +SOLR_LOGS_DIR="$TUTORIAL_HOME/node1/logs" \ + bin/solr start -p 8983 --solr-home "$TUTORIAL_HOME/node1/solr" +SOLR_LOGS_DIR="$TUTORIAL_HOME/node2/logs" \ + bin/solr start -p 8984 --solr-home "$TUTORIAL_HOME/node2/solr" -z localhost:9983 +---- + +Verify each node with the trusted PEM certificate: + +[source,bash] +---- +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" \ + 'https://localhost:8983/api/node/health' +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" \ + 'https://127.0.0.1:8984/api/node/health' +---- + +Both requests should succeed. +A request without the certificate should fail certificate verification, because your operating system does not trust this self-signed certificate. +Plaintext HTTP requests to either port should fail: + +[source,bash] +---- +curl --fail 'https://localhost:8983/api/node/health' +curl --fail 'http://localhost:8983/api/node/health' +curl --fail 'http://localhost:8984/api/node/health' +---- + +Do not use `curl -k` to bypass verification. + +== Authenticate Users and Assign Roles + +Enable Basic Authentication with the existing control-script command. +It writes authentication settings into the private include file and creates `basicAuth.conf` beside it: + +[source,bash] +---- +SOLR_HOME="$TUTORIAL_HOME/tls" bin/solr auth enable --type basicAuth \ + --credentials admin:SolrRocks --block-unknown true -z localhost:9983 +chmod 600 "$TUTORIAL_HOME/tls/basicAuth.conf" "$SOLR_INCLUDE" +---- + +The security configuration is shared through ZooKeeper, so both nodes enforce it. +The command's `SOLR_HOME` override selects the directory for `basicAuth.conf`; it does not change either running node's home. +The bootstrap account initially has all template roles. +Use the authentication API to set passwords for the indexing and search accounts: + +[source,bash] +---- +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + -H 'Content-Type: application/json' \ + --data '{"set-user":{"index":"SolrRocks","search":"SolrRocks"}}' \ + https://localhost:8983/api/cluster/security/authentication +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + -H 'Content-Type: application/json' \ + --data '{"set-user-role":{"admin":["superadmin","admin"],"index":["index","search"],"search":["search"]}}' \ + https://localhost:8983/api/cluster/security/authorization +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + https://localhost:8983/api/cluster/security/authorization +---- + +Inspect the permission list in the last response. +In the built-in template, `collection-admin-read` is permission index 9 and grants only the `search` role. +Allow both `admin` and `search` to inspect collection state: + +[source,bash] +---- +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + -H 'Content-Type: application/json' \ + --data '{"update-permission":{"index":9,"role":["admin","search"]}}' \ + https://localhost:8983/api/cluster/security/authorization +---- + +The accounts now have these responsibilities: + +[cols="1,2",options="header"] +|=== +|Account |Permissions +|`admin` |Manage security, configuration, and collections; cannot index or search. +|`index` |Index documents and search. +|`search` |Search; cannot index documents. +|=== + +The predefined `read` and `update` permissions take precedence over the template's final `all` permission. +Removing `index` and `search` roles from `admin` therefore separates administration from document access. +For permission details, see xref:deployment-guide:rule-based-authorization-plugin.adoc[]. + +== Protect ZooKeeper Data + +Solr user accounts do not protect direct ZooKeeper access. +Create separate digest credentials for ZooKeeper administration and read-only inspection: + +[source,bash] +---- +cat > "$TUTORIAL_HOME/tls/zk-credentials.properties" <<'EOF' +zkDigestUsername=zk-admin +zkDigestPassword=SolrRocks +zkDigestReadonlyUsername=zk-readonly +zkDigestReadonlyPassword=SolrRocks +EOF +chmod 600 "$TUTORIAL_HOME/tls/zk-credentials.properties" +printf '\n' >> "$SOLR_INCLUDE" +cat >> "$SOLR_INCLUDE" <<EOF +SOLR_ZK_CREDS_AND_ACLS="-DzkCredentialsInjector=org.apache.solr.common.cloud.VMParamsZkCredentialsInjector -DzkCredentialsProvider=org.apache.solr.common.cloud.DigestZkCredentialsProvider -DzkACLProvider=org.apache.solr.common.cloud.DigestZkACLProvider -DzkDigestCredentialsFile=$TUTORIAL_HOME/tls/zk-credentials.properties" +SOLR_OPTS="\$SOLR_OPTS \$SOLR_ZK_CREDS_AND_ACLS" +EOF +tail -n 2 "$SOLR_INCLUDE" +bin/solr stop -p 8984 +bin/solr stop -p 8983 +SOLR_LOGS_DIR="$TUTORIAL_HOME/node1/logs" \ + bin/solr start -p 8983 --solr-home "$TUTORIAL_HOME/node1/solr" +SOLR_LOGS_DIR="$TUTORIAL_HOME/node2/logs" \ + bin/solr start -p 8984 --solr-home "$TUTORIAL_HOME/node2/solr" -z localhost:9983 +bin/solr zk updateacls / -z localhost:9983 +ADMIN_ZK_OPTS='-DzkCredentialsInjector=org.apache.solr.common.cloud.VMParamsZkCredentialsInjector -DzkCredentialsProvider=org.apache.solr.common.cloud.DigestZkCredentialsProvider -DzkACLProvider=org.apache.solr.common.cloud.DigestZkACLProvider -DzkDigestUsername=zk-admin -DzkDigestPassword=SolrRocks' +SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS="$ADMIN_ZK_OPTS" \ + bin/solr zk updateacls /security.json -z localhost:9983 +---- + +The `tail` command displays the two settings just appended to the include file. +`SOLR_ZK_CREDS_AND_ACLS` configures command-line ZooKeeper clients; adding the same settings to `SOLR_OPTS` also configures each server. +The servers authenticate as `zk-admin` and create znodes with administrator access plus read-only access for `zk-readonly`. +The `zk-readonly` account is for direct inspection of ordinary cluster metadata; Solr nodes do not use it. +The first `updateacls` command migrates existing znodes: changing the provider alone would leave their previous ACLs in place. +When using ZooKeeper's root namespace, explicitly restrict `/security.json` to the administrator with the second command, which omits the read-only credentials. +This protects the Solr passwords stored there. +Repeat that command after any future ACL migration of the entire tree. + +Check administrator access: + +[source,bash] +---- +bin/solr zk ls / -z localhost:9983 +---- + +For a read-only CLI session, pass only the read-only user's credentials, using the injector's primary username/password fields. +This authenticates the client as that user without supplying the administrator secret: + +[source,bash] +---- +READONLY_ZK_OPTS='-DzkCredentialsInjector=org.apache.solr.common.cloud.VMParamsZkCredentialsInjector -DzkCredentialsProvider=org.apache.solr.common.cloud.DigestZkCredentialsProvider -DzkDigestUsername=zk-readonly -DzkDigestPassword=SolrRocks' +SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS="$READONLY_ZK_OPTS" \ + bin/solr zk ls /collections -z localhost:9983 +printf 'read-only probe\n' > "$TUTORIAL_HOME/readonly-probe.txt" +SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS="$READONLY_ZK_OPTS" \ + bin/solr zk cp "$TUTORIAL_HOME/readonly-probe.txt" zk:/readonly-probe -z localhost:9983 +SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS="$READONLY_ZK_OPTS" \ + bin/solr zk cp zk:/security.json "$TUTORIAL_HOME/forbidden-security.json" -z localhost:9983 +SOLR_INCLUDE=/dev/null SOLR_ZK_CREDS_AND_ACLS= \ + bin/solr zk ls / -z localhost:9983 +---- + +The directory listing as `zk-readonly` succeeds. +The attempted write, the read of `security.json`, and the anonymous listing must fail with authorization errors. +These ACLs control access but do not provide transport encryption. + +== Index and Verify Distributed HTTPS Queries + +Create a collection with two shards and one replica per shard, using the techproducts configuration, then index the sample XML documents as `index`: + +[source,bash] +---- +bin/solr create -c techproducts --shards 2 --replication-factor 1 \ + -d sample_techproducts_configs --credentials admin:SolrRocks \ + -s https://localhost:8983 +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + 'https://localhost:8983/api/collections?detailed=true&collection=techproducts' +bin/solr post -c techproducts --credentials index:SolrRocks \ + -s https://localhost:8983 example/exampledocs/*.xml +---- + +Check that `collectionsDetail.techproducts.shards` reports one shard replica on port 8983 and the other on port 8984, both `active`, with `https://` base URLs. +Each node should hold only part of the collection. + +Query through both nodes as `search`, asking Solr to include shard details: + +[source,bash] +---- +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u search:SolrRocks \ + 'https://localhost:8983/api/collections/techproducts/select?q=*:*&rows=0&shards.info=true' +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u search:SolrRocks \ + 'https://localhost:8984/api/collections/techproducts/select?q=*:*&rows=0&shards.info=true' +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u search:SolrRocks \ + 'https://localhost:8983/api/collections/techproducts/select?q=*:*&rows=0&distrib=false' +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u search:SolrRocks \ + 'https://localhost:8984/api/collections/techproducts/select?q=*:*&rows=0&distrib=false' +---- + +The distributed requests return the same total `numFound` and show two responding shard addresses under `shards.info`. +The bundled XML examples produce 31 documents. +Every address must start with `https://`, including the remote node. +With `distrib=false`, each node returns its local shard's count; the two local counts add up to the distributed total. +This confirms that a full query requires communication between the nodes. + +Verify the role boundaries and anonymous access. +The first three requests should return HTTP 403; the last two should return HTTP 401: + +[source,bash] +---- +curl --cacert "$TUTORIAL_HOME/tls/cert.pem" -u search:SolrRocks \ + -H 'Content-Type: application/json' --data '[{"id":"forbidden"}]' \ + -w '\nHTTP %{http_code}\n' https://localhost:8983/api/collections/techproducts/update +curl --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + -w '\nHTTP %{http_code}\n' 'https://localhost:8983/api/collections/techproducts/select?q=*:*' +curl --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + -H 'Content-Type: application/json' --data '[{"id":"forbidden-admin"}]' \ + -w '\nHTTP %{http_code}\n' https://localhost:8983/api/collections/techproducts/update +curl --cacert "$TUTORIAL_HOME/tls/cert.pem" -w '\nHTTP %{http_code}\n' \ + 'https://localhost:8983/api/collections/techproducts/select?q=*:*' +curl --cacert "$TUTORIAL_HOME/tls/cert.pem" -w '\nHTTP %{http_code}\n' \ + 'https://localhost:8984/api/collections/techproducts/select?q=*:*' +---- + +== Test Trust Between the Nodes + +A successful `curl` request verifies curl's trust in the server. +To also test the outbound trust used by Solr, temporarily give node 2 a truststore containing an unrelated certificate. +Keep the normal server keystore and truststore unchanged: + +[source,bash] +---- +keytool -genkeypair -alias unrelated -keyalg RSA -keysize 2048 \ + -validity 1 -dname 'CN=unrelated' -storetype PKCS12 \ + -keystore "$TUTORIAL_HOME/tls/unrelated-keystore.p12" \ + -storepass SolrRocks -keypass SolrRocks +keytool -exportcert -alias unrelated -rfc -storetype PKCS12 \ + -keystore "$TUTORIAL_HOME/tls/unrelated-keystore.p12" -storepass SolrRocks \ + -file "$TUTORIAL_HOME/tls/unrelated-cert.pem" +keytool -importcert -noprompt -alias unrelated -storetype PKCS12 \ + -file "$TUTORIAL_HOME/tls/unrelated-cert.pem" \ + -keystore "$TUTORIAL_HOME/tls/untrusted-truststore.p12" -storepass SolrRocks +bin/solr stop -p 8984 +SOLR_SSL_CLIENT_TRUST_STORE="$TUTORIAL_HOME/tls/untrusted-truststore.p12" \ +SOLR_LOGS_DIR="$TUTORIAL_HOME/node2/logs" \ + bin/solr start -p 8984 --solr-home "$TUTORIAL_HOME/node2/solr" -z localhost:9983 +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + 'https://localhost:8983/api/node/health' +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + 'https://localhost:8984/api/node/health' +---- + +Wait for node 2's replica to finish loading before testing the distributed query. +Inspect collection state and confirm a local query succeeds: + +[source,bash] +---- +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u admin:SolrRocks \ + 'https://localhost:8983/api/collections?detailed=true&collection=techproducts' +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u search:SolrRocks \ + 'https://localhost:8984/api/collections/techproducts/select?q=*:*&rows=0&distrib=false' +---- + +Repeat these checks until both replicas are `active` and the local query returns node 2's document count. +Then issue the distributed query: + +[source,bash] +---- +curl --cacert "$TUTORIAL_HOME/tls/cert.pem" -u search:SolrRocks \ + -w '\nHTTP %{http_code}\n' \ + 'https://localhost:8984/api/collections/techproducts/select?q=*:*&rows=0&shards.info=true&shards.tolerant=false' +---- + +Both external HTTPS checks still succeed with the original certificate. +The distributed query through node 2 must fail when its outbound client cannot verify node 1's certificate. +Inspect `tutorial/secure/node2/logs/solr-8984-console.log` or `tutorial/secure/node2/logs/solr.log` for the certificate trust error, such as `SSLHandshakeException` or `PKIX path building failed`. + +Restore node 2's normal outbound trust by starting it without the temporary override, then repeat the same query: + +[source,bash] +---- +bin/solr stop -p 8984 +SOLR_LOGS_DIR="$TUTORIAL_HOME/node2/logs" \ + bin/solr start -p 8984 --solr-home "$TUTORIAL_HOME/node2/solr" -z localhost:9983 +---- + +Repeat the collection-state and local-query checks above until node 2's replica is `active`, then run: + +[source,bash] +---- +curl --fail --cacert "$TUTORIAL_HOME/tls/cert.pem" -u search:SolrRocks \ + 'https://localhost:8984/api/collections/techproducts/select?q=*:*&rows=0&shards.info=true&shards.tolerant=false' +---- + +The distributed query should succeed again with the original total count and HTTPS shard addresses. + +== Stop, Restart, and Retain the Configuration + +Stop node 2 before node 1, because node 1 hosts ZooKeeper: + +[source,bash] +---- +bin/solr stop -p 8984 +bin/solr stop -p 8983 +---- + +The homes retain indexed data. +Node 1 also retains embedded ZooKeeper data, including the security configuration and ACLs, under `tutorial/secure/node1/solr/zoo_data`. +The private files under `tutorial/secure/tls` retain the key, certificate, passwords, and launch settings. +To restart in a new shell, return to this Solr installation directory and run: + +[source,bash] +---- +export TUTORIAL_HOME="$PWD/tutorial/secure" +export SOLR_INCLUDE="$TUTORIAL_HOME/tls/solr.in.sh" +SOLR_LOGS_DIR="$TUTORIAL_HOME/node1/logs" \ + bin/solr start -p 8983 --solr-home "$TUTORIAL_HOME/node1/solr" +SOLR_LOGS_DIR="$TUTORIAL_HOME/node2/logs" \ + bin/solr start -p 8984 --solr-home "$TUTORIAL_HOME/node2/solr" -z localhost:9983 +---- + +The certificate expires after 365 days. +Before expiry, replace the certificate and private key, update the trusted certificate in the truststore and PEM file, and restart both nodes with matching trust settings. +Do not replace the truststore with an empty store or disable verification. + +To repeat from scratch, stop both nodes and unpack a fresh Solr distribution into a new directory. +This preserves the current exercise and avoids deleting unrelated data. + +== Shortcut: Start the Secure Example + +After completing the manual exercise, you can create the same kind of demonstration cluster in a fresh installation. +Clear the manual tutorial's include file setting so the shortcut starts with its own configuration: + +[source,bash] +---- +unset SOLR_INCLUDE +bin/solr start -e secure +---- + +The shortcut uses `example/secure`, independently of the tutorial's `tutorial/secure` directory. +Stop the manual tutorial nodes first if you use the same ports. +Each invocation stops the nodes recorded in this example's PID directory and replaces its generated certificates, accounts, and collection data. +All contents of the example home are deleted; only pass a dedicated, disposable directory to `--solr-home`. +Stop any other cluster first if it uses the same ports. +The example creates isolated homes in `example/secure/node1/solr` and `example/secure/node2/solr`, plus certificates and configuration in `example/secure/tls`. +Each node writes its logs beside its home, in `node1/logs` or `node2/logs`. +Its include file is `example/secure/tls/solr.in.sh`. +Unlike the manual steps above, the shortcut generates a fresh password each run instead of reusing a fixed one; it prints that password, and the demonstration accounts `admin`, `index`, `search`, `zk-admin`, and `zk-readonly` all use it. +The example performs the setup from this tutorial and prints its configuration path and commands for checking status and stopping the nodes. +Inspect its generated files to connect the automated setup to the manual steps above. + +For unattended startup, a different first port, or a separate cluster directory, use the existing start options: + +[source,bash] +---- +bin/solr start -e secure --no-prompt -p 8993 \ + --solr-home "$PWD/example/secure/another-cluster" +---- + +The second node uses the next port; embedded ZooKeeper uses the first port plus 1000. +Re-running the example creates a fresh cluster. +To retain this exercise's configuration and indexed data, use the manual stop/start commands above. +The example supports `--no-prompt`, `-p`, `--solr-home`, `-m`, and `--force`; other startup overrides are not supported.
