Search in sources :

Example 1 with ConfigKeyPair

use of com.quorum.tessera.config.keypairs.ConfigKeyPair in project tessera by ConsenSys.

the class KeyPairConverter method convert.

private KeyPair convert(ConfigKeyPair configKeyPair) {
    final String base64PublicKey;
    final String base64PrivateKey;
    if (configKeyPair instanceof AzureVaultKeyPair) {
        KeyVaultServiceFactory keyVaultServiceFactory = KeyVaultServiceFactory.getInstance(KeyVaultType.AZURE);
        KeyVaultService keyVaultService = keyVaultServiceFactory.create(config, envProvider);
        AzureVaultKeyPair akp = (AzureVaultKeyPair) configKeyPair;
        Map<String, String> getPublicKeyData = new HashMap<>(Map.of("secretName", akp.getPublicKeyId()));
        getPublicKeyData.put("secretVersion", akp.getPublicKeyVersion());
        Map<String, String> getPrivateKeyData = new HashMap<>(Map.of("secretName", akp.getPrivateKeyId()));
        getPrivateKeyData.put("secretVersion", akp.getPrivateKeyVersion());
        base64PublicKey = keyVaultService.getSecret(getPublicKeyData);
        base64PrivateKey = keyVaultService.getSecret(getPrivateKeyData);
    } else if (configKeyPair instanceof HashicorpVaultKeyPair) {
        KeyVaultServiceFactory keyVaultServiceFactory = KeyVaultServiceFactory.getInstance(KeyVaultType.HASHICORP);
        KeyVaultService keyVaultService = keyVaultServiceFactory.create(config, envProvider);
        HashicorpVaultKeyPair hkp = (HashicorpVaultKeyPair) configKeyPair;
        Map<String, String> getPublicKeyData = Map.of("secretEngineName", hkp.getSecretEngineName(), "secretName", hkp.getSecretName(), "secretId", hkp.getPublicKeyId(), "secretVersion", Objects.toString(hkp.getSecretVersion()));
        Map<String, String> getPrivateKeyData = Map.of("secretEngineName", hkp.getSecretEngineName(), "secretName", hkp.getSecretName(), "secretId", hkp.getPrivateKeyId(), "secretVersion", Objects.toString(hkp.getSecretVersion()));
        base64PublicKey = keyVaultService.getSecret(getPublicKeyData);
        base64PrivateKey = keyVaultService.getSecret(getPrivateKeyData);
    } else if (configKeyPair instanceof AWSKeyPair) {
        KeyVaultServiceFactory keyVaultServiceFactory = KeyVaultServiceFactory.getInstance(KeyVaultType.AWS);
        KeyVaultService keyVaultService = keyVaultServiceFactory.create(config, envProvider);
        AWSKeyPair akp = (AWSKeyPair) configKeyPair;
        Map<String, String> getPublicKeyData = Map.of("secretName", akp.getPublicKeyId());
        Map<String, String> getPrivateKeyData = Map.of("secretName", akp.getPrivateKeyId());
        base64PublicKey = keyVaultService.getSecret(getPublicKeyData);
        base64PrivateKey = keyVaultService.getSecret(getPrivateKeyData);
    } else {
        base64PublicKey = configKeyPair.getPublicKey();
        base64PrivateKey = configKeyPair.getPrivateKey();
    }
    return new KeyPair(PublicKey.from(Base64.getDecoder().decode(base64PublicKey.trim())), PrivateKey.from(Base64.getDecoder().decode(base64PrivateKey.trim())));
}
Also used : HashicorpVaultKeyPair(com.quorum.tessera.config.keypairs.HashicorpVaultKeyPair) KeyVaultService(com.quorum.tessera.key.vault.KeyVaultService) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) KeyPair(com.quorum.tessera.encryption.KeyPair) AWSKeyPair(com.quorum.tessera.config.keypairs.AWSKeyPair) AzureVaultKeyPair(com.quorum.tessera.config.keypairs.AzureVaultKeyPair) HashicorpVaultKeyPair(com.quorum.tessera.config.keypairs.HashicorpVaultKeyPair) AWSKeyPair(com.quorum.tessera.config.keypairs.AWSKeyPair) KeyVaultServiceFactory(com.quorum.tessera.key.vault.KeyVaultServiceFactory) AzureVaultKeyPair(com.quorum.tessera.config.keypairs.AzureVaultKeyPair)

