2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.dmaap.dbcapi.service;
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;
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;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.Response.Status;
41 import javax.xml.bind.DatatypeConverter;
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;
54 public class ApiService extends BaseLoggingClass {
55 private class StopWatch {
56 private long clock = 0;
57 private long elapsed = 0;
67 clock = System.currentTimeMillis();
71 Long stopTime = System.currentTimeMillis();
72 elapsed += stopTime - clock;
74 MDC.put( MDC_END_TIMESTAMP, isoFormatter.format(new Date(stopTime)));
75 MDC.put( MDC_ELAPSED_TIME, String.valueOf(elapsed));
82 clock = System.currentTimeMillis();
83 MDC.put( MDC_BEGIN_TIMESTAMP, isoFormatter.format(new Date(clock)));
85 private long getElapsed() {
90 private String apiNamespace;
93 private String uriPath;
94 private String method;
95 private String authorization;
96 private String requestId;
98 private StopWatch stopwatch;
99 private ApiPolicy apiPolicy;
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);
106 isoFormatter.setTimeZone(utc);
108 public ApiService() {
110 stopwatch = new StopWatch();
112 err = new ApiError();
113 requestId = (new RandomString(10)).nextString();
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.");
120 apiPolicy = new ApiPolicy();
122 logger.info( "apiNamespace=" + apiNamespace);
125 public ApiService setAuth( String auth ) {
126 this.authorization = auth;
127 logger.info( "setAuth: authorization={} ", authorization);
130 private void setServiceName(){
131 String svcRequest = new String( this.method + " " + this.uriPath );
132 MDC.put(MDC_SERVICE_NAME, svcRequest );
134 public ApiService setHttpMethod( String httpMethod ) {
135 this.method = httpMethod;
136 logger.info( "setHttpMethod: method={} ", method);
140 public ApiService setUriPath( String uriPath ) {
141 this.uriPath = uriPath;
142 this.uri = setUriFromPath( uriPath );
143 logger.info( "setUriPath: uriPath={} uri={}", uriPath, uri);
147 private String setUriFromPath( String uriPath ) {
148 int ch = uriPath.indexOf("/");
150 return( (String) uriPath.subSequence(0, ch ) );
156 public ApiError getErr() {
161 public void setErr(ApiError err) {
166 // test for presence of a required field
167 public void required( String name, Object val, String expr ) throws RequiredFieldException {
169 err.setCode(Status.BAD_REQUEST.getStatusCode());
170 err.setMessage("missing required field");
171 err.setFields( name );
172 throw new RequiredFieldException();
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();
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() );
192 public void setCode(int statusCode) {
193 err.setCode(statusCode);
197 public void setMessage(String string) {
198 err.setMessage(string);
202 public void setFields(String string) {
203 err.setFields(string);
206 private Response buildResponse( Object obj ) {
208 MDC.put( MDC_RESPONSE_CODE, String.valueOf(err.getCode()) );
210 auditLogger.auditEvent( "" );
211 return Response.status( err.getCode())
215 private Response buildSuccessResponse(Object d) {
216 MDC.put( MDC_STATUS_CODE, "COMPLETE");
217 MDC.put( MDC_RESPONSE_DESC, "");
218 return buildResponse( d );
220 private Response buildErrResponse() {
222 MDC.put( MDC_STATUS_CODE, "ERROR");
223 MDC.put( MDC_RESPONSE_DESC, err.getMessage());
225 return buildResponse(getErr());
227 public Response success( Object d ) {
228 err.setCode(Status.OK.getStatusCode());
229 return buildSuccessResponse(d);
232 public Response success( int code, Object d ) {
234 return buildSuccessResponse(d);
237 public Response unauthorized( String msg ) {
238 err.setCode(Status.UNAUTHORIZED.getStatusCode());
239 err.setFields( "Authorization");
240 err.setMessage( msg );
241 return buildErrResponse();
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();
249 public Response unavailable() {
250 err.setCode(Status.SERVICE_UNAVAILABLE.getStatusCode());
251 err.setMessage( "Request is unavailable due to unexpected condition");
252 return buildErrResponse();
254 public Response notFound() {
255 err.setCode(Status.NOT_FOUND.getStatusCode());
256 err.setMessage( "Requested object not found");
257 return buildErrResponse();
259 public Response error() {
260 return buildErrResponse();
263 public void checkAuthorization( String auth, String uriPath, String httpMethod ) throws AuthenticationErrorException, Exception {
264 authorization = auth;
265 setUriFromPath( uriPath );
268 checkAuthorization();
272 public void checkAuthorization() throws AuthenticationErrorException, Exception {
274 MDC.put(MDC_KEY_REQUEST_ID, requestId);
276 logger.info("request: uri={} method={} auth={}", uri, method, authorization );
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( );
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( );
290 DmaapService dmaapService = new DmaapService();
291 Dmaap dmaap = dmaapService.getDmaap();
292 String env = dmaap.getDmaapName();
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() ) {
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( );
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);
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);
327 public String getRequestId() {
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 );
335 this.requestId = requestId;
337 MDC.put(MDC_KEY_REQUEST_ID, this.requestId);