Remove Tabs, per Jococo
[aaf/authz.git] / auth / auth-certman / src / main / java / org / onap / aaf / auth / cm / AAF_CM.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
22
23 package org.onap.aaf.auth.cm;
24
25 import java.lang.reflect.Constructor;
26 import java.lang.reflect.InvocationTargetException;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.TreeMap;
30
31 import javax.servlet.Filter;
32
33 import org.onap.aaf.auth.cache.Cache;
34 import org.onap.aaf.auth.cache.Cache.Dated;
35 import org.onap.aaf.auth.cm.api.API_Artifact;
36 import org.onap.aaf.auth.cm.api.API_Cert;
37 import org.onap.aaf.auth.cm.ca.CA;
38 import org.onap.aaf.auth.cm.facade.Facade1_0;
39 import org.onap.aaf.auth.cm.facade.FacadeFactory;
40 import org.onap.aaf.auth.cm.mapper.Mapper.API;
41 import org.onap.aaf.auth.cm.service.CMService;
42 import org.onap.aaf.auth.cm.service.Code;
43 import org.onap.aaf.auth.cm.validation.CertmanValidator;
44 import org.onap.aaf.auth.dao.CassAccess;
45 import org.onap.aaf.auth.dao.cass.LocateDAO;
46 import org.onap.aaf.auth.direct.DirectLocatorCreator;
47 import org.onap.aaf.auth.direct.DirectRegistrar;
48 import org.onap.aaf.auth.env.AuthzEnv;
49 import org.onap.aaf.auth.env.AuthzTrans;
50 import org.onap.aaf.auth.env.AuthzTransFilter;
51 import org.onap.aaf.auth.rserv.HttpMethods;
52 import org.onap.aaf.auth.server.AbsService;
53 import org.onap.aaf.auth.server.JettyServiceStarter;
54 import org.onap.aaf.auth.server.Log4JLogIt;
55 import org.onap.aaf.cadi.Access;
56 import org.onap.aaf.cadi.Access.Level;
57 import org.onap.aaf.cadi.CadiException;
58 import org.onap.aaf.cadi.LocatorException;
59 import org.onap.aaf.cadi.PropAccess;
60 import org.onap.aaf.cadi.aaf.v2_0.AAFAuthn;
61 import org.onap.aaf.cadi.aaf.v2_0.AAFLurPerm;
62 import org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker;
63 import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator;
64 import org.onap.aaf.cadi.config.Config;
65 import org.onap.aaf.cadi.register.Registrant;
66 import org.onap.aaf.misc.env.APIException;
67 import org.onap.aaf.misc.env.Data;
68 import org.onap.aaf.misc.env.Env;
69 import org.onap.aaf.misc.env.util.Split;
70
71 import com.datastax.driver.core.Cluster;
72
73 public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> {
74
75     private static final String USER_PERMS = "userPerms";
76     private static final String CM_ALLOW_TMP = "cm_allow_tmp";
77     private static final Map<String,CA> certAuths = new TreeMap<>();
78     public static  Facade1_0 facade1_0; // this is the default Facade
79     public static  Facade1_0 facade1_0_XML; // this is the XML Facade
80     public static  Map<String, Dated> cacheUser;
81     public static  AAFAuthn<?> aafAuthn;
82     public static  AAFLurPerm aafLurPerm;
83     public final  Cluster cluster;
84     public final LocateDAO locateDAO;
85     public static AuthzEnv envLog;
86     CMService service;
87
88     //Added for junits
89     public CMService getService() {
90         return null;
91     }
92     /**
93      * Construct AuthzAPI with all the Context Supporting Routes that Authz needs
94      * 
95      * @param env
96      * @param si 
97      * @param dm 
98      * @param decryptor 
99      * @throws APIException 
100      */
101     public AAF_CM(AuthzEnv env) throws Exception {
102         super(env.access(),env);
103         aafLurPerm = aafCon().newLur();
104         // Note: If you need both Authn and Authz construct the following:
105         aafAuthn = aafCon().newAuthn(aafLurPerm);
106
107         String aafEnv = env.getProperty(Config.AAF_ENV);
108         if (aafEnv==null) {
109             throw new APIException("aaf_env needs to be set");
110         }
111         
112         // Check for allowing /tmp in Properties
113         String allowTmp = env.getProperty(CM_ALLOW_TMP);
114         if("true".equalsIgnoreCase(allowTmp)) {
115             CertmanValidator.allowTmp();
116         }
117
118
119         // Initialize Facade for all uses
120         AuthzTrans trans = env.newTrans();
121
122         cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null);
123         locateDAO = new LocateDAO(trans,cluster,CassAccess.KEYSPACE);
124
125         // Have AAFLocator object Create DirectLocators for Location needs
126         AbsAAFLocator.setCreator(new DirectLocatorCreator(env, locateDAO));
127
128         // Load Supported Certificate Authorities by property
129         // Note: Some will be dynamic Properties, so we need to look through all
130         for (Entry<Object, Object> es : env.access().getProperties().entrySet()) {
131             String key = es.getKey().toString();
132             if (key.startsWith(CA.CM_CA_PREFIX)) {
133                 int idx = key.indexOf('.');
134                 if (idx==key.lastIndexOf('.')) { // else it's a regular property 
135                     env.log(Level.INIT, "Loading Certificate Authority Module: " + key.substring(idx+1));
136                     String[] segs = Split.split(',', env.getProperty(key));
137                     if (segs.length>0) {
138                         String[][] multiParams = new String[segs.length-1][];
139                         for (int i=0;i<multiParams.length;++i) {
140                             multiParams[i]=Split.split(';',segs[1+i]);
141                         }
142                         @SuppressWarnings("unchecked")
143                         Class<CA> cac = (Class<CA>)Class.forName(segs[0]);
144                         Constructor<CA> cons = cac.getConstructor(new Class<?>[] {
145                             Access.class,String.class,String.class,String[][].class
146                         });
147                         Object pinst[] = new Object[4];
148                         pinst[0]=env;
149                         pinst[1]= key.substring(idx+1);
150                         pinst[2]= aafEnv;
151                         pinst[3] = multiParams; 
152                         try {
153                             CA ca = cons.newInstance(pinst);
154                             certAuths.put(ca.getName(),ca);
155                         } catch (InvocationTargetException e) {
156                             access.log(e, "Loading", segs[0]);
157                         }
158                     }
159                 }
160             }
161         }
162         if (certAuths.size()==0) {
163             throw new APIException("No Certificate Authorities have been configured in CertMan");
164         }
165
166         service = getService();
167         if(service == null) {
168             service = new CMService(trans, this);
169         }
170         // note: Service knows how to shutdown Cluster on Shutdown, etc.  See Constructor
171         facade1_0 = FacadeFactory.v1_0(this,trans, service,Data.TYPE.JSON);   // Default Facade
172         facade1_0_XML = FacadeFactory.v1_0(this,trans,service,Data.TYPE.XML); 
173
174
175         synchronized(env) {
176             if (cacheUser == null) {
177                 cacheUser = Cache.obtain(USER_PERMS);
178                 Cache.startCleansing(env, USER_PERMS);
179             }
180         }
181
182         ////////////////////////////////////////////////////////////////////////////
183         // APIs
184         ////////////////////////////////////////////////////////////////////////
185         API_Cert.init(this);
186         API_Artifact.init(this);
187
188         StringBuilder sb = new StringBuilder();
189         trans.auditTrail(2, sb);
190         trans.init().log(sb);
191     }
192
193     public CA getCA(String key) {
194         return certAuths.get(key);
195     }
196     
197
198     /**
199      * Setup XML and JSON implementations for each supported Version type
200      * 
201      * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties
202      * to do Versions and Content switches
203      * 
204      */
205     public void route(HttpMethods meth, String path, API api, Code code) throws Exception {
206         String version = "1.0";
207         // Get Correct API Class from Mapper
208         Class<?> respCls = facade1_0.mapper().getClass(api); 
209         if (respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name());
210         // setup Application API HTML ContentTypes for JSON and Route
211         String application = applicationJSON(respCls, version);
212         route(env,meth,path,code,application,"application/json;version="+version,"*/*");
213
214         // setup Application API HTML ContentTypes for XML and Route
215         application = applicationXML(respCls, version);
216         route(env,meth,path,code.clone(facade1_0_XML),application,"application/xml;version="+version);
217
218         // Add other Supported APIs here as created
219     }
220
221     public void routeAll(HttpMethods meth, String path, API api, Code code) throws Exception {
222         route(env,meth,path,code,""); // this will always match
223     }
224
225     @Override
226     public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException {
227         try {
228             return new Filter[] {
229                     new AuthzTransFilter(env,aafCon(),
230                         new AAFTrustChecker((Env)env),
231                         additionalTafLurs)
232                 };
233         } catch (NumberFormatException e) {
234             throw new CadiException("Invalid Property information", e);
235         }
236     }
237
238     @SuppressWarnings("unchecked")
239     @Override
240     public Registrant<AuthzEnv>[] registrants(final int port) throws CadiException, LocatorException {
241         return new Registrant[] {
242             new DirectRegistrar(access,locateDAO,port)
243         };
244     }
245
246     public void destroy() {
247         Cache.stopTimer();
248         locateDAO.close(env.newTransNoAvg());
249         cluster.close();
250     }
251
252     public static void main(final String[] args) {
253         try {
254             Log4JLogIt logIt = new Log4JLogIt(args, "cm");
255             PropAccess propAccess = new PropAccess(logIt,args);
256             try {
257                 new JettyServiceStarter<AuthzEnv,AuthzTrans>(
258                     new AAF_CM(new AuthzEnv(propAccess)),true)
259                         .start();
260             } catch (Exception e) {
261                 propAccess.log(e);
262             }
263         } catch (APIException e) {
264             e.printStackTrace(System.err);
265         }
266     }
267 }