Example 2 with ConfigKeyPair

use of com.quorum.tessera.config.keypairs.ConfigKeyPair in project tessera by ConsenSys.

the class ThirdPartyIT method partyInfoKeys.

@Test
public void partyInfoKeys() {
    Response partyinfoResponse = client.target(thirdPartyServerConfig.getServerUri()).path("partyinfo").path("keys").request().get();
    JsonObject partyinfokeysJson = partyinfoResponse.readEntity(JsonObject.class);
    assertThat(partyinfoResponse).isNotNull();
    assertThat(partyinfoResponse.getStatus()).isEqualTo(200);
    List<JsonObject> keys = Stream.of(firstNodeExecManager, secondNodeExecManager).map(NodeExecManager::getConfigDescriptor).map(ConfigDescriptor::getKey).map(ConfigKeyPair::getPublicKey).map(k -> Json.createObjectBuilder().add("key", k).build()).collect(Collectors.toUnmodifiableList());
    assertThat(partyinfokeysJson.getJsonArray("keys")).describedAs("partyInfo response that caused failure %s", partyinfokeysJson.toString()).containsAnyElementsOf(keys);
}
Also used : Response(jakarta.ws.rs.core.Response) DBType(com.quorum.tessera.test.DBType) ExecutionContext(suite.ExecutionContext) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) EnclaveType(suite.EnclaveType) Response(jakarta.ws.rs.core.Response) JaxbUtil(com.quorum.tessera.config.util.JaxbUtil) JsonObject(jakarta.json.JsonObject) Path(java.nio.file.Path) OutputStream(java.io.OutputStream) NodeExecManager(exec.NodeExecManager) SocketType(suite.SocketType) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) Client(jakarta.ws.rs.client.Client) Files(java.nio.file.Files) ClientFactory(com.quorum.tessera.jaxrs.client.ClientFactory) PortUtil(config.PortUtil) Collectors(java.util.stream.Collectors) Json(jakarta.json.Json) List(java.util.List) Stream(java.util.stream.Stream) com.quorum.tessera.config(com.quorum.tessera.config) Paths(java.nio.file.Paths) NodeAlias(suite.NodeAlias) org.junit(org.junit) ConfigDescriptor(config.ConfigDescriptor) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) JsonObject(jakarta.json.JsonObject) NodeExecManager(exec.NodeExecManager)

Example 3 with ConfigKeyPair

use of com.quorum.tessera.config.keypairs.ConfigKeyPair in project tessera by ConsenSys.

the class SendIT method sendToMultipleRecipientsOnSameNode.

