a6dff6769f711f1c53dca8c23ac510f2c92c7bbe
[ccsdk/features.git] /
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 Config _instance;
48
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         Random random = new Random();
170
171         String generatedString = random.ints(leftLimit, rightLimit + 1)
172                 .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength)
173                 .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
174         return generatedString;
175     }
176
177     /**
178      *
179      * @param key environment var
180      * @param defValue default value if no env var found
181      * @return
182      */
183     public static String getProperty(final String key, final String defValue) {
184         String value = defValue;
185         //try to read env var
186         boolean found = false;
187         if (isEnvExpression(key)) {
188
189             LOG.info("try to find env var(s) for {}", key);
190             final Matcher matcher = pattern.matcher(key);
191             String tmp = new String(key);
192             while (matcher.find() && matcher.groupCount() > 0) {
193                 final String mkey = matcher.group(1);
194                 if (mkey != null) {
195                     try {
196                         LOG.info("match found for v={} and env key={}", key, mkey);
197                         String envvar = mkey.substring(2, mkey.length() - 1);
198                         String env = System.getenv(envvar);
199                         tmp = tmp.replace(mkey, env == null ? "" : env);
200                         if (env != null && env != "") {
201                             found = true;
202                         }
203                     } catch (SecurityException e) {
204                         LOG.warn("unable to read env {}: {}", key, e);
205                     }
206                 }
207             }
208             if (found) {
209                 value = tmp;
210             }
211         }
212         return value;
213     }
214
215     public static boolean getPropertyBoolean(String key, boolean defaultValue) {
216         final String value = getProperty(key, String.valueOf(defaultValue));
217         return value.equals("true");
218     }
219
220     public static Config load(String filename) throws IOException {
221         CustomObjectMapper mapper = new CustomObjectMapper();
222         File file = new File(filename);
223         if (!file.exists()) {
224             throw new FileNotFoundException();
225         }
226         String content = String.join("", Files.readAllLines(file.toPath()));
227         Config cfg = mapper.readValue(content, Config.class);
228         cfg.handleEnvironmentVars();
229         cfg.handleDefaultValues();
230         return cfg;
231     }
232
233
234     @JsonIgnore
235     public boolean doSupportOdlUsers() {
236         return "true".equals(this.supportOdlUsers);
237     }
238
239
240     public static Config getInstance() throws IOException {
241         return getInstance(DEFAULT_CONFIGFILENAME);
242     }
243
244     public static Config getInstance(String filename) throws IOException {
245         if (_instance == null) {
246             _instance = load(filename);
247         }
248         return _instance;
249     }
250
251
252 }