-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathUtils.java
More file actions
217 lines (199 loc) · 9.61 KB
/
Utils.java
File metadata and controls
217 lines (199 loc) · 9.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package com.skyflow.utils;
import com.google.gson.JsonObject;
import com.skyflow.config.ConnectionConfig;
import com.skyflow.config.Credentials;
import com.skyflow.enums.Env;
import com.skyflow.errors.ErrorCode;
import com.skyflow.errors.ErrorMessage;
import com.skyflow.errors.SkyflowException;
import com.skyflow.logs.ErrorLogs;
import com.skyflow.logs.InfoLogs;
import com.skyflow.serviceaccount.util.BearerToken;
import com.skyflow.utils.logger.LogUtil;
import com.skyflow.vault.connection.InvokeConnectionRequest;
import org.apache.commons.codec.binary.Base64;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public final class Utils {
public static String getVaultURL(String clusterId, Env env) {
StringBuilder sb = new StringBuilder(Constants.SECURE_PROTOCOL);
sb.append(clusterId);
switch (env) {
case DEV:
sb.append(Constants.DEV_DOMAIN);
break;
case STAGE:
sb.append(Constants.STAGE_DOMAIN);
break;
case SANDBOX:
sb.append(Constants.SANDBOX_DOMAIN);
break;
case PROD:
default:
sb.append(Constants.PROD_DOMAIN);
break;
}
return sb.toString();
}
public static String generateBearerToken(Credentials credentials) throws SkyflowException {
if (credentials.getPath() != null) {
return BearerToken.builder()
.setCredentials(new File(credentials.getPath()))
.setRoles(credentials.getRoles())
.setCtx(credentials.getContext())
.build()
.getBearerToken();
} else if (credentials.getCredentialsString() != null) {
return BearerToken.builder()
.setCredentials(credentials.getCredentialsString())
.setRoles(credentials.getRoles())
.setCtx(credentials.getContext())
.build()
.getBearerToken();
} else {
return credentials.getToken();
}
}
public static PrivateKey getPrivateKeyFromPem(String pemKey) throws SkyflowException {
@SuppressWarnings("checkstyle:LocalVariableName")
String PKCS8PrivateHeader = Constants.PKCS8_PRIVATE_HEADER;
@SuppressWarnings("checkstyle:LocalVariableName")
String PKCS8PrivateFooter = Constants.PKCS8_PRIVATE_FOOTER;
String privateKeyContent = pemKey;
PrivateKey privateKey = null;
if (pemKey.contains(PKCS8PrivateHeader)) {
privateKeyContent = privateKeyContent.replace(PKCS8PrivateHeader, Constants.EMPTY_STRING);
privateKeyContent = privateKeyContent.replace(PKCS8PrivateFooter, Constants.EMPTY_STRING);
privateKeyContent = privateKeyContent.replace("\n", Constants.EMPTY_STRING);
privateKeyContent = privateKeyContent.replace("\r\n", Constants.EMPTY_STRING);
privateKey = parsePkcs8PrivateKey(Base64.decodeBase64(privateKeyContent));
} else {
LogUtil.printErrorLog(ErrorLogs.JWT_INVALID_FORMAT.getLog());
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtInvalidFormat.getMessage());
}
return privateKey;
}
public static String getBaseURL(String url) throws MalformedURLException {
URL parsedUrl = new URL(url);
String protocol = parsedUrl.getProtocol();
String host = parsedUrl.getHost();
return String.format(Constants.UrlFormat.PROTOCOL_HOST_FORMAT, protocol, host);
}
public static String parameterizedString(String base, String... args) {
for (int index = 0; index < args.length; index++) {
base = base.replace("%s" + (index + 1), args[index]);
}
return base;
}
public static String constructConnectionURL(ConnectionConfig config, InvokeConnectionRequest invokeConnectionRequest) {
StringBuilder filledURL = new StringBuilder(config.getConnectionUrl());
if (invokeConnectionRequest.getPathParams() != null && !invokeConnectionRequest.getPathParams().isEmpty()) {
for (Map.Entry<String, String> entry : invokeConnectionRequest.getPathParams().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
try {
String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.name());
filledURL = new StringBuilder(filledURL.toString().replace(String.format(Constants.CURLY_PLACEHOLDER, key), encodedValue));
} catch (Exception e) {
filledURL = new StringBuilder(filledURL.toString().replace(String.format(Constants.CURLY_PLACEHOLDER, key), value));
}
}
}
if (invokeConnectionRequest.getQueryParams() != null && !invokeConnectionRequest.getQueryParams().isEmpty()) {
filledURL.append("?");
for (Map.Entry<String, String> entry : invokeConnectionRequest.getQueryParams().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
try {
String encodedKey = URLEncoder.encode(key, StandardCharsets.UTF_8.name());
String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.name());
filledURL.append(encodedKey).append(Constants.HttpUtility.FORM_ENCODE_SEPARATOR).append(encodedValue).append(Constants.HttpUtility.FORM_ENCODE_DELIMITER);
} catch (Exception e) {
filledURL.append(key).append(Constants.HttpUtility.FORM_ENCODE_SEPARATOR).append(value).append(Constants.HttpUtility.FORM_ENCODE_DELIMITER);
}
}
filledURL = new StringBuilder(filledURL.substring(0, filledURL.length() - 1));
}
return filledURL.toString();
}
public static Map<String, String> constructConnectionHeadersMap(Map<String, String> requestHeaders) {
Map<String, String> headersMap = new HashMap<>();
for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
headersMap.put(key.toLowerCase(), value);
}
return headersMap;
}
public static JsonObject getMetrics() {
JsonObject details = new JsonObject();
String sdkVersion = Constants.SDK_VERSION;
String deviceModel;
String osDetails;
String javaVersion;
// Retrieve device model
try {
deviceModel = System.getProperty(Constants.SystemProperty.OS_NAME);
if (deviceModel == null) throw new Exception();
} catch (Exception e) {
LogUtil.printInfoLog(parameterizedString(
InfoLogs.UNABLE_TO_GENERATE_SDK_METRIC.getLog(),
Constants.SDK_METRIC_CLIENT_DEVICE_MODEL
));
deviceModel = Constants.EMPTY_STRING;
}
// Retrieve OS details
try {
osDetails = System.getProperty(Constants.SystemProperty.OS_VERSION);
if (osDetails == null) throw new Exception();
} catch (Exception e) {
LogUtil.printInfoLog(parameterizedString(
InfoLogs.UNABLE_TO_GENERATE_SDK_METRIC.getLog(),
Constants.SDK_METRIC_CLIENT_OS_DETAILS
));
osDetails = Constants.EMPTY_STRING;
}
// Retrieve Java version details
try {
javaVersion = System.getProperty(Constants.SystemProperty.JAVA_VERSION);
if (javaVersion == null) throw new Exception();
} catch (Exception e) {
LogUtil.printInfoLog(parameterizedString(
InfoLogs.UNABLE_TO_GENERATE_SDK_METRIC.getLog(),
Constants.SDK_METRIC_RUNTIME_DETAILS
));
javaVersion = Constants.EMPTY_STRING;
}
details.addProperty(Constants.SDK_METRIC_NAME_VERSION, Constants.SDK_METRIC_NAME_VERSION_PREFIX + sdkVersion);
details.addProperty(Constants.SDK_METRIC_CLIENT_DEVICE_MODEL, deviceModel);
details.addProperty(Constants.SDK_METRIC_RUNTIME_DETAILS, Constants.SDK_METRIC_RUNTIME_DETAILS_PREFIX + javaVersion);
details.addProperty(Constants.SDK_METRIC_CLIENT_OS_DETAILS, osDetails);
return details;
}
private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws SkyflowException {
KeyFactory keyFactory;
PrivateKey privateKey = null;
try {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
keyFactory = KeyFactory.getInstance(Constants.CryptoAlgorithm.RSA);
privateKey = keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
LogUtil.printErrorLog(ErrorLogs.INVALID_ALGORITHM.getLog());
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidAlgorithm.getMessage());
} catch (InvalidKeySpecException e) {
LogUtil.printErrorLog(ErrorLogs.INVALID_KEY_SPEC.getLog());
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidKeySpec.getMessage());
}
return privateKey;
}
}