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