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