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.fatalFailure;
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 public class CbamTokenProvider {
55 public static final int MAX_RETRY_COUNT = 5;
56 public static final String GRANT_TYPE = "password";
57 public static final String CLIENT_SECRET = "password";
58 private static final String CBAM_TOKEN_URL = "/realms/cbam/protocol/openid-connect/token";
59 private static Logger logger = getLogger(CbamTokenProvider.class);
60 private final VnfmInfoProvider vnfmInfoProvider;
61 @Value("${cbamKeyCloakBaseUrl}")
62 private String cbamKeyCloakBaseUrl;
63 @Value("${cbamUsername}")
64 private String username;
65 @Value("${cbamPassword}")
66 private String password;
67 @Value("${trustedCertificates}")
68 private String trustedCertificates;
69 @Value("${skipCertificateVerification}")
70 private boolean skipCertificateVerification;
71 @Value("${skipHostnameVerification}")
72 private boolean skipHostnameVerification;
73 private volatile CurrentToken token;
76 CbamTokenProvider(VnfmInfoProvider vnfmInfoProvider) {
77 this.vnfmInfoProvider = vnfmInfoProvider;
81 * @return the token to access CBAM APIs (ex. 123456)
83 public String getToken(String vnfmId) {
84 VnfmInfo vnfmInfo = vnfmInfoProvider.getVnfmInfo(vnfmId);
85 return getToken(vnfmInfo.getUserName(), vnfmInfo.getPassword());
88 private String getToken(String clientId, String clientSecret) {
89 logger.trace("Requesting token for accessing CBAM API");
91 long now = SystemFunctions.systemFunctions().currentTimeMillis();
92 if (token == null || token.refreshAfter < now) {
94 logger.debug("No token: getting first token");
96 logger.debug("Token expired {} ms ago", (now - token.refreshAfter));
98 refresh(clientId, clientSecret);
100 logger.debug("Token will expire in {} ms", (now - token.refreshAfter));
103 return token.token.accessToken;
106 private void refresh(String clientId, String clientSecret) {
107 FormBody body = new FormBody.Builder()
108 .add("grant_type", GRANT_TYPE)
109 .add("client_id", clientId)
110 .add("client_secret", clientSecret)
111 .add("username", username)
112 .add(CLIENT_SECRET, password).build();
113 Request request = new Request.Builder().url(cbamKeyCloakBaseUrl + CBAM_TOKEN_URL).addHeader(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE).post(body).build();
114 OkHttpClient.Builder builder = new OkHttpClient.Builder();
115 SSLSocketFactory sslSocketFac = buildSSLSocketFactory();
116 HostnameVerifier hostnameVerifier = buildHostnameVerifier();
117 OkHttpClient client = builder.sslSocketFactory(sslSocketFac).hostnameVerifier(hostnameVerifier).build();
118 Exception lastException = null;
119 for (int i = 0; i < MAX_RETRY_COUNT; i++) {
121 Response response = execute(client.newCall(request));
122 if (response.isSuccessful()) {
123 String json = response.body().string();
124 TokenResponse tokenResponse = new Gson().fromJson(json, TokenResponse.class);
125 //token is scheduled to be refreshed in the half time before expiring
126 token = new CurrentToken(tokenResponse, getTokenRefreshTime(tokenResponse));
129 fatalFailure(logger, "Bad response from CBAM KeyStone");
131 } catch (Exception e) {
133 logger.warn("Unable to get token to access CBAM API (" + (i + 1) + "/" + MAX_RETRY_COUNT + ")", e);
136 throw fatalFailure(logger, "Unable to get token to access CBAM API (giving up retries)", lastException);
140 Response execute(Call call) throws IOException {
141 return call.execute();
145 * - a new token is requested after the half of the time has expired till which the currently
146 * used token is valid
148 * @param token the currently held token
149 * @return the point in time after which a new token must be requested
151 private long getTokenRefreshTime(TokenResponse token) {
152 return SystemFunctions.systemFunctions().currentTimeMillis() + token.expiresIn * (1000 / 2);
155 private HostnameVerifier buildHostnameVerifier() {
156 if (skipHostnameVerification) {
157 return (hostname, session) -> true;
159 return new DefaultHostnameVerifier();
164 SSLSocketFactory buildSSLSocketFactory() {
166 TrustManager[] trustManagers = buildTrustManager();
167 SSLContext sslContext = SSLContext.getInstance("TLS");
168 sslContext.init(null, trustManagers, new SecureRandom());
169 return sslContext.getSocketFactory();
170 } catch (GeneralSecurityException e) {
171 throw fatalFailure(logger, "Unable to create SSL socket factory", e);
176 TrustManager[] buildTrustManager() throws KeyStoreException, NoSuchAlgorithmException {
177 if (skipCertificateVerification) {
178 return new TrustManager[]{new AllTrustedTrustManager()};
180 if (StringUtils.isEmpty(trustedCertificates)) {
181 throw new IllegalArgumentException("If the skipCertificateVerification is set to false (default) the trustedCertificates can not be empty");
183 Set<String> trustedPems;
185 trustedPems = StoreLoader.getCertifacates(new String(BaseEncoding.base64().decode(trustedCertificates), StandardCharsets.UTF_8));
186 } catch (Exception e) {
187 throw new UserVisibleError("The trustedCertificates must be a base64 encoded collection of PEM certificates", e);
189 KeyStore keyStore = StoreLoader.loadStore(Joiner.on("\n").join(trustedPems), randomUUID().toString(), randomUUID().toString());
190 TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
191 trustManagerFactory.init(keyStore);
192 return trustManagerFactory.getTrustManagers();
197 private static class CurrentToken {
198 private final TokenResponse token;
199 private final long refreshAfter;
201 CurrentToken(TokenResponse token, long refreshAfter) {
202 this.refreshAfter = refreshAfter;
207 static class AllTrustedTrustManager implements X509TrustManager {
209 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
210 //no need to check certificates if everything is trusted
214 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
215 //no need to check certificates if everything is trusted
219 public X509Certificate[] getAcceptedIssuers() {
220 return new X509Certificate[0];
225 * Represents the token received from CBAM
227 private static class TokenResponse {
228 @SerializedName("access_token")
230 @SerializedName("expires_in")
232 @SerializedName("id_token")
234 @SerializedName("not-before-policy")
236 @SerializedName("refresh_expires_in")
237 int refreshExpiresIn;
238 @SerializedName("refresh_token")
240 @SerializedName("session_state")
242 @SerializedName("token_type")