Search in sources :

Example 16 with CliResult

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

the class KeyGenCommand method call.

@Override
public CliResult call() throws IOException {
    if (Objects.nonNull(fileUpdateOptions) && Objects.isNull(fileUpdateOptions.getConfig())) {
        throw new CliException("Missing required argument(s): --configfile=<config>");
    }
    final EncryptorConfig encryptorConfig = Optional.ofNullable(fileUpdateOptions).map(KeyGenFileUpdateOptions::getConfig).map(Config::getEncryptor).orElseGet(() -> Optional.ofNullable(encryptorOptions).map(EncryptorOptions::parseEncryptorConfig).orElse(EncryptorConfig.getDefault()));
    final KeyVaultOptions keyVaultOptions = Optional.ofNullable(keyVaultConfigOptions).map(KeyVaultConfigOptions::getHashicorpSecretEnginePath).map(KeyVaultOptions::new).orElse(null);
    final KeyVaultConfig keyVaultConfig;
    if (keyVaultConfigOptions == null) {
        keyVaultConfig = null;
    } else if (keyVaultConfigOptions.getVaultType() == null) {
        throw new CliException("Key vault type either not provided or not recognised");
    } else if (fileUpdateOptions != null) {
        keyVaultConfig = Optional.of(fileUpdateOptions).map(KeyGenFileUpdateOptions::getConfig).map(Config::getKeys).flatMap(c -> c.getKeyVaultConfig(keyVaultConfigOptions.getVaultType())).orElse(null);
    } else {
        final KeyVaultHandler keyVaultHandler = new DispatchingKeyVaultHandler();
        keyVaultConfig = keyVaultHandler.handle(keyVaultConfigOptions);
        if (keyVaultConfig.getKeyVaultType() == KeyVaultType.HASHICORP) {
            if (Objects.isNull(keyOut)) {
                throw new CliException("At least one -filename must be provided when saving generated keys in a Hashicorp Vault");
            }
        }
        final Set<ConstraintViolation<KeyVaultConfig>> violations = validator.validate(keyVaultConfig);
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }
    final KeyGenerator keyGenerator = keyGeneratorFactory.create(keyVaultConfig, encryptorConfig);
    final List<String> newKeyNames = Optional.ofNullable(keyOut).filter(Predicate.not(List::isEmpty)).map(List::copyOf).orElseGet(() -> List.of(""));
    final List<ConfigKeyPair> newConfigKeyPairs = newKeyNames.stream().map(name -> keyGenerator.generate(name, argonOptions, keyVaultOptions)).collect(Collectors.toList());
    final List<char[]> newPasswords = newConfigKeyPairs.stream().filter(Objects::nonNull).map(ConfigKeyPair::getPassword).collect(Collectors.toList());
    final List<KeyData> newKeyData = newConfigKeyPairs.stream().map(keyDataMarshaller::marshal).collect(Collectors.toList());
    if (Objects.isNull(fileUpdateOptions)) {
        return new CliResult(0, true, null);
    }
    // prepare config for addition of new keys if required
    prepareConfigForNewKeys(fileUpdateOptions.getConfig());
    if (Objects.nonNull(fileUpdateOptions.getConfigOut())) {
        if (Objects.nonNull(fileUpdateOptions.getPwdOut())) {
            passwordFileUpdaterWriter.updateAndWrite(newPasswords, fileUpdateOptions.getConfig(), fileUpdateOptions.getPwdOut());
            fileUpdateOptions.getConfig().getKeys().setPasswordFile(fileUpdateOptions.getPwdOut());
        }
        configFileUpdaterWriter.updateAndWrite(newKeyData, keyVaultConfig, fileUpdateOptions.getConfig(), fileUpdateOptions.getConfigOut());
    } else {
        configFileUpdaterWriter.updateAndWriteToCLI(newKeyData, keyVaultConfig, fileUpdateOptions.getConfig());
    }
    return new CliResult(0, true, fileUpdateOptions.getConfig());
}
Also used : ConstraintViolation(jakarta.validation.ConstraintViolation) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) Validation(jakarta.validation.Validation) java.util(java.util) Predicate(java.util.function.Predicate) Validator(jakarta.validation.Validator) IOException(java.io.IOException) Callable(java.util.concurrent.Callable) ConstraintViolationException(jakarta.validation.ConstraintViolationException) KeyVaultOptions(com.quorum.tessera.key.generation.KeyVaultOptions) Collectors(java.util.stream.Collectors) KeyGeneratorFactory(com.quorum.tessera.key.generation.KeyGeneratorFactory) PasswordFileUpdaterWriter(com.quorum.tessera.config.util.PasswordFileUpdaterWriter) com.quorum.tessera.config(com.quorum.tessera.config) KeyGenerator(com.quorum.tessera.key.generation.KeyGenerator) CliException(com.quorum.tessera.cli.CliException) CliResult(com.quorum.tessera.cli.CliResult) ConfigFileUpdaterWriter(com.quorum.tessera.config.util.ConfigFileUpdaterWriter) CommandLine(picocli.CommandLine) KeyVaultOptions(com.quorum.tessera.key.generation.KeyVaultOptions) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) CliException(com.quorum.tessera.cli.CliException) CliResult(com.quorum.tessera.cli.CliResult) ConstraintViolation(jakarta.validation.ConstraintViolation) ConstraintViolationException(jakarta.validation.ConstraintViolationException) KeyGenerator(com.quorum.tessera.key.generation.KeyGenerator)

Example 17 with CliResult

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