@Test
public void sendToMultipleRecipientsOnSameNode() throws UnsupportedEncodingException {
    // Node C has 2 keys, use them both
    final String[] recipientPublicKeys = ExecutionContext.currentContext().getConfigs().stream().filter(c -> c.getAlias() == NodeAlias.C).findFirst().map(ConfigDescriptor::getAllKeys).get().stream().map(ConfigKeyPair::getPublicKey).toArray(String[]::new);
    final Party sendingParty = partyHelper.findByAlias(NodeAlias.A);
    final Party recipientParty = partyHelper.findByAlias(NodeAlias.C);
    final byte[] transactionData = utils.createTransactionData();
    final SendRequest sendRequest = new SendRequest();
    sendRequest.setFrom(sendingParty.getPublicKey());
    sendRequest.setTo(recipientPublicKeys);
    sendRequest.setPayload(transactionData);
    final Response response = sendingParty.getRestClient().target(sendingParty.getQ2TUri()).path(SEND_PATH).request().post(Entity.entity(sendRequest, MIME_TYPE_JSON_2_1));
    final SendResponse result = response.readEntity(SendResponse.class);
    assertThat(result.getKey()).isNotNull().isNotBlank();
    assertThat(result.getManagedParties()).containsExactlyInAnyOrder(sendingParty.getPublicKey());
    assertThat(result.getSenderKey()).isEqualTo(sendingParty.getPublicKey());
    assertThat(response).isNotNull();
    assertThat(response.getStatus()).isEqualTo(201);
    URI location = response.getLocation();
    {
        final Response checkPersistedTxnResponse = recipientParty.getRestClient().target(location).request().get();
        assertThat(checkPersistedTxnResponse.getStatus()).isEqualTo(200);
        ReceiveResponse receiveResponse = checkPersistedTxnResponse.readEntity(ReceiveResponse.class);
        assertThat(receiveResponse.getPayload()).isEqualTo(transactionData);
        assertThat(result.getManagedParties()).containsExactlyInAnyOrder(sendingParty.getPublicKey());
        assertThat(result.getSenderKey()).isEqualTo(sendingParty.getPublicKey());
    }
    {
        String encodedId = URLEncoder.encode(result.getKey(), StandardCharsets.UTF_8.toString());
        Stream.of(recipientParty).map(Party::getRestClientWebTarget).map(target -> target.path("transaction")).map(target -> target.path(encodedId)).map(target -> target.request().accept(MIME_TYPE_JSON_2_1).get()).forEach(r -> {
            assertThat(r.getStatus()).isEqualTo(200);
            ReceiveResponse receiveResponse = r.readEntity(ReceiveResponse.class);
            assertThat(receiveResponse.getManagedParties()).containsExactlyInAnyOrder(recipientPublicKeys);
            assertThat(receiveResponse.getSenderKey()).isEqualTo(sendingParty.getPublicKey());
        });
    }
}
Also used : SendResponse(com.quorum.tessera.api.SendResponse) Response(jakarta.ws.rs.core.Response) ReceiveResponse(com.quorum.tessera.api.ReceiveResponse) ConfigKeyPair(com.quorum.tessera.config.keypairs.ConfigKeyPair) ExecutionContext(suite.ExecutionContext) SendResponse(com.quorum.tessera.api.SendResponse) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) PartyHelper(com.quorum.tessera.test.PartyHelper) ServerConfig(com.quorum.tessera.config.ServerConfig) RestUtils(com.quorum.tessera.test.rest.RestUtils) Utils.generateValidButUnknownPublicKey(transaction.utils.Utils.generateValidButUnknownPublicKey) StandardCharsets(java.nio.charset.StandardCharsets) Json(jakarta.json.Json) Entity(jakarta.ws.rs.client.Entity) Response(jakarta.ws.rs.core.Response) URLEncoder(java.net.URLEncoder) SendRequest(com.quorum.tessera.api.SendRequest) Stream(java.util.stream.Stream) ReceiveResponse(com.quorum.tessera.api.ReceiveResponse) MIME_TYPE_JSON_2_1(com.quorum.tessera.version.MultiTenancyVersion.MIME_TYPE_JSON_2_1) NodeAlias(suite.NodeAlias) URI(java.net.URI) ConfigDescriptor(config.ConfigDescriptor) Party(com.quorum.tessera.test.Party) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Party(com.quorum.tessera.test.Party) SendRequest(com.quorum.tessera.api.SendRequest) SendResponse(com.quorum.tessera.api.SendResponse) ReceiveResponse(com.quorum.tessera.api.ReceiveResponse) ConfigDescriptor(config.ConfigDescriptor) URI(java.net.URI) Test(org.junit.Test)

Example 4 with ConfigKeyPair

use of com.quorum.tessera.config.keypairs.ConfigKeyPair 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 5 with ConfigKeyPair

use of com.quorum.tessera.config.keypairs.ConfigKeyPair 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)

Aggregations

ConfigKeyPair (com.quorum.tessera.config.keypairs.ConfigKeyPair)16 Test (org.junit.Test)11 Stream (java.util.stream.Stream)5 CliResult (com.quorum.tessera.cli.CliResult)4 Response (jakarta.ws.rs.core.Response)4 Collectors (java.util.stream.Collectors)4 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)4 CommandLine (picocli.CommandLine)4 NodeAlias (suite.NodeAlias)4 com.quorum.tessera.config (com.quorum.tessera.config)3 ServerConfig (com.quorum.tessera.config.ServerConfig)3 KeyEncryptor (com.quorum.tessera.config.keys.KeyEncryptor)3 ConfigDescriptor (config.ConfigDescriptor)3 Json (jakarta.json.Json)3 ConstraintViolation (jakarta.validation.ConstraintViolation)3 Client (jakarta.ws.rs.client.Client)3 ReceiveResponse (com.quorum.tessera.api.ReceiveResponse)2 SendRequest (com.quorum.tessera.api.SendRequest)2 SendResponse (com.quorum.tessera.api.SendResponse)2 AzureVaultKeyPair (com.quorum.tessera.config.keypairs.AzureVaultKeyPair)2