@Before public void prepare(TestContext context) { vertx = Vertx.vertx(); JsonObject dbConf = new JsonObject() .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:mem:testdb;shutdown=true") .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 4); vertx.deployVerticle(new WikiDatabaseVerticle(), new DeploymentOptions().setConfig(dbConf), context.asyncAssertSuccess()); vertx.deployVerticle(new HttpServerVerticle(), context.asyncAssertSuccess()); webClient = WebClient.create(vertx, new WebClientOptions() .setDefaultHost("localhost") .setDefaultPort(8080) .setSsl(true) .setTrustOptions(new JksOptions().setPath("server-keystore.jks").setPassword("secret"))); }
@Before public void prepare(TestContext context) { vertx = Vertx.vertx(); JsonObject dbConf = new JsonObject() .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:mem:testdb;shutdown=true") .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 4); vertx.deployVerticle(new WikiDatabaseVerticle(), new DeploymentOptions().setConfig(dbConf), context.asyncAssertSuccess()); vertx.deployVerticle(new HttpServerVerticle(), context.asyncAssertSuccess()); // tag::test-https[] webClient = WebClient.create(vertx, new WebClientOptions() .setDefaultHost("localhost") .setDefaultPort(8080) .setSsl(true) // <1> .setTrustOptions(new JksOptions().setPath("server-keystore.jks").setPassword("secret"))); // <2> // end::test-https[] }
@Test public void testDifferentCharset(TestContext context) throws Exception { termHandler = term -> { term.write("\u20AC"); term.close(); }; startShell(new SSHTermOptions().setDefaultCharset("ISO_8859_1").setPort(5000).setHost("localhost").setKeyPairOptions( new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")). setAuthOptions(new ShiroAuthOptions().setType(ShiroAuthRealmType.PROPERTIES).setConfig( new JsonObject().put("properties_path", "classpath:test-auth.properties")))); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); InputStream in = channel.getInputStream(); int b = in.read(); context.assertEquals(63, b); }
private HttpServerOptions configSSL(JsonObject conf) { String ssl_keystore= conf.getString("ssl.keystore"); String keystore_pass = conf.getString("ssl.keystore.pass"); String ssl_client_keystore= conf.getString("ssl.client.keystore"); String client_keystore_pass = conf.getString("ssl.client.keystore.pass"); HttpServerOptions options = new HttpServerOptions(); options.setCompressionSupported(true); if(S.isNotBlank(ssl_keystore) && S.isNotBlank(keystore_pass)){ options.setSsl(true).setKeyStoreOptions( new JksOptions().setPath(ssl_keystore).setPassword(keystore_pass)); if(S.isNotBlank(ssl_client_keystore) && S.isNotBlank(client_keystore_pass)) options.setClientAuth(ClientAuth.REQUIRED).setTrustStoreOptions( new JksOptions().setPath(ssl_client_keystore).setPassword(client_keystore_pass)); } return options; }
@Test public void clientSslClientTruststoreTest(TestContext context) { this.context = context; URL trustStore = this.getClass().getResource("/tls/client-truststore.jks"); JksOptions jksOptions = new JksOptions().setPath(trustStore.getPath()); MqttClientOptions clientOptions = new MqttClientOptions() .setSsl(true) .setTrustStoreOptions(jksOptions); MqttClient client = MqttClient.create(vertx, clientOptions); client.exceptionHandler(t -> context.assertTrue(false)); Async async = context.async(); client.connect(MQTT_SERVER_TLS_PORT, MQTT_SERVER_HOST, s -> client.disconnect(d -> async.countDown())); async.await(); }
/** * 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); }
/** * Tests authentication with the cert auth backend using PEM file */ @Test public void testLoginByCert_usingJKSConfig(TestContext tc) throws VaultException { JsonObject config = new JsonObject(); config.put("host", process.getHost()); config.put("port", process.getPort()); config.put("ssl", true); JksOptions options = new JksOptions(); options.setPassword("password").setPath("target/vault/config/ssl/keystore.jks"); config.put("keyStoreOptions", options.toJson()); JksOptions jks = new JksOptions() .setPassword("password") .setPath("target/vault/config/ssl/truststore.jks"); config.put("trustStoreOptions", jks.toJson()); client = new SlimVaultClient(vertx, config); checkWeCanLoginAndAccessRestrictedSecrets(tc); }
@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; }
public VertxHttpServer(MapWrap config) { port = config.asInt("port", DEFAULT_PORT); observableListenersByTag = new HashMap<>(); // Setup vertx vertx = Vertx.vertx(); vertx.deployVerticle(this); if (config.exists("keyStorePath") ) { httpServer = vertx.createHttpServer(new HttpServerOptions().setSsl(true) .setKeyStoreOptions( new JksOptions(). setPath(config.asString("keyStorePath")). setPassword(config.asString("keyStorePassword")) )); } else { httpServer = vertx.createHttpServer(); } router = Router.router(vertx); }
SMTPConnectionPool(Vertx vertx, MailConfig config) { this.config = config; this.vertx = vertx; maxSockets = config.getMaxPoolSize(); keepAlive = config.isKeepAlive(); NetClientOptions netClientOptions = new NetClientOptions().setSsl(config.isSsl()).setTrustAll(config.isTrustAll()); if ((config.isSsl() || config.getStarttls() != StartTLSOptions.DISABLED) && !config.isTrustAll()) { // we can use HTTPS verification, which matches the requirements for SMTPS netClientOptions.setHostnameVerificationAlgorithm("HTTPS"); } if (config.getKeyStore() != null) { // assume that password could be null if the keystore doesn't use one netClientOptions.setTrustStoreOptions(new JksOptions().setPath(config.getKeyStore()) .setPassword(config.getKeyStorePassword())); } netClient = vertx.createNetClient(netClientOptions); }
public void runSSHServiceWithShiro(Vertx vertx) throws Exception { ShellService service = ShellService.create(vertx, new ShellServiceOptions().setSSHOptions( new SSHTermOptions(). setHost("localhost"). setPort(5000). setKeyPairOptions(new JksOptions(). setPath("server-keystore.jks"). setPassword("wibble") ). setAuthOptions(new ShiroAuthOptions(). setType(ShiroAuthRealmType.PROPERTIES). setConfig(new JsonObject(). put("properties_path", "file:/path/to/my/auth.properties")) ) ) ); service.start(); }
public void runSSHServiceWithMongo(Vertx vertx) throws Exception { ShellService service = ShellService.create(vertx, new ShellServiceOptions().setSSHOptions( new SSHTermOptions(). setHost("localhost"). setPort(5000). setKeyPairOptions(new JksOptions(). setPath("server-keystore.jks"). setPassword("wibble") ). setAuthOptions(new MongoAuthOptions().setConfig(new JsonObject(). put("connection_string", "mongodb://localhost:27018")) ) ) ); service.start(); }
public void runSSHServiceWithJDBC(Vertx vertx) throws Exception { ShellService service = ShellService.create(vertx, new ShellServiceOptions().setSSHOptions( new SSHTermOptions(). setHost("localhost"). setPort(5000). setKeyPairOptions(new JksOptions(). setPath("server-keystore.jks"). setPassword("wibble") ). setAuthOptions(new JDBCAuthOptions().setConfig(new JsonObject() .put("url", "jdbc:hsqldb:mem:test?shutdown=true") .put("driver_class", "org.hsqldb.jdbcDriver")) ) ) ); service.start(); }
@Test public void testExternalAuthProviderFails(TestContext context) throws Exception { AtomicInteger count = new AtomicInteger(); authProvider = (authInfo, resultHandler) -> { count.incrementAndGet(); resultHandler.handle(Future.failedFuture("not authenticated")); }; termHandler = term -> { context.fail(); }; startShell(new SSHTermOptions().setPort(5000).setHost("localhost").setKeyPairOptions( new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble"))); Session session = createSession("paulo", "anothersecret", false); try { session.connect(); context.fail("Was not expected to login"); } catch (JSchException e) { assertEquals("Auth cancel", e.getMessage()); } context.assertEquals(1, count.get()); }
@Test public void testKeymapFromFilesystem() throws Exception { URL url = TermServer.class.getResource(SSHTermOptions.DEFAULT_INPUTRC); File f = new File(url.toURI()); termHandler = Term::close; startShell(new SSHTermOptions().setIntputrc(f.getAbsolutePath()).setPort(5000).setHost("localhost").setKeyPairOptions( new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")). setAuthOptions(new ShiroAuthOptions().setType(ShiroAuthRealmType.PROPERTIES).setConfig( new JsonObject().put("properties_path", "classpath:test-auth.properties")))); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); }
public static JksOptions getTrustStoreOption(final ServiceAccessor accessor) { final File root = accessor.getConfiguration().getBaseDir(); final String ca = accessor.getConfiguration().get("https.trustStore"); if (ca == null) { LOGGER.info("Using default trust store for client side CA verification"); return null; } else if ("noCA".equalsIgnoreCase(ca)) { //TODO LOGGER.info("Using default trust store for client side CA verification - noCA"); return null; } else { File file = new File(ca); if (!file.isFile()) { // Second chance. file = new File(root, ca); } LOGGER.info("\t trust store: " + file.getAbsolutePath()); final char[] password = accessor.getConfiguration() .getWithDefault("https.trustStorePassword", "").toCharArray(); LOGGER.info("\t trust store password length: " + password.length); return new JksOptions().setPath(file.getAbsolutePath()).setPassword(new String(password)); } }
private void enableSsl(ServerConfiguration configuration, HttpServerOptions options) { options.setSsl(TRUE); options.setHost("localhost"); options.setKeyStoreOptions(new JksOptions() .setPath(getPath(configuration)) .setPassword(getSecret(configuration))) .setPort(getPort(configuration)); }
@Test public void givenSslEnabledInConfigurationWithJksPathAndPassword_whenConfiguringServer_thenHttpOptionSslShouldBeEnabledAndConfiguredWithThePathAndPassword() throws Exception { configuration.put(SSL_CONFIGURATION_KEY, TRUE); configureServer(); assertThat(options.isSsl()).isTrue(); assertThat(options.getKeyStoreOptions() instanceof JksOptions).isTrue(); assertThat(options.getKeyStoreOptions().getPath()).isEqualTo(TEST_JKS_PATH); assertThat(options.getKeyStoreOptions().getPassword()).isEqualTo(TEST_JKS_SECRET); }
private BotMainTest(String[] args) throws Exception { UpdateProvider provider; if (args[1].equalsIgnoreCase("webhooks")) { provider = WebhookUpdateProvider.builder() .serverOptions(new HttpServerOptions().setSsl(true) .setKeyStoreOptions(new JksOptions().setPath("bot.jks").setPassword("aaaaaa")) .setPort(443) .setHost(args[2])) .selfSignedCertificate(new File("bot-certificate.pem")) .build(); } else { provider = new PollingUpdateProvider(); } this.registry = TelegramBotRegistry.builder() .updateProvider(provider) .build(); registry.registerBot(args[0], (bot, error) -> { if (error != null) { System.out.println("Could not log in!"); error.printStackTrace(); System.exit(-1); return; } this.bot = bot; System.out.printf("Logged in as @%s\n", bot.getBotInfo().getUsername()); registerModules(); bot.getCommandRegistry().registerCommand(new TextFilter("test", false, this::handleTestCommand)); }); }
private void loadKeystore(CoreContext core, KeyStore store) { try { loadedKeyStores.put(store.getShortName(), TrustAndKeyProvider.of(new JksOptions() .setValue(Buffer.buffer(Files.readAllBytes(Paths.get(store.getPath())))) .setPassword(store.getPassword()))); } catch (Throwable e) { // failed to load keystore due to wrong password or missing file etc. // cannot recover from this in a safe manner: shut down. core.logger(getClass()).onError(e); System.exit(0); } }
@Override public void start() throws Exception { /* Certificado para servidor de seguridad, proocolo JWT */ JWTAuth jwt = JWTAuth.create(vertx, new JsonObject() .put("keyStore", new JsonObject() .put("type", "jceks") .put("path", "D:/VertX/Fuentes/RestMicroServiciosVertx/src/main/java/co/com/quipux/viaticos/webapp/examples/keystore.jceks") .put("password", "secret"))); /* Certificado para HTTPS */ HttpServerOptions options = new HttpServerOptions().setSsl(true).setKeyStoreOptions( new JksOptions(). setPath("C:/opt/vigia/SSO/wso2is-5.0.0/repository/resources/security/server.jks"). setPassword("password") ); /* EN CASO DE USAR SSL */ /* Se crea una instancia del servidor web con el certificaso SSL para desplegar HTTPS */ // HttpServer server = vertx.createHttpServer(options); /* Se crea una instancia del servidor web sin certificado SSl */ HttpServer server = vertx.createHttpServer(); /* Se crea instancia de Router para el manejo de peticiones */ router = Router.router(vertx); String PACKAGE = "examples.simpleRestService.restServices"; CarmenRestVertx.initScan(vertx, router, jwt, PACKAGE); /* Se inicializa el servicio de autenticación */ /* ServerAuth serverAuth = new ServerAuth(jwt); */ /*RestVertx.register(vertx, router, serverAuth);*/ /* En caso de querer publicar una carpeta estatica */ //router.route().handler(StaticHandler.create("D:/VertX/Fuentes/RestMicroServiciosVertx/src/main/java/co/com/quipux/viaticos/webapp/webroot")); server.requestHandler(router::accept).listen(8081); }
/** * Gets the trust options derived from the trust store properties. * * @return The trust options or {@code null} if trust store path is not set or not supported. */ public final TrustOptions getTrustOptions() { if (trustStorePath == null) { return null; } final FileFormat format = FileFormat.orDetect(trustStoreFormat, trustStorePath); if (format == null) { LOG.debug("unsupported trust store format"); return null; } switch (format) { case PEM: LOG.debug("using certificates from file [{}] as trust anchor", trustStorePath); return new PemTrustOptions().addCertPath(trustStorePath); case PKCS12: LOG.debug("using certificates from PKCS12 key store [{}] as trust anchor", trustStorePath); return new PfxOptions() .setPath(getTrustStorePath()) .setPassword(getTrustStorePassword()); case JKS: LOG.debug("using certificates from JKS key store [{}] as trust anchor", trustStorePath); return new JksOptions() .setPath(getTrustStorePath()) .setPassword(getTrustStorePassword()); default: LOG.debug("unsupported trust store format: {}", format); return null; } }
public void example1WithConfig(Vertx vertx) { JsonObject vault_config = new JsonObject() .put("host", "127.0.0.1") // The host name .put("port", 8200) // The port .put("ssl", true); // Whether or not SSL is used (disabled by default) // Certificates 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()); // Truststore JksOptions jks = new JksOptions() .setPath("target/vault/config/ssl/truststore.jks"); vault_config.put("trustStoreOptions", jks.toJson()); // 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)); }
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)); }
public JsonObject getConfiguration() { JsonObject config = new JsonObject(); config.put("host", getHost()); config.put("port", 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()); JksOptions jks = new JksOptions() .setPath("target/vault/config/ssl/truststore.jks"); config.put("trustStoreOptions", jks.toJson()); return config; }
@Override public void start() { ProtonServerOptions options = new ProtonServerOptions(); if(useTls) { options.setSsl(true); String path; if((path = config.get("jksKeyStorePath")) != null) { final JksOptions jksOptions = new JksOptions(); jksOptions.setPath(path); jksOptions.setPassword(config.get("keyStorePassword")); options.setKeyStoreOptions(jksOptions); } else if((path = config.get("pfxKeyStorePath")) != null) { final PfxOptions pfxOptions = new PfxOptions(); pfxOptions.setPath(path); pfxOptions.setPassword(config.get("keyStorePassword")); options.setPfxKeyCertOptions(pfxOptions); } else if((path = config.get("pemCertificatePath")) != null) { final PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions(); pemKeyCertOptions.setCertPath(path); pemKeyCertOptions.setKeyPath(config.get("pemKeyPath")); options.setPemKeyCertOptions(pemKeyCertOptions); } else { // use JDK settings? } } server = ProtonServer.create(vertx, options); server.saslAuthenticatorFactory(() -> new SaslAuthenticator(keycloakSessionFactory, config, useTls)); server.connectHandler(this::connectHandler); LOG.info("Starting server on "+hostname+":"+ port); server.listen(port, hostname, event -> { if(event.failed()) { LOG.error("Unable to listen for AMQP on "+hostname+":" + port, event.cause()); } }); }
@Override public HttpServer getObject() throws Exception { HttpServerOptions options = new HttpServerOptions(); // Binding port options.setPort(httpServerConfiguration.getPort()); options.setHost(httpServerConfiguration.getHost()); // Netty pool buffers must be enabled by default options.setUsePooledBuffers(true); if (httpServerConfiguration.isSecured()) { options.setSsl(httpServerConfiguration.isSecured()); options.setUseAlpn(httpServerConfiguration.isAlpn()); if (httpServerConfiguration.isClientAuth()) { options.setClientAuth(ClientAuth.REQUIRED); } if (httpServerConfiguration.getTrustStorePath() != null) { options.setTrustStoreOptions(new JksOptions() .setPath(httpServerConfiguration.getTrustStorePath()) .setPassword(httpServerConfiguration.getTrustStorePassword())); } if (httpServerConfiguration.getKeyStorePath() != null) { options.setKeyStoreOptions(new JksOptions() .setPath(httpServerConfiguration.getKeyStorePath()) .setPassword(httpServerConfiguration.getKeyStorePassword())); } } // Customizable configuration options.setCompressionSupported(httpServerConfiguration.isCompressionSupported()); options.setIdleTimeout(httpServerConfiguration.getIdleTimeout()); options.setTcpKeepAlive(httpServerConfiguration.isTcpKeepAlive()); return vertx.createHttpServer(options); }
public HttpServerOptions getServerOptions(JsonObject config) { if (!new File(KeyUtil.DEMO_KEYSTTORE).exists()) { KeyUtil.generateKey(); // only for demo, create keystore } return new HttpServerOptions(). setKeyStoreOptions(new JksOptions().setPath(KeyUtil.DEMO_KEYSTTORE).setPassword(KeyUtil.DEMO_PWD)). setSsl(true); }
@Test public void testNoAuthenticationConfigured() throws Exception { try { startShell(new SSHTermOptions().setPort(5000).setHost("localhost").setKeyPairOptions( new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")) ); fail(); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof VertxException); assertEquals("No authenticator", e.getCause().getMessage()); } }
public static void main(String[] args) { // TODO start a vertx instance // deploy verticles / one per resource in this case Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Vertx vertx = Vertx.vertx(); HttpClientOptions clientOptions = new HttpClientOptions() .setSsl(true) .setTrustStoreOptions(new JksOptions() .setPath(System.getProperty("javax.net.ssl.trustStore")) .setPassword(System.getProperty("javax.net.ssl.trustStorePassword"))); HttpClient httpClient = vertx.createHttpClient(clientOptions); Router router = Router.router(vertx); AuthHandler auth = new BearerAuthHandler(new FacebookOauthTokenVerifier(httpClient)); router.route("/*").handler(auth); HelloResource helloResource = new HelloResource(httpClient); router.get("/hello").produces("text/plain").handler(helloResource::hello); CarRepository carRepository = new InMemoryCarRepository(); CarsResource carsResource = new CarsResource(carRepository); router.route("/cars*").handler(BodyHandler.create()); router.get("/cars").produces("application/json").handler(carsResource::all); router.post("/cars").consumes("application/json").handler(carsResource::create); CarResource carResource = new CarResource(carRepository); router.get("/cars/:id").produces("application/json").handler(carResource::byId); HttpServerOptions serverOptions = new HttpServerOptions() .setSsl(true) .setKeyStoreOptions(new JksOptions() .setPath(System.getProperty("javax.net.ssl.keyStorePath")) .setPassword(System.getProperty("javax.net.ssl.keyStorePassword"))) .setPort(8090); HttpServer server = vertx.createHttpServer(serverOptions); server.requestHandler(router::accept).listen(); }
@BeforeClass public static void createServer() throws InterruptedException { vertx = Vertx.vertx(); CountDownLatch latch = new CountDownLatch(1); Router router = Router.router(vertx); // events specific to THOPs are made available over the bridge SockJSHandler sockJSHandler = SockJSHandler.create(vertx); BridgeOptions options = new BridgeOptions(); options.addOutboundPermitted(new PermittedOptions().setAddress("test")). addInboundPermitted(new PermittedOptions().setAddress("test")). addOutboundPermitted(new PermittedOptions().setAddress("end")). addInboundPermitted(new PermittedOptions().setAddress("end")). addInboundPermitted(new PermittedOptions().setAddress("reply")). addOutboundPermitted(new PermittedOptions().setAddress("replyTest")); sockJSHandler.bridge(options); router.route("/bridge/*").handler(sockJSHandler); // for reply test vertx.eventBus().consumer("reply", msg -> { vertx.eventBus().send("replyTest", "replyToMe", reply -> { assertEquals("bubu", reply.result().body().toString()); reply.result().reply("ok", replyOfreply -> { assertEquals("roger", replyOfreply.result().body().toString()); }); msg.reply("ok"); vertx.eventBus().send("test", "ok"); }); }); vertx.createHttpServer(new HttpServerOptions().setSsl(true).setKeyStoreOptions(new JksOptions().setPath("keystore.jks").setPassword("bubulala"))).requestHandler(router::accept).listen(8765, (res) -> { latch.countDown(); }); latch.await(); System.out.println("SSL Server listening on port 8765"); }
HttpServer build() { HttpServerOptions options = new HttpServerOptions(); if (secure) { options. setSsl(true). setKeyStoreOptions( new JksOptions(). setPath("src/test/resources/server-keystore.jks"). setPassword("wibble")); } return vertx.createHttpServer(options).requestHandler(req -> { if (authenticated && !auth.equals(req.getHeader("Authorization"))) { req.response(). setStatusCode(401). putHeader("WWW-Authenticate", "Basic realm=\"TheRealm\""). end(); return; } if (req.path().equals("/the_verticle.zip")) { req.response(). putHeader("Content-Length", "" + verticle.length()). putHeader("Content-type", "application/octet-stream"). write(verticle). end(); return; } else if (req.path().equals("/the_verticle.zip.asc") && signature != null) { req.response(). putHeader("Content-Length", "" + signature.length()). putHeader("Content-type", "application/octet-stream"). write(signature). end(); return; } req.response().setStatusCode(404).end(); }); }
HttpServer build() { HttpServerOptions options = new HttpServerOptions(); if (secure) { options. setSsl(true). setKeyStoreOptions( new JksOptions(). setPath("src/test/resources/server-keystore.jks"). setPassword("wibble")); } return vertx.createHttpServer(options).requestHandler(handler); }
private void connect(final Runnable runnable) { final HttpClientOptions httpClientOptions = new HttpClientOptions(); final JksOptions jksOptions = new JksOptions(); jksOptions.setPath(trustStorePath).setPassword(trustStorePassword); httpClientOptions.setDefaultHost(host).setDefaultPort(port) .setConnectTimeout(timeOutInMilliseconds) .setMaxPoolSize(poolSize) .setKeepAlive(keepAlive) .setPipelining(pipeline) .setSoLinger(soLinger) .setTcpNoDelay(tcpNoDelay) .setTryUseCompression(tryUseCompression) .setSsl(ssl) .setTrustAll(trustAll) .setVerifyHost(verifyHost) .setMaxWebsocketFrameSize(maxWebSocketFrameSize) .setUsePooledBuffers(true); httpClient = vertx.createHttpClient(httpClientOptions); if (debug) logger.debug("HTTP CLIENT: connect:: \nhost {} \nport {}\n", host, port); closed.set(false); Sys.sleep(100); if (runnable != null) runnable.run(); }
public static HttpClientOptions parseTlsOptions(TLSOptions tlsOptions, URI apiEndpoint) { HttpClientOptions clientOptions = new HttpClientOptions(); if (apiEndpoint.getScheme().equals("http")) { //$NON-NLS-1$ return clientOptions.setSsl(false); } else { clientOptions.setSsl(true); } clientOptions.setTrustAll(tlsOptions.isTrustSelfSigned() || tlsOptions.isDevMode()) .setVerifyHost(!(tlsOptions.isAllowAnyHost() || tlsOptions.isDevMode())); if (tlsOptions.getTrustStore() != null) { clientOptions.setTrustStoreOptions( new JksOptions().setPath(tlsOptions.getTrustStore()).setPassword(tlsOptions.getTrustStorePassword()) ); } if (tlsOptions.getKeyStore() != null) { clientOptions.setKeyStoreOptions( new JksOptions().setPath(tlsOptions.getKeyStore()).setPassword(tlsOptions.getKeyStorePassword()) ); } if (tlsOptions.getAllowedCiphers() != null) { String[] ciphers = arrayDifference(tlsOptions.getAllowedCiphers(), tlsOptions.getDisallowedCiphers(), getDefaultCipherSuites()); for (String cipher : ciphers) { clientOptions.addEnabledCipherSuite(cipher); } } if (tlsOptions.getAllowedProtocols() != null) { log.info("Can't set allowed protocols on Vert.x gateway"); //$NON-NLS-1$ } return clientOptions; }
@Override public void start(Future<Void> startFuture) { super.start(startFuture); HttpApiFactory.init(engine.getApiRequestPathParser()); InheritingHttpServerOptions httpsServerOptions = new InheritingHttpServerOptions(); httpsServerOptions .setSsl(true) .setKeyStoreOptions( new JksOptions() .setPath(apimanConfig.getKeyStore()) .setPassword(apimanConfig.getKeyStorePassword()) ) .setTrustStoreOptions( new JksOptions() .setPath(apimanConfig.getTrustStore()) .setPassword(apimanConfig.getTrustStorePassword()) ); if (JdkSSLEngineOptions.isAlpnAvailable()) { httpsServerOptions.setUseAlpn(true); } // Load any provided configuration into the HttpServerOptions. JsonObject httpServerOptionsJson = apimanConfig.getVerticleConfig(verticleType().name()) .getJsonObject("httpServerOptions", new JsonObject()); //$NON-NLS-1$ InheritingHttpServerOptionsConverter.fromJson(httpServerOptionsJson, httpsServerOptions); vertx.createHttpServer(httpsServerOptions) .requestHandler(this::requestHandler) .listen(apimanConfig.getPort(VERTICLE_TYPE), apimanConfig.getHostname()); }
@Override public void start(Future<Void> startFuture) { Future<Void> superFuture = Future.future(); Future<HttpServer> listenFuture = Future.future(); super.start(superFuture); CompositeFuture.all(superFuture, listenFuture) .setHandler(compositeResult -> { if (compositeResult.succeeded()) { startFuture.complete(null); } else { startFuture.fail(compositeResult.cause()); } }); VertxResteasyDeployment deployment = new VertxResteasyDeployment(); deployment.start(); addResources(deployment.getRegistry(), new SystemResourceImpl(apimanConfig, engine), new ApiResourceImpl(apimanConfig, engine), new ClientResourceImpl(apimanConfig, engine), new OrgResourceImpl(apimanConfig, engine)); deployment.getProviderFactory().register(RestExceptionMapper.class); VertxRequestHandler resteasyRh = new VertxRequestHandler(vertx, deployment); Router router = Router.router(vertx) .exceptionHandler(error -> log.error(error.getMessage(), error)); // Ensure body handler is attached early so that if AuthHandler takes an external action // we don't end up losing the body (e.g OAuth2). router.route() .handler(BodyHandler.create()); AuthHandler authHandler = AuthFactory.getAuth(vertx, router, apimanConfig); router.route("/*") .handler(authHandler); router.route("/*") // We did the previous stuff, now we call into JaxRS. .handler(context -> resteasyRh.handle(new Router2ResteasyRequestAdapter(context))); HttpServerOptions httpOptions = new HttpServerOptions(); if (apimanConfig.isSSL()) { httpOptions.setSsl(true) .setKeyStoreOptions( new JksOptions() .setPath(apimanConfig.getKeyStore()) .setPassword(apimanConfig.getKeyStorePassword()) ) .setTrustStoreOptions( new JksOptions() .setPath(apimanConfig.getTrustStore()) .setPassword(apimanConfig.getTrustStorePassword()) ); } else { log.warn("API is running in plaintext mode. Enable SSL in config for production deployments."); } vertx.createHttpServer(httpOptions) .requestHandler(router::accept) .listen(apimanConfig.getPort(VERTICLE_TYPE), apimanConfig.getHostname(), listenFuture.completer()); }
private JksOptions getJksOptions(String key, String defaultResource) { JsonObject config = config() .getJsonObject(key, new JsonObject()); JksOptions jksOptions = new JksOptions() .setPassword(config.getString("password", "secret")) .setValue(getResource(config.getString("resourceName", defaultResource))); return jksOptions; }