6ae639de5729bade364a496fe22561ec16e87854
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / service / ApiService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 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 package org.onap.dmaap.dbcapi.service;
22
23 import static com.att.eelf.configuration.Configuration.MDC_BEGIN_TIMESTAMP;
24 import static com.att.eelf.configuration.Configuration.MDC_ELAPSED_TIME;
25 import static com.att.eelf.configuration.Configuration.MDC_END_TIMESTAMP;
26 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
27 import static com.att.eelf.configuration.Configuration.MDC_PARTNER_NAME;
28 import static com.att.eelf.configuration.Configuration.MDC_RESPONSE_CODE;
29 import static com.att.eelf.configuration.Configuration.MDC_RESPONSE_DESC;
30 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
31 import static com.att.eelf.configuration.Configuration.MDC_STATUS_CODE;
32
33 import java.text.SimpleDateFormat;
34 import java.util.Date;
35 import java.util.TimeZone;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.Response.Status;
41 import javax.xml.bind.DatatypeConverter;
42
43 import org.onap.dmaap.dbcapi.aaf.DmaapPerm;
44 import org.onap.dmaap.dbcapi.authentication.ApiPolicy;
45 import org.onap.dmaap.dbcapi.authentication.AuthenticationErrorException;
46 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
47 import org.onap.dmaap.dbcapi.model.ApiError;
48 import org.onap.dmaap.dbcapi.model.Dmaap;
49 import org.onap.dmaap.dbcapi.resources.RequiredFieldException;
50 import org.onap.dmaap.dbcapi.util.DmaapConfig;
51 import org.onap.dmaap.dbcapi.util.RandomString;
52 import org.slf4j.MDC;
53
54 public class ApiService extends BaseLoggingClass {
55         private class StopWatch {
56                 private long clock = 0;
57                 private long elapsed = 0;
58                 
59
60                 
61                 public StopWatch() {
62                         clock = 0;
63                         elapsed = 0;
64                 }
65                 
66                 public void reset() {
67                         clock = System.currentTimeMillis();
68                         elapsed = 0;
69                 }
70                 public void stop() {
71                         Long stopTime = System.currentTimeMillis();
72                         elapsed +=  stopTime - clock;
73                         clock = 0;
74                         MDC.put( MDC_END_TIMESTAMP, isoFormatter.format(new Date(stopTime)));
75                         MDC.put( MDC_ELAPSED_TIME, String.valueOf(elapsed));
76                 }
77                 public void start() {
78                         if ( clock != 0 ) {
79                                 //not stopped
80                                 return;
81                         }
82                         clock = System.currentTimeMillis();     
83                         MDC.put( MDC_BEGIN_TIMESTAMP, isoFormatter.format(new Date(clock)));
84                 }
85                 private long getElapsed() {
86                         return elapsed;
87                 }
88         }
89
90          private String apiNamespace;
91
92          private String uri;
93          private String uriPath;
94          private String method;
95          private String authorization;
96          private String requestId;
97         private ApiError err;
98         private StopWatch stopwatch;
99         private ApiPolicy apiPolicy;
100         
101         public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
102     public final static TimeZone utc = TimeZone.getTimeZone("UTC");
103     public final static SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
104         
105     static {
106         isoFormatter.setTimeZone(utc);
107     }   
108         public ApiService() {
109
110                 stopwatch = new StopWatch();
111                 stopwatch.start();
112                 err = new ApiError();
113                 requestId = (new RandomString(10)).nextString();
114                 
115                 if (apiNamespace == null) {
116                         DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
117                         apiNamespace = p.getProperty("ApiNamespace", "org.openecomp.dmaapBC.api");
118                         logger.info( "config param usePE has been deprecated.  Use ApiPermission.Class property instead.");
119                 }
120                 apiPolicy = new ApiPolicy();
121
122                 logger.info(  "apiNamespace=" + apiNamespace);  
123         }
124
125         public ApiService setAuth( String auth ) {
126                 this.authorization = auth;
127                 logger.info( "setAuth:  authorization={} ",  authorization);
128                 return this;
129         }
130         private void setServiceName(){
131                 String svcRequest = new String( this.method + " " + this.uriPath );
132         MDC.put(MDC_SERVICE_NAME, svcRequest );
133         }
134         public ApiService setHttpMethod( String httpMethod ) {
135                 this.method = httpMethod;
136                 logger.info( "setHttpMethod: method={} ", method);
137                 setServiceName();
138                 return this;
139         }
140         public ApiService setUriPath( String uriPath ) {
141                 this.uriPath = uriPath;
142                 this.uri = setUriFromPath( uriPath );
143                 logger.info( "setUriPath: uriPath={} uri={}", uriPath, uri);
144                 setServiceName();
145                 return this;
146         }
147         private String setUriFromPath( String uriPath ) {
148                 int ch = uriPath.indexOf("/");
149                 if ( ch > 0 ) {
150                         return( (String) uriPath.subSequence(0, ch ) );
151                 } else {
152                         return uriPath;
153                 }
154         }       
155         
156         public ApiError getErr() {
157                 return err;
158         }
159
160
161         public void setErr(ApiError err) {
162                 this.err = err;
163         }
164
165
166         // test for presence of a required field
167         public void required( String name, Object val, String expr ) throws RequiredFieldException {
168                 if ( val == null  ) {
169                         err.setCode(Status.BAD_REQUEST.getStatusCode());
170                         err.setMessage("missing required field");
171                         err.setFields( name );  
172                         throw new RequiredFieldException();
173                 }
174                 if ( expr != null && ! expr.isEmpty() ) {
175                         Pattern pattern = Pattern.compile(expr);
176                         Matcher matcher = pattern.matcher((CharSequence) val);
177                         if ( ! matcher.find() ) {
178                                 err.setCode(Status.BAD_REQUEST.getStatusCode());
179                                 err.setMessage( "value '" + val + "' violates regexp check '" + expr + "'");
180                                 err.setFields( name );
181                                 throw new RequiredFieldException();
182                         }
183                 }
184         }
185         
186         // utility to serialize ApiErr object
187         public String toString() {
188                 return String.format( "code=%d msg=%s fields=%s", err.getCode(), err.getMessage(), err.getFields() );
189         }
190
191
192         public void setCode(int statusCode) {
193                 err.setCode(statusCode);        
194         }
195
196
197         public void setMessage(String string) {
198                 err.setMessage(string);
199         }
200
201
202         public void setFields(String string) {
203                 err.setFields(string);
204         }
205
206         private Response  buildResponse( Object obj ) {
207                 stopwatch.stop();
208                 MDC.put( MDC_RESPONSE_CODE, String.valueOf(err.getCode()) );
209                 
210                 auditLogger.auditEvent( "" );
211                 return Response.status( err.getCode())
212                                 .entity(obj)
213                                 .build();
214         }
215         private Response  buildSuccessResponse(Object d) {
216                 MDC.put( MDC_STATUS_CODE,  "COMPLETE");
217                 MDC.put( MDC_RESPONSE_DESC, "");
218                 return buildResponse( d );
219         }
220         private Response  buildErrResponse() {
221         
222                 MDC.put( MDC_STATUS_CODE,  "ERROR");
223                 MDC.put( MDC_RESPONSE_DESC, err.getMessage());
224                 
225                 return buildResponse(getErr());
226         }
227         public Response success( Object d ) {
228                 err.setCode(Status.OK.getStatusCode());
229                 return buildSuccessResponse(d);
230                                 
231         }
232         public Response success( int code, Object d ) {
233                 err.setCode(code);
234                 return buildSuccessResponse(d);
235         }
236
237         public Response unauthorized( String msg ) {
238                 err.setCode(Status.UNAUTHORIZED.getStatusCode());
239                 err.setFields( "Authorization");
240                 err.setMessage( msg );
241                 return buildErrResponse();
242         }
243         public Response unauthorized() {
244                 err.setCode(Status.UNAUTHORIZED.getStatusCode());
245                 err.setFields( "Authorization");
246                 err.setMessage( "User credentials in HTTP Header field Authorization are not authorized for the requested action");
247                 return buildErrResponse();
248         }
249         public Response unavailable() {
250                 err.setCode(Status.SERVICE_UNAVAILABLE.getStatusCode());
251                 err.setMessage( "Request is unavailable due to unexpected condition");
252                 return buildErrResponse();
253         }
254         public Response notFound() {
255                 err.setCode(Status.NOT_FOUND.getStatusCode());
256                 err.setMessage( "Requested object not found");
257                 return buildErrResponse();
258         }
259         public Response error() {
260                 return buildErrResponse();
261         }
262         
263         public void checkAuthorization( String auth, String uriPath, String httpMethod ) throws AuthenticationErrorException, Exception {
264                 authorization = auth;
265                 setUriFromPath( uriPath );
266                 method = httpMethod;
267                 
268                 checkAuthorization();
269         }
270
271         
272         public void checkAuthorization() throws AuthenticationErrorException, Exception {
273
274                 MDC.put(MDC_KEY_REQUEST_ID, requestId); 
275         
276                 logger.info("request: uri={} method={} auth={}", uri, method, authorization );
277
278                 if ( uri == null || uri.isEmpty()) {
279                         String errmsg = "No URI value provided ";
280                         err.setMessage(errmsg);
281                         logger.info( errmsg );
282                         throw new AuthenticationErrorException( );                      
283                 }
284                 if ( method == null || method.isEmpty()) {
285                         String errmsg = "No method value provided ";
286                         err.setMessage(errmsg);
287                         logger.info( errmsg );
288                         throw new AuthenticationErrorException( );                      
289                 }
290                 DmaapService dmaapService = new DmaapService();
291                 Dmaap dmaap = dmaapService.getDmaap();
292                 String env =            dmaap.getDmaapName();
293                 
294                 // special case during bootstrap of app when DMaaP environment may not be set.
295                 // this allows us to authorize certain APIs used for initialization during this window.
296                 if ( env == null || env.isEmpty() ) {
297                         env = "boot";
298                 }
299                 if ( ! apiPolicy.getUseAuthClass() ) return;  // skip authorization if not enabled
300                 if ( authorization == null || authorization.isEmpty()) {
301                         String errmsg = "No basic authorization value provided ";
302                         err.setMessage(errmsg);
303                         logger.info( errmsg );
304                         throw new AuthenticationErrorException( );
305                 }
306                 String credentials = authorization.substring("Basic".length()).trim();
307         byte[] decoded = DatatypeConverter.parseBase64Binary(credentials);
308         String decodedString = new String(decoded);
309         String[] actualCredentials = decodedString.split(":");
310         String ID = actualCredentials[0];
311         String Password = actualCredentials[1];
312         MDC.put(MDC_PARTNER_NAME, ID);
313                 try {
314                         
315                         DmaapPerm p = new DmaapPerm( apiNamespace + "." + uri, env, method );
316                         apiPolicy.check( ID, Password, p);
317                 } catch ( AuthenticationErrorException ae ) {
318                         String errmsg =  "User " + ID + " failed authentication/authorization for " + apiNamespace + "." + uriPath + " " + env + " " + method;
319                         logger.info( errmsg );
320                         err.setMessage(errmsg);
321                         throw ae;
322
323                 } 
324                 
325
326         }
327         public String getRequestId() {
328                 return requestId;
329         }
330         public ApiService setRequestId(String requestId) {
331                 if ( requestId == null || requestId.isEmpty()) {        
332                         this.requestId = (new RandomString(10)).nextString();
333                         logger.warn( "X-ECOMP-RequestID not set in HTTP Header.  Setting RequestId value to: " + this.requestId );
334                 } else {
335                         this.requestId = requestId;
336                 }
337                 MDC.put(MDC_KEY_REQUEST_ID, this.requestId); 
338                 return this;
339         }
340 }