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