Search in sources :

Example 71 with Config

use of com.quorum.tessera.config.Config in project tessera by ConsenSys.

the class PayloadDigestTest method create.

@Test
public void create() {
    ServiceLoader<PayloadDigest> serviceLoader = mock(ServiceLoader.class);
    Stream<ServiceLoader.Provider<PayloadDigest>> providerStream = Stream.of(DefaultPayloadDigest.class, SHA512256PayloadDigest.class).map(type -> new ServiceLoader.Provider<PayloadDigest>() {

        @Override
        public Class<? extends PayloadDigest> type() {
            return type;
        }

        @Override
        public PayloadDigest get() {
            return mock(type);
        }
    });
    when(serviceLoader.stream()).thenReturn(providerStream);
    Config config = mock(Config.class);
    when(config.getClientMode()).thenReturn(clientMode);
    ConfigFactory configFactory = mock(ConfigFactory.class);
    when(configFactory.getConfig()).thenReturn(config);
    PayloadDigest result;
    try (var serviceLoaderMockedStatic = mockStatic(ServiceLoader.class);
        var configFactoryMockedStatic = mockStatic(ConfigFactory.class)) {
        serviceLoaderMockedStatic.when(() -> ServiceLoader.load(PayloadDigest.class)).thenReturn(serviceLoader);
        configFactoryMockedStatic.when(ConfigFactory::create).thenReturn(configFactory);
        result = PayloadDigest.create();
        serviceLoaderMockedStatic.verify(() -> ServiceLoader.load(PayloadDigest.class));
        serviceLoaderMockedStatic.verifyNoMoreInteractions();
        configFactoryMockedStatic.verify(ConfigFactory::create);
        configFactoryMockedStatic.verifyNoMoreInteractions();
    }
    assertThat(result).isExactlyInstanceOf(digestType).isNotNull();
}
Also used : Config(com.quorum.tessera.config.Config) ConfigFactory(com.quorum.tessera.config.ConfigFactory) ServiceLoader(java.util.ServiceLoader) Test(org.junit.Test)

Example 72 with Config

use of com.quorum.tessera.config.Config in project tessera by ConsenSys.

the class EnclaveServerProvider method provider.

public static EnclaveServer provider() {
    Config config = ConfigFactory.create().getConfig();
    Enclave enclave = EnclaveFactoryImpl.createServer(config);
    LOGGER.debug("Creating server with {}", enclave);
    return new EnclaveServerImpl(enclave);
}
Also used : Config(com.quorum.tessera.config.Config)

Example 73 with Config

use of com.quorum.tessera.config.Config in project tessera by ConsenSys.

the class AwsKeyVaultIT method tesseraStartupRequestsKeysWhosIdsAreConfigured.

