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 {
170 err.setCode(Status.BAD_REQUEST.getStatusCode());
171 err.setMessage("missing required field");
172 err.setFields( name );
173 throw new RequiredFieldException();
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();
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() );
193 public void setCode(int statusCode) {
194 err.setCode(statusCode);
198 public void setMessage(String string) {
199 err.setMessage(string);
203 public void setFields(String string) {
204 err.setFields(string);
207 private Response buildResponse( Object obj ) {
209 MDC.put( MDC_RESPONSE_CODE, String.valueOf(err.getCode()) );
211 auditLogger.auditEvent( "" );
212 return Response.status( err.getCode())
216 private Response buildSuccessResponse(Object d) {
217 MDC.put( MDC_STATUS_CODE, "COMPLETE");
218 MDC.put( MDC_RESPONSE_DESC, "");
219 return buildResponse( d );
221 private Response buildErrResponse() {
223 MDC.put( MDC_STATUS_CODE, "ERROR");
224 MDC.put( MDC_RESPONSE_DESC, err.getMessage());
226 return buildResponse(getErr());
228 public Response success( Object d ) {
229 err.setCode(Status.OK.getStatusCode());
230 return buildSuccessResponse(d);
233 public Response success( int code, Object d ) {
235 return buildSuccessResponse(d);
238 public Response unauthorized( String msg ) {
239 err.setCode(Status.UNAUTHORIZED.getStatusCode());
240 err.setFields( "Authorization");
241 err.setMessage( msg );
242 return buildErrResponse();
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();
250 public Response unavailable() {
251 err.setCode(Status.SERVICE_UNAVAILABLE.getStatusCode());
252 err.setMessage( "Request is unavailable due to unexpected condition");
253 return buildErrResponse();
255 public Response notFound() {
256 err.setCode(Status.NOT_FOUND.getStatusCode());
257 err.setMessage( "Requested object not found");
258 return buildErrResponse();
260 public Response error() {
261 return buildErrResponse();
264 public void checkAuthorization( String auth, String uriPath, String httpMethod ) throws AuthenticationErrorException, Exception {
265 authorization = auth;
266 setUriFromPath( uriPath );
269 checkAuthorization();
273 public void checkAuthorization() throws AuthenticationErrorException, Exception {
275 MDC.put(MDC_KEY_REQUEST_ID, requestId);
277 logger.info("request: uri={} method={} auth={}", uri, method, authorization );
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( );
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( );
291 DmaapService dmaapService = new DmaapService();
292 Dmaap dmaap = dmaapService.getDmaap();
293 String env = dmaap.getDmaapName();
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() ) {
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( );
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);
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);
328 public String getRequestId() {
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 );
336 this.requestId = requestId;
338 MDC.put(MDC_KEY_REQUEST_ID, this.requestId);