Allow POST dr_sub using FeedName
[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                 err.setCode(0);
169                 if ( val == null  ) {
170                         err.setCode(Status.BAD_REQUEST.getStatusCode());
171                         err.setMessage("missing required field");
172                         err.setFields( name );  
173                         throw new RequiredFieldException();
174                 }
175                 if ( expr != null && ! expr.isEmpty() ) {
176                         Pattern pattern = Pattern.compile(expr);
177                         Matcher matcher = pattern.matcher((CharSequence) val);
178                         if ( ! matcher.find() ) {
179                                 err.setCode(Status.BAD_REQUEST.getStatusCode());
180                                 err.setMessage( "value '" + val + "' violates regexp check '" + expr + "'");
181                                 err.setFields( name );
182                                 throw new RequiredFieldException();
183                         }
184                 }
185         }
186         
187         // utility to serialize ApiErr object
188         public String toString() {
189                 return String.format( "code=%d msg=%s fields=%s", err.getCode(), err.getMessage(), err.getFields() );
190         }
191
192
193         public void setCode(int statusCode) {
194                 err.setCode(statusCode);        
195         }
196
197
198         public void setMessage(String string) {
199                 err.setMessage(string);
200         }
201
202
203         public void setFields(String string) {
204                 err.setFields(string);
205         }
206
207         private Response  buildResponse( Object obj ) {
208                 stopwatch.stop();
209                 MDC.put( MDC_RESPONSE_CODE, String.valueOf(err.getCode()) );
210                 
211                 auditLogger.auditEvent( "" );
212                 return Response.status( err.getCode())
213                                 .entity(obj)
214                                 .build();
215         }
216         private Response  buildSuccessResponse(Object d) {
217                 MDC.put( MDC_STATUS_CODE,  "COMPLETE");
218                 MDC.put( MDC_RESPONSE_DESC, "");
219                 return buildResponse( d );
220         }
221         private Response  buildErrResponse() {
222         
223                 MDC.put( MDC_STATUS_CODE,  "ERROR");
224                 MDC.put( MDC_RESPONSE_DESC, err.getMessage());
225                 
226                 return buildResponse(getErr());
227         }
228         public Response success( Object d ) {
229                 err.setCode(Status.OK.getStatusCode());
230                 return buildSuccessResponse(d);
231                                 
232         }
233         public Response success( int code, Object d ) {
234                 err.setCode(code);
235                 return buildSuccessResponse(d);
236         }
237
238         public Response unauthorized( String msg ) {
239                 err.setCode(Status.UNAUTHORIZED.getStatusCode());
240                 err.setFields( "Authorization");
241                 err.setMessage( msg );
242                 return buildErrResponse();
243         }
244         public Response unauthorized() {
245                 err.setCode(Status.UNAUTHORIZED.getStatusCode());
246                 err.setFields( "Authorization");
247                 err.setMessage( "User credentials in HTTP Header field Authorization are not authorized for the requested action");
248                 return buildErrResponse();
249         }
250         public Response unavailable() {
251                 err.setCode(Status.SERVICE_UNAVAILABLE.getStatusCode());
252                 err.setMessage( "Request is unavailable due to unexpected condition");
253                 return buildErrResponse();
254         }
255         public Response notFound() {
256                 err.setCode(Status.NOT_FOUND.getStatusCode());
257                 err.setMessage( "Requested object not found");
258                 return buildErrResponse();
259         }
260         public Response error() {
261                 return buildErrResponse();
262         }
263         
264         public void checkAuthorization( String auth, String uriPath, String httpMethod ) throws AuthenticationErrorException, Exception {
265                 authorization = auth;
266                 setUriFromPath( uriPath );
267                 method = httpMethod;
268                 
269                 checkAuthorization();
270         }
271
272         
273         public void checkAuthorization() throws AuthenticationErrorException, Exception {
274
275                 MDC.put(MDC_KEY_REQUEST_ID, requestId); 
276         
277                 logger.info("request: uri={} method={} auth={}", uri, method, authorization );
278
279                 if ( uri == null || uri.isEmpty()) {
280                         String errmsg = "No URI value provided ";
281                         err.setMessage(errmsg);
282                         logger.info( errmsg );
283                         throw new AuthenticationErrorException( );                      
284                 }
285                 if ( method == null || method.isEmpty()) {
286                         String errmsg = "No method value provided ";
287                         err.setMessage(errmsg);
288                         logger.info( errmsg );
289                         throw new AuthenticationErrorException( );                      
290                 }
291                 DmaapService dmaapService = new DmaapService();
292                 Dmaap dmaap = dmaapService.getDmaap();
293                 String env =            dmaap.getDmaapName();
294                 
295                 // special case during bootstrap of app when DMaaP environment may not be set.
296                 // this allows us to authorize certain APIs used for initialization during this window.
297                 if ( env == null || env.isEmpty() ) {
298                         env = "boot";
299                 }
300                 if ( ! apiPolicy.getUseAuthClass() ) return;  // skip authorization if not enabled
301                 if ( authorization == null || authorization.isEmpty()) {
302                         String errmsg = "No basic authorization value provided ";
303                         err.setMessage(errmsg);
304                         logger.info( errmsg );
305                         throw new AuthenticationErrorException( );
306                 }
307                 String credentials = authorization.substring("Basic".length()).trim();
308         byte[] decoded = DatatypeConverter.parseBase64Binary(credentials);
309         String decodedString = new String(decoded);
310         String[] actualCredentials = decodedString.split(":");
311         String ID = actualCredentials[0];
312         String Password = actualCredentials[1];
313         MDC.put(MDC_PARTNER_NAME, ID);
314                 try {
315                         
316                         DmaapPerm p = new DmaapPerm( apiNamespace + "." + uri, env, method );
317                         apiPolicy.check( ID, Password, p);
318                 } catch ( AuthenticationErrorException ae ) {
319                         String errmsg =  "User " + ID + " failed authentication/authorization for " + apiNamespace + "." + uriPath + " " + env + " " + method;
320                         logger.info( errmsg );
321                         err.setMessage(errmsg);
322                         throw ae;
323
324                 } 
325                 
326
327         }
328         public String getRequestId() {
329                 return requestId;
330         }
331         public ApiService setRequestId(String requestId) {
332                 if ( requestId == null || requestId.isEmpty()) {        
333                         this.requestId = (new RandomString(10)).nextString();
334                         logger.warn( "X-ECOMP-RequestID not set in HTTP Header.  Setting RequestId value to: " + this.requestId );
335                 } else {
336                         this.requestId = requestId;
337                 }
338                 MDC.put(MDC_KEY_REQUEST_ID, this.requestId); 
339                 return this;
340         }
341 }