Adjust line-lengths for license-tools

This commit is a reformatting of the source files in license-tools to
bring them under the 100-column line-length limit.

Original commit: elastic/x-pack-elasticsearch@7d7a6c7a23
This commit is contained in:
Jason Tedor 2017-03-17 14:16:29 -04:00
parent ca931f4b39
commit edf810a422
10 changed files with 232 additions and 111 deletions

View File

@ -5,17 +5,6 @@
<suppressions> <suppressions>
<!-- On Windows, Checkstyle matches files using \ path separator --> <!-- On Windows, Checkstyle matches files using \ path separator -->
<suppress files="qa[/\\]smoke-test-plugins-ssl[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestMonitoringWithSecurityIT.java" checks="LineLength" />
<suppress files="qa[/\\]smoke-test-plugins-ssl[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestPluginsSslClientYamlTestSuiteIT.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]LicenseSigner.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]tools[/\\]KeyPairGeneratorTool.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]tools[/\\]LicenseGeneratorTool.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]tools[/\\]LicenseVerificationTool.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]LicenseVerificationTests.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]TestUtils.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]tools[/\\]KeyPairGenerationToolTests.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]tools[/\\]LicenseGenerationToolTests.java" checks="LineLength" />
<suppress files="license-tools[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]licensor[/\\]tools[/\\]LicenseVerificationToolTests.java" checks="LineLength" />
<suppress files="plugin[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]common[/\\]network[/\\]InetAddressHelper.java" checks="LineLength" /> <suppress files="plugin[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]common[/\\]network[/\\]InetAddressHelper.java" checks="LineLength" />
<suppress files="plugin[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]CryptUtils.java" checks="LineLength" /> <suppress files="plugin[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]CryptUtils.java" checks="LineLength" />
<suppress files="plugin[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]DateUtils.java" checks="LineLength" /> <suppress files="plugin[/\\]src[/\\]main[/\\]java[/\\]org[/\\]elasticsearch[/\\]license[/\\]DateUtils.java" checks="LineLength" />
@ -1404,6 +1393,8 @@
<suppress files="qa[/\\]smoke-test-monitoring-with-security[/\\]insufficient-rights[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestMonitoringWithSecurityClientYamlTestSuiteIT.java" checks="LineLength" /> <suppress files="qa[/\\]smoke-test-monitoring-with-security[/\\]insufficient-rights[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestMonitoringWithSecurityClientYamlTestSuiteIT.java" checks="LineLength" />
<suppress files="qa[/\\]smoke-test-monitoring-with-security[/\\]sufficient-rights[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestMonitoringWithSecurityClientYamlTestSuiteIT.java" checks="LineLength" /> <suppress files="qa[/\\]smoke-test-monitoring-with-security[/\\]sufficient-rights[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestMonitoringWithSecurityClientYamlTestSuiteIT.java" checks="LineLength" />
<suppress files="qa[/\\]smoke-test-plugins[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]XSmokeTestPluginsClientYamlTestSuiteIT.java" checks="LineLength" /> <suppress files="qa[/\\]smoke-test-plugins[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]XSmokeTestPluginsClientYamlTestSuiteIT.java" checks="LineLength" />
<suppress files="qa[/\\]smoke-test-plugins-ssl[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestMonitoringWithSecurityIT.java" checks="LineLength" />
<suppress files="qa[/\\]smoke-test-plugins-ssl[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestPluginsSslClientYamlTestSuiteIT.java" checks="LineLength" />
<suppress files="qa[/\\]smoke-test-security-with-mustache[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestSecurityWithMustacheClientYamlTestSuiteIT.java" checks="LineLength" /> <suppress files="qa[/\\]smoke-test-security-with-mustache[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestSecurityWithMustacheClientYamlTestSuiteIT.java" checks="LineLength" />
<suppress files="qa[/\\]smoke-test-watcher-with-mustache[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestWatchesWithMustacheClientYamlTestSuiteTestCase.java" checks="LineLength" /> <suppress files="qa[/\\]smoke-test-watcher-with-mustache[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]SmokeTestWatchesWithMustacheClientYamlTestSuiteTestCase.java" checks="LineLength" />
<suppress files="qa[/\\]smoke-test-watcher-with-mustache[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]WatcherTemplateIT.java" checks="LineLength" /> <suppress files="qa[/\\]smoke-test-watcher-with-mustache[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]smoketest[/\\]WatcherTemplateIT.java" checks="LineLength" />

View File

