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