Search in sources :

Example 11 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class PicoCliDelegateTest method withValidConfigAndPidfileAlreadyExists.

@Test
public void withValidConfigAndPidfileAlreadyExists() throws Exception {
    Path configFile = Paths.get(getClass().getResource("/sample-config.json").toURI());
    Path pidFilePath = Files.createTempFile(UUID.randomUUID().toString(), "");
    pidFilePath.toFile().deleteOnExit();
    assertThat(pidFilePath).exists();
    CliResult result = cliDelegate.execute("-configfile", configFile.toString(), "-pidfile", pidFilePath.toString());
    assertThat(pidFilePath).exists();
    assertThat(result).isNotNull();
    assertThat(result.getConfig()).isPresent();
    assertThat(result.getStatus()).isEqualTo(0);
    assertThat(result.isSuppressStartup()).isFalse();
}
Also used : Path(java.nio.file.Path) CliResult(com.quorum.tessera.cli.CliResult) Test(org.junit.Test)

Example 12 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class PicoCliDelegateTest method suppressStartupForKeygenOptionWithFileOutputOptions.

@Test
public void suppressStartupForKeygenOptionWithFileOutputOptions() throws Exception {
    Path publicKeyPath = Files.createTempFile(UUID.randomUUID().toString(), "");
    Path privateKeyPath = Files.createTempFile(UUID.randomUUID().toString(), "");
    Files.write(privateKeyPath, Arrays.asList("SOMEDATA"));
    Files.write(publicKeyPath, Arrays.asList("SOMEDATA"));
    FilesystemKeyPair keypair = new FilesystemKeyPair(publicKeyPath, privateKeyPath, null);
    when(keyGenerator.generate(anyString(), eq(null), eq(null))).thenReturn(keypair);
    final Path configFile = Paths.get(getClass().getResource("/sample-config.json").toURI());
    final Path configOutputPath = configFile.resolveSibling(UUID.randomUUID().toString() + ".json");
    final CliResult cliResult = cliDelegate.execute("-keygen", "-configfile", configFile.toString(), "-output", configOutputPath.toString());
    assertThat(cliResult.isSuppressStartup()).isTrue();
}
Also used : Path(java.nio.file.Path) FilesystemKeyPair(com.quorum.tessera.config.keypairs.FilesystemKeyPair) CliResult(com.quorum.tessera.cli.CliResult) Test(org.junit.Test)

Example 13 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class KeyGenCommandTest method onlySingleOutputFileProvided.

@Test
public void onlySingleOutputFileProvided() throws Exception {
    List<String> optionVariations = List.of("--keyout", "-filename");
    ConfigKeyPair configKeyPair = mock(ConfigKeyPair.class);
    when(keyGenerator.generate("myfile", null, null)).thenReturn(configKeyPair);
    when(keyGeneratorFactory.create(refEq(null), any(EncryptorConfig.class))).thenReturn(keyGenerator);
    for (String option : optionVariations) {
        String arg = option.concat("=myfile");
        int exitCode = commandLine.execute(arg);
        assertThat(exitCode).isZero();
        CommandLine.ParseResult parseResult = commandLine.getParseResult();
        assertThat(parseResult).isNotNull();
        assertThat(parseResult.matchedArgs()).hasSize(1);
        assertThat(parseResult.hasMatchedOption("--keyout"));
        assertThat(parseResult.unmatched()).isEmpty();
        CliResult result = commandLine.getExecutionResult();
        assertThat(result).isNotNull();
        assertThat(result.isSuppressStartup()).isTrue();
        assertThat(result.getConfig()).isNotPresent();
        assertThat(result.getStatus()).isEqualTo(0);
    }
    verify(keyDataMarshaller, times(optionVariations.size())).marshal(configKeyPair);
    verify(keyGeneratorFactory, times(optionVariations.size())).create(refEq(null), any(EncryptorConfig.class));
    verify(keyGenerator, times(optionVariations.size())).generate("myfile", null, null);
}
Also used : CommandLine(picocli.CommandLine) CliResult(com.quorum.tessera.cli.CliResult) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) Test(org.junit.Test)

Example 14 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class PicoCliDelegate method execute.

