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