io.vertx.core.net.PemTrustOptions Java Examples

The following examples show how to use io.vertx.core.net.PemTrustOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClientProducers.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Produces
@Named("my-named-options")
public AmqpClientOptions getNamedOptions() {
    // You can use the produced options to configure the TLS connection
    PemKeyCertOptions keycert = new PemKeyCertOptions()
        .addCertPath("./tls/tls.crt")
        .addKeyPath("./tls/tls.key");
    PemTrustOptions trust =
        new PemTrustOptions().addCertPath("./tlc/ca.crt");

    return new AmqpClientOptions()
        .setSsl(true)
        .setPemKeyCertOptions(keycert)
        .setPemTrustOptions(trust)
        .addEnabledSaslMechanism("EXTERNAL")
        .setHostnameVerificationAlgorithm("")
        .setConnectTimeout(30000)
        .setReconnectInterval(5000)
        .setContainerId("my-container");
}
 
Example #2
Source File: AmqpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
/**
 * Create an options instance for the ProtonServer
 * based on AMQP-Kafka bridge internal configuration
 *
 * @return ProtonServer options instance
 */
private ProtonServerOptions createServerOptions() {

    ProtonServerOptions options = new ProtonServerOptions();
    options.setHost(this.bridgeConfig.getAmqpConfig().getHost());
    options.setPort(this.bridgeConfig.getAmqpConfig().getPort());

    if (this.bridgeConfig.getAmqpConfig().getCertDir() != null && this.bridgeConfig.getAmqpConfig().getCertDir().length() > 0) {
        String certDir = this.bridgeConfig.getAmqpConfig().getCertDir();
        log.info("Enabling SSL configuration for AMQP with TLS certificates from {}", certDir);
        options.setSsl(true)
                .setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()))
                .setPemKeyCertOptions(new PemKeyCertOptions()
                        .addCertPath(new File(certDir, "tls.crt").getAbsolutePath())
                        .addKeyPath(new File(certDir, "tls.key").getAbsolutePath()));
    }

    return options;
}
 
Example #3
Source File: AmqpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
/**
 * Create an options instance for the ProtonClient
 *
 * @return ProtonClient options instance
 */
private ProtonClientOptions createClientOptions() {

    ProtonClientOptions options = new ProtonClientOptions();
    options.setConnectTimeout(1000);
    options.setReconnectAttempts(-1).setReconnectInterval(1000); // reconnect forever, every 1000 millisecs

    if (this.bridgeConfig.getAmqpConfig().getCertDir() != null && this.bridgeConfig.getAmqpConfig().getCertDir().length() > 0) {
        String certDir = this.bridgeConfig.getAmqpConfig().getCertDir();
        log.info("Enabling SSL configuration for AMQP with TLS certificates from {}", certDir);
        options.setSsl(true)
                .addEnabledSaslMechanism("EXTERNAL")
                .setHostnameVerificationAlgorithm("")
                .setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()))
                .setPemKeyCertOptions(new PemKeyCertOptions()
                        .addCertPath(new File(certDir, "tls.crt").getAbsolutePath())
                        .addKeyPath(new File(certDir, "tls.key").getAbsolutePath()));
    }

    return options;
}
 
Example #4
Source File: MqttTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Opens a connection to the MQTT adapter using an X.509 client certificate.
 *
 * @param cert The client certificate to use for authentication.
 * @return A future that will be completed with the CONNACK packet received
 *         from the adapter or failed with a {@link MqttConnectionException}
 *         if the connection could not be established.
 */
protected final Future<MqttConnAckMessage> connectToAdapter(
        final SelfSignedCertificate cert) {

    final Promise<MqttConnAckMessage> result = Promise.promise();
    VERTX.runOnContext(connect -> {
        final MqttClientOptions options = new MqttClientOptions()
                .setTrustOptions(new PemTrustOptions().addCertPath(IntegrationTestSupport.TRUST_STORE_PATH))
                .setKeyCertOptions(cert.keyCertOptions())
                .setSsl(true);
        options.setHostnameVerificationAlgorithm("");
        mqttClient = MqttClient.create(VERTX, options);
        mqttClient.connect(IntegrationTestSupport.MQTTS_PORT, IntegrationTestSupport.MQTT_HOST, result);
    });
    return result.future().map(conAck -> {
        LOGGER.debug(
                "MQTTS connection to adapter [host: {}, port: {}] established",
                IntegrationTestSupport.MQTT_HOST, IntegrationTestSupport.MQTTS_PORT);
        this.context = Vertx.currentContext();
        return conAck;
    });
}
 
