Improve Batches
[aaf/authz.git] / auth / auth-core / src / main / java / org / onap / aaf / auth / server / JettyServiceStarter.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21 package org.onap.aaf.auth.server;
22
23 import java.io.IOException;
24 import java.net.Inet4Address;
25 import java.net.InetAddress;
26 import java.util.Properties;
27
28 import javax.servlet.Filter;
29 import javax.servlet.FilterChain;
30 import javax.servlet.ServletException;
31 import javax.servlet.ServletRequest;
32 import javax.servlet.ServletResponse;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.eclipse.jetty.http.HttpVersion;
37 import org.eclipse.jetty.server.HttpConfiguration;
38 import org.eclipse.jetty.server.HttpConnectionFactory;
39 import org.eclipse.jetty.server.Request;
40 import org.eclipse.jetty.server.SecureRequestCustomizer;
41 import org.eclipse.jetty.server.Server;
42 import org.eclipse.jetty.server.ServerConnector;
43 import org.eclipse.jetty.server.SslConnectionFactory;
44 import org.eclipse.jetty.server.handler.AbstractHandler;
45 import org.eclipse.jetty.util.ssl.SslContextFactory;
46 import org.onap.aaf.auth.org.OrganizationException;
47 import org.onap.aaf.auth.rserv.RServlet;
48 import org.onap.aaf.cadi.Access.Level;
49 import org.onap.aaf.cadi.CadiException;
50 import org.onap.aaf.cadi.LocatorException;
51 import org.onap.aaf.cadi.config.Config;
52 import org.onap.aaf.misc.env.Trans;
53 import org.onap.aaf.misc.env.util.Split;
54 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
55
56
57 public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> extends AbsServiceStarter<ENV,TRANS> {
58     private boolean secure;
59
60     public JettyServiceStarter(final AbsService<ENV,TRANS> service) throws OrganizationException {
61         super(service);
62         secure = true;
63     }
64     
65     /**
66      * Specifically set this Service starter to Insecure (HTTP) Mode. 
67      * @return
68      */
69     public JettyServiceStarter<ENV,TRANS> insecure() {
70         secure = false;
71         return this;
72     }
73
74
75     @Override
76     public void _propertyAdjustment() {
77 //        System.setProperty("com.sun.management.jmxremote.port", "8081");
78         Properties props = access().getProperties();
79         Object httpproto = null;
80         // Critical - if no Security Protocols set, then set it.  We'll just get messed up if not
81         if ((httpproto=props.get(Config.CADI_PROTOCOLS))==null) {
82             if ((httpproto=props.get(Config.HTTPS_PROTOCOLS))==null) {
83                 props.put(Config.CADI_PROTOCOLS, (httpproto=Config.HTTPS_PROTOCOLS_DEFAULT));
84             } else {
85                 props.put(Config.CADI_PROTOCOLS, httpproto);
86             }
87         }
88     
89         if ("1.7".equals(System.getProperty("java.specification.version")) && (httpproto==null || (httpproto instanceof String && ((String)httpproto).contains("TLSv1.2")))) {
90             System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT);
91         }
92     }
93
94     @Override
95     public void _start(RServlet<TRANS> rserv) throws Exception {
96         String hostname = access().getProperty(Config.HOSTNAME, null);
97         if (hostname==null) {
98             hostname = Inet4Address.getLocalHost().getHostName();
99         }
100         final int port = Integer.parseInt(access().getProperty("port","0"));
101         final String keystore = access().getProperty(Config.CADI_KEYSTORE, null);
102         final int IDLE_TIMEOUT = Integer.parseInt(access().getProperty(Config.AAF_CONN_IDLE_TIMEOUT, Config.AAF_CONN_IDLE_TIMEOUT_DEF));
103         Server server = new Server();
104         
105         ServerConnector conn;
106         String protocol;
107         if (!secure || keystore==null) {
108             conn = new ServerConnector(server);
109             protocol = "http";
110         } else {
111             protocol = "https";
112             
113
114             String keystorePassword = access().getProperty(Config.CADI_KEYSTORE_PASSWORD, null);
115             if (keystorePassword==null) {
116                 throw new CadiException("No Keystore Password configured for " + keystore);
117             }
118             SslContextFactory sslContextFactory = new SslContextFactory();
119             sslContextFactory.setKeyStorePath(keystore);
120             String temp;
121             sslContextFactory.setKeyStorePassword(temp=access().decrypt(keystorePassword, true)); // don't allow unencrypted
122             sslContextFactory.setKeyManagerPassword(temp);
123             temp=null; // don't leave lying around
124             
125             String truststore = access().getProperty(Config.CADI_TRUSTSTORE, null);
126             if (truststore!=null) {
127                 String truststorePassword = access().getProperty(Config.CADI_TRUSTSTORE_PASSWORD, null);
128                 if (truststorePassword==null) {
129                     throw new CadiException("No Truststore Password configured for " + truststore);
130                 }
131                 sslContextFactory.setTrustStorePath(truststore);
132                 sslContextFactory.setTrustStorePassword(access().decrypt(truststorePassword, false)); 
133             }
134             // Be able to accept only certain protocols, i.e. TLSv1.1+
135             String subprotocols = access().getProperty(Config.CADI_PROTOCOLS, Config.HTTPS_PROTOCOLS_DEFAULT);
136             service.setSubprotocol(subprotocols);
137             final String[] protocols = Split.splitTrim(',', subprotocols);
138             sslContextFactory.setIncludeProtocols(protocols);
139             
140             // Want to use Client Certificates, if they exist.
141             sslContextFactory.setWantClientAuth(true);
142             
143             // Optional future checks.
144             //   sslContextFactory.setValidateCerts(true);
145             //     sslContextFactory.setValidatePeerCerts(true);
146             //     sslContextFactory.setEnableCRLDP(false);
147             //     sslContextFactory.setEnableOCSP(false);
148             String certAlias = access().getProperty(Config.CADI_ALIAS, null);
149             if (certAlias!=null) {
150                 sslContextFactory.setCertAlias(certAlias);
151             }
152             
153             HttpConfiguration httpConfig = new HttpConfiguration();
154             httpConfig.setSecureScheme(protocol);
155             httpConfig.setSecurePort(port);
156             httpConfig.addCustomizer(new SecureRequestCustomizer());
157             //  httpConfig.setOutputBufferSize(32768);  Not sure why take this setting
158             
159             conn = new ServerConnector(server,
160                 new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
161                     new HttpConnectionFactory(httpConfig)
162                 );
163         }
164         service.setProtocol(protocol);
165
166         
167         // Setup JMX 
168         // TODO trying to figure out how to set up/log ports
169 //        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
170 //        MBeanContainer mbContainer=new MBeanContainer(mbeanServer);
171 //        server.addEventListener(mbContainer);
172 //        server.addBean(mbContainer);
173         
174         // Add loggers MBean to server (will be picked up by MBeanContainer above)
175 //        server.addBean(Log.getLog());
176     
177         conn.setHost(hostname);
178         conn.setPort(port);
179         conn.setIdleTimeout(IDLE_TIMEOUT);
180         server.addConnector(conn);
181         
182         server.setHandler(new AbstractHandler() {
183                 private FilterChain fc = buildFilterChain(service,new FilterChain() {
184                     @Override
185                     public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException {
186                         rserv.service(req, resp);
187                     }
188                 });
189                 
190                 @Override
191                 public void handle(String target, Request baseRequest, HttpServletRequest hreq, HttpServletResponse hresp) throws IOException, ServletException {
192                     try {
193                         fc.doFilter(hreq,hresp);
194                     } catch (Exception e) {
195                         service.access.log(e, "Error Processing " + target);
196                         hresp.setStatus(500 /* Service Error */);
197                     }
198                     baseRequest.setHandled(true);
199                 }
200             }
201         );
202         
203         try {
204             access().printf(Level.INIT, "Starting service on %s:%d (%s)",hostname,port,InetAddress.getByName(hostname).getHostAddress());
205             server.start();
206             access().log(Level.INIT,server.dump());
207         } catch (Exception e) {
208             access().log(e,"Error starting " + hostname + ':' + port + ' ' + InetAddress.getLocalHost().getHostAddress());
209             String doExit = access().getProperty("cadi_exitOnFailure", "true");
210             if (doExit == "true") {
211                 System.exit(1);
212             } else {
213                 throw e;
214             }
215         }
216         try {
217                 String no_register = env().getProperty("aaf_no_register",null);
218                 if(no_register==null) {
219                         register(service.registrants(port));
220                 } else {
221                         access().printf(Level.INIT,"'aaf_no_register' is set.  %s will not be registered with Locator", service.app_name);
222                 }
223             access().printf(Level.INIT, "Starting Jetty Service for %s, version %s, on %s://%s:%d", service.app_name,service.app_version,protocol,hostname,port);
224             //server.join();
225         } catch (Exception e) {
226             access().log(e,"Error registering " + service.app_name);
227             String doExit = access().getProperty("cadi_exitOnFailure", "true");
228             if (doExit == "true") {
229                 System.exit(1);
230             } else {
231                 throw e;
232             }
233         }
234     }
235
236     private FilterChain buildFilterChain(final AbsService<?,?> as, final FilterChain doLast) throws CadiException, LocatorException {
237         Filter[] filters = as.filters();
238         FilterChain fc = doLast;
239         for (int i=filters.length-1;i>=0;--i) {
240             fc = new FCImpl(filters[i],fc);
241         }
242         return fc;
243     }
244     
245     private class FCImpl implements FilterChain {
246         private Filter f;
247         private FilterChain next;
248         
249         public FCImpl(final Filter f, final FilterChain fc) {
250             this.f=f;
251             next = fc;
252             
253         }
254         @Override
255         public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException {
256             f.doFilter(req,resp, next);
257         }
258     }
259 }