From bd64bd6ff3866413d114d66546a3f52ef3d57d9d Mon Sep 17 00:00:00 2001 From: Ryan Ernst Date: Tue, 1 Mar 2016 12:21:05 -0800 Subject: [PATCH] Switched licence gen and keypair gen tools to use jopt simple Original commit: elastic/x-pack-elasticsearch@310229b4a5dff8c8f9540cb8d99b34891a08982b --- .../licensor/tools/KeyPairGeneratorTool.java | 135 ++++++--------- .../licensor/tools/LicenseGeneratorTool.java | 154 +++++++++--------- .../tools/KeyPairGenerationToolTests.java | 88 +++------- .../tools/LicenseGenerationToolTests.java | 141 +++++----------- .../tools/LicenseVerificationToolTests.java | 2 +- 5 files changed, 189 insertions(+), 331 deletions(-) diff --git a/elasticsearch/license/licensor/src/main/java/org/elasticsearch/license/licensor/tools/KeyPairGeneratorTool.java b/elasticsearch/license/licensor/src/main/java/org/elasticsearch/license/licensor/tools/KeyPairGeneratorTool.java index a5ef4a2492c..64bc8b85e84 100644 --- a/elasticsearch/license/licensor/src/main/java/org/elasticsearch/license/licensor/tools/KeyPairGeneratorTool.java +++ b/elasticsearch/license/licensor/src/main/java/org/elasticsearch/license/licensor/tools/KeyPairGeneratorTool.java @@ -5,105 +5,74 @@ */ package org.elasticsearch.license.licensor.tools; -import org.apache.commons.cli.CommandLine; -import org.elasticsearch.common.SuppressForbidden; -import org.elasticsearch.common.cli.CliTool; -import org.elasticsearch.common.cli.CliToolConfig; -import org.elasticsearch.common.cli.Terminal; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.env.Environment; - -import java.io.IOException; +import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyPair; import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; -import static org.elasticsearch.common.cli.CliToolConfig.Builder.cmd; -import static org.elasticsearch.common.cli.CliToolConfig.Builder.option; -import static org.elasticsearch.common.cli.CliToolConfig.config; +import joptsimple.OptionSet; +import joptsimple.OptionSpec; +import org.elasticsearch.cli.Command; +import org.elasticsearch.cli.ExitCodes; +import org.elasticsearch.cli.UserError; +import org.elasticsearch.common.cli.Terminal; + import static org.elasticsearch.license.core.CryptUtils.writeEncryptedPrivateKey; import static org.elasticsearch.license.core.CryptUtils.writeEncryptedPublicKey; -public class KeyPairGeneratorTool extends CliTool { +public class KeyPairGeneratorTool extends Command { - public static final String NAME = "key-pair-generator"; - private static final CliToolConfig CONFIG = config("licensor", KeyPairGeneratorTool.class) - .cmds(KeyGenerator.CMD) - .build(); + private final OptionSpec publicKeyPathOption; + private final OptionSpec privateKeyPathOption; public KeyPairGeneratorTool() { - super(CONFIG); - } - - @Override - protected Command parse(String s, CommandLine commandLine) throws Exception { - return KeyGenerator.parse(terminal, commandLine, env); - } - - public static class KeyGenerator extends Command { - - private static final CliToolConfig.Cmd CMD = cmd(NAME, KeyGenerator.class) - .options( - option("pub", "publicKeyPath").required(true).hasArg(true), - option("pri", "privateKeyPath").required(true).hasArg(true) - ).build(); - - public final Path publicKeyPath; - public final Path privateKeyPath; - - protected KeyGenerator(Terminal terminal, Path publicKeyPath, Path privateKeyPath) { - super(terminal); - this.privateKeyPath = privateKeyPath; - this.publicKeyPath = publicKeyPath; - } - - public static Command parse(Terminal terminal, CommandLine commandLine, Environment environment) { - Path publicKeyPath = environment.binFile().getParent().resolve(commandLine.getOptionValue("publicKeyPath")); - Path privateKeyPath = environment.binFile().getParent().resolve(commandLine.getOptionValue("privateKeyPath")); - - if (Files.exists(privateKeyPath)) { - return exitCmd(ExitStatus.USAGE, terminal, privateKeyPath + " already exists"); - } else if (Files.exists(publicKeyPath)) { - return exitCmd(ExitStatus.USAGE, terminal, publicKeyPath + " already exists"); - } - return new KeyGenerator(terminal, publicKeyPath, privateKeyPath); - } - - @Override - public ExitStatus execute(Settings settings, Environment env) throws Exception { - KeyPair keyPair = generateKeyPair(privateKeyPath, publicKeyPath); - terminal.println(Terminal.Verbosity.VERBOSE, "generating key pair [public key: " + publicKeyPath + ", private key: " - + privateKeyPath + "]"); - return (keyPair != null) ? ExitStatus.OK : ExitStatus.CANT_CREATE; - } - - private static KeyPair generateKeyPair(Path privateKeyPath, Path publicKeyPath) throws IOException, NoSuchAlgorithmException { - SecureRandom random = new SecureRandom(); - - KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); - keyGen.initialize(2048, random); - KeyPair keyPair = keyGen.generateKeyPair(); - - saveKeyPairToFiles(keyPair, privateKeyPath, publicKeyPath); - return keyPair; - } - } - - private static void saveKeyPairToFiles(KeyPair keyPair, Path privateKeyPath, Path publicKeyPath) throws IOException { - Files.write(privateKeyPath, writeEncryptedPrivateKey(keyPair.getPrivate())); - Files.write(publicKeyPath, writeEncryptedPublicKey(keyPair.getPublic())); + super("Generates a key pair with RSA 2048-bit security"); + // TODO: in jopt-simple 5.0 we can use a PathConverter to take Path instead of File + this.publicKeyPathOption = parser.accepts("publicKeyPath", "public key path") + .withRequiredArg().ofType(File.class).required(); + this.privateKeyPathOption = parser.accepts("privateKeyPath", "private key path") + .withRequiredArg().ofType(File.class).required(); } public static void main(String[] args) throws Exception { - ExitStatus exitStatus = new KeyPairGeneratorTool().execute(args); - exit(exitStatus.status()); + exit(new KeyPairGeneratorTool().main(args, Terminal.DEFAULT)); } - @SuppressForbidden(reason = "Allowed to exit explicitly from #main()") - private static void exit(int status) { - System.exit(status); + @Override + protected void printAdditionalHelp(Terminal terminal) { + terminal.println("This tool generates and saves a key pair to the provided publicKeyPath"); + terminal.println("and privateKeyPath. The tool checks the existence of the provided key paths"); + terminal.println("and will not override if any existing keys are found."); + terminal.println(""); + } + + @Override + protected int execute(Terminal terminal, OptionSet options) throws Exception { + File publicKeyPath = publicKeyPathOption.value(options); + File privateKeyPath = privateKeyPathOption.value(options); + execute(terminal, publicKeyPath.toPath(), privateKeyPath.toPath()); + return ExitCodes.OK; + } + + // pkg private for tests + void execute(Terminal terminal, Path publicKeyPath, Path privateKeyPath) throws Exception { + if (Files.exists(privateKeyPath)) { + throw new UserError(ExitCodes.USAGE, privateKeyPath + " already exists"); + } else if (Files.exists(publicKeyPath)) { + throw new UserError(ExitCodes.USAGE, publicKeyPath + " already exists"); + } + + SecureRandom random = new SecureRandom(); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); + keyGen.initialize(2048, random); + KeyPair keyPair = keyGen.generateKeyPair(); + + Files.write(privateKeyPath, writeEncryptedPrivateKey(keyPair.getPrivate())); + Files.write(publicKeyPath, writeEncryptedPublicKey(keyPair.getPublic())); + + terminal.println(Terminal.Verbosity.VERBOSE, "generating key pair [public key: " + publicKeyPath + ", private key: " + + privateKeyPath + "]"); } } diff --git a/elasticsearch/license/licensor/src/main/java/org/elasticsearch/license/licensor/tools/LicenseGeneratorTool.java b/elasticsearch/license/licensor/src/main/java/org/elasticsearch/license/licensor/tools/LicenseGeneratorTool.java index 7d3ae1f7cca..3cfd2dcf742 100644 --- a/elasticsearch/license/licensor/src/main/java/org/elasticsearch/license/licensor/tools/LicenseGeneratorTool.java +++ b/elasticsearch/license/licensor/src/main/java/org/elasticsearch/license/licensor/tools/LicenseGeneratorTool.java @@ -5,7 +5,13 @@ */ package org.elasticsearch.license.licensor.tools; +import joptsimple.OptionSet; +import joptsimple.OptionSpec; import org.apache.commons.cli.CommandLine; +import org.apache.lucene.index.Term; +import org.elasticsearch.cli.Command; +import org.elasticsearch.cli.ExitCodes; +import org.elasticsearch.cli.UserError; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.cli.CliTool; import org.elasticsearch.common.cli.CliToolConfig; @@ -19,6 +25,7 @@ import org.elasticsearch.env.Environment; import org.elasticsearch.license.core.License; import org.elasticsearch.license.licensor.LicenseSigner; +import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -27,99 +34,84 @@ import static org.elasticsearch.common.cli.CliToolConfig.Builder.cmd; import static org.elasticsearch.common.cli.CliToolConfig.Builder.option; import static org.elasticsearch.common.cli.CliToolConfig.config; -public class LicenseGeneratorTool extends CliTool { - public static final String NAME = "license-generator"; +public class LicenseGeneratorTool extends Command { - private static final CliToolConfig CONFIG = config("licensor", LicenseGeneratorTool.class) - .cmds(LicenseGenerator.CMD) - .build(); + private final OptionSpec publicKeyPathOption; + private final OptionSpec privateKeyPathOption; + private final OptionSpec licenseOption; + private final OptionSpec licenseFileOption; public LicenseGeneratorTool() { - super(CONFIG); + super("Generates signed elasticsearch license(s) for a given license spec(s)"); + publicKeyPathOption = parser.accepts("publicKeyPath", "path to public key file") + .withRequiredArg().ofType(File.class).required(); + privateKeyPathOption = parser.accepts("privateKeyPath", "path to private key file") + .withRequiredArg().ofType(File.class).required(); + // TODO: with jopt-simple 5.0, we can make these requiredUnless each other + // which is effectively "one must be present" + licenseOption = parser.accepts("license", "license json spec") + .withRequiredArg(); + licenseFileOption = parser.accepts("licenseFile", "license json spec file") + .withRequiredArg().ofType(File.class); } @Override - protected Command parse(String s, CommandLine commandLine) throws Exception { - return LicenseGenerator.parse(terminal, commandLine, env); + protected void printAdditionalHelp(Terminal terminal) { + terminal.println("This tool generate elasticsearch license(s) for the provided"); + terminal.println("license spec(s). The tool can take arbitrary number of"); + terminal.println("`--license` and/or `--licenseFile` to generate corresponding"); + terminal.println("signed license(s)."); + terminal.println(""); } - public static class LicenseGenerator extends Command { - - private static final CliToolConfig.Cmd CMD = cmd(NAME, LicenseGenerator.class) - .options( - option("pub", "publicKeyPath").required(true).hasArg(true), - option("pri", "privateKeyPath").required(true).hasArg(true), - option("l", "license").required(false).hasArg(true), - option("lf", "licenseFile").required(false).hasArg(true) - ).build(); - - public final License licenseSpec; - public final Path publicKeyFilePath; - public final Path privateKeyFilePath; - - public LicenseGenerator(Terminal terminal, Path publicKeyFilePath, Path privateKeyFilePath, License licenseSpec) { - super(terminal); - this.licenseSpec = licenseSpec; - this.privateKeyFilePath = privateKeyFilePath; - this.publicKeyFilePath = publicKeyFilePath; + @Override + protected int execute(Terminal terminal, OptionSet options) throws Exception { + Path publicKeyPath = publicKeyPathOption.value(options).toPath(); + Path privateKeyPath = privateKeyPathOption.value(options).toPath(); + String licenseSpecString = null; + if (options.has(licenseOption)) { + licenseSpecString = licenseOption.value(options); } - - public static Command parse(Terminal terminal, CommandLine commandLine, Environment environment) throws IOException { - Path publicKeyPath = environment.binFile().getParent().resolve(commandLine.getOptionValue("publicKeyPath")); - Path privateKeyPath = environment.binFile().getParent().resolve(commandLine.getOptionValue("privateKeyPath")); - String licenseSpecSource = commandLine.getOptionValue("license"); - String licenseSpecSourceFile = commandLine.getOptionValue("licenseFile"); - - if (!Files.exists(privateKeyPath)) { - return exitCmd(ExitStatus.USAGE, terminal, privateKeyPath + " does not exist"); - } else if (!Files.exists(publicKeyPath)) { - return exitCmd(ExitStatus.USAGE, terminal, publicKeyPath + " does not exist"); - } - - License license = null; - if (licenseSpecSource != null) { - license = License.fromSource(licenseSpecSource); - } else if (licenseSpecSourceFile != null) { - Path licenseSpecPath = environment.binFile().getParent().resolve(licenseSpecSourceFile); - if (!Files.exists(licenseSpecPath)) { - return exitCmd(ExitStatus.USAGE, terminal, licenseSpecSourceFile + " does not exist"); - } - license = License.fromSource(Files.readAllBytes(licenseSpecPath)); - } - - if (license == null) { - return exitCmd(ExitStatus.USAGE, terminal, "no license spec provided"); - } - return new LicenseGenerator(terminal, publicKeyPath, privateKeyPath, license); - } - - @Override - public ExitStatus execute(Settings settings, Environment env) throws Exception { - - // sign - License license = new LicenseSigner(privateKeyFilePath, publicKeyFilePath).sign(licenseSpec); - - // dump - XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); - builder.startObject(); - builder.startObject("license"); - license.toInnerXContent(builder, ToXContent.EMPTY_PARAMS); - builder.endObject(); - builder.endObject(); - builder.flush(); - terminal.println(builder.string()); - - return ExitStatus.OK; + Path licenseSpecPath = null; + if (options.has(licenseFileOption)) { + licenseSpecPath = licenseFileOption.value(options).toPath(); } + execute(terminal, publicKeyPath, privateKeyPath, licenseSpecString, licenseSpecPath); + return ExitCodes.OK; } - public static void main(String[] args) throws Exception { - ExitStatus exitStatus = new LicenseGeneratorTool().execute(args); - exit(exitStatus.status()); - } + // pkg private for testing + void execute(Terminal terminal, Path publicKeyPath, Path privateKeyPath, + String licenseSpecString, Path licenseSpecPath) throws Exception { + if (Files.exists(privateKeyPath) == false) { + throw new UserError(ExitCodes.USAGE, privateKeyPath + " does not exist"); + } else if (Files.exists(publicKeyPath) == false) { + throw new UserError(ExitCodes.USAGE, publicKeyPath + " does not exist"); + } - @SuppressForbidden(reason = "Allowed to exit explicitly from #main()") - private static void exit(int status) { - System.exit(status); + final License licenseSpec; + if (licenseSpecString != null) { + licenseSpec = License.fromSource(licenseSpecString); + } else if (licenseSpecPath != null) { + if (Files.exists(licenseSpecPath) == false) { + throw new UserError(ExitCodes.USAGE, licenseSpecPath + " does not exist"); + } + licenseSpec = License.fromSource(Files.readAllBytes(licenseSpecPath)); + } else { + throw new UserError(ExitCodes.USAGE, "Must specify either --license or --licenseFile"); + } + + // sign + License license = new LicenseSigner(privateKeyPath, publicKeyPath).sign(licenseSpec); + + // dump + XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); + builder.startObject(); + builder.startObject("license"); + license.toInnerXContent(builder, ToXContent.EMPTY_PARAMS); + builder.endObject(); + builder.endObject(); + builder.flush(); + terminal.println(builder.string()); } } diff --git a/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/KeyPairGenerationToolTests.java b/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/KeyPairGenerationToolTests.java index aaa14753f16..348c3b58279 100644 --- a/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/KeyPairGenerationToolTests.java +++ b/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/KeyPairGenerationToolTests.java @@ -8,87 +8,39 @@ package org.elasticsearch.license.licensor.tools; import java.nio.file.Files; import java.nio.file.Path; -import org.elasticsearch.common.cli.CliTool.Command; -import org.elasticsearch.common.cli.CliTool.ExitStatus; -import org.elasticsearch.common.cli.CliToolTestCase; -import org.elasticsearch.common.cli.UserError; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.env.Environment; -import org.elasticsearch.license.licensor.tools.KeyPairGeneratorTool.KeyGenerator; +import org.elasticsearch.cli.ExitCodes; +import org.elasticsearch.cli.UserError; +import org.elasticsearch.common.cli.Terminal; +import org.elasticsearch.test.ESTestCase; import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.core.IsEqual.equalTo; -public class KeyPairGenerationToolTests extends CliToolTestCase { - public void testParsingMissingPath() throws Exception { +public class KeyPairGenerationToolTests extends ESTestCase { + + public void testMissingKeyPaths() throws Exception { KeyPairGeneratorTool keyPairGeneratorTool = new KeyPairGeneratorTool(); - Path tempFile = createTempFile(); + Path exists = createTempFile(); + Path dne = createTempDir().resolve("dne"); UserError e = expectThrows(UserError.class, () -> { - keyPairGeneratorTool.parse(KeyPairGeneratorTool.NAME, - new String[]{"--privateKeyPath", tempFile.toAbsolutePath().toString()}); + keyPairGeneratorTool.execute(Terminal.DEFAULT, exists, dne); }); assertThat(e.getMessage(), containsString("pub")); + assertEquals(ExitCodes.USAGE, e.exitCode); e = expectThrows(UserError.class, () -> { - keyPairGeneratorTool.parse(KeyPairGeneratorTool.NAME, - new String[] { "--publicKeyPath", tempFile.toAbsolutePath().toString() }); + keyPairGeneratorTool.execute(Terminal.DEFAULT, dne, exists); }); assertThat(e.getMessage(), containsString("pri")); + assertEquals(ExitCodes.USAGE, e.exitCode); } - public void testParsingNeverOverrideKey() throws Exception { + public void testTool() throws Exception { KeyPairGeneratorTool keyPairGeneratorTool = new KeyPairGeneratorTool(); - Path tempFile = createTempFile(); - Path tempFile2 = createTempFile(); - String nonExistentFilePath = tempFile2.toAbsolutePath().toString(); - Files.delete(tempFile2); - assertThat(Files.exists(tempFile2), equalTo(false)); + Path keysDir = createTempDir(); + Path publicKeyFilePath = keysDir.resolve("public"); + Path privateKeyFilePath = keysDir.resolve("private"); - Command command = keyPairGeneratorTool.parse(KeyPairGeneratorTool.NAME, new String[] { - "--privateKeyPath", tempFile.toAbsolutePath().toString(), - "--publicKeyPath", nonExistentFilePath }); - - assertThat(command, instanceOf(Command.Exit.class)); - Command.Exit exitCommand = (Command.Exit) command; - assertThat(exitCommand.status(), equalTo(ExitStatus.USAGE)); - - command = keyPairGeneratorTool.parse(KeyPairGeneratorTool.NAME, new String[] { - "--publicKeyPath", tempFile.toAbsolutePath().toString(), - "--privateKeyPath", nonExistentFilePath }); - - assertThat(command, instanceOf(Command.Exit.class)); - exitCommand = (Command.Exit) command; - assertThat(exitCommand.status(), equalTo(ExitStatus.USAGE)); - } - - public void testToolSimple() throws Exception { - KeyPairGeneratorTool keyPairGeneratorTool = new KeyPairGeneratorTool(); - Path publicKeyFilePath = createTempFile().toAbsolutePath(); - Path privateKeyFilePath = createTempFile().toAbsolutePath(); - Settings settings = Settings.builder().put("path.home", createTempDir("KeyPairGenerationToolTests")).build(); - - Files.delete(publicKeyFilePath); - Files.delete(privateKeyFilePath); - assertThat(Files.exists(publicKeyFilePath), equalTo(false)); - assertThat(Files.exists(privateKeyFilePath), equalTo(false)); - - Command command = keyPairGeneratorTool.parse(KeyPairGeneratorTool.NAME, new String[] { - "--privateKeyPath", privateKeyFilePath.toString(), - "--publicKeyPath", publicKeyFilePath.toString() }); - - assertThat(command, instanceOf(KeyGenerator.class)); - KeyGenerator keyGenerator = (KeyGenerator) command; - assertThat(keyGenerator.privateKeyPath, equalTo(privateKeyFilePath)); - assertThat(keyGenerator.publicKeyPath, equalTo(publicKeyFilePath)); - - assertThat(Files.exists(publicKeyFilePath), equalTo(false)); - assertThat(Files.exists(privateKeyFilePath), equalTo(false)); - - assertThat(keyGenerator.execute(settings, new Environment(settings)), equalTo(ExitStatus.OK)); - assertThat(Files.exists(publicKeyFilePath), equalTo(true)); - assertThat(Files.exists(privateKeyFilePath), equalTo(true)); - - Files.delete(publicKeyFilePath); - Files.delete(privateKeyFilePath); + keyPairGeneratorTool.execute(Terminal.DEFAULT, publicKeyFilePath, privateKeyFilePath); + assertTrue(publicKeyFilePath.toString(), Files.exists(publicKeyFilePath)); + assertTrue(privateKeyFilePath.toString(), Files.exists(privateKeyFilePath)); } } diff --git a/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/LicenseGenerationToolTests.java b/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/LicenseGenerationToolTests.java index a001849c54d..7e8cfc6bf37 100644 --- a/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/LicenseGenerationToolTests.java +++ b/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/LicenseGenerationToolTests.java @@ -9,131 +9,76 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import org.elasticsearch.common.cli.CliTool.Command; -import org.elasticsearch.common.cli.CliTool.ExitStatus; +import org.elasticsearch.cli.ExitCodes; +import org.elasticsearch.cli.UserError; import org.elasticsearch.common.cli.CliToolTestCase; -import org.elasticsearch.common.cli.UserError; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.env.Environment; +import org.elasticsearch.common.cli.Terminal; import org.elasticsearch.license.core.License; import org.elasticsearch.license.licensor.TestUtils; -import org.elasticsearch.license.licensor.tools.LicenseGeneratorTool.LicenseGenerator; +import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.core.IsEqual.equalTo; - -public class LicenseGenerationToolTests extends CliToolTestCase { +public class LicenseGenerationToolTests extends ESTestCase { protected Path pubKeyPath = null; protected Path priKeyPath = null; @Before public void setup() throws Exception { - logger.error("project.basedir [{}]", System.getProperty("project.basedir")); pubKeyPath = getDataPath(TestUtils.PUBLIC_KEY_RESOURCE); priKeyPath = getDataPath(TestUtils.PRIVATE_KEY_RESOURCE); } - public void testParsingNonExistentKeyFile() throws Exception { - TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); + public void testMissingKeyPaths() throws Exception { LicenseGeneratorTool licenseGeneratorTool = new LicenseGeneratorTool(); - Command command = licenseGeneratorTool.parse(LicenseGeneratorTool.NAME, - new String[] {"--license", TestUtils.generateLicenseSpecString(inputLicenseSpec), - "--publicKeyPath", pubKeyPath.toString().concat("invalid"), - "--privateKeyPath", priKeyPath.toString() }); - - assertThat(command, instanceOf(Command.Exit.class)); - Command.Exit exitCommand = (Command.Exit) command; - assertThat(exitCommand.status(), equalTo(ExitStatus.USAGE)); - - command = licenseGeneratorTool.parse(LicenseGeneratorTool.NAME, - new String[] {"--license", TestUtils.generateLicenseSpecString(inputLicenseSpec), - "--privateKeyPath", priKeyPath.toString().concat("invalid"), - "--publicKeyPath", pubKeyPath.toString() }); - - assertThat(command, instanceOf(Command.Exit.class)); - exitCommand = (Command.Exit) command; - assertThat(exitCommand.status(), equalTo(ExitStatus.USAGE)); - } - - public void testParsingMissingLicenseSpec() throws Exception { - LicenseGeneratorTool licenseGeneratorTool = new LicenseGeneratorTool(); - Command command = licenseGeneratorTool.parse(LicenseGeneratorTool.NAME, - new String[] { "--publicKeyPath", pubKeyPath.toString(), - "--privateKeyPath", priKeyPath.toString() }); - - assertThat(command, instanceOf(Command.Exit.class)); - Command.Exit exitCommand = (Command.Exit) command; - assertThat(exitCommand.status(), equalTo(ExitStatus.USAGE)); - } - - public void testParsingMissingArgs() throws Exception { - TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); - LicenseGeneratorTool licenseGeneratorTool = new LicenseGeneratorTool(); - boolean pubKeyMissing = randomBoolean(); + Path pub = createTempDir().resolve("pub"); + Path priv = createTempDir().resolve("pri"); UserError e = expectThrows(UserError.class, () -> { - licenseGeneratorTool.parse(LicenseGeneratorTool.NAME, - new String[]{"--license", TestUtils.generateLicenseSpecString(inputLicenseSpec), - ((pubKeyMissing) ? "--privateKeyPath" : "--publicKeyPath"), - ((pubKeyMissing) ? priKeyPath.toString() : pubKeyPath.toString())}); + licenseGeneratorTool.execute(Terminal.DEFAULT, pub, priv, null, null); }); - assertThat(e.getMessage(), containsString((pubKeyMissing) ? "pub" : "pri")); + assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist")); + assertEquals(ExitCodes.USAGE, e.exitCode); + + Files.createFile(pub); + e = expectThrows(UserError.class, () -> { + licenseGeneratorTool.execute(Terminal.DEFAULT, pub, priv, null, null); + }); + assertTrue(e.getMessage(), e.getMessage().contains("pri does not exist")); + assertEquals(ExitCodes.USAGE, e.exitCode); } - public void testParsingSimple() throws Exception { - TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); + public void testMissingLicenseSpec() throws Exception { LicenseGeneratorTool licenseGeneratorTool = new LicenseGeneratorTool(); - Command command = licenseGeneratorTool.parse(LicenseGeneratorTool.NAME, - new String[]{"--license", TestUtils.generateLicenseSpecString(inputLicenseSpec), - "--publicKeyPath", pubKeyPath.toString(), - "--privateKeyPath", priKeyPath.toString() }); - - assertThat(command, instanceOf(LicenseGenerator.class)); - LicenseGenerator licenseGenerator = (LicenseGenerator) command; - assertThat(licenseGenerator.publicKeyFilePath, equalTo(pubKeyPath)); - assertThat(licenseGenerator.privateKeyFilePath, equalTo(priKeyPath)); - TestUtils.assertLicenseSpec(inputLicenseSpec, licenseGenerator.licenseSpec); + UserError e = expectThrows(UserError.class, () -> { + licenseGeneratorTool.execute(Terminal.DEFAULT, pubKeyPath, priKeyPath, null, null); + }); + assertTrue(e.getMessage(), e.getMessage().contains("Must specify either --license or --licenseFile")); + assertEquals(ExitCodes.USAGE, e.exitCode); } - public void testParsingLicenseFile() throws Exception { + public void testLicenseSpecString() throws Exception { TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); - Path tempFile = createTempFile(); - Files.write(tempFile, TestUtils.generateLicenseSpecString(inputLicenseSpec).getBytes(StandardCharsets.UTF_8)); - - LicenseGeneratorTool licenseGeneratorTool = new LicenseGeneratorTool(); - Command command = licenseGeneratorTool.parse(LicenseGeneratorTool.NAME, - new String[] { "--licenseFile", tempFile.toAbsolutePath().toString(), - "--publicKeyPath", pubKeyPath.toString(), - "--privateKeyPath", priKeyPath.toString() }); - - assertThat(command, instanceOf(LicenseGenerator.class)); - LicenseGenerator licenseGenerator = (LicenseGenerator) command; - assertThat(licenseGenerator.publicKeyFilePath, equalTo(pubKeyPath)); - assertThat(licenseGenerator.privateKeyFilePath, equalTo(priKeyPath)); - TestUtils.assertLicenseSpec(inputLicenseSpec, licenseGenerator.licenseSpec); - } - - public void testTool() throws Exception { - TestUtils.LicenseSpec licenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); - License license = License.fromSource(TestUtils.generateLicenseSpecString(licenseSpec).getBytes(StandardCharsets.UTF_8)); - String output = runLicenseGenerationTool(pubKeyPath, priKeyPath, license, ExitStatus.OK); + String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec); + String output = runTool(licenseSpecString, null); License outputLicense = License.fromSource(output.getBytes(StandardCharsets.UTF_8)); - TestUtils.assertLicenseSpec(licenseSpec, outputLicense); + TestUtils.assertLicenseSpec(inputLicenseSpec, outputLicense); } - private String runLicenseGenerationTool(Path pubKeyPath, Path priKeyPath, License licenseSpec, - ExitStatus expectedExitStatus) throws Exception { - CaptureOutputTerminal outputTerminal = new CaptureOutputTerminal(); - Settings settings = Settings.builder().put("path.home", createTempDir("LicenseGenerationToolTests")).build(); - LicenseGenerator licenseGenerator = new LicenseGenerator(outputTerminal, pubKeyPath, priKeyPath, licenseSpec); - assertThat(execute(licenseGenerator, settings), equalTo(expectedExitStatus)); - assertThat(outputTerminal.getTerminalOutput().size(), equalTo(1)); + public void testLicenseSpecFile() throws Exception { + TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); + String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec); + Path licenseSpecFile = createTempFile(); + Files.write(licenseSpecFile, licenseSpecString.getBytes(StandardCharsets.UTF_8)); + String output = runTool(null, licenseSpecFile); + License outputLicense = License.fromSource(output.getBytes(StandardCharsets.UTF_8)); + TestUtils.assertLicenseSpec(inputLicenseSpec, outputLicense); + } + + private String runTool(String licenseSpecString, Path licenseSpecPath) throws Exception { + CliToolTestCase.CaptureOutputTerminal outputTerminal = new CliToolTestCase.CaptureOutputTerminal(); + LicenseGeneratorTool licenseGeneratorTool = new LicenseGeneratorTool(); + licenseGeneratorTool.execute(outputTerminal, pubKeyPath, priKeyPath, licenseSpecString, licenseSpecPath); + assertEquals(1, outputTerminal.getTerminalOutput().size()); return outputTerminal.getTerminalOutput().get(0); } - private ExitStatus execute(Command cmd, Settings settings) throws Exception { - Environment env = new Environment(settings); - return cmd.execute(settings, env); - } } diff --git a/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/LicenseVerificationToolTests.java b/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/LicenseVerificationToolTests.java index 5c2e519bdf1..b8bfd005795 100644 --- a/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/LicenseVerificationToolTests.java +++ b/elasticsearch/license/licensor/src/test/java/org/elasticsearch/license/licensor/tools/LicenseVerificationToolTests.java @@ -14,7 +14,7 @@ import java.util.List; import org.elasticsearch.common.cli.CliTool.Command; import org.elasticsearch.common.cli.CliTool.ExitStatus; import org.elasticsearch.common.cli.CliToolTestCase; -import org.elasticsearch.common.cli.UserError; +import org.elasticsearch.cli.UserError; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.env.Environment;