Removing jackson to mitigate cve-2017-4995
[vfc/nfvo/driver/vnfm/svnfm.git] / nokiav2 / driver / src / main / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / nokia / vnfm / CbamTokenProvider.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm;
17
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.gson.Gson;
20 import com.google.gson.annotations.SerializedName;
21 import java.io.IOException;
22 import javax.net.ssl.HostnameVerifier;
23 import javax.net.ssl.SSLSocketFactory;
24 import okhttp3.*;
25 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.VnfmInfoProvider;
26 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions;
27 import org.onap.vnfmdriver.model.VnfmInfo;
28 import org.slf4j.Logger;
29 import org.springframework.beans.factory.annotation.Autowired;
30 import org.springframework.beans.factory.annotation.Value;
31 import org.springframework.stereotype.Component;
32
33 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.buildFatalFailure;
34 import static org.slf4j.LoggerFactory.getLogger;
35 import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
36 import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
37
38 /**
39  * Responsible for providing a token to access CBAM APIs
40  */
41 @Component
42 //even if the value for grant type an user password is the same they do not mean the same thing
43 //the duplication of this is intentional
44 @SuppressWarnings("squid:S1192")
45 public class CbamTokenProvider extends CbamSecurityProvider {
46     public static final int MAX_RETRY_COUNT = 5;
47     public static final String GRANT_TYPE = "password";
48     public static final String CLIENT_SECRET = "password";
49     private static final String CBAM_TOKEN_URL = "realms/cbam/protocol/openid-connect/token";
50     private static Logger logger = getLogger(CbamTokenProvider.class);
51     private final VnfmInfoProvider vnfmInfoProvider;
52     @Value("${cbamKeyCloakBaseUrl}")
53     private String cbamKeyCloakBaseUrl;
54     @Value("${cbamUsername}")
55     private String username;
56     @Value("${cbamPassword}")
57     private String password;
58     private volatile CurrentToken token;
59
60     @Autowired
61     CbamTokenProvider(VnfmInfoProvider vnfmInfoProvider) {
62         this.vnfmInfoProvider = vnfmInfoProvider;
63     }
64
65     /**
66      * @return the token to access CBAM APIs (ex. 123456)
67      */
68     public Interceptor getToken(String vnfmId) {
69         VnfmInfo vnfmInfo = vnfmInfoProvider.getVnfmInfo(vnfmId);
70         return new OauthInterceptor(getToken(vnfmInfo.getUserName(), vnfmInfo.getPassword()));
71     }
72
73     private String getToken(String clientId, String clientSecret) {
74         logger.trace("Requesting token for accessing CBAM API");
75         synchronized (this) {
76             long now = SystemFunctions.systemFunctions().currentTimeMillis();
77             if (token == null || token.refreshAfter < now) {
78                 if (token == null) {
79                     logger.debug("No token: getting first token");
80                 } else {
81                     logger.debug("Token expired {} ms ago", (now - token.refreshAfter));
82                 }
83                 refresh(clientId, clientSecret);
84             } else {
85                 logger.debug("Token will expire in {} ms", (now - token.refreshAfter));
86             }
87         }
88         return token.token.accessToken;
89     }
90
91     private void refresh(String clientId, String clientSecret) {
92         FormBody body = new FormBody.Builder()
93                 .add("grant_type", GRANT_TYPE)
94                 .add("client_id", clientId)
95                 .add("client_secret", clientSecret)
96                 .add("username", username)
97                 .add(CLIENT_SECRET, password).build();
98         Request request = new Request.Builder().url(cbamKeyCloakBaseUrl + CBAM_TOKEN_URL).addHeader(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE).post(body).build();
99         OkHttpClient.Builder builder = new OkHttpClient.Builder();
100         SSLSocketFactory sslSocketFac = buildSSLSocketFactory();
101         HostnameVerifier hostnameVerifier = buildHostnameVerifier();
102         OkHttpClient client = builder.sslSocketFactory(sslSocketFac).hostnameVerifier(hostnameVerifier).build();
103         Exception lastException = null;
104         for (int i = 0; i < MAX_RETRY_COUNT; i++) {
105             try {
106                 Response response = execute(client.newCall(request));
107                 if (response.isSuccessful()) {
108                     String json = response.body().string();
109                     TokenResponse tokenResponse = new Gson().fromJson(json, TokenResponse.class);
110                     //token is scheduled to be refreshed in the half time before expiring
111                     token = new CurrentToken(tokenResponse, getTokenRefreshTime(tokenResponse));
112                     return;
113                 } else {
114                     throw buildFatalFailure(logger, "Bad response from CBAM KeyStone");
115                 }
116             } catch (Exception e) {
117                 lastException = e;
118                 logger.warn("Unable to get token to access CBAM API (" + (i + 1) + "/" + MAX_RETRY_COUNT + ")", e);
119             }
120         }
121         throw buildFatalFailure(logger, "Unable to get token to access CBAM API (giving up retries)", lastException);
122     }
123
124     @VisibleForTesting
125     Response execute(Call call) throws IOException {
126         return call.execute();
127     }
128
129     /**
130      * - a new token is requested after the half of the time has expired till which the currently
131      * used token is valid
132      *
133      * @param token the currently held token
134      * @return the point in time after which a new token must be requested
135      */
136     private long getTokenRefreshTime(TokenResponse token) {
137         return SystemFunctions.systemFunctions().currentTimeMillis() + token.expiresIn * (1000 / 2);
138     }
139
140     private static class OauthInterceptor implements Interceptor {
141         private final String token;
142
143         OauthInterceptor(String token) {
144             this.token = token;
145         }
146
147         @Override
148         public Response intercept(Chain chain) throws IOException {
149             Request request = chain.request();
150             Request.Builder builder = request.newBuilder();
151             builder.addHeader("Authorization", "Bearer " + token);
152             Request request1 = builder.build();
153             return chain.proceed(request1);
154         }
155     }
156
157     private static class CurrentToken {
158         private final TokenResponse token;
159         private final long refreshAfter;
160
161         CurrentToken(TokenResponse token, long refreshAfter) {
162             this.refreshAfter = refreshAfter;
163             this.token = token;
164         }
165     }
166
167     /**
168      * Represents the token received from CBAM
169      */
170     private static class TokenResponse {
171         @SerializedName("access_token")
172         String accessToken;
173         @SerializedName("expires_in")
174         int expiresIn;
175         @SerializedName("id_token")
176         String tokenId;
177         @SerializedName("not-before-policy")
178         int notBeforePolicy;
179         @SerializedName("refresh_expires_in")
180         int refreshExpiresIn;
181         @SerializedName("refresh_token")
182         String refreshToken;
183         @SerializedName("session_state")
184         String sessionState;
185         @SerializedName("token_type")
186         String tokenType;
187     }
188 }