public CliResult execute(String... args) throws Exception {
    LOGGER.debug("Execute with args [{}]", String.join(",", args));
    final CommandLine commandLine = new CommandLine(TesseraCommand.class);
    final CLIExceptionCapturer exceptionCapturer = new CLIExceptionCapturer();
    commandLine.addSubcommand(new CommandLine(CommandLine.HelpCommand.class));
    commandLine.addSubcommand(new CommandLine(VersionCommand.class));
    commandLine.addSubcommand(new CommandLine(KeyGenCommand.class, new KeyGenCommandFactory()));
    commandLine.addSubcommand(new CommandLine(KeyUpdateCommand.class, new KeyUpdateCommandFactory()));
    commandLine.registerConverter(Config.class, new ConfigConverter()).registerConverter(ArgonOptions.class, new ArgonOptionsConverter()).setSeparator(" ").setCaseInsensitiveEnumValuesAllowed(true).setExecutionExceptionHandler(exceptionCapturer).setParameterExceptionHandler(exceptionCapturer).setStopAtUnmatched(false);
    try {
        // parse the args so that we can print usage help if no cmd args were provided
        final CommandLine.ParseResult parseResult = commandLine.parseArgs(args);
        final List<CommandLine> l = parseResult.asCommandLineList();
        final CommandLine lastCmd = l.get(l.size() - 1);
        // print help if no args were provided
        if (lastCmd.getParseResult().matchedArgs().size() == 0 && !"help".equals(lastCmd.getCommandName()) && !"version".equals(lastCmd.getCommandName())) {
            lastCmd.usage(lastCmd.getOut());
        } else {
            commandLine.execute(args);
        }
    } catch (CommandLine.ParameterException ex) {
        exceptionCapturer.handleParseException(ex, args);
    }
    // if an exception occurred, throw it to to the upper levels where it gets handled
    if (exceptionCapturer.getThrown() != null) {
        throw exceptionCapturer.getThrown();
    }
    return (CliResult) Optional.ofNullable(commandLine.getExecutionResult()).orElse(new CliResult(0, true, null));
}
Also used : ConfigConverter(com.quorum.tessera.cli.parsers.ConfigConverter) ArgonOptions(com.quorum.tessera.config.ArgonOptions) CommandLine(picocli.CommandLine) CLIExceptionCapturer(com.quorum.tessera.cli.CLIExceptionCapturer) CliResult(com.quorum.tessera.cli.CliResult)

Example 15 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class TesseraCommand method call.

@Override
public CliResult call() throws Exception {
    // all subcmds
    if (Objects.isNull(config)) {
        throw new NoTesseraConfigfileOptionException();
    }
    // overrides using '-o <KEY>=<VALUE>'
    overrides.forEach(this::overrideConfigValue);
    // legacy overrides using unmatched options
    if (Objects.nonNull(unmatchedEntries)) {
        LOGGER.warn("Using unmatched CLI options for config overrides is deprecated.  Use the --override option instead.");
        List<String> unmatched = new ArrayList<>(unmatchedEntries);
        for (int i = 0; i < unmatched.size(); i += 2) {
            String line = unmatched.get(i);
            if (!line.startsWith("-")) {
                throw new CliException(LEGACY_OVERRIDE_EXCEPTION_MSG);
            }
            final String target = line.replaceFirst("-{1,2}", "");
            final int nextIndex = i + 1;
            if (nextIndex > (unmatched.size() - 1)) {
                throw new CliException(LEGACY_OVERRIDE_EXCEPTION_MSG);
            }
            final String value = unmatched.get(nextIndex);
            try {
                overrideConfigValue(target, value);
            } catch (CliException ex) {
                throw new CliException(String.join("\n", LEGACY_OVERRIDE_EXCEPTION_MSG, ex.getMessage()));
            }
        }
    }
    if (recover) {
        config.setRecoveryMode(true);
    }
    final Set<ConstraintViolation<Config>> violations = validator.validate(config);
    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
    keyPasswordResolver.resolveKeyPasswords(config);
    pidFileMixin.createPidFile();
    serverURIOutputPath.updateConfig(config);
    return new CliResult(0, false, config);
}
Also used : CliException(com.quorum.tessera.cli.CliException) CliResult(com.quorum.tessera.cli.CliResult) ConstraintViolation(jakarta.validation.ConstraintViolation) ConstraintViolationException(jakarta.validation.ConstraintViolationException)

Aggregations

CliResult (com.quorum.tessera.cli.CliResult)38 Test (org.junit.Test)29 Path (java.nio.file.Path)15 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)10 CommandLine (picocli.CommandLine)9 CliException (com.quorum.tessera.cli.CliException)7 ConstraintViolationException (jakarta.validation.ConstraintViolationException)7 FilesystemKeyPair (com.quorum.tessera.config.keypairs.FilesystemKeyPair)6 Config (com.quorum.tessera.config.Config)5 ConfigConverter (com.quorum.tessera.cli.parsers.ConfigConverter)4 ConfigKeyPair (com.quorum.tessera.config.keypairs.ConfigKeyPair)4 KeyDataConfig (com.quorum.tessera.config.KeyDataConfig)3 KeyEncryptor (com.quorum.tessera.config.keys.KeyEncryptor)3 ConstraintViolation (jakarta.validation.ConstraintViolation)3 UncheckedIOException (java.io.UncheckedIOException)3 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)3 HashMap (java.util.HashMap)3 Enclave (com.quorum.tessera.enclave.Enclave)2 EnclaveCliAdapter (com.quorum.tessera.enclave.server.EnclaveCliAdapter)2 TesseraServer (com.quorum.tessera.server.TesseraServer)2