Example #5
Source File: ZookeeperLeaderFinder.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the cluster CA certificate(s) passed in the given Secret
 * and return the PemTrustOptions for trusting them.
 */
protected PemTrustOptions trustOptions(Secret clusterCaCertificateSecret) {
    Base64.Decoder decoder = Base64.getDecoder();
    CertificateFactory x509 = x509Factory();
    PemTrustOptions pto = new PemTrustOptions();
    for (Map.Entry<String, String> entry : clusterCaCertificateSecret.getData().entrySet()) {
        String entryName = entry.getKey();
        if (entryName.endsWith(".crt")) {
            log.info("Trusting certificate {} from Secret {}", entryName, clusterCaCertificateSecret.getMetadata().getName());
            byte[] certBytes = decoder.decode(entry.getValue());
            try {
                x509.generateCertificate(new ByteArrayInputStream(certBytes));
            } catch (CertificateException e) {
                throw corruptCertificate(clusterCaCertificateSecret, entryName, e);
            }
            pto.addCertValue(Buffer.buffer(certBytes));
        } else {
            log.warn("Ignoring non-certificate {} in Secret {}", entryName, clusterCaCertificateSecret.getMetadata().getName());
        }
    }
    return pto;
}
 
Example #6
Source File: VaultClientWithCertTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
/**
 * Tests authentication with the cert auth backend using PEM file
 */
@Test
public void testLoginByCert_usingPemConfig(TestContext tc) throws VaultException {
  JsonObject config = new JsonObject();
  config.put("host", process.getHost());
  config.put("port", process.getPort());
  config.put("ssl", true);
  PemKeyCertOptions options = new PemKeyCertOptions()
    .addCertPath("target/vault/config/ssl/client-cert.pem")
    .addKeyPath("target/vault/config/ssl/client-privatekey.pem");
  config.put("pemKeyCertOptions", options.toJson());

  PemTrustOptions trust = new PemTrustOptions()
    .addCertPath("target/vault/config/ssl/cert.pem");
  config.put("pemTrustStoreOptions", trust.toJson());

  JksOptions jks = new JksOptions()
    .setPath("target/vault/config/ssl/truststore.jks");
  config.put("trustStoreOptions", jks.toJson());

  client = new SlimVaultClient(vertx, config);

  checkWeCanLoginAndAccessRestrictedSecrets(tc);
}
 
Example #7
Source File: VaultConfigStoreWithCertsTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
@Override
protected JsonObject getRetrieverConfiguration() {

  JsonObject config = new JsonObject();
  config.put("host", process.getHost());
  config.put("port", process.getPort());
  config.put("ssl", true);
  PemKeyCertOptions options = new PemKeyCertOptions()
    .addCertPath("target/vault/config/ssl/client-cert.pem")
    .addKeyPath("target/vault/config/ssl/client-privatekey.pem");
  config.put("pemKeyCertOptions", options.toJson());

  PemTrustOptions trust = new PemTrustOptions()
    .addCertPath("target/vault/config/ssl/cert.pem");
  config.put("pemTrustStoreOptions", trust.toJson());

  JksOptions jks = new JksOptions()
    .setPath("target/vault/config/ssl/truststore.jks");
  config.put("trustStoreOptions", jks.toJson());

  config.put("auth-backend", "cert");

  return config;
}
 