@Test
public void tesseraStartupRequestsKeysWhosIdsAreConfigured() throws Exception {
    Map<String, Object> params = Map.of("awsSecretsManagerEndpoint", keyVaultUrl);
    Path tempTesseraConfig = ElUtil.createTempFileFromTemplate(getClass().getResource("/vault/tessera-aws-config.json"), params);
    List<String> args = new ExecArgsBuilder().withStartScript(startScript).withClassPathItem(distDirectory).withArg("-configfile", tempTesseraConfig.toString()).withArg("-pidfile", pid.toAbsolutePath().toString()).withArg("-jdbc.autoCreateTables", "true").build();
    ProcessBuilder processBuilder = new ProcessBuilder(args);
    processBuilder.environment().putAll(env());
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();
    executorService.submit(new StreamConsumer(process.getInputStream(), LOGGER::info));
    executorService.submit(() -> {
        int exitCode = process.waitFor();
        assertThat(exitCode).describedAs("Tessera node exited with code %d", exitCode).isEqualTo(0);
        return null;
    });
    final Config config = JaxbUtil.unmarshal(Files.newInputStream(tempTesseraConfig), Config.class);
    final URI bindingUrl = Optional.of(config).map(Config::getP2PServerConfig).map(ServerConfig::getBindingUri).map(UriBuilder::fromUri).map(u -> u.path("upcheck")).map(UriBuilder::build).get();
    HttpClient httpClient = HttpClient.newHttpClient();
    final HttpRequest request = HttpRequest.newBuilder().uri(bindingUrl).GET().build();
    CountDownLatch startUpLatch = new CountDownLatch(1);
    executorService.submit(() -> {
        while (true) {
            try {
                HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
                if (response.statusCode() == 200) {
                    startUpLatch.countDown();
                }
            } catch (InterruptedException | IOException e) {
            }
        }
    });
    assertThat(startUpLatch.await(2, TimeUnit.MINUTES)).isTrue();
    assertThat(httpHandler.getCounter()).isEqualTo(2);
    List<JsonObject> requests = httpHandler.getRequests().get("secretsmanager.GetSecretValue");
    assertThat(requests).hasSize(2);
    List<String> secretIds = requests.stream().map(j -> j.getString("SecretId")).collect(Collectors.toList());
    assertThat(secretIds).containsExactlyInAnyOrder("secretIdPub", "secretIdKey");
}
Also used : Path(java.nio.file.Path) HttpRequest(java.net.http.HttpRequest) HttpURLConnection(java.net.HttpURLConnection) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(com.quorum.tessera.ssl.context.SSLContextBuilder) URL(java.net.URL) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) LoggerFactory(org.slf4j.LoggerFactory) ServerConfig(com.quorum.tessera.config.ServerConfig) HttpRequest(java.net.http.HttpRequest) JaxbUtil(com.quorum.tessera.config.util.JaxbUtil) Map(java.util.Map) After(org.junit.After) JsonObject(jakarta.json.JsonObject) HttpClient(java.net.http.HttpClient) URI(java.net.URI) Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) HttpResponse(java.net.http.HttpResponse) Before(org.junit.Before) ElUtil(com.quorum.tessera.test.util.ElUtil) Logger(org.slf4j.Logger) HttpsParameters(com.sun.net.httpserver.HttpsParameters) Files(java.nio.file.Files) IOException(java.io.IOException) Test(org.junit.Test) PortUtil(config.PortUtil) UUID(java.util.UUID) ExecArgsBuilder(exec.ExecArgsBuilder) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ExecUtils(exec.ExecUtils) Executors(java.util.concurrent.Executors) Json(jakarta.json.Json) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) UriBuilder(jakarta.ws.rs.core.UriBuilder) Paths(java.nio.file.Paths) Optional(java.util.Optional) Config(com.quorum.tessera.config.Config) HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) HttpsServer(com.sun.net.httpserver.HttpsServer) StreamConsumer(exec.StreamConsumer) StreamConsumer(exec.StreamConsumer) ServerConfig(com.quorum.tessera.config.ServerConfig) Config(com.quorum.tessera.config.Config) JsonObject(jakarta.json.JsonObject) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ServerConfig(com.quorum.tessera.config.ServerConfig) HttpClient(java.net.http.HttpClient) JsonObject(jakarta.json.JsonObject) ExecArgsBuilder(exec.ExecArgsBuilder) Test(org.junit.Test)

Example 74 with Config

use of com.quorum.tessera.config.Config in project tessera by ConsenSys.

the class AzureStepDefs method startTessera.

private void startTessera(List<String> args, List<String> jvmArgs, Path verifyConfig) throws Exception {
    LOGGER.info("Starting: {}", String.join(" ", args));
    String jvmArgsStr = String.join(" ", jvmArgs);
    LOGGER.info("JVM Args: {}", jvmArgsStr);
    ProcessBuilder tesseraProcessBuilder = new ProcessBuilder(args);
    Map<String, String> tesseraEnvironment = tesseraProcessBuilder.environment();
    tesseraEnvironment.put(AZURE_CLIENT_ID, "my-client-id");
    tesseraEnvironment.put(AZURE_CLIENT_SECRET, "my-client-secret");
    tesseraEnvironment.put("AZURE_TENANT_ID", "my-tenant-id");
    tesseraEnvironment.put("JAVA_OPTS", // JAVA_OPTS is read by start script and is used to provide jvm args
    jvmArgsStr);
    try {
        tesseraProcess.set(tesseraProcessBuilder.redirectErrorStream(true).start());
    } catch (NullPointerException ex) {
        ex.printStackTrace();
        throw new NullPointerException("Check that application.jar property has been set");
    }
    executorService.submit(() -> {
        try (BufferedReader reader = Stream.of(tesseraProcess.get().getInputStream()).map(InputStreamReader::new).map(BufferedReader::new).findAny().get()) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    });
    CountDownLatch startUpLatch = new CountDownLatch(1);
    if (Objects.nonNull(verifyConfig)) {
        final Config config = JaxbUtil.unmarshal(Files.newInputStream(verifyConfig), Config.class);
        final URL bindingUrl = UriBuilder.fromUri(config.getP2PServerConfig().getBindingUri()).path("upcheck").build().toURL();
        executorService.submit(() -> {
            while (true) {
                try {
                    HttpURLConnection conn = (HttpURLConnection) bindingUrl.openConnection();
                    conn.connect();
                    System.out.println(bindingUrl + " started." + conn.getResponseCode());
                    startUpLatch.countDown();
                    return;
                } catch (IOException ex) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(200L);
                    } catch (InterruptedException ex1) {
                    }
                }
            }
        });
        boolean started = startUpLatch.await(30, TimeUnit.SECONDS);
        if (!started) {
            System.err.println(bindingUrl + " Not started. ");
        }
    }
    executorService.submit(() -> {
        try {
            int exitCode = tesseraProcess.get().waitFor();
            startUpLatch.countDown();
            if (0 != exitCode) {
                System.err.println("Tessera node exited with code " + exitCode);
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    });
    startUpLatch.await(30, TimeUnit.SECONDS);
}
Also used : Config(com.quorum.tessera.config.Config) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) CountDownLatch(java.util.concurrent.CountDownLatch) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) BufferedReader(java.io.BufferedReader)

