2 * Copyright 2016-2017, Nokia Corporation
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Joiner;
20 import com.google.common.io.BaseEncoding;
21 import com.google.gson.Gson;
22 import com.google.gson.annotations.SerializedName;
24 import org.apache.http.conn.ssl.DefaultHostnameVerifier;
25 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.VnfmInfoProvider;
26 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.StoreLoader;
27 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions;
28 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.UserVisibleError;
29 import org.onap.vnfmdriver.model.VnfmInfo;
30 import org.slf4j.Logger;
31 import org.springframework.beans.factory.annotation.Autowired;
32 import org.springframework.beans.factory.annotation.Value;
33 import org.springframework.stereotype.Component;
34 import org.springframework.util.StringUtils;
36 import javax.net.ssl.*;
37 import java.io.IOException;
38 import java.nio.charset.StandardCharsets;
39 import java.security.*;
40 import java.security.cert.CertificateException;
41 import java.security.cert.X509Certificate;
44 import static java.util.UUID.randomUUID;
45 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.buildFatalFailure;
46 import static org.slf4j.LoggerFactory.getLogger;
47 import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
48 import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
51 * Responsible for providing a token to access CBAM APIs
54 //even if the value for grant type an user password is the same they do not mean the same thing
55 //the duplication of this is intentional
56 @SuppressWarnings("squid:S1192")
57 public class CbamTokenProvider {
58 public static final int MAX_RETRY_COUNT = 5;
59 public static final String GRANT_TYPE = "password";
60 public static final String CLIENT_SECRET = "password";
61 private static final String CBAM_TOKEN_URL = "/realms/cbam/protocol/openid-connect/token";
62 private static Logger logger = getLogger(CbamTokenProvider.class);
63 private final VnfmInfoProvider vnfmInfoProvider;
64 @Value("${cbamKeyCloakBaseUrl}")
65 private String cbamKeyCloakBaseUrl;
66 @Value("${cbamUsername}")
67 private String username;
68 @Value("${cbamPassword}")
69 private String password;
70 @Value("${trustedCertificates}")
71 private String trustedCertificates;
72 @Value("${skipCertificateVerification}")
73 private boolean skipCertificateVerification;
74 @Value("${skipHostnameVerification}")
75 private boolean skipHostnameVerification;
76 private volatile CurrentToken token;
79 CbamTokenProvider(VnfmInfoProvider vnfmInfoProvider) {
80 this.vnfmInfoProvider = vnfmInfoProvider;
84 * @return the token to access CBAM APIs (ex. 123456)
86 public String getToken(String vnfmId) {
87 VnfmInfo vnfmInfo = vnfmInfoProvider.getVnfmInfo(vnfmId);
88 return getToken(vnfmInfo.getUserName(), vnfmInfo.getPassword());
91 private String getToken(String clientId, String clientSecret) {
92 logger.trace("Requesting token for accessing CBAM API");
94 long now = SystemFunctions.systemFunctions().currentTimeMillis();
95 if (token == null || token.refreshAfter < now) {
97 logger.debug("No token: getting first token");
99 logger.debug("Token expired {} ms ago", (now - token.refreshAfter));
101 refresh(clientId, clientSecret);
103 logger.debug("Token will expire in {} ms", (now - token.refreshAfter));
106 return token.token.accessToken;
109 private void refresh(String clientId, String clientSecret) {
110 FormBody body = new FormBody.Builder()
111 .add("grant_type", GRANT_TYPE)
112 .add("client_id", clientId)
113 .add("client_secret", clientSecret)
114 .add("username", username)
115 .add(CLIENT_SECRET, password).build();
116 Request request = new Request.Builder().url(cbamKeyCloakBaseUrl + CBAM_TOKEN_URL).addHeader(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE).post(body).build();
117 OkHttpClient.Builder builder = new OkHttpClient.Builder();
118 SSLSocketFactory sslSocketFac = buildSSLSocketFactory();
119 HostnameVerifier hostnameVerifier = buildHostnameVerifier();
120 OkHttpClient client = builder.sslSocketFactory(sslSocketFac).hostnameVerifier(hostnameVerifier).build();
121 Exception lastException = null;
122 for (int i = 0; i < MAX_RETRY_COUNT; i++) {
124 Response response = execute(client.newCall(request));
125 if (response.isSuccessful()) {
126 String json = response.body().string();
127 TokenResponse tokenResponse = new Gson().fromJson(json, TokenResponse.class);
128 //token is scheduled to be refreshed in the half time before expiring
129 token = new CurrentToken(tokenResponse, getTokenRefreshTime(tokenResponse));
132 throw buildFatalFailure(logger, "Bad response from CBAM KeyStone");
134 } catch (Exception e) {
136 logger.warn("Unable to get token to access CBAM API (" + (i + 1) + "/" + MAX_RETRY_COUNT + ")", e);
139 throw buildFatalFailure(logger, "Unable to get token to access CBAM API (giving up retries)", lastException);
143 Response execute(Call call) throws IOException {
144 return call.execute();
148 * - a new token is requested after the half of the time has expired till which the currently
149 * used token is valid
151 * @param token the currently held token
152 * @return the point in time after which a new token must be requested
154 private long getTokenRefreshTime(TokenResponse token) {
155 return SystemFunctions.systemFunctions().currentTimeMillis() + token.expiresIn * (1000 / 2);
158 private HostnameVerifier buildHostnameVerifier() {
159 if (skipHostnameVerification) {
160 return (hostname, session) -> true;
162 return new DefaultHostnameVerifier();
167 SSLSocketFactory buildSSLSocketFactory() {
169 TrustManager[] trustManagers = buildTrustManager();
170 SSLContext sslContext = SSLContext.getInstance("TLS");
171 sslContext.init(null, trustManagers, new SecureRandom());
172 return sslContext.getSocketFactory();
173 } catch (GeneralSecurityException e) {
174 throw buildFatalFailure(logger, "Unable to create SSL socket factory", e);
179 TrustManager[] buildTrustManager() throws KeyStoreException, NoSuchAlgorithmException {
180 if (skipCertificateVerification) {
181 return new TrustManager[]{new AllTrustedTrustManager()};
183 if (StringUtils.isEmpty(trustedCertificates)) {
184 throw new IllegalArgumentException("If the skipCertificateVerification is set to false (default) the trustedCertificates can not be empty");
186 Set<String> trustedPems;
188 trustedPems = StoreLoader.getCertifacates(new String(BaseEncoding.base64().decode(trustedCertificates), StandardCharsets.UTF_8));
189 } catch (Exception e) {
190 throw new UserVisibleError("The trustedCertificates must be a base64 encoded collection of PEM certificates", e);
192 KeyStore keyStore = StoreLoader.loadStore(Joiner.on("\n").join(trustedPems), randomUUID().toString(), randomUUID().toString());
193 TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
194 trustManagerFactory.init(keyStore);
195 return trustManagerFactory.getTrustManagers();
200 private static class CurrentToken {
201 private final TokenResponse token;
202 private final long refreshAfter;
204 CurrentToken(TokenResponse token, long refreshAfter) {
205 this.refreshAfter = refreshAfter;
210 static class AllTrustedTrustManager implements X509TrustManager {
212 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
213 //no need to check certificates if everything is trusted
217 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
218 //no need to check certificates if everything is trusted
222 public X509Certificate[] getAcceptedIssuers() {
223 return new X509Certificate[0];
228 * Represents the token received from CBAM
230 private static class TokenResponse {
231 @SerializedName("access_token")
233 @SerializedName("expires_in")
235 @SerializedName("id_token")
237 @SerializedName("not-before-policy")
239 @SerializedName("refresh_expires_in")
240 int refreshExpiresIn;
241 @SerializedName("refresh_token")
243 @SerializedName("session_state")
245 @SerializedName("token_type")