the class KeyUpdateCommand method execute.

public CliResult execute() throws IOException {
    final ArgonOptions argonOptions = argonOptions();
    final List<char[]> passwords = passwords();
    final Path keypath = privateKeyPath();
    final KeyDataConfig keyDataConfig = JaxbUtil.unmarshal(Files.newInputStream(keypath), KeyDataConfig.class);
    final PrivateKey privateKey = this.getExistingKey(keyDataConfig, passwords);
    final char[] newPassword = passwordReader.requestUserPassword();
    final KeyDataConfig updatedKey;
    if (newPassword.length == 0) {
        final PrivateKeyData privateKeyData = new PrivateKeyData(privateKey.encodeToBase64(), null, null, null, null);
        updatedKey = new KeyDataConfig(privateKeyData, PrivateKeyType.UNLOCKED);
    } else {
        final PrivateKeyData privateKeyData = keyEncryptor.encryptPrivateKey(privateKey, newPassword, argonOptions);
        updatedKey = new KeyDataConfig(privateKeyData, PrivateKeyType.LOCKED);
    }
    // write the key to file
    Files.write(keypath, JaxbUtil.marshalToString(updatedKey).getBytes(UTF_8));
    System.out.println("Private key at " + keypath.toString() + " updated.");
    return new CliResult(0, true, null);
}
Also used : Path(java.nio.file.Path) PrivateKey(com.quorum.tessera.encryption.PrivateKey) CliResult(com.quorum.tessera.cli.CliResult)

Example 18 with CliResult

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

the class Main method main.

public static void main(String... args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    final CommandLine commandLine = new CommandLine(new EnclaveCliAdapter());
    commandLine.registerConverter(Config.class, new ConfigConverter()).setSeparator(" ").setCaseInsensitiveEnumValuesAllowed(true);
    commandLine.execute(args);
    final CliResult cliResult = commandLine.getExecutionResult();
    if (cliResult == null) {
        System.exit(1);
    }
    if (!cliResult.getConfig().isPresent()) {
        System.exit(cliResult.getStatus());
    }
    final TesseraServerFactory restServerFactory = TesseraServerFactory.create(CommunicationType.REST);
    final Config config = cliResult.getConfig().get();
    ConfigFactory.create().store(config);
    final ServerConfig serverConfig = config.getServerConfigs().stream().findFirst().get();
    Enclave enclave = EnclaveServer.create();
    LOGGER.debug("Created enclave {}", enclave);
    final TesseraServer server = restServerFactory.createServer(serverConfig, Set.of(new EnclaveApplication(enclave)));
    server.start();
    CountDownLatch latch = new CountDownLatch(1);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            server.stop();
        } catch (Exception ex) {
            LOGGER.error(null, ex);
        } finally {
        }
    }));
    latch.await();
}
Also used : ConfigConverter(com.quorum.tessera.cli.parsers.ConfigConverter) TesseraServerFactory(com.quorum.tessera.server.TesseraServerFactory) ServerConfig(com.quorum.tessera.config.ServerConfig) Config(com.quorum.tessera.config.Config) CountDownLatch(java.util.concurrent.CountDownLatch) ServerConfig(com.quorum.tessera.config.ServerConfig) TesseraServer(com.quorum.tessera.server.TesseraServer) CommandLine(picocli.CommandLine) CliResult(com.quorum.tessera.cli.CliResult) EnclaveCliAdapter(com.quorum.tessera.enclave.server.EnclaveCliAdapter) Enclave(com.quorum.tessera.enclave.Enclave) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 19 with CliResult

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

the class EnclaveRestIT method setUp.

@Before
public void setUp() throws Exception {
    System.setProperty(CliType.CLI_TYPE_KEY, CliType.ENCLAVE.name());
    URL url = EnclaveRestIT.class.getResource("/sample-config.json");
    final CommandLine commandLine = new CommandLine(new EnclaveCliAdapter());
    commandLine.registerConverter(Config.class, new ConfigConverter()).setSeparator(" ").setCaseInsensitiveEnumValuesAllowed(true);
    commandLine.execute("-configfile", url.getFile());
    CliResult cliResult = commandLine.getExecutionResult();
    Config config = cliResult.getConfig().get();
    ConfigFactory.create().store(config);
    this.enclave = Enclave.create();
    jersey = Util.create(enclave);
    jersey.setUp();
    enclaveClient = new RestfulEnclaveClient(jersey.client(), jersey.target().getUri());
}
Also used : ConfigConverter(com.quorum.tessera.cli.parsers.ConfigConverter) CommandLine(picocli.CommandLine) CliResult(com.quorum.tessera.cli.CliResult) EnclaveCliAdapter(com.quorum.tessera.enclave.server.EnclaveCliAdapter) Config(com.quorum.tessera.config.Config) URL(java.net.URL) Before(org.junit.Before)

Example 20 with CliResult

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

the class EnclaveCliAdapterTest method configPassedToResolver.

@Test
public void configPassedToResolver() throws Exception {
    final Path inputFile = Paths.get(getClass().getResource("/sample-config.json").toURI());
    commandLine.execute("-configfile", inputFile.toString());
    final CliResult result = commandLine.getExecutionResult();
    assertThat(result).isNotNull();
    assertThat(result.getStatus()).isEqualTo(0);
    assertThat(result.isSuppressStartup()).isFalse();
    assertThat(result.getConfig()).isPresent();
}
Also used : Path(java.nio.file.Path) CliResult(com.quorum.tessera.cli.CliResult) Test(org.junit.Test)

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