Example 75 with Config

use of com.quorum.tessera.config.Config in project tessera by ConsenSys.

the class HashicorpStepDefs method startTessera.

private void startTessera(List<String> args, List<String> jvmArgs, Path verifyConfig, String authMethod) throws Exception {
    String jvmArgsStr = String.join(" ", jvmArgs);
    LOGGER.info("Starting: {}", String.join(" ", args));
    LOGGER.info("JVM Args: {}", jvmArgsStr);
    ProcessBuilder tesseraProcessBuilder = new ProcessBuilder(args);
    Map<String, String> tesseraEnvironment = tesseraProcessBuilder.environment();
    tesseraEnvironment.put(HASHICORP_CLIENT_KEYSTORE_PWD, "testtest");
    tesseraEnvironment.put(HASHICORP_CLIENT_TRUSTSTORE_PWD, "testtest");
    tesseraEnvironment.put("JAVA_OPTS", // JAVA_OPTS is read by start script and is used to provide jvm args
    jvmArgsStr);
    if ("token".equals(authMethod)) {
        Objects.requireNonNull(vaultToken);
        tesseraEnvironment.put(HASHICORP_TOKEN, vaultToken);
    } else {
        Objects.requireNonNull(approleRoleId);
        Objects.requireNonNull(approleSecretId);
        tesseraEnvironment.put(HASHICORP_ROLE_ID, approleRoleId);
        tesseraEnvironment.put(HASHICORP_SECRET_ID, approleSecretId);
    }
    try {
        tesseraProcess.set(tesseraProcessBuilder.redirectErrorStream(true).start());
    } catch (NullPointerException ex) {
        throw new NullPointerException("Check that application.jar property has been set");
    }
    executorService.submit(() -> {
        try (BufferedReader reader = Stream.of(tesseraProcess.get().getInputStream()).map(InputStreamReader::new).map(BufferedReader::new).findAny().get()) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    });
    CountDownLatch startUpLatch = new CountDownLatch(1);
    if (Objects.nonNull(verifyConfig)) {
        final Config config = JaxbUtil.unmarshal(Files.newInputStream(verifyConfig), Config.class);
        final URL bindingUrl = UriBuilder.fromUri(config.getP2PServerConfig().getBindingUri()).path("upcheck").build().toURL();
        executorService.submit(() -> {
            while (true) {
                try {
                    HttpURLConnection conn = (HttpURLConnection) bindingUrl.openConnection();
                    conn.connect();
                    System.out.println(bindingUrl + " started." + conn.getResponseCode());
                    startUpLatch.countDown();
                    return;
                } catch (IOException ex) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(200L);
                    } catch (InterruptedException ex1) {
                    }
                }
            }
        });
        boolean started = startUpLatch.await(30, TimeUnit.SECONDS);
        if (!started) {
            System.err.println(bindingUrl + " Not started. ");
        }
    }
    executorService.submit(() -> {
        try {
            int exitCode = tesseraProcess.get().waitFor();
            startUpLatch.countDown();
            if (0 != exitCode) {
                System.err.println("Tessera node exited with code " + exitCode);
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    });
    startUpLatch.await(30, TimeUnit.SECONDS);
}
Also used : HashicorpKeyVaultConfig(com.quorum.tessera.config.HashicorpKeyVaultConfig) Config(com.quorum.tessera.config.Config) CountDownLatch(java.util.concurrent.CountDownLatch) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection)

Aggregations

Config (com.quorum.tessera.config.Config)78 Test (org.junit.Test)54 ServerConfig (com.quorum.tessera.config.ServerConfig)20 ConfigFactory (com.quorum.tessera.config.ConfigFactory)18 Path (java.nio.file.Path)11 Before (org.junit.Before)11 ResidentGroup (com.quorum.tessera.config.ResidentGroup)9 ClientFactory (com.quorum.tessera.jaxrs.client.ClientFactory)9 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)9 Client (jakarta.ws.rs.client.Client)9 JdbcConfig (com.quorum.tessera.config.JdbcConfig)7 Map (java.util.Map)7 Collectors (java.util.stream.Collectors)7 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)7 After (org.junit.After)7 CommandLine (picocli.CommandLine)7 PrivacyViolationException (com.quorum.tessera.transaction.exception.PrivacyViolationException)6 CliResult (com.quorum.tessera.cli.CliResult)5 EncryptorConfig (com.quorum.tessera.config.EncryptorConfig)5 PublicKey (com.quorum.tessera.encryption.PublicKey)5