6eec667481670a6aa6cd923430ed3331b3831c6d
[dcaegen2/services/sdk.git] /
1 /*
2  * ============LICENSE_START====================================
3  * DCAEGEN2-SERVICES-SDK
4  * =========================================================
5  * Copyright (C) 2019-2021 Nokia. All rights reserved.
6  * Copyright (C) 2021 Wipro Limited.
7  * =========================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=====================================
20  */
21
22 package org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model;
23
24 import org.immutables.value.Value;
25 import org.jetbrains.annotations.Nullable;
26 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.exceptions.CbsClientConfigurationException;
27 import org.onap.dcaegen2.services.sdk.security.ssl.ImmutableTrustStoreKeys;
28 import org.onap.dcaegen2.services.sdk.security.ssl.Passwords;
29 import org.onap.dcaegen2.services.sdk.security.ssl.SecurityKeysStore;
30 import org.onap.dcaegen2.services.sdk.security.ssl.TrustStoreKeys;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import java.nio.file.Files;
35 import java.nio.file.Paths;
36 import java.util.Optional;
37
38 /**
39  * Immutable object which helps with construction of cloudRequestObject for specified Client. For usage take a look in
40  * CloudConfigurationClient.class
41  *
42  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 11/16/18
43  * @version 1.0.0 can be passed to ReactiveCloudConfigurationProvider, can be constructed out of
44  * org.onap.dcaegen2.services.sdk library.
45  * @since 1.0.0
46  */
47 @Value.Immutable(prehash = true)
48 public interface CbsClientConfiguration {
49     Logger LOGGER = LoggerFactory.getLogger(CbsClientConfiguration.class);
50
51     String TRUST_JKS = "trust.jks";
52     String TRUST_PASS = "trust.pass";
53     Integer PORT_FOR_CBS_OVER_TLS = 10443;
54
55     /**
56      * Name of environment variable containing path to the cacert.pem file.
57      */
58     String DCAE_CA_CERT_PATH = "DCAE_CA_CERTPATH";
59
60     /**
61      * Name of environment variable containing Config Binding Service network hostname.
62      */
63     String ENV_CBS_HOSTNAME = "CONFIG_BINDING_SERVICE";
64
65     /**
66      * Name of environment variable containing Config Binding Service network port.
67      */
68     String ENV_CBS_PORT = "CONFIG_BINDING_SERVICE_SERVICE_PORT";
69
70     /**
71      * Name of environment variable containing current application name.
72      */
73     String ENV_APP_NAME = "HOSTNAME";
74
75     /**
76      * Name of environment variable containing path to application config file.
77      */
78     String ENV_CBS_CLIENT_CONFIG_PATH = "CBS_CLIENT_CONFIG_PATH";
79
80     /**
81      * Name of environment variable containing path to policies file.
82      */
83     String ENV_CBS_CLIENT_POLICY_PATH = "CBS_CLIENT_POLICY_PATH";
84
85     /**
86      * Name of environment variable containing Consul host name.
87      *
88      * @deprecated CBS lookup in Consul service should not be needed,
89      * instead {@link #ENV_CBS_HOSTNAME} should be used directly.
90      */
91     @Deprecated
92     String ENV_CONSUL_HOST = "CONSUL_HOST";
93
94     /**
95      * Name of environment variable containing Config Binding Service <em>service name</em> as registered in Consul
96      * services API.
97      *
98      * @deprecated CBS lookup in Consul service should not be needed,
99      * instead {@link #ENV_CBS_HOSTNAME} should be used directly.
100      */
101     @Deprecated
102     String ENV_CBS_NAME = "CONFIG_BINDING_SERVICE";
103
104     @Value.Parameter
105     @Nullable
106     String hostname();
107
108     @Value.Parameter
109     @Nullable
110     Integer port();
111
112     @Value.Parameter
113     String appName();
114
115     @Value.Parameter
116     @Nullable
117     String protocol();
118
119     @Value.Default
120     default @Nullable TrustStoreKeys trustStoreKeys() {
121         return null;
122     }
123
124     @Value.Default
125     @Deprecated
126     default String consulHost() {
127         return "consul-server";
128     }
129     @Value.Default
130     @Deprecated
131     default Integer consulPort() {
132         return 8500;
133     }
134     @Value.Default
135     @Deprecated
136     default String cbsName() {
137         return "config-binding-service";
138     }
139     @Value.Default
140     default String configMapFilePath() {
141         return "/app-config/application_config.yaml";
142     }
143     @Value.Default
144     default String policySyncFilePath() {
145         return "/etc/policies/policies.json";
146     }
147
148     /**
149      * Creates CbsClientConfiguration from system environment variables.
150      *
151      * @return an instance of CbsClientConfiguration
152      * @throws CbsClientConfigurationException when at least one of required parameters is missing
153      */
154     static CbsClientConfiguration fromEnvironment() {
155         String pathToCaCert = System.getenv(DCAE_CA_CERT_PATH);
156
157         ImmutableCbsClientConfiguration.Builder configBuilder = ImmutableCbsClientConfiguration.builder()
158                 .hostname(getEnv(ENV_CBS_HOSTNAME))
159                 .appName(getEnv(ENV_APP_NAME));
160
161         Optional.ofNullable(System.getenv(ENV_CBS_CLIENT_CONFIG_PATH))
162             .ifPresent(configBuilder::configMapFilePath);
163
164         Optional.ofNullable(System.getenv(ENV_CBS_CLIENT_POLICY_PATH))
165             .ifPresent(configBuilder::policySyncFilePath);
166
167         return Optional.ofNullable(pathToCaCert).filter(certPath -> !"".equals(certPath))
168                 .map(certPath -> createSslHttpConfig(configBuilder, certPath))
169                 .orElseGet(() -> createPlainHttpConfig(configBuilder));
170     }
171
172     static CbsClientConfiguration createPlainHttpConfig(ImmutableCbsClientConfiguration.Builder configBuilder) {
173         LOGGER.info("CBS client will use plain http protocol.");
174         return configBuilder
175                 .protocol("http")
176                 .port(Integer.valueOf(getEnv(ENV_CBS_PORT)))
177                 .build();
178     }
179
180     static CbsClientConfiguration createSslHttpConfig(ImmutableCbsClientConfiguration.Builder configBuilder,
181                                                       String pathToCaCert) {
182         LOGGER.info("CBS client will use http over TLS.");
183         return configBuilder
184                 .trustStoreKeys(crateSecurityKeysFromEnvironment(createPathToJksFile(pathToCaCert)))
185                 .port(PORT_FOR_CBS_OVER_TLS)
186                 .protocol("https")
187                 .build();
188     }
189
190     static TrustStoreKeys crateSecurityKeysFromEnvironment(String pathToCerts) {
191         LOGGER.info("Path to cert files: {}", pathToCerts + "/");
192         validateIfFilesExist(pathToCerts);
193         return ImmutableTrustStoreKeys.builder()
194                 .trustStore(SecurityKeysStore.fromPath(Paths.get(pathToCerts + "/" + TRUST_JKS)))
195                 .trustStorePassword(Passwords.fromPath(Paths.get(pathToCerts + "/" + TRUST_PASS)))
196                 .build();
197     }
198
199     static String createPathToJksFile(String pathToCaCertPemFile) {
200         return pathToCaCertPemFile.substring(0, pathToCaCertPemFile.lastIndexOf("/"));
201     }
202
203     static String getEnv(String envName) {
204         String envValue = System.getenv(envName);
205         validateEnv(envName, envValue);
206         return envValue;
207     }
208
209     static void validateEnv(String envName, String envValue) {
210         if (envValue == null || "".equals(envValue)) {
211             throw new CbsClientConfigurationException("Cannot read " + envName + " from environment.");
212         }
213     }
214
215     static void validateIfFilesExist(String pathToFile) {
216         boolean areFilesExist = Files.exists(Paths.get(pathToFile + "/" + TRUST_JKS)) &&
217                 Files.exists(Paths.get(pathToFile + "/" + TRUST_PASS));
218
219         if (!areFilesExist) {
220             throw new CbsClientConfigurationException("Required files do not exist in " + pathToFile + " directory.");
221         }
222     }
223 }