@ -25,10 +25,11 @@ import java.security.Signature;
import java.security.SignatureException; import java.security.SignatureException;
import java.util.Base64; import java.util.Base64;
import java.util.Collections; import java.util.Collections;
import java.util.Map;
/** /**
* Responsible for generating a license signature according to * Responsible for generating a license signature according to the signature spec and sign it with
* the signature spec and sign it with the provided encrypted private key * the provided encrypted private key
*/ */
public class LicenseSigner { public class LicenseSigner {
@ -44,15 +45,18 @@ public class LicenseSigner {
} }
/** /**
* Generates a signature for the <code>licenseSpec</code>. * Generates a signature for the {@code licenseSpec}. Signature structure:
* Signature structure: * <code>
* | VERSION | MAGIC | PUB_KEY_DIGEST | SIGNED_LICENSE_CONTENT | * | VERSION | MAGIC | PUB_KEY_DIGEST | SIGNED_LICENSE_CONTENT |
* </code>
* *
* @return a signed License * @return a signed License
*/ */
public License sign(License licenseSpec) throws IOException { public License sign(License licenseSpec) throws IOException {
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
licenseSpec.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); final Map<String, String> licenseSpecViewMode =
Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true");
licenseSpec.toXContent(contentBuilder, new ToXContent.MapParams(licenseSpecViewMode));
final byte[] signedContent; final byte[] signedContent;
try { try {
final Signature rsa = Signature.getInstance("SHA512withRSA"); final Signature rsa = Signature.getInstance("SHA512withRSA");
@ -63,7 +67,10 @@ public class LicenseSigner {
rsa.update(ref.bytes, ref.offset, ref.length); rsa.update(ref.bytes, ref.offset, ref.length);
} }
signedContent = rsa.sign(); signedContent = rsa.sign();
} catch (InvalidKeyException | IOException | NoSuchAlgorithmException | SignatureException e) { } catch (InvalidKeyException
| IOException
| NoSuchAlgorithmException
| SignatureException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
final byte[] magic = new byte[MAGIC_LENGTH]; final byte[] magic = new byte[MAGIC_LENGTH];

View File

@ -44,8 +44,8 @@ public class KeyPairGeneratorTool extends Command {
@Override @Override
protected void printAdditionalHelp(Terminal terminal) { protected void printAdditionalHelp(Terminal terminal) {
terminal.println("This tool generates and saves a key pair to the provided publicKeyPath"); 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 privateKeyPath. The tool checks the existence of the provided key");
terminal.println("and will not override if any existing keys are found."); terminal.println("paths and will not override if any existing keys are found.");
terminal.println(""); terminal.println("");
} }
@ -67,7 +67,11 @@ public class KeyPairGeneratorTool extends Command {
Files.write(privateKeyPath, writeEncryptedPrivateKey(keyPair.getPrivate())); Files.write(privateKeyPath, writeEncryptedPrivateKey(keyPair.getPrivate()));
Files.write(publicKeyPath, writeEncryptedPublicKey(keyPair.getPublic())); Files.write(publicKeyPath, writeEncryptedPublicKey(keyPair.getPublic()));
terminal.println(Terminal.Verbosity.VERBOSE, "generating key pair [public key: " + publicKeyPath + ", private key: " terminal.println(
Terminal.Verbosity.VERBOSE,
"generating key pair [public key: "
+ publicKeyPath
+ ", private key: "
+ privateKeyPath + "]"); + privateKeyPath + "]");
} }
@ -75,4 +79,5 @@ public class KeyPairGeneratorTool extends Command {
private static Path parsePath(String path) { private static Path parsePath(String path) {
return PathUtils.get(path); return PathUtils.get(path);
} }
} }

View File

@ -5,16 +5,12 @@
*/ */
package org.elasticsearch.license.licensor.tools; package org.elasticsearch.license.licensor.tools;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import joptsimple.OptionSet; import joptsimple.OptionSet;
import joptsimple.OptionSpec; import joptsimple.OptionSpec;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.cli.Terminal; import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.io.PathUtils;
@ -25,6 +21,10 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.license.License; import org.elasticsearch.license.License;
import org.elasticsearch.license.licensor.LicenseSigner; import org.elasticsearch.license.licensor.LicenseSigner;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class LicenseGeneratorTool extends Command { public class LicenseGeneratorTool extends Command {
private final OptionSpec<String> publicKeyPathOption; private final OptionSpec<String> publicKeyPathOption;
@ -71,16 +71,21 @@ public class LicenseGeneratorTool extends Command {
final License licenseSpec; final License licenseSpec;
if (options.has(licenseOption)) { if (options.has(licenseOption)) {
final BytesArray bytes =
new BytesArray(licenseOption.value(options).getBytes(StandardCharsets.UTF_8));
licenseSpec = licenseSpec =
License.fromSource(new BytesArray(licenseOption.value(options).getBytes(StandardCharsets.UTF_8)), XContentType.JSON); License.fromSource(bytes, XContentType.JSON);
} else if (options.has(licenseFileOption)) { } else if (options.has(licenseFileOption)) {
Path licenseSpecPath = parsePath(licenseFileOption.value(options)); Path licenseSpecPath = parsePath(licenseFileOption.value(options));
if (Files.exists(licenseSpecPath) == false) { if (Files.exists(licenseSpecPath) == false) {
throw new UserException(ExitCodes.USAGE, licenseSpecPath + " does not exist"); throw new UserException(ExitCodes.USAGE, licenseSpecPath + " does not exist");
} }
licenseSpec = License.fromSource(new BytesArray(Files.readAllBytes(licenseSpecPath)), XContentType.JSON); final BytesArray bytes = new BytesArray(Files.readAllBytes(licenseSpecPath));
licenseSpec = License.fromSource(bytes, XContentType.JSON);
} else { } else {
throw new UserException(ExitCodes.USAGE, "Must specify either --license or --licenseFile"); throw new UserException(
ExitCodes.USAGE,
"Must specify either --license or --licenseFile");
} }
// sign // sign
@ -101,4 +106,5 @@ public class LicenseGeneratorTool extends Command {
private static Path parsePath(String path) { private static Path parsePath(String path) {
return PathUtils.get(path); return PathUtils.get(path);
} }
} }

View File

@ -5,16 +5,12 @@
*/ */
package org.elasticsearch.license.licensor.tools; package org.elasticsearch.license.licensor.tools;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import joptsimple.OptionSet; import joptsimple.OptionSet;
import joptsimple.OptionSpec; import joptsimple.OptionSpec;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.cli.Terminal; import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.io.PathUtils;
@ -25,6 +21,10 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.license.License; import org.elasticsearch.license.License;
import org.elasticsearch.license.LicenseVerifier; import org.elasticsearch.license.LicenseVerifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class LicenseVerificationTool extends Command { public class LicenseVerificationTool extends Command {
private final OptionSpec<String> publicKeyPathOption; private final OptionSpec<String> publicKeyPathOption;
@ -56,20 +56,25 @@ public class LicenseVerificationTool extends Command {
final License licenseSpec; final License licenseSpec;
if (options.has(licenseOption)) { if (options.has(licenseOption)) {
final BytesArray bytes =
new BytesArray(licenseOption.value(options).getBytes(StandardCharsets.UTF_8));
licenseSpec = licenseSpec =
License.fromSource(new BytesArray(licenseOption.value(options).getBytes(StandardCharsets.UTF_8)), XContentType.JSON); License.fromSource(bytes, XContentType.JSON);
} else if (options.has(licenseFileOption)) { } else if (options.has(licenseFileOption)) {
Path licenseSpecPath = parsePath(licenseFileOption.value(options)); Path licenseSpecPath = parsePath(licenseFileOption.value(options));
if (Files.exists(licenseSpecPath) == false) { if (Files.exists(licenseSpecPath) == false) {
throw new UserException(ExitCodes.USAGE, licenseSpecPath + " does not exist"); throw new UserException(ExitCodes.USAGE, licenseSpecPath + " does not exist");
} }
licenseSpec = License.fromSource(new BytesArray(Files.readAllBytes(licenseSpecPath)), XContentType.JSON); final BytesArray bytes = new BytesArray(Files.readAllBytes(licenseSpecPath));
licenseSpec = License.fromSource(bytes, XContentType.JSON);
} else { } else {
throw new UserException(ExitCodes.USAGE, "Must specify either --license or --licenseFile"); throw new UserException(
ExitCodes.USAGE,
"Must specify either --license or --licenseFile");
} }
// verify // verify
if (LicenseVerifier.verifyLicense(licenseSpec, Files.readAllBytes(publicKeyPath)) == false) { if (!LicenseVerifier.verifyLicense(licenseSpec, Files.readAllBytes(publicKeyPath))) {
throw new UserException(ExitCodes.DATA_ERROR, "Invalid License!"); throw new UserException(ExitCodes.DATA_ERROR, "Invalid License!");
} }
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);

View File

@ -16,9 +16,8 @@ import org.junit.Before;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import static org.hamcrest.Matchers.equalTo;
public class LicenseVerificationTests extends ESTestCase { public class LicenseVerificationTests extends ESTestCase {
protected Path pubKeyPath = null; protected Path pubKeyPath = null;
protected Path priKeyPath = null; protected Path priKeyPath = null;
@ -35,12 +34,15 @@ public class LicenseVerificationTests extends ESTestCase {
} }
public void testGeneratedLicenses() throws Exception { public void testGeneratedLicenses() throws Exception {
assertThat(LicenseVerifier.verifyLicense(TestUtils.generateSignedLicense(TimeValue.timeValueHours(2 * 24), pubKeyPath, priKeyPath), final TimeValue fortyEightHours = TimeValue.timeValueHours(2 * 24);
Files.readAllBytes(pubKeyPath)), equalTo(true)); final License license =
TestUtils.generateSignedLicense(fortyEightHours, pubKeyPath, priKeyPath);
assertTrue(LicenseVerifier.verifyLicense(license, Files.readAllBytes(pubKeyPath)));
} }
public void testLicenseTampering() throws Exception { public void testLicenseTampering() throws Exception {
License license = TestUtils.generateSignedLicense(TimeValue.timeValueHours(2), pubKeyPath, priKeyPath); final TimeValue twoHours = TimeValue.timeValueHours(2);
License license = TestUtils.generateSignedLicense(twoHours, pubKeyPath, priKeyPath);
final License tamperedLicense = License.builder() final License tamperedLicense = License.builder()
.fromLicenseSpec(license, license.signature()) .fromLicenseSpec(license, license.signature())
@ -48,17 +50,18 @@ public class LicenseVerificationTests extends ESTestCase {
.validate() .validate()
.build(); .build();
assertThat(LicenseVerifier.verifyLicense(tamperedLicense, Files.readAllBytes(pubKeyPath)), equalTo(false)); assertFalse(LicenseVerifier.verifyLicense(tamperedLicense, Files.readAllBytes(pubKeyPath)));
} }
public void testRandomLicenseVerification() throws Exception { public void testRandomLicenseVerification() throws Exception {
TestUtils.LicenseSpec licenseSpec = TestUtils.generateRandomLicenseSpec( TestUtils.LicenseSpec licenseSpec = TestUtils.generateRandomLicenseSpec(
randomIntBetween(License.VERSION_START, License.VERSION_CURRENT)); randomIntBetween(License.VERSION_START, License.VERSION_CURRENT));
License generatedLicense = generateSignedLicense(licenseSpec, pubKeyPath, priKeyPath); License generatedLicense = generateSignedLicense(licenseSpec, pubKeyPath, priKeyPath);
assertThat(LicenseVerifier.verifyLicense(generatedLicense, Files.readAllBytes(pubKeyPath)), equalTo(true)); assertTrue(LicenseVerifier.verifyLicense(generatedLicense, Files.readAllBytes(pubKeyPath)));
} }
private static License generateSignedLicense(TestUtils.LicenseSpec spec, Path pubKeyPath, Path priKeyPath) throws Exception { private static License generateSignedLicense(
TestUtils.LicenseSpec spec, Path pubKeyPath, Path priKeyPath) throws Exception {
LicenseSigner signer = new LicenseSigner(priKeyPath, pubKeyPath); LicenseSigner signer = new LicenseSigner(priKeyPath, pubKeyPath);
License.Builder builder = License.builder() License.Builder builder = License.builder()
.uid(spec.uid) .uid(spec.uid)
@ -82,4 +85,5 @@ public class LicenseVerificationTests extends ESTestCase {
builder.version(spec.version); builder.version(spec.version);
return signer.sign(builder.build()); return signer.sign(builder.build());
} }
} }

View File

@ -22,6 +22,7 @@ import org.joda.time.format.DateTimeFormatter;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.UUID; import java.util.UUID;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomBoolean; import static com.carrotsearch.randomizedtesting.RandomizedTest.randomBoolean;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomInt; import static com.carrotsearch.randomizedtesting.RandomizedTest.randomInt;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomIntBetween; import static com.carrotsearch.randomizedtesting.RandomizedTest.randomIntBetween;
@ -34,8 +35,10 @@ public class TestUtils {
public static final String PUBLIC_KEY_RESOURCE = "/public.key"; public static final String PUBLIC_KEY_RESOURCE = "/public.key";
public static final String PRIVATE_KEY_RESOURCE = "/private.key"; public static final String PRIVATE_KEY_RESOURCE = "/private.key";
private static final FormatDateTimeFormatter formatDateTimeFormatter = Joda.forPattern("yyyy-MM-dd"); private static final FormatDateTimeFormatter formatDateTimeFormatter =
private static final DateMathParser dateMathParser = new DateMathParser(formatDateTimeFormatter); Joda.forPattern("yyyy-MM-dd");
private static final DateMathParser dateMathParser =
new DateMathParser(formatDateTimeFormatter);
private static final DateTimeFormatter dateTimeFormatter = formatDateTimeFormatter.printer(); private static final DateTimeFormatter dateTimeFormatter = formatDateTimeFormatter.printer();
public static String dumpLicense(License license) throws Exception { public static String dumpLicense(License license) throws Exception {
@ -78,12 +81,30 @@ public class TestUtils {
if (datesInMillis) { if (datesInMillis) {
long issueDateInMillis = dateMath("now", now); long issueDateInMillis = dateMath("now", now);
long expiryDateInMillis = dateMath("now+10d/d", now); long expiryDateInMillis = dateMath("now+10d/d", now);
return new LicenseSpec(version, uid, feature, issueDateInMillis, expiryDateInMillis, type, subscriptionType, issuedTo, issuer, return new LicenseSpec(
version,
uid,
feature,
issueDateInMillis,
expiryDateInMillis,
type,
subscriptionType,
issuedTo,
issuer,
maxNodes); maxNodes);
} else { } else {
String issueDate = dateMathString("now", now); String issueDate = dateMathString("now", now);
String expiryDate = dateMathString("now+10d/d", now); String expiryDate = dateMathString("now+10d/d", now);
return new LicenseSpec(version, uid, feature, issueDate, expiryDate, type, subscriptionType, issuedTo, issuer, maxNodes); return new LicenseSpec(
version,
uid,
feature,
issueDate,
expiryDate, type,
subscriptionType,
issuedTo,
issuer,
maxNodes);
} }
} }
@ -122,18 +143,23 @@ public class TestUtils {
MatcherAssert.assertThat(license.type(), equalTo(spec.type)); MatcherAssert.assertThat(license.type(), equalTo(spec.type));
MatcherAssert.assertThat(license.maxNodes(), equalTo(spec.maxNodes)); MatcherAssert.assertThat(license.maxNodes(), equalTo(spec.maxNodes));
if (spec.issueDate != null) { if (spec.issueDate != null) {
MatcherAssert.assertThat(license.issueDate(), equalTo(DateUtils.beginningOfTheDay(spec.issueDate))); MatcherAssert.assertThat(
license.issueDate(),
equalTo(DateUtils.beginningOfTheDay(spec.issueDate)));
} else { } else {
MatcherAssert.assertThat(license.issueDate(), equalTo(spec.issueDateInMillis)); MatcherAssert.assertThat(license.issueDate(), equalTo(spec.issueDateInMillis));
} }
if (spec.expiryDate != null) { if (spec.expiryDate != null) {
MatcherAssert.assertThat(license.expiryDate(), equalTo(DateUtils.endOfTheDay(spec.expiryDate))); MatcherAssert.assertThat(
license.expiryDate(),
equalTo(DateUtils.endOfTheDay(spec.expiryDate)));
} else { } else {
MatcherAssert.assertThat(license.expiryDate(), equalTo(spec.expiryDateInMillis)); MatcherAssert.assertThat(license.expiryDate(), equalTo(spec.expiryDateInMillis));
} }
} }
public static License generateSignedLicense(TimeValue expiryDuration, Path pubKeyPath, Path priKeyPath) throws Exception { public static License generateSignedLicense(
TimeValue expiryDuration, Path pubKeyPath, Path priKeyPath) throws Exception {
long issue = System.currentTimeMillis(); long issue = System.currentTimeMillis();
int version = ESTestCase.randomIntBetween(License.VERSION_START, License.VERSION_CURRENT); int version = ESTestCase.randomIntBetween(License.VERSION_START, License.VERSION_CURRENT);
String type = version < License.VERSION_NO_FEATURE_TYPE ? String type = version < License.VERSION_NO_FEATURE_TYPE ?
@ -170,8 +196,17 @@ public class TestUtils {
public final String issuer; public final String issuer;
public final int maxNodes; public final int maxNodes;
public LicenseSpec(int version, String uid, String feature, long issueDateInMillis, long expiryDateInMillis, String type, public LicenseSpec(
String subscriptionType, String issuedTo, String issuer, int maxNodes) { int version,
String uid,
String feature,
long issueDateInMillis,
long expiryDateInMillis,
String type,
String subscriptionType,
String issuedTo,
String issuer,
int maxNodes) {
this.version = version; this.version = version;
this.feature = feature; this.feature = feature;
this.issueDateInMillis = issueDateInMillis; this.issueDateInMillis = issueDateInMillis;
@ -186,8 +221,17 @@ public class TestUtils {
this.maxNodes = maxNodes; this.maxNodes = maxNodes;
} }
public LicenseSpec(int version, String uid, String feature, String issueDate, String expiryDate, String type, public LicenseSpec(
String subscriptionType, String issuedTo, String issuer, int maxNodes) { int version,
String uid,
String feature,
String issueDate,
String expiryDate,
String type,
String subscriptionType,
String issuedTo,
String issuer,
int maxNodes) {
this.version = version; this.version = version;
this.feature = feature; this.feature = feature;
this.issueDate = issueDate; this.issueDate = issueDate;
@ -202,4 +246,5 @@ public class TestUtils {
this.maxNodes = maxNodes; this.maxNodes = maxNodes;
} }
} }
} }

View File

@ -5,14 +5,14 @@
*/ */
package org.elasticsearch.license.licensor.tools; package org.elasticsearch.license.licensor.tools;
import java.nio.file.Files;
import java.nio.file.Path;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.CommandTestCase; import org.elasticsearch.cli.CommandTestCase;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserException; import org.elasticsearch.cli.UserException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
public class KeyPairGenerationToolTests extends CommandTestCase { public class KeyPairGenerationToolTests extends CommandTestCase {
@ -25,14 +25,22 @@ public class KeyPairGenerationToolTests extends CommandTestCase {
public void testMissingKeyPaths() throws Exception { public void testMissingKeyPaths() throws Exception {
Path exists = createTempFile("", "existing"); Path exists = createTempFile("", "existing");
Path dne = createTempDir().resolve("dne"); Path dne = createTempDir().resolve("dne");
UserException e = expectThrows(UserException.class, () -> { UserException e = expectThrows(
execute("--publicKeyPath", exists.toString(), "--privateKeyPath", dne.toString()); UserException.class,
}); () -> execute(
"--publicKeyPath",
exists.toString(),
"--privateKeyPath",
dne.toString()));
assertThat(e.getMessage(), containsString("existing")); assertThat(e.getMessage(), containsString("existing"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
e = expectThrows(UserException.class, () -> { e = expectThrows(
execute("--publicKeyPath", dne.toString(), "--privateKeyPath", exists.toString()); UserException.class,
}); () -> execute(
"--publicKeyPath",
dne.toString(),
"--privateKeyPath",
exists.toString()));
assertThat(e.getMessage(), containsString("existing")); assertThat(e.getMessage(), containsString("existing"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
} }
@ -42,8 +50,13 @@ public class KeyPairGenerationToolTests extends CommandTestCase {
Path publicKeyFilePath = keysDir.resolve("public"); Path publicKeyFilePath = keysDir.resolve("public");
Path privateKeyFilePath = keysDir.resolve("private"); Path privateKeyFilePath = keysDir.resolve("private");
execute("--publicKeyPath", publicKeyFilePath.toString(), "--privateKeyPath", privateKeyFilePath.toString()); execute(
"--publicKeyPath",
publicKeyFilePath.toString(),
"--privateKeyPath",
privateKeyFilePath.toString());
assertTrue(publicKeyFilePath.toString(), Files.exists(publicKeyFilePath)); assertTrue(publicKeyFilePath.toString(), Files.exists(publicKeyFilePath));
assertTrue(privateKeyFilePath.toString(), Files.exists(privateKeyFilePath)); assertTrue(privateKeyFilePath.toString(), Files.exists(privateKeyFilePath));
} }
} }

View File

@ -5,10 +5,6 @@
*/ */
package org.elasticsearch.license.licensor.tools; package org.elasticsearch.license.licensor.tools;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.CommandTestCase; import org.elasticsearch.cli.CommandTestCase;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
@ -19,7 +15,12 @@ import org.elasticsearch.license.License;
import org.elasticsearch.license.licensor.TestUtils; import org.elasticsearch.license.licensor.TestUtils;
import org.junit.Before; import org.junit.Before;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class LicenseGenerationToolTests extends CommandTestCase { public class LicenseGenerationToolTests extends CommandTestCase {
protected Path pubKeyPath = null; protected Path pubKeyPath = null;
protected Path priKeyPath = null; protected Path priKeyPath = null;
@ -37,47 +38,74 @@ public class LicenseGenerationToolTests extends CommandTestCase {
public void testMissingKeyPaths() throws Exception { public void testMissingKeyPaths() throws Exception {
Path pub = createTempDir().resolve("pub"); Path pub = createTempDir().resolve("pub");
Path pri = createTempDir().resolve("pri"); Path pri = createTempDir().resolve("pri");
UserException e = expectThrows(UserException.class, () -> { UserException e = expectThrows(
execute("--publicKeyPath", pub.toString(), "--privateKeyPath", pri.toString()); UserException.class,
}); () -> execute(
"--publicKeyPath",
pub.toString(),
"--privateKeyPath",
pri.toString()));
assertTrue(e.getMessage(), e.getMessage().contains("pri does not exist")); assertTrue(e.getMessage(), e.getMessage().contains("pri does not exist"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
Files.createFile(pri); Files.createFile(pri);
e = expectThrows(UserException.class, () -> { e = expectThrows(
execute("--publicKeyPath", pub.toString(), "--privateKeyPath", pri.toString()); UserException.class,
}); () -> execute(
"--publicKeyPath",
pub.toString(),
"--privateKeyPath",
pri.toString()));
assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist")); assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
} }
public void testMissingLicenseSpec() throws Exception { public void testMissingLicenseSpec() throws Exception {
UserException e = expectThrows(UserException.class, () -> { UserException e = expectThrows(
execute("--publicKeyPath", pubKeyPath.toString(), "--privateKeyPath", priKeyPath.toString()); UserException.class,
}); () -> execute(
assertTrue(e.getMessage(), e.getMessage().contains("Must specify either --license or --licenseFile")); "--publicKeyPath",
pubKeyPath.toString(),
"--privateKeyPath",
priKeyPath.toString()));
assertTrue(
e.getMessage(),
e.getMessage().contains("Must specify either --license or --licenseFile"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
} }
public void testLicenseSpecString() throws Exception { public void testLicenseSpecString() throws Exception {
TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); TestUtils.LicenseSpec inputLicenseSpec =
TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT);
String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec); String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec);
String output = execute("--publicKeyPath", pubKeyPath.toString(), String output = execute(
"--privateKeyPath", priKeyPath.toString(), "--publicKeyPath",
"--license", licenseSpecString); pubKeyPath.toString(),
License outputLicense = License.fromSource(new BytesArray(output.getBytes(StandardCharsets.UTF_8)), XContentType.JSON); "--privateKeyPath",
priKeyPath.toString(),
"--license",
licenseSpecString);
final BytesArray bytes = new BytesArray(output.getBytes(StandardCharsets.UTF_8));
License outputLicense = License.fromSource(bytes, XContentType.JSON);
TestUtils.assertLicenseSpec(inputLicenseSpec, outputLicense); TestUtils.assertLicenseSpec(inputLicenseSpec, outputLicense);
} }
public void testLicenseSpecFile() throws Exception { public void testLicenseSpecFile() throws Exception {
TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); TestUtils.LicenseSpec inputLicenseSpec =
TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT);
String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec); String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec);
Path licenseSpecFile = createTempFile(); Path licenseSpecFile = createTempFile();
Files.write(licenseSpecFile, licenseSpecString.getBytes(StandardCharsets.UTF_8)); Files.write(licenseSpecFile, licenseSpecString.getBytes(StandardCharsets.UTF_8));
String output = execute("--publicKeyPath", pubKeyPath.toString(), String output = execute(
"--privateKeyPath", priKeyPath.toString(), "--publicKeyPath",
"--licenseFile", licenseSpecFile.toString()); pubKeyPath.toString(),
License outputLicense = License.fromSource(new BytesArray(output.getBytes(StandardCharsets.UTF_8)), XContentType.JSON); "--privateKeyPath",
priKeyPath.toString(),
"--licenseFile",
licenseSpecFile.toString());
final BytesArray bytes = new BytesArray(output.getBytes(StandardCharsets.UTF_8));
License outputLicense = License.fromSource(bytes, XContentType.JSON);
TestUtils.assertLicenseSpec(inputLicenseSpec, outputLicense); TestUtils.assertLicenseSpec(inputLicenseSpec, outputLicense);
} }
} }

View File

@ -5,10 +5,6 @@
*/ */
package org.elasticsearch.license.licensor.tools; package org.elasticsearch.license.licensor.tools;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.CommandTestCase; import org.elasticsearch.cli.CommandTestCase;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
@ -18,6 +14,10 @@ import org.elasticsearch.license.License;
import org.elasticsearch.license.licensor.TestUtils; import org.elasticsearch.license.licensor.TestUtils;
import org.junit.Before; import org.junit.Before;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class LicenseVerificationToolTests extends CommandTestCase { public class LicenseVerificationToolTests extends CommandTestCase {
protected Path pubKeyPath = null; protected Path pubKeyPath = null;
protected Path priKeyPath = null; protected Path priKeyPath = null;
@ -36,9 +36,9 @@ public class LicenseVerificationToolTests extends CommandTestCase {
public void testMissingKeyPath() throws Exception { public void testMissingKeyPath() throws Exception {
Path pub = createTempDir().resolve("pub"); Path pub = createTempDir().resolve("pub");
UserException e = expectThrows(UserException.class, () -> { UserException e = expectThrows(
execute("--publicKeyPath", pub.toString()); UserException.class,
}); () -> execute("--publicKeyPath", pub.toString()));
assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist")); assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
} }
@ -47,36 +47,53 @@ public class LicenseVerificationToolTests extends CommandTestCase {
UserException e = expectThrows(UserException.class, () -> { UserException e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", pubKeyPath.toString()); execute("--publicKeyPath", pubKeyPath.toString());
}); });
assertTrue(e.getMessage(), e.getMessage().contains("Must specify either --license or --licenseFile")); assertTrue(
e.getMessage(),
e.getMessage().contains("Must specify either --license or --licenseFile"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
} }
public void testBrokenLicense() throws Exception { public void testBrokenLicense() throws Exception {
License signedLicense = TestUtils.generateSignedLicense(TimeValue.timeValueHours(1), pubKeyPath, priKeyPath); final TimeValue oneHour = TimeValue.timeValueHours(1);
License signedLicense = TestUtils.generateSignedLicense(oneHour, pubKeyPath, priKeyPath);
License tamperedLicense = License.builder() License tamperedLicense = License.builder()
.fromLicenseSpec(signedLicense, signedLicense.signature()) .fromLicenseSpec(signedLicense, signedLicense.signature())
.expiryDate(signedLicense.expiryDate() + randomIntBetween(1, 1000)).build(); .expiryDate(signedLicense.expiryDate() + randomIntBetween(1, 1000)).build();
UserException e = expectThrows(UserException.class, () -> { UserException e = expectThrows(
execute("--publicKeyPath", pubKeyPath.toString(), UserException.class,
"--license", TestUtils.dumpLicense(tamperedLicense)); () -> execute(
}); "--publicKeyPath",
pubKeyPath.toString(),
"--license",
TestUtils.dumpLicense(tamperedLicense)));
assertEquals("Invalid License!", e.getMessage()); assertEquals("Invalid License!", e.getMessage());
assertEquals(ExitCodes.DATA_ERROR, e.exitCode); assertEquals(ExitCodes.DATA_ERROR, e.exitCode);
} }
public void testLicenseSpecString() throws Exception { public void testLicenseSpecString() throws Exception {
License signedLicense = TestUtils.generateSignedLicense(TimeValue.timeValueHours(1), pubKeyPath, priKeyPath); final TimeValue oneHour = TimeValue.timeValueHours(1);
String output = execute("--publicKeyPath", pubKeyPath.toString(), License signedLicense = TestUtils.generateSignedLicense(oneHour, pubKeyPath, priKeyPath);
"--license", TestUtils.dumpLicense(signedLicense)); String output = execute(
"--publicKeyPath",
pubKeyPath.toString(),
"--license",
TestUtils.dumpLicense(signedLicense));
assertFalse(output, output.isEmpty()); assertFalse(output, output.isEmpty());
} }
public void testLicenseSpecFile() throws Exception { public void testLicenseSpecFile() throws Exception {
License signedLicense = TestUtils.generateSignedLicense(TimeValue.timeValueHours(1), pubKeyPath, priKeyPath); final TimeValue oneHour = TimeValue.timeValueHours(1);
License signedLicense = TestUtils.generateSignedLicense(oneHour, pubKeyPath, priKeyPath);
Path licenseSpecFile = createTempFile(); Path licenseSpecFile = createTempFile();
Files.write(licenseSpecFile, TestUtils.dumpLicense(signedLicense).getBytes(StandardCharsets.UTF_8)); Files.write(
String output = execute("--publicKeyPath", pubKeyPath.toString(), licenseSpecFile,
"--licenseFile", licenseSpecFile.toString()); TestUtils.dumpLicense(signedLicense).getBytes(StandardCharsets.UTF_8));
String output = execute(
"--publicKeyPath",
pubKeyPath.toString(),
"--licenseFile",
licenseSpecFile.toString());
assertFalse(output, output.isEmpty()); assertFalse(output, output.isEmpty());
} }
} }