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