Example #8
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeUser(TestContext ctx) {
  options.setSslMode(SslMode.REQUIRED);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.query("SELECT current_user()").execute(ctx.asyncAssertSuccess(res1 -> {
      Row row1 = res1.iterator().next();
      String username = row1.getString(0);
      ctx.assertEquals("mysql", username.substring(0, username.lastIndexOf('@')));
      MySQLAuthOptions changeUserOptions = new MySQLAuthOptions()
        .setUser("superuser")
        .setPassword("password")
        .setDatabase("emptyschema");
      conn.changeUser(changeUserOptions, ctx.asyncAssertSuccess(v2 -> {
        conn.query("SELECT current_user();SELECT database();").execute(ctx.asyncAssertSuccess(res2 -> {
          ctx.assertEquals("superuser@%", res2.iterator().next().getString(0));
          ctx.assertEquals("emptyschema", res2.next().iterator().next().getValue(0));
          conn.close();
        }));
      }));
    }));
  }));
}
 
Example #9
Source File: MessagingEndpointTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
void doTestSendReceiveOutsideCluster(String host, int port, String address, boolean tls, boolean verifyHost, String caCert) throws Exception {
    ProtonClientOptions protonClientOptions = new ProtonClientOptions();
    if (tls) {
        protonClientOptions.setSsl(true);
        if (!verifyHost) {
            protonClientOptions.setHostnameVerificationAlgorithm("");
        }
        if (caCert != null) {
            protonClientOptions.setTrustOptions(new PemTrustOptions()
                    .addCertValue(Buffer.buffer(caCert)));
        }
    }
    AmqpClient client = resourceManager.getAmqpClientFactory().createClient(new AmqpConnectOptions()
            .setSaslMechanism("ANONYMOUS")
            .setQos(ProtonQoS.AT_LEAST_ONCE)
            .setEndpoint(new Endpoint(host, port))
            .setProtonClientOptions(protonClientOptions)
            .setTerminusFactory(new QueueTerminusFactory()));

    assertEquals(1, client.sendMessages(address, Collections.singletonList("hello")).get(1, TimeUnit.MINUTES));
    var result = client.recvMessages(address, 1).get();
    assertEquals(1, result.size());
    assertEquals("hello", ((AmqpValue) result.get(0).getBody()).getValue());
}
 
Example #10
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessWithVerifyCaSslMode(TestContext ctx) {
  options.setSslMode(SslMode.VERIFY_CA);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    ctx.assertTrue(conn.isSSL());
    conn.query("SELECT 1").execute(ctx.asyncAssertSuccess(res -> {
      ctx.assertEquals(1, res.size());
      conn.close();
    }));
  }));
}
 
Example #11
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessWithRequiredSslMode(TestContext ctx) {
  options.setSslMode(SslMode.REQUIRED);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    ctx.assertTrue(conn.isSSL());
    conn.query("SELECT 1").execute(ctx.asyncAssertSuccess(res -> {
      ctx.assertEquals(1, res.size());
      conn.close();
    }));
  }));
}
 
Example #12
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessWithPreferredSslMode(TestContext ctx) {
  options.setSslMode(SslMode.PREFERRED);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    ctx.assertTrue(conn.isSSL());
    conn.query("SELECT 1").execute(ctx.asyncAssertSuccess(res -> {
      ctx.assertEquals(1, res.size());
      conn.close();
    }));
  }));
}
 
Example #13
Source File: MySQLClientExamples.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
public void tlsExample(Vertx vertx) {

    MySQLConnectOptions options = new MySQLConnectOptions()
      .setPort(3306)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret")
      .setSslMode(SslMode.VERIFY_CA)
      .setPemTrustOptions(new PemTrustOptions().addCertPath("/path/to/cert.pem"));

    MySQLConnection.connect(vertx, options, res -> {
      if (res.succeeded()) {
        // Connected with SSL
      } else {
        System.out.println("Could not connect " + res.cause());
      }
    });
  }
 
Example #14
Source File: TLSTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testTLS(TestContext ctx) {
  Async async = ctx.async();

  PgConnectOptions options = new PgConnectOptions(rule.options())
    .setSslMode(SslMode.REQUIRE)
    .setPemTrustOptions(new PemTrustOptions().addCertPath("tls/server.crt"));
  PgConnection.connect(vertx, options.setSslMode(SslMode.REQUIRE).setTrustAll(true), ctx.asyncAssertSuccess(conn -> {
    ctx.assertTrue(conn.isSSL());
    conn
      .query("SELECT * FROM Fortune WHERE id=1")
      .execute(ctx.asyncAssertSuccess(result -> {
      ctx.assertEquals(1, result.size());
      Tuple row = result.iterator().next();
      ctx.assertEquals(1, row.getInteger(0));
      ctx.assertEquals("fortune: No such file or directory", row.getString(1));
      async.complete();
    }));
  }));
}
 
