Update DCAE Startup Info
[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 is DEPRECATED
139          *
140          * Need to move towards NS declaration... is this even being used?
141          * @deprecated
142          */
143         gwAPI.route(HttpMethods.GET,"/ask/:user/has/:type/:instance/:action",API.VOID,new LocateCode(facade,USER_HAS_PERM, true) {
144             @Override
145             public void handle(final AuthzTrans trans, final HttpServletRequest req, HttpServletResponse resp) throws Exception {
146                 try {
147                     String type = pathParam(req,":type");
148                     int idx = type.lastIndexOf('.');
149                     String ns = type.substring(0,idx);
150                     type = type.substring(idx+1);
151                     resp.getOutputStream().print(
152                             gwAPI.aafLurPerm.fish(new Principal() {
153                                 public String getName() {
154                                     return pathParam(req,":user");
155                                 };
156                             }, new AAFPermission(
157                                 ns,
158                                 type,
159                                 pathParam(req,":instance"),
160                                 pathParam(req,":action"))));
161                     resp.setStatus(HttpStatus.OK_200);
162                 } catch (Exception e) {
163                     context.error(trans, resp, Result.ERR_General, e.getMessage());
164                 }
165             }
166         });
167
168         gwAPI.route(HttpMethods.GET,"/gui/:path*",API.VOID,new LocateCode(facade,"Short Access PROD GUI for AAF", true) {
169             @Override
170             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
171                 try {
172                     redirect(trans, req, resp, context,
173                             gwAPI.getGUILocator(),
174                             "gui/"+pathParam(req,":path"));
175                 } catch (LocatorException e) {
176                     context.error(trans, resp, Result.ERR_BadData, e.getMessage());
177                 } catch (Exception e) {
178                     context.error(trans, resp, Result.ERR_General, e.getMessage());
179                 }
180             }
181         });
182
183         gwAPI.route(HttpMethods.GET,"/aaf/:version/:path*",API.VOID,new LocateCode(facade,"Access PROD GUI for AAF", true) {
184             @Override
185             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
186                 try {
187                     redirect(trans, req, resp, context,
188                             gwAPI.getGUILocator(),
189                             pathParam(req,":path"));
190                 } catch (LocatorException e) {
191                     context.error(trans, resp, Result.ERR_BadData, e.getMessage());
192                 } catch (Exception e) {
193                     context.error(trans, resp, Result.ERR_General, e.getMessage());
194                 }
195             }
196         });
197     }
198
199     public static void initDefault(final AAF_Locate gwAPI, LocateFacade facade) throws Exception {
200
201         /**
202          * "login" url
203          */
204         gwAPI.route(HttpMethods.GET,"/login",API.VOID,new LocateCode(facade,"Access Login GUI for AAF", true) {
205             @Override
206             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
207                 try {
208                     redirect(trans, req, resp, context,
209                             gwAPI.getGUILocator(),
210                             "login");
211                 } catch (LocatorException e) {
212                     context.error(trans, resp, Result.ERR_BadData, e.getMessage());
213                 } catch (Exception e) {
214                     context.error(trans, resp, Result.ERR_General, e.getMessage());
215                 }
216             }
217         });
218
219
220         /**
221          * Default URL
222          */
223         gwAPI.route(HttpMethods.GET,"/",API.VOID,new LocateCode(facade,"Access GUI for AAF", true) {
224             @Override
225             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
226                 try {
227                     redirect(trans, req, resp, context,
228                             gwAPI.getGUILocator(),
229                             "gui/home");
230                 } catch (Exception e) {
231                     context.error(trans, resp, Result.ERR_General, e.getMessage());
232                 }
233             }
234         });
235
236         /**
237          * Configuration
238          */
239         gwAPI.route(HttpMethods.GET,"/configure/:id/:type",API.CONFIG,new LocateCode(facade,"Deliver Configuration Properties to AAF", true) {
240             @Override
241             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
242                 try {
243                     Result<Void> r = facade.getConfig(trans, req, resp, pathParam(req, ":id"),pathParam(req,":type"));
244                     switch(r.status) {
245                         case OK:
246                             resp.setStatus(HttpStatus.OK_200);
247                             break;
248                         default:
249                             context.error(trans,resp,r);
250                     }
251
252                 } catch (Exception e) {
253                     context.error(trans, resp, Result.ERR_General, e.getMessage());
254                 }
255             }
256         });
257     }
258
259     private static void redirect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, LocateFacade context, Locator<URI> loc, String path) throws IOException {
260         try {
261             if (loc.hasItems()) {
262                 Item item = loc.best();
263                 URI uri = loc.get(item);
264                 StringBuilder redirectURL = new StringBuilder(uri.toString());
265                 redirectURL.append('/');
266                 redirectURL.append(path);
267                 String str = req.getQueryString();
268                 if (str!=null) {
269                     redirectURL.append('?');
270                     redirectURL.append(str);
271                 }
272                 trans.info().log("Redirect to",redirectURL);
273                 resp.sendRedirect(redirectURL.toString());
274             } else {
275                 context.error(trans, resp, Result.err(Result.ERR_NotFound,"No Locations found for redirection"));
276             }
277         } catch (LocatorException e) {
278             context.error(trans, resp, Result.err(Result.ERR_NotFound,"No Endpoints found for %s",req.getPathInfo()));
279         }
280     }
281
282     private static class User {
283         public final int code;
284         public final String resp;
285
286         public User(int code, String resp) {
287             this.code = code;
288             this.resp = resp;
289         }
290     }
291 }