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