Example #15
Source File: PgClientExamples.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
public void ex10(Vertx vertx) {

    PgConnectOptions options = new PgConnectOptions()
      .setPort(5432)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret")
      .setSslMode(SslMode.VERIFY_CA)
      .setPemTrustOptions(new PemTrustOptions().addCertPath("/path/to/cert.pem"));

    PgConnection.connect(vertx, options, res -> {
      if (res.succeeded()) {
        // Connected with SSL
      } else {
        System.out.println("Could not connect " + res.cause());
      }
    });
  }
 
Example #16
Source File: RouterManagement.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static RouterManagement withCertsInDir(Vertx vertx, String containerId, Duration connectTimeout, Duration queryTimeout, String certDir) {
    ProtonClientOptions clientOptions = new ProtonClientOptions()
            .setSsl(true)
            .addEnabledSaslMechanism("EXTERNAL")
            .setHostnameVerificationAlgorithm("")
            .setPemTrustOptions(new PemTrustOptions()
                    .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()))
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .setCertPath(new File(certDir, "tls.crt").getAbsolutePath())
                    .setKeyPath(new File(certDir, "tls.key").getAbsolutePath()));
    return new RouterManagement(vertx, containerId, clientOptions, connectTimeout, queryTimeout);
}
 
Example #17
Source File: RouterManagement.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static RouterManagement withCerts(Vertx vertx, String containerId, Duration connectTimeout, Duration queryTimeout, byte[] caCert, byte[] clientCert, byte[] clientKey) {
    ProtonClientOptions clientOptions = new ProtonClientOptions()
            .setSsl(true)
            .addEnabledSaslMechanism("EXTERNAL")
            .setHostnameVerificationAlgorithm("")
            .setPemTrustOptions(new PemTrustOptions()
                    .addCertValue(Buffer.buffer(caCert)))
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .addCertValue(Buffer.buffer(clientCert))
                    .addKeyValue(Buffer.buffer(clientKey)));
    return new RouterManagement(vertx, containerId, clientOptions, connectTimeout, queryTimeout);
}
 
Example #18
Source File: AmqpConnectOptions.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public AmqpConnectOptions setCert(String pemCert) {
    this.protonClientOptions
            .setSsl(true)
            .setHostnameVerificationAlgorithm("")
            .setPemTrustOptions(new PemTrustOptions().addCertValue(Buffer.buffer(pemCert)))
            .setTrustAll(false);
    return this;
}
 
Example #19
Source File: SecureClient.java    From vertx-consul-client with Apache License 2.0 5 votes vote down vote up
private void go(TestContext tc, boolean trustAll, PemTrustOptions trustOptions) {
  ConsulClient secureClient = ctx.createSecureClient(trustAll, trustOptions);
  secureClient.putValue("foo/bars42", "value42", tc.asyncAssertSuccess(b -> {
    tc.assertTrue(b);
    secureClient.getValue("foo/bars42", tc.asyncAssertSuccess(pair -> {
      tc.assertEquals(pair.getValue(), "value42");
      ctx.closeClient(secureClient);
    }));
  }));
}
 
Example #20
Source File: ConfigVaultExamples.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
public void exampleWithCerts(Vertx vertx) {
  JsonObject vault_config = new JsonObject();

  // ...

  PemKeyCertOptions certs = new PemKeyCertOptions()
    .addCertPath("target/vault/config/ssl/client-cert.pem")
    .addKeyPath("target/vault/config/ssl/client-privatekey.pem");
  vault_config.put("pemKeyCertOptions", certs.toJson());

  PemTrustOptions trust = new PemTrustOptions()
    .addCertPath("target/vault/config/ssl/cert.pem");
  vault_config.put("pemTrustStoreOptions", trust.toJson());

  JksOptions jks = new JksOptions()
    .setPath("target/vault/config/ssl/truststore.jks");
  vault_config.put("trustStoreOptions", jks.toJson());

  vault_config.put("auth-backend", "cert");

  // Path to the secret to read.
  vault_config.put("path", "secret/my-secret");

  ConfigStoreOptions store = new ConfigStoreOptions()
    .setType("vault")
    .setConfig(vault_config);

  ConfigRetriever retriever = ConfigRetriever.create(vertx,
    new ConfigRetrieverOptions().addStore(store));
}
 
Example #21
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoHttp2Push() throws Exception {
  stat.setWebRoot("webroot/somedir3");
  router.route().handler(stat);
  HttpServer http2Server = vertx.createHttpServer(new HttpServerOptions()
    .setUseAlpn(true)
    .setSsl(true)
    .setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert.pem")));
  http2Server.requestHandler(router).listen(8443);

  HttpClientOptions options = new HttpClientOptions()
    .setSsl(true)
    .setUseAlpn(true)
    .setProtocolVersion(HttpVersion.HTTP_2)
    .setPemTrustOptions(new PemTrustOptions().addCertPath("tls/server-cert.pem"));
  HttpClient client = vertx.createHttpClient(options);
  client.request(HttpMethod.GET, 8443, "localhost", "/testLinkPreload.html")
    .onComplete(onSuccess(resp -> {
      assertEquals(200, resp.statusCode());
      assertEquals(HttpVersion.HTTP_2, resp.version());
      resp.bodyHandler(this::assertNotNull);
      testComplete();
    }))
    .pushHandler(pushedReq -> pushedReq.onComplete(pushedResp -> {
      fail();
    }))
    .end();
  await();
}
 
Example #22
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttp2Push() throws Exception {
  List<Http2PushMapping> mappings = new ArrayList<>();
  mappings.add(new Http2PushMapping("style.css", "style", false));
  mappings.add(new Http2PushMapping("coin.png", "image", false));
  stat.setHttp2PushMapping(mappings)
      .setWebRoot("webroot/somedir3");
  router.route().handler(stat);
  HttpServer http2Server = vertx.createHttpServer(new HttpServerOptions()
      .setUseAlpn(true)
      .setSsl(true)
      .setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert.pem")));
  http2Server.requestHandler(router).listen(8443);

  HttpClientOptions options = new HttpClientOptions()
    .setSsl(true)
    .setUseAlpn(true)
    .setProtocolVersion(HttpVersion.HTTP_2)
    .setPemTrustOptions(new PemTrustOptions().addCertPath("tls/server-cert.pem"));
  HttpClient client = vertx.createHttpClient(options);
  CountDownLatch latch = new CountDownLatch(2);
  client.request(HttpMethod.GET, 8443, "localhost", "/testLinkPreload.html")
    .onComplete(onSuccess(resp -> {
      assertEquals(200, resp.statusCode());
      assertEquals(HttpVersion.HTTP_2, resp.version());
      resp.bodyHandler(this::assertNotNull);
    }))
    .pushHandler(pushedReq -> pushedReq.onComplete(onSuccess(pushedResp -> {
      assertNotNull(pushedResp);
      pushedResp.bodyHandler(this::assertNotNull);
      latch.countDown();
    })))
    .end();
  latch.await();
}
 
Example #23
Source File: SSLConfigHelper.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static PemTrustOptions toPemTrustOptions(PemTrustCertConfiguration configuration) {
    PemTrustOptions pemTrustOptions = new PemTrustOptions();
    if (configuration.certs.isPresent()) {
        for (String cert : configuration.certs.get()) {
            pemTrustOptions.addCertPath(cert);
        }
    }
    return pemTrustOptions;
}
 
Example #24
Source File: AmqpAdapterTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a HTTP client for accessing the device registry (for registering devices and credentials) and
 * an AMQP 1.0 client for consuming messages from the messaging network.
 *
 * @param ctx The Vert.x test context.
 */
@BeforeAll
public static void setup(final VertxTestContext ctx) {

    VERTX = Vertx.vertx();

    defaultOptions = new ProtonClientOptions()
            .setTrustOptions(new PemTrustOptions().addCertPath(IntegrationTestSupport.TRUST_STORE_PATH))
            .setHostnameVerificationAlgorithm("")
            .setSsl(true);

    helper = new IntegrationTestSupport(VERTX);
    helper.init().onComplete(ctx.completing());

}
 
Example #25
Source File: HttpTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets up clients.
 *
 * @param ctx The vert.x test context.
 */
@BeforeAll
public static void init(final VertxTestContext ctx) {

    defaultOptions = new HttpClientOptions()
            .setDefaultHost(IntegrationTestSupport.HTTP_HOST)
            .setDefaultPort(IntegrationTestSupport.HTTPS_PORT)
            .setTrustOptions(new PemTrustOptions().addCertPath(IntegrationTestSupport.TRUST_STORE_PATH))
            .setVerifyHost(false)
            .setSsl(true);

    helper = new IntegrationTestSupport(VERTX);
    helper.init().onComplete(ctx.completing());
}
 
Example #26
Source File: HttpTlsOptionHelpers.java    From orion with Apache License 2.0 5 votes vote down vote up
public static PemTrustOptions createPemTrustOptions(final List<Path> certChain) {
  if (!certChain.isEmpty()) {
    final PemTrustOptions pemTrustOptions = new PemTrustOptions();
    for (final Path certPath : certChain) {
      pemTrustOptions.addCertPath(certPath.toAbsolutePath().toString());
    }
    return pemTrustOptions;
  }
  return null;
}
 
Example #27
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnFailWithVerifyIdentitySslMode(TestContext ctx) {
  options.setSslMode(SslMode.VERIFY_IDENTITY);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertFailure(error -> {
    ctx.assertEquals("Host verification algorithm must be specified under VERIFY_IDENTITY ssl-mode.", error.getMessage());
  }));
}
 
Example #28
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessWithOnlyCertificate(TestContext ctx) {
  options.setSslMode(SslMode.REQUIRED);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    ctx.assertTrue(conn.isSSL());
    conn.query("SELECT 1").execute(ctx.asyncAssertSuccess(res -> {
      ctx.assertEquals(1, res.size());
      conn.close();
    }));
  }));
}
 
Example #29
Source File: ConsulContext.java    From vertx-consul-client with Apache License 2.0 4 votes vote down vote up
public ConsulClient createSecureClient(boolean trustAll, PemTrustOptions trustOptions) {
  ConsulClientOptions options = config(ConsulCluster.writeToken(), true)
    .setTrustAll(trustAll)
    .setPemTrustOptions(trustOptions);
  return creator.apply(options);
}
 
Example #30
Source File: EventBusBridgeWebsocketServerVerticle.java    From vertx-mqtt-broker with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    address = MQTTSession.ADDRESS;

    JsonObject conf = config();

    localBridgePort = conf.getInteger("local_bridge_port", 7007);
    idleTimeout = conf.getInteger("socket_idle_timeout", 120);
    ssl_cert_key = conf.getString("ssl_cert_key");
    ssl_cert = conf.getString("ssl_cert");
    ssl_trust = conf.getString("ssl_trust");


    // [WebSocket -> BUS] listen WebSocket publish to BUS
    HttpServerOptions opt = new HttpServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout)
            .setPort(localBridgePort)
    ;

    if(ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
        opt.setSsl(true).setClientAuth(ClientAuth.REQUIRED)
            .setPemKeyCertOptions(new PemKeyCertOptions()
                .setKeyPath(ssl_cert_key)
                .setCertPath(ssl_cert)
            )
            .setPemTrustOptions(new PemTrustOptions()
                .addCertPath(ssl_trust)
            )
        ;
    }

    netServer = vertx.createHttpServer(opt);
    netServer.requestHandler(httpServerRequest -> httpServerRequest.response().end() );
    netServer.websocketHandler(sock -> {
        final EventBusWebsocketBridge ebnb = new EventBusWebsocketBridge(sock, vertx.eventBus(), address);
        sock.closeHandler(aVoid -> {
            logger.info("Bridge Server - closed connection from client ip: " + sock.remoteAddress());
            ebnb.stop();
        });
        sock.exceptionHandler(throwable -> {
            logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
            ebnb.stop();
        });

        logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());

        RecordParser parser = ebnb.initialHandhakeProtocolParser();
        sock.handler(parser::handle);

    }).listen();
}