e32ee6b03433e41df7e88940470c2b8c384eff28
[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.common.base.Joiner;
20 import com.google.common.io.BaseEncoding;
21 import com.google.gson.Gson;
22 import com.google.gson.annotations.SerializedName;
23 import okhttp3.*;
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;
35
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;
42 import java.util.Set;
43
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;
49
50 /**
51  * Responsible for providing a token to access CBAM APIs
52  */
53 @Component
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;
74
75     @Autowired
76     CbamTokenProvider(VnfmInfoProvider vnfmInfoProvider) {
77         this.vnfmInfoProvider = vnfmInfoProvider;
78     }
79
80     /**
81      * @return the token to access CBAM APIs (ex. 123456)
82      */
83     public String getToken(String vnfmId) {
84         VnfmInfo vnfmInfo = vnfmInfoProvider.getVnfmInfo(vnfmId);
85         return getToken(vnfmInfo.getUserName(), vnfmInfo.getPassword());
86     }
87
88     private String getToken(String clientId, String clientSecret) {
89         logger.trace("Requesting token for accessing CBAM API");
90         synchronized (this) {
91             long now = SystemFunctions.systemFunctions().currentTimeMillis();
92             if (token == null || token.refreshAfter < now) {
93                 if (token == null) {
94                     logger.debug("No token: getting first token");
95                 } else {
96                     logger.debug("Token expired {} ms ago", (now - token.refreshAfter));
97                 }
98                 refresh(clientId, clientSecret);
99             } else {
100                 logger.debug("Token will expire in {} ms", (now - token.refreshAfter));
101             }
102         }
103         return token.token.accessToken;
104     }
105
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++) {
120             try {
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));
127                     return;
128                 } else {
129                     fatalFailure(logger, "Bad response from CBAM KeyStone");
130                 }
131             } catch (Exception e) {
132                 lastException = e;
133                 logger.warn("Unable to get token to access CBAM API (" + (i + 1) + "/" + MAX_RETRY_COUNT + ")", e);
134             }
135         }
136         throw fatalFailure(logger, "Unable to get token to access CBAM API (giving up retries)", lastException);
137     }
138
139     @VisibleForTesting
140     Response execute(Call call) throws IOException {
141         return call.execute();
142     }
143
144     /**
145      * - a new token is requested after the half of the time has expired till which the currently
146      * used token is valid
147      *
148      * @param token the currently held token
149      * @return the point in time after which a new token must be requested
150      */
151     private long getTokenRefreshTime(TokenResponse token) {
152         return SystemFunctions.systemFunctions().currentTimeMillis() + token.expiresIn * (1000 / 2);
153     }
154
155     private HostnameVerifier buildHostnameVerifier() {
156         if (skipHostnameVerification) {
157             return (hostname, session) -> true;
158         } else {
159             return new DefaultHostnameVerifier();
160         }
161     }
162
163     @VisibleForTesting
164     SSLSocketFactory buildSSLSocketFactory() {
165         try {
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);
172         }
173     }
174
175     @VisibleForTesting
176     TrustManager[] buildTrustManager() throws KeyStoreException, NoSuchAlgorithmException {
177         if (skipCertificateVerification) {
178             return new TrustManager[]{new AllTrustedTrustManager()};
179         } else {
180             if (StringUtils.isEmpty(trustedCertificates)) {
181                 throw new IllegalArgumentException("If the skipCertificateVerification is set to false (default) the trustedCertificates can not be empty");
182             }
183             Set<String> trustedPems;
184             try {
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);
188             }
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();
193
194         }
195     }
196
197     private static class CurrentToken {
198         private final TokenResponse token;
199         private final long refreshAfter;
200
201         CurrentToken(TokenResponse token, long refreshAfter) {
202             this.refreshAfter = refreshAfter;
203             this.token = token;
204         }
205     }
206
207     static class AllTrustedTrustManager implements X509TrustManager {
208         @Override
209         public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
210             //no need to check certificates if everything is trusted
211         }
212
213         @Override
214         public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
215             //no need to check certificates if everything is trusted
216         }
217
218         @Override
219         public X509Certificate[] getAcceptedIssuers() {
220             return new X509Certificate[0];
221         }
222     }
223
224     /**
225      * Represents the token received from CBAM
226      */
227     private static class TokenResponse {
228         @SerializedName("access_token")
229         String accessToken;
230         @SerializedName("expires_in")
231         int expiresIn;
232         @SerializedName("id_token")
233         String tokenId;
234         @SerializedName("not-before-policy")
235         int notBeforePolicy;
236         @SerializedName("refresh_expires_in")
237         int refreshExpiresIn;
238         @SerializedName("refresh_token")
239         String refreshToken;
240         @SerializedName("session_state")
241         String sessionState;
242         @SerializedName("token_type")
243         String tokenType;
244     }
245 }