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