fix some sdnr sonar bugs
[ccsdk/features.git] / sdnr / wt / oauth-provider / provider-jar / src / main / java / org / onap / ccsdk / features / sdnr / wt / oauthprovider / data / Config.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
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.ccsdk.features.sdnr.wt.oauthprovider.data;
23
24 import com.fasterxml.jackson.annotation.JsonIgnore;
25 import java.io.File;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.nio.file.Files;
29 import java.util.List;
30 import java.util.Random;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 public class Config {
37
38     private static final Logger LOG = LoggerFactory.getLogger(Config.class);
39     private static final String DEFAULT_CONFIGFILENAME = "etc/oauth-provider.config.json";
40     private static final String ENVVARIABLE = "${";
41     private static final String REGEXENVVARIABLE = "(\\$\\{[A-Z0-9_-]+\\})";
42     private static final Pattern pattern = Pattern.compile(REGEXENVVARIABLE);
43     private static final String DEFAULT_TOKENISSUER = "Opendaylight";
44     private static final String DEFAULT_TOKENSECRET = generateSecret();
45     private static final String DEFAULT_REDIRECTURI = "/odlux/index.html#/oauth?token=";
46     private static final String DEFAULT_SUPPORTODLUSERS = "true";
47     private static Random random;
48     private static Config _instance;
49
50     private List<OAuthProviderConfig> providers;
51     private String redirectUri;
52     private String supportOdlUsers;
53     private String tokenSecret;
54     private String tokenIssuer;
55     private String publicUrl;
56
57
58     @Override
59     public String toString() {
60         return "Config [providers=" + providers + ", redirectUri=" + redirectUri + ", supportOdlUsers="
61                 + supportOdlUsers + ", tokenSecret=" + tokenSecret + ", tokenIssuer=" + tokenIssuer + "]";
62     }
63
64
65
66     public List<OAuthProviderConfig> getProviders() {
67         return providers;
68     }
69
70     public void setProviders(List<OAuthProviderConfig> providers) {
71         this.providers = providers;
72     }
73
74     public String getRedirectUri() {
75         return redirectUri;
76     }
77
78     public void setRedirectUri(String redirectUri) {
79         this.redirectUri = redirectUri;
80     }
81
82     public String getSupportOdlUsers() {
83         return supportOdlUsers;
84     }
85
86     public void setSupportOdlUsers(String supportOdlUsers) {
87         this.supportOdlUsers = supportOdlUsers;
88     }
89
90     public String getTokenSecret() {
91         return tokenSecret;
92     }
93
94     public void setTokenSecret(String tokenSecret) {
95         this.tokenSecret = tokenSecret;
96     }
97
98     public String getTokenIssuer() {
99         return tokenIssuer;
100     }
101
102     public void setTokenIssuer(String tokenIssuer) {
103         this.tokenIssuer = tokenIssuer;
104     }
105
106
107     public String getPublicUrl() {
108         return publicUrl;
109     }
110
111     public void setPublicUrl(String publicUrl) {
112         this.publicUrl = publicUrl;
113     }
114
115     @JsonIgnore
116     private void handleEnvironmentVars() {
117         if (isEnvExpression(tokenIssuer)) {
118             this.tokenIssuer = getProperty(tokenIssuer, null);
119         }
120         if (isEnvExpression(tokenSecret)) {
121             this.tokenSecret = getProperty(tokenSecret, null);
122         }
123         if (isEnvExpression(publicUrl)) {
124             this.publicUrl = getProperty(publicUrl, null);
125         }
126         if (isEnvExpression(redirectUri)) {
127             this.redirectUri = getProperty(redirectUri, null);
128         }
129         if (isEnvExpression(supportOdlUsers)) {
130             this.supportOdlUsers = getProperty(supportOdlUsers, null);
131         }
132         if (this.providers != null && !this.providers.isEmpty()) {
133             for(OAuthProviderConfig cfg : this.providers) {
134                 cfg.handleEnvironmentVars();
135             }
136         }
137     }
138
139     @JsonIgnore
140     private void handleDefaultValues() {
141         if (tokenIssuer == null || tokenIssuer.isEmpty()) {
142             this.tokenIssuer = DEFAULT_TOKENISSUER;
143         }
144         if (tokenSecret == null || tokenSecret.isEmpty()) {
145             this.tokenSecret = DEFAULT_TOKENSECRET;
146         }
147         if (redirectUri == null || redirectUri.isEmpty() || "null".equals(redirectUri)) {
148             this.redirectUri = DEFAULT_REDIRECTURI;
149         }
150         if (publicUrl != null && (publicUrl.isEmpty() || "null".equals(publicUrl))) {
151             this.publicUrl = null;
152         }
153         if (supportOdlUsers == null || supportOdlUsers.isEmpty()) {
154             this.supportOdlUsers = DEFAULT_SUPPORTODLUSERS;
155         }
156     }
157
158     static boolean isEnvExpression(String key) {
159         return key != null && key.contains(ENVVARIABLE);
160     }
161
162     public static String generateSecret() {
163         return generateSecret(30);
164     }
165
166     public static String generateSecret(int targetStringLength) {
167         int leftLimit = 48; // numeral '0'
168         int rightLimit = 122; // letter 'z'
169         if(random==null) {
170             random = new Random();
171         }
172         String generatedString = random.ints(leftLimit, rightLimit + 1)
173                 .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength)
174                 .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
175         return generatedString;
176     }
177
178     /**
179      *
180      * @param key environment var
181      * @param defValue default value if no env var found
182      * @return
183      */
184     public static String getProperty(final String key, final String defValue) {
185         String value = defValue;
186         //try to read env var
187         boolean found = false;
188         if (isEnvExpression(key)) {
189
190             LOG.info("try to find env var(s) for {}", key);
191             final Matcher matcher = pattern.matcher(key);
192             String tmp = new String(key);
193             while (matcher.find() && matcher.groupCount() > 0) {
194                 final String mkey = matcher.group(1);
195                 if (mkey != null) {
196                     try {
197                         LOG.info("match found for v={} and env key={}", key, mkey);
198                         String envvar = mkey.substring(2, mkey.length() - 1);
199                         String env = System.getenv(envvar);
200                         tmp = tmp.replace(mkey, env == null ? "" : env);
201                         if (env != null && env.isEmpty()) {
202                             found = true;
203                         }
204                     } catch (SecurityException e) {
205                         LOG.warn("unable to read env {}: {}", key, e);
206                     }
207                 }
208             }
209             if (found) {
210                 value = tmp;
211             }
212         }
213         return value;
214     }
215
216     public static boolean getPropertyBoolean(String key, boolean defaultValue) {
217         final String value = getProperty(key, String.valueOf(defaultValue));
218         return value.equals("true");
219     }
220
221     public static Config load(String filename) throws IOException {
222         CustomObjectMapper mapper = new CustomObjectMapper();
223         File file = new File(filename);
224         if (!file.exists()) {
225             throw new FileNotFoundException();
226         }
227         String content = String.join("", Files.readAllLines(file.toPath()));
228         Config cfg = mapper.readValue(content, Config.class);
229         cfg.handleEnvironmentVars();
230         cfg.handleDefaultValues();
231         return cfg;
232     }
233
234
235     @JsonIgnore
236     public boolean doSupportOdlUsers() {
237         return "true".equals(this.supportOdlUsers);
238     }
239
240
241     public static Config getInstance() throws IOException {
242         return getInstance(DEFAULT_CONFIGFILENAME);
243     }
244
245     public static Config getInstance(String filename) throws IOException {
246         if (_instance == null) {
247             _instance = load(filename);
248         }
249         return _instance;
250     }
251
252
253 }