Initial Interface for remote Configuration
[aaf/authz.git] / auth / auth-locate / src / main / java / org / onap / aaf / auth / locate / api / API_AAFAccess.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 package org.onap.aaf.auth.locate.api;
23
24 import static org.onap.aaf.auth.layer.Result.OK;
25
26 import java.io.IOException;
27 import java.net.ConnectException;
28 import java.net.URI;
29 import java.security.Principal;
30
31 import javax.servlet.ServletOutputStream;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34
35 import org.eclipse.jetty.http.HttpStatus;
36 import org.onap.aaf.auth.cache.Cache.Dated;
37 import org.onap.aaf.auth.env.AuthzTrans;
38 import org.onap.aaf.auth.layer.Result;
39 import org.onap.aaf.auth.locate.AAF_Locate;
40 import org.onap.aaf.auth.locate.BasicAuthCode;
41 import org.onap.aaf.auth.locate.LocateCode;
42 import org.onap.aaf.auth.locate.facade.LocateFacade;
43 import org.onap.aaf.auth.locate.mapper.Mapper.API;
44 import org.onap.aaf.auth.rserv.HttpMethods;
45 import org.onap.aaf.cadi.CadiException;
46 import org.onap.aaf.cadi.Locator;
47 import org.onap.aaf.cadi.Locator.Item;
48 import org.onap.aaf.cadi.LocatorException;
49 import org.onap.aaf.cadi.aaf.AAFPermission;
50 import org.onap.aaf.cadi.client.Future;
51 import org.onap.aaf.cadi.client.Rcli;
52 import org.onap.aaf.cadi.client.Retryable;
53 import org.onap.aaf.misc.env.APIException;
54 import org.onap.aaf.misc.env.Env;
55 import org.onap.aaf.misc.env.TimeTaken;
56
57 public class API_AAFAccess {
58 //      private static String service, version, envContext; 
59
60         private static final String GET_PERMS_BY_USER = "Get Perms by User";
61         private static final String USER_HAS_PERM ="User Has Perm";
62 //      private static final String USER_IN_ROLE ="User Has Role";
63         
64         /**
65          * Normal Init level APIs
66          * 
67          * @param gwAPI
68          * @param facade
69          * @throws Exception
70          */
71         public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception {
72                 
73                 
74                 gwAPI.route(HttpMethods.GET,"/authz/perms/user/:user",API.VOID,new LocateCode(facade,GET_PERMS_BY_USER, true) {
75                         @Override
76                         public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception {
77                                 TimeTaken tt = trans.start(GET_PERMS_BY_USER, Env.SUB);
78                                 try {
79                                         final String accept = req.getHeader("ACCEPT");
80                                         final String user = pathParam(req,":user");
81                                         if(!user.contains("@")) {
82                                                 context.error(trans,resp,Result.ERR_BadData,"User [%s] must be fully qualified with domain",user);
83                                                 return;
84                                         }
85                                         final String key = trans.user() + user + (accept!=null&&accept.contains("xml")?"-xml":"-json");
86                                         TimeTaken tt2 = trans.start("Cache Lookup",Env.SUB);
87                                         Dated d;
88                                         try {
89                                                 d = gwAPI.cacheUser.get(key);
90                                         } finally {
91                                                 tt2.done();
92                                         }
93                                         
94                                         if(d==null || d.data.isEmpty()) {
95                                                 tt2 = trans.start("AAF Service Call",Env.REMOTE);
96                                                 try {
97                                                         gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable<Void>() {
98                                                                 @Override
99                                                                 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
100                                                                         Future<String> fp = client.read("/authz/perms/user/"+user,accept);
101                                                                         if(fp.get(5000)) {
102                                                                                 gwAPI.cacheUser.put(key, new Dated(new User(fp.code(),fp.body()),gwAPI.expireIn));
103                                                                                 resp.setStatus(HttpStatus.OK_200);
104                                                                                 ServletOutputStream sos;
105                                                                                 try {
106                                                                                         sos = resp.getOutputStream();
107                                                                                         sos.print(fp.value);
108                                                                                 } catch (IOException e) {
109                                                                                         throw new CadiException(e);
110                                                                                 }
111                                                                         } else {
112                                                                                 gwAPI.cacheUser.put(key, new Dated(new User(fp.code(),fp.body()),gwAPI.expireIn));
113                                                                                 context.error(trans,resp,fp.code(),fp.body());
114                                                                         }
115                                                                         return null;
116                                                                 }
117                                                         });
118                                                 } finally {
119                                                         tt2.done();
120                                                 }
121                                         } else {
122                                                 User u = (User)d.data.get(0);
123                                                 resp.setStatus(u.code);
124                                                 ServletOutputStream sos = resp.getOutputStream();
125                                                 sos.print(u.resp);
126                                         }
127                                 } finally {
128                                         tt.done();
129                                 }
130                         }
131                 });
132
133
134                 gwAPI.route(gwAPI.env,HttpMethods.GET,"/authn/basicAuth",new BasicAuthCode(gwAPI.aafAuthn,facade)
135                                 ,"text/plain","*/*","*");
136
137                 /**
138                  * Query User Has Perm
139                  */
140                 gwAPI.route(HttpMethods.GET,"/ask/:user/has/:type/:instance/:action",API.VOID,new LocateCode(facade,USER_HAS_PERM, true) {
141                         @Override
142                         public void handle(final AuthzTrans trans, final HttpServletRequest req, HttpServletResponse resp) throws Exception {
143                                 try {
144                                         resp.getOutputStream().print(
145                                                         gwAPI.aafLurPerm.fish(new Principal() {
146                                                                 public String getName() {
147                                                                         return pathParam(req,":user");
148                                                                 };
149                                                         }, new AAFPermission(
150                                                                 pathParam(req,":type"),
151                                                                 pathParam(req,":instance"),
152                                                                 pathParam(req,":action"))));
153                                         resp.setStatus(HttpStatus.OK_200);
154                                 } catch(Exception e) {
155                                         context.error(trans, resp, Result.ERR_General, e.getMessage());
156                                 }
157                         }
158                 });
159
160                 gwAPI.route(HttpMethods.GET,"/gui/:path*",API.VOID,new LocateCode(facade,"Short Access PROD GUI for AAF", true) {
161                         @Override
162                         public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
163                                 try {
164                                         redirect(trans, req, resp, context, 
165                                                         gwAPI.getGUILocator(), 
166                                                         "gui/"+pathParam(req,":path"));
167                                 } catch (LocatorException e) {
168                                         context.error(trans, resp, Result.ERR_BadData, e.getMessage());
169                                 } catch (Exception e) {
170                                         context.error(trans, resp, Result.ERR_General, e.getMessage());
171                                 }
172                         }
173                 });
174
175                 gwAPI.route(HttpMethods.GET,"/aaf/:version/:path*",API.VOID,new LocateCode(facade,"Access PROD GUI for AAF", true) {
176                         @Override
177                         public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
178                                 try {
179                                         redirect(trans, req, resp, context, 
180                                                         gwAPI.getGUILocator(), 
181                                                         pathParam(req,":path"));
182                                 } catch (LocatorException e) {
183                                         context.error(trans, resp, Result.ERR_BadData, e.getMessage());
184                                 } catch (Exception e) {
185                                         context.error(trans, resp, Result.ERR_General, e.getMessage());
186                                 }
187                         }
188                 });
189         }
190         
191         public static void initDefault(final AAF_Locate gwAPI, LocateFacade facade) throws Exception {
192
193                 /**
194                  * "login" url
195                  */
196                 gwAPI.route(HttpMethods.GET,"/login",API.VOID,new LocateCode(facade,"Access Login GUI for AAF", true) {
197                         @Override
198                         public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
199                                 try {
200                                         redirect(trans, req, resp, context, 
201                                                         gwAPI.getGUILocator(),
202                                                         "login");
203                                 } catch (LocatorException e) {
204                                         context.error(trans, resp, Result.ERR_BadData, e.getMessage());
205                                 } catch (Exception e) {
206                                         context.error(trans, resp, Result.ERR_General, e.getMessage());
207                                 }
208                         }
209                 });
210
211                 
212                 /**
213                  * Default URL
214                  */
215                 gwAPI.route(HttpMethods.GET,"/",API.VOID,new LocateCode(facade,"Access GUI for AAF", true) {
216                         @Override
217                         public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
218                                 try {
219                                         redirect(trans, req, resp, context, 
220                                                         gwAPI.getGUILocator(), 
221                                                         "gui/home");
222                                 } catch (Exception e) {
223                                         context.error(trans, resp, Result.ERR_General, e.getMessage());
224                                 }
225                         }
226                 });
227                 
228                 /**
229                  * Configuration 
230                  */
231                 gwAPI.route(HttpMethods.GET,"/configure/:id/:type",API.CONFIG,new LocateCode(facade,"Deliver Configuration Properties to AAF", true) {
232                         @Override
233                         public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
234                                 try {
235                                         Result<Void> r = facade.getConfig(trans, req, resp, pathParam(req, ":id"),pathParam(req,":type"));
236                                         switch(r.status) {
237                                                 case OK:
238                                                         resp.setStatus(HttpStatus.OK_200);
239                                                         break;
240                                                 default:
241                                                         context.error(trans,resp,r);
242                                         }
243
244                                 } catch (Exception e) {
245                                         context.error(trans, resp, Result.ERR_General, e.getMessage());
246                                 }
247                         }
248                 });
249         }
250
251         private static void redirect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, LocateFacade context, Locator<URI> loc, String path) throws IOException {
252                 try {
253                         if(loc.hasItems()) {
254                                 Item item = loc.best();
255                                 URI uri = loc.get(item);
256                                 StringBuilder redirectURL = new StringBuilder(uri.toString()); 
257                                 redirectURL.append('/');
258                                 redirectURL.append(path);
259                                 String str = req.getQueryString();
260                                 if(str!=null) {
261                                         redirectURL.append('?');
262                                         redirectURL.append(str);
263                                 }
264                                 trans.info().log("Redirect to",redirectURL);
265                                 resp.sendRedirect(redirectURL.toString());
266                         } else {
267                                 context.error(trans, resp, Result.err(Result.ERR_NotFound,"No Locations found for redirection"));
268                         }
269                 } catch (LocatorException e) {
270                         context.error(trans, resp, Result.err(Result.ERR_NotFound,"No Endpoints found for %s",req.getPathInfo()));
271                 }
272         }
273
274         private static class User {
275                 public final int code;
276                 public final String resp;
277                 
278                 public User(int code, String resp) {
279                         this.code = code;
280                         this.resp = resp;
281                 }
282         }
283 }