Search in sources :

Example 26 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project vespa by vespa-engine.

the class ConnectorFactory method newHttpConnectionFactory.

private HttpConnectionFactory newHttpConnectionFactory() {
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSendDateHeader(true);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendXPoweredBy(false);
    httpConfig.setHeaderCacheSize(connectorConfig.headerCacheSize());
    httpConfig.setOutputBufferSize(connectorConfig.outputBufferSize());
    httpConfig.setRequestHeaderSize(connectorConfig.requestHeaderSize());
    httpConfig.setResponseHeaderSize(connectorConfig.responseHeaderSize());
    if (connectorConfig.ssl().enabled()) {
        httpConfig.addCustomizer(new SecureRequestCustomizer());
    }
    return new HttpConnectionFactory(httpConfig);
}
Also used : SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration)

Example 27 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project activemq-artemis by apache.

the class WebServerComponent method configure.

@Override
public void configure(ComponentDTO config, String artemisInstance, String artemisHome) throws Exception {
    webServerConfig = (WebServerDTO) config;
    uri = new URI(webServerConfig.bind);
    server = new Server();
    String scheme = uri.getScheme();
    if ("https".equals(scheme)) {
        SslContextFactory sslFactory = new SslContextFactory();
        sslFactory.setKeyStorePath(webServerConfig.keyStorePath == null ? artemisInstance + "/etc/keystore.jks" : webServerConfig.keyStorePath);
        sslFactory.setKeyStorePassword(webServerConfig.getKeyStorePassword() == null ? "password" : webServerConfig.getKeyStorePassword());
        if (webServerConfig.clientAuth != null) {
            sslFactory.setNeedClientAuth(webServerConfig.clientAuth);
            if (webServerConfig.clientAuth) {
                sslFactory.setTrustStorePath(webServerConfig.trustStorePath);
                sslFactory.setTrustStorePassword(webServerConfig.getTrustStorePassword());
            }
        }
        SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslFactory, "HTTP/1.1");
        HttpConfiguration https = new HttpConfiguration();
        https.addCustomizer(new SecureRequestCustomizer());
        HttpConnectionFactory httpFactory = new HttpConnectionFactory(https);
        connector = new ServerConnector(server, sslConnectionFactory, httpFactory);
    } else {
        connector = new ServerConnector(server);
    }
    connector.setPort(uri.getPort());
    connector.setHost(uri.getHost());
    server.setConnectors(new Connector[] { connector });
    handlers = new HandlerList();
    Path homeWarDir = Paths.get(artemisHome != null ? artemisHome : ".").resolve(webServerConfig.path).toAbsolutePath();
    Path instanceWarDir = Paths.get(artemisInstance != null ? artemisInstance : ".").resolve(webServerConfig.path).toAbsolutePath();
    if (webServerConfig.apps != null && webServerConfig.apps.size() > 0) {
        webContexts = new ArrayList<>();
        for (AppDTO app : webServerConfig.apps) {
            Path dirToUse = homeWarDir;
            if (new File(instanceWarDir.toFile().toString() + File.separator + app.war).exists()) {
                dirToUse = instanceWarDir;
            }
            WebAppContext webContext = deployWar(app.url, app.war, dirToUse);
            webContexts.add(webContext);
            if (app.war.startsWith("console")) {
                consoleUrl = webServerConfig.bind + "/" + app.url;
            }
        }
    }
    ResourceHandler homeResourceHandler = new ResourceHandler();
    homeResourceHandler.setResourceBase(homeWarDir.toString());
    homeResourceHandler.setDirectoriesListed(false);
    homeResourceHandler.setWelcomeFiles(new String[] { "index.html" });
    ContextHandler homeContext = new ContextHandler();
    homeContext.setContextPath("/");
    homeContext.setResourceBase(homeWarDir.toString());
    homeContext.setHandler(homeResourceHandler);
    homeContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    ResourceHandler instanceResourceHandler = new ResourceHandler();
    instanceResourceHandler.setResourceBase(instanceWarDir.toString());
    instanceResourceHandler.setDirectoriesListed(false);
    instanceResourceHandler.setWelcomeFiles(new String[] { "index.html" });
    ContextHandler instanceContext = new ContextHandler();
    instanceContext.setContextPath("/");
    instanceContext.setResourceBase(instanceWarDir.toString());
    instanceContext.setHandler(instanceResourceHandler);
    homeContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    DefaultHandler defaultHandler = new DefaultHandler();
    defaultHandler.setServeIcon(false);
    handlers.addHandler(homeContext);
    handlers.addHandler(instanceContext);
    handlers.addHandler(defaultHandler);
    server.setHandler(handlers);
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) Path(java.nio.file.Path) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) URI(java.net.URI) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) AppDTO(org.apache.activemq.artemis.dto.AppDTO) File(java.io.File)

Example 28 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project serverless by bluenimble.

the class JettyPlugin method init.

@Override
public void init(final ApiServer server) throws Exception {
    Log.setLog(new JettyLogger(this));
    // load favicon
    InputStream favicon = null;
    try {
        favicon = new FileInputStream(new File(home, FavIcon));
        FavIconContent = IOUtils.toByteArray(favicon);
    } finally {
        IOUtils.closeQuietly(favicon);
    }
    Integer poolIdleTimeout = Json.getInteger(pool, Pool.IdleTimeout, 300);
    /*
		It is very important to limit the task queue of Jetty. By default, the queue is unbounded! As a result, 
		if under high load in excess of the processing power of the webapp, jetty will keep a lot of requests on the queue. 
		Even after the load has stopped, Jetty will appear to have stopped responding to new requests as it still has lots of requests on 
		the queue to handle.
		
		For a high reliability system, it should reject the excess requests immediately (fail fast) by using a queue with 
		a bounded capability. The capability (maximum queue length) should be calculated according to the "no-response" time tolerable. 
		For example, if the webapp can handle 100 requests per second, and if you can allow it one minute to recover from excessive high load, 
		you can set the queue capability to 60*100=6000. If it is set too low, it will reject requests too soon and can't handle normal load 
		spike.
		
		Below is a sample configuration:
		
		<Configure id="Server" class="org.eclipse.jetty.server.Server">
		    <Set name="ThreadPool">
		      <New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
		        <!-- specify a bounded queue -->
		        <Arg>
		           <New class="java.util.concurrent.ArrayBlockingQueue">
		              <Arg type="int">6000</Arg>
		           </New>
		      </Arg>
		        <Set name="minThreads">10</Set>
		        <Set name="maxThreads">200</Set>
		        <Set name="detailedDump">false</Set>
		      </New>
		    </Set>
		</Configure>
		Configure the number of threads according to the webapp. 
		That is, how many threads it needs in order to achieve the best performance. 
		Configure with mind to limiting memory usage maximum available. Typically >50 and <500.
		 */
    int capacity = server.weight() + 2;
    QueuedThreadPool tp = new QueuedThreadPool(capacity, capacity, poolIdleTimeout * 1000, new ArrayBlockingQueue<Runnable>(capacity * 2));
    tp.setDetailedDump(false);
    tp.setThreadsPriority(Thread.NORM_PRIORITY);
    httpServer = new Server(tp);
    ServerConnector connector = new ServerConnector(httpServer);
    connector.setPort(port);
    connector.setIdleTimeout(idleTimeout * 1000);
    httpServer.addConnector(connector);
    if (ssl != null && !Lang.isNullOrEmpty(ssl.getString(Ssl.Keystore)) && !Lang.isNullOrEmpty(ssl.getString(Ssl.Password))) {
        HttpConfiguration https = new HttpConfiguration();
        https.addCustomizer(new SecureRequestCustomizer());
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(new File(ssl.getString(Ssl.Keystore)).getAbsolutePath());
        sslContextFactory.setKeyStorePassword(Json.getString(ssl, Ssl.Password));
        sslContextFactory.setKeyManagerPassword(Json.getString(ssl, Ssl.StorePassword, Json.getString(ssl, Ssl.Password)));
        sslContextFactory.setKeyStoreType(Json.getString(ssl, Ssl.StoreType, "JKS"));
        String[] aCiphers = null;
        // include ciphers
        JsonArray ciphers = Json.getArray(Json.getObject(ssl, Ssl.ciphers.class.getSimpleName()), Ssl.ciphers.Include);
        if (ciphers != null && !ciphers.isEmpty()) {
            aCiphers = new String[ciphers.count()];
            for (int i = 0; i < ciphers.count(); i++) {
                aCiphers[i] = (String) ciphers.get(i);
            }
            sslContextFactory.setIncludeCipherSuites(aCiphers);
        }
        // exclude ciphers
        ciphers = Json.getArray(Json.getObject(ssl, Ssl.ciphers.class.getSimpleName()), Ssl.ciphers.Exclude);
        if (ciphers != null && !ciphers.isEmpty()) {
            aCiphers = new String[ciphers.count()];
            for (int i = 0; i < ciphers.count(); i++) {
                aCiphers[i] = (String) ciphers.get(i);
            }
            sslContextFactory.setExcludeCipherSuites(aCiphers);
        }
        ServerConnector sslConnector = new ServerConnector(httpServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https));
        int sslPort = Json.getInteger(ssl, Ssl.Port, 443);
        sslConnector.setPort(sslPort);
        sslConnector.setIdleTimeout(Json.getInteger(ssl, Ssl.IdleTimeout, idleTimeout) * 1000);
        httpServer.addConnector(sslConnector);
    }
    for (Connector cn : httpServer.getConnectors()) {
        for (ConnectionFactory x : cn.getConnectionFactories()) {
            if (x instanceof HttpConnectionFactory) {
                ((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(false);
                ((HttpConnectionFactory) x).getHttpConfiguration().setSendXPoweredBy(false);
            }
        }
    }
    ServletContextHandler sContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    sContext.setContextPath(context);
    if (gzip) {
        sContext.setGzipHandler(new GzipHandler());
    }
    httpServer.setHandler(sContext);
    ServletHolder apiHolder = new ServletHolder(new HttpServlet() {

        private static final long serialVersionUID = -4391155835460802144L;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            if (FavIconPath.equals(req.getRequestURI())) {
                resp.getOutputStream().write(FavIconContent);
                return;
            }
            execute(req, resp);
        }

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            execute(req, resp);
        }

        @Override
        protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            execute(req, resp);
        }

        @Override
        protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            execute(req, resp);
        }

        protected void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try {
                ApiRequest request = new HttpApiRequest(req, tracer());
                request.getNode().set(ApiRequest.Fields.Node.Id, server.id());
                request.getNode().set(ApiRequest.Fields.Node.Type, server.type());
                request.getNode().set(ApiRequest.Fields.Node.Version, server.version());
                server.execute(request, new HttpApiResponse(request.getNode(), request.getId(), resp), CodeExecutor.Mode.Async);
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        }
    });
    sContext.addServlet(apiHolder, Lang.SLASH + Lang.STAR);
    // cross origin
    FilterHolder holder = new FilterHolder(CORSFilter.class);
    holder.setName("CORS");
    holder.setInitParameter("cors.supportedMethods", "GET, POST, HEAD, PUT, DELETE, PATCH, OPTIONS");
    holder.setInitParameter("cors.exposedHeaders", "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With,BN-Execution-Time,BN-Node-Id,BN-Node-Type");
    sContext.addFilter(holder, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD, DispatcherType.REQUEST, DispatcherType.ERROR));
    // monitor
    if (monitor) {
        MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
        httpServer.addEventListener(mbContainer);
        httpServer.addBean(mbContainer);
        httpServer.addBean(Log.getLog());
    }
    // start server
    httpServer.start();
    httpServer.join();
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ApiServer(com.bluenimble.platform.server.ApiServer) Server(org.eclipse.jetty.server.Server) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ApiRequest(com.bluenimble.platform.api.ApiRequest) HttpApiRequest(com.bluenimble.platform.plugins.inbound.http.impl.HttpApiRequest) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpApiResponse(com.bluenimble.platform.plugins.inbound.http.impl.HttpApiResponse) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ConnectionFactory(org.eclipse.jetty.server.ConnectionFactory) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) MBeanContainer(org.eclipse.jetty.jmx.MBeanContainer) HttpApiRequest(com.bluenimble.platform.plugins.inbound.http.impl.HttpApiRequest) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) JsonArray(com.bluenimble.platform.json.JsonArray) GzipHandler(org.eclipse.jetty.server.handler.gzip.GzipHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File)

Example 29 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project killbill by killbill.

the class HttpServer method configureSslConnector.

private ServerConnector configureSslConnector(final HttpConfiguration httpConfiguration, final boolean isStatsOn, final int localSslPort, final String sslKeyStorePath, final String sslKeyStorePassword) {
    // SSL Context Factory for HTTPS
    final SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(sslKeyStorePath);
    sslContextFactory.setKeyStorePassword(sslKeyStorePassword);
    // HTTPS Configuration
    final HttpConfiguration httpsConfig = new HttpConfiguration(httpConfiguration);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());
    // HTTPS connector
    final ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    https.setPort(localSslPort);
    if (isStatsOn) {
        final ConnectorStatistics stats = new ConnectorStatistics();
        https.addBean(stats);
    }
    return https;
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ConnectorStatistics(org.eclipse.jetty.server.ConnectorStatistics) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory)

Example 30 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project ninja by ninjaframework.

the class NinjaJetty method doConfigure.

@Override
protected void doConfigure() throws Exception {
    // current value or system property or conf/application.conf or default value
    jettyConfiguration(overlayedNinjaProperties.get(KEY_NINJA_JETTY_CONFIGURATION, this.jettyConfiguration, DEFAULT_JETTY_CONFIGURATION));
    // build jetty server, context, and servlet
    if (this.jettyConfiguration != null) {
        String[] configs = this.jettyConfiguration.split(",");
        for (String config : configs) {
            jetty = buildServerOrApplyConfiguration(config, jetty);
        }
        // since we don't know host and port, try to get it from jetty
        tryToSetHostAndPortFromJetty();
    } else {
        // create very simple jetty configuration
        jetty = new Server();
        if (port > -1) {
            // build http cleartext connector
            ServerConnector http = new ServerConnector(jetty);
            http.setPort(port);
            http.setIdleTimeout(idleTimeout);
            if (host != null) {
                http.setHost(host);
            }
            jetty.addConnector(http);
        }
        if (sslPort > -1) {
            // build https secure connector
            // http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java
            HttpConfiguration httpConfig = new HttpConfiguration();
            httpConfig.setSecureScheme("https");
            httpConfig.setSecurePort(sslPort);
            httpConfig.setOutputBufferSize(32768);
            HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
            httpsConfig.addCustomizer(new SecureRequestCustomizer());
            // unfortunately jetty seems to only work when we pass a keystore
            // and truststore (as opposed to our own prepared SSLContext)
            // call createSSLContext() to simply verify configuration is correct
            this.createSSLContext();
            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStore(StandaloneHelper.loadKeyStore(this.sslKeystoreUri, this.sslKeystorePassword.toCharArray()));
            sslContextFactory.setKeyManagerPassword(this.sslKeystorePassword);
            sslContextFactory.setTrustStore(StandaloneHelper.loadKeyStore(this.sslTruststoreUri, this.sslTruststorePassword.toCharArray()));
            ServerConnector https = new ServerConnector(jetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
            https.setPort(sslPort);
            https.setIdleTimeout(idleTimeout);
            jetty.addConnector(https);
        }
    }
    this.ninjaServletListener.setNinjaProperties(ninjaProperties);
    if (overrideModuleOpt.isPresent()) {
        this.ninjaServletListener.setOverrideModule(overrideModuleOpt.get());
    }
    this.contextHandler = new ServletContextHandler(jetty, getContextPath());
    this.contextHandler.addEventListener(ninjaServletListener);
    this.contextHandler.addFilter(NinjaServletFilter.class, "/*", null);
    this.contextHandler.addServlet(DefaultServlet.class, "/");
    // Note: adding websockets support (e.g. upgrade filter) last (after user filters)
    // is how jetty, tomcat, and wildfly all do it. We mimic it here.
    WebSocketServerContainerInitializer.configureContext(this.contextHandler);
    // disable directory browsing
    this.contextHandler.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    // Add an error handler that does not print stack traces in case
    // something happens that is not under control of Ninja
    this.contextHandler.setErrorHandler(new SilentErrorHandler());
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Aggregations

SecureRequestCustomizer (org.eclipse.jetty.server.SecureRequestCustomizer)91 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)89 ServerConnector (org.eclipse.jetty.server.ServerConnector)87 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)85 SslConnectionFactory (org.eclipse.jetty.server.SslConnectionFactory)82 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)74 Server (org.eclipse.jetty.server.Server)50 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)16 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)16 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)13 File (java.io.File)12 IOException (java.io.IOException)12 MBeanContainer (org.eclipse.jetty.jmx.MBeanContainer)10 Connector (org.eclipse.jetty.server.Connector)10 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)10 ServletException (javax.servlet.ServletException)9 HTTP2ServerConnectionFactory (org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory)8 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)8 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)6