-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathSFConnectionConfigParser.java
More file actions
232 lines (214 loc) · 10.3 KB
/
SFConnectionConfigParser.java
File metadata and controls
232 lines (214 loc) · 10.3 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package net.snowflake.client.config;
import static net.snowflake.client.jdbc.SnowflakeUtil.convertSystemGetEnvToBooleanValue;
import static net.snowflake.client.jdbc.SnowflakeUtil.isNullOrEmpty;
import static net.snowflake.client.jdbc.SnowflakeUtil.isWindows;
import static net.snowflake.client.jdbc.SnowflakeUtil.systemGetEnv;
import com.fasterxml.jackson.dataformat.toml.TomlMapper;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import net.snowflake.client.core.SnowflakeJdbcInternalApi;
import net.snowflake.client.jdbc.SnowflakeSQLException;
import net.snowflake.client.log.SFLogger;
import net.snowflake.client.log.SFLoggerFactory;
@SnowflakeJdbcInternalApi
public class SFConnectionConfigParser {
private static final SFLogger logger = SFLoggerFactory.getLogger(SFConnectionConfigParser.class);
private static final TomlMapper mapper = new TomlMapper();
public static final String SNOWFLAKE_HOME_KEY = "SNOWFLAKE_HOME";
public static final String SNOWFLAKE_DIR = ".snowflake";
public static final String SNOWFLAKE_DEFAULT_CONNECTION_NAME_KEY =
"SNOWFLAKE_DEFAULT_CONNECTION_NAME";
public static final String DEFAULT = "default";
public static final String SNOWFLAKE_TOKEN_FILE_PATH = "/snowflake/session/token";
public static final String SKIP_TOKEN_FILE_PERMISSIONS_VERIFICATION =
"SKIP_TOKEN_FILE_PERMISSIONS_VERIFICATION";
public static final String SF_SKIP_WARNING_FOR_READ_PERMISSIONS_ON_CONFIG_FILE =
"SF_SKIP_WARNING_FOR_READ_PERMISSIONS_ON_CONFIG_FILE";
private static final List<PosixFilePermission> REQUIRED_PERMISSIONS =
Arrays.asList(PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_READ);
public static ConnectionParameters buildConnectionParameters() throws SnowflakeSQLException {
String defaultConnectionName =
Optional.ofNullable(systemGetEnv(SNOWFLAKE_DEFAULT_CONNECTION_NAME_KEY)).orElse(DEFAULT);
Map<String, String> fileConnectionConfiguration =
loadDefaultConnectionConfiguration(defaultConnectionName);
if (fileConnectionConfiguration != null && !fileConnectionConfiguration.isEmpty()) {
Properties connectionProperties = new Properties();
connectionProperties.putAll(fileConnectionConfiguration);
String url = createUrl(fileConnectionConfiguration);
logger.debug("Url created using parameters from connection configuration file: {}", url);
if ("oauth".equals(fileConnectionConfiguration.get("authenticator"))
&& fileConnectionConfiguration.get("token") == null) {
Path path =
Paths.get(
Optional.ofNullable(fileConnectionConfiguration.get("token_file_path"))
.orElse(SNOWFLAKE_TOKEN_FILE_PATH));
logger.debug("Token used in connect is read from file: {}", path);
try {
boolean shouldSkipTokenFilePermissionsVerification =
convertSystemGetEnvToBooleanValue(SKIP_TOKEN_FILE_PERMISSIONS_VERIFICATION, false);
if (!shouldSkipTokenFilePermissionsVerification) {
verifyFilePermissionSecure(path);
} else {
logger.debug("Skip token file permissions verification");
}
String token = new String(Files.readAllBytes(path), Charset.defaultCharset());
if (!token.isEmpty()) {
putPropertyIfNotNull(connectionProperties, "token", token.trim());
} else {
throw new SnowflakeSQLException(
"Non-empty token must be set when the authenticator type is OAUTH");
}
} catch (Exception ex) {
throw new SnowflakeSQLException(ex, "There is a problem during reading token from file");
}
}
return new ConnectionParameters(url, connectionProperties);
} else {
return null;
}
}
private static Map<String, String> loadDefaultConnectionConfiguration(
String defaultConnectionName) throws SnowflakeSQLException {
String configDirectory =
Optional.ofNullable(systemGetEnv(SNOWFLAKE_HOME_KEY))
.orElse(Paths.get(System.getProperty("user.home"), SNOWFLAKE_DIR).toString());
Path configFilePath = Paths.get(configDirectory, "connections.toml");
if (Files.exists(configFilePath)) {
logger.debug(
"Reading connection parameters from file using key: {} []",
configFilePath,
defaultConnectionName);
Map<String, Map> parametersMap = readParametersMap(configFilePath);
Map<String, String> defaultConnectionParametersMap = parametersMap.get(defaultConnectionName);
return defaultConnectionParametersMap;
} else {
logger.debug("Connection configuration file does not exist");
return new HashMap<>();
}
}
private static Map<String, Map> readParametersMap(Path configFilePath)
throws SnowflakeSQLException {
try {
File file = new File(configFilePath.toUri());
verifyFilePermissionSecure(configFilePath);
return mapper.readValue(file, Map.class);
} catch (IOException ex) {
throw new SnowflakeSQLException(ex, "Problem during reading a configuration file.");
}
}
static void verifyFilePermissionSecure(Path configFilePath)
throws IOException, SnowflakeSQLException {
final String fileName = "connections.toml";
if (!isWindows()) {
if (configFilePath.getFileName().toString().equals(fileName)) {
boolean shouldSkipWarningForReadPermissions =
convertSystemGetEnvToBooleanValue(
SF_SKIP_WARNING_FOR_READ_PERMISSIONS_ON_CONFIG_FILE, false);
PosixFileAttributeView posixFileAttributeView =
Files.getFileAttributeView(configFilePath, PosixFileAttributeView.class);
Set<PosixFilePermission> permissions =
posixFileAttributeView.readAttributes().permissions();
if (!shouldSkipWarningForReadPermissions) {
boolean groupRead = permissions.contains(PosixFilePermission.GROUP_READ);
boolean othersRead = permissions.contains(PosixFilePermission.OTHERS_READ);
// Warning if readable by group/others (must be 600 or stricter)
if (groupRead || othersRead) {
logger.warn(
"File %s is readable by group or others. Permissions should be 600 or stricter for maximum security.",
configFilePath);
}
}
boolean groupWrite = permissions.contains(PosixFilePermission.GROUP_WRITE);
boolean othersWrite = permissions.contains(PosixFilePermission.OTHERS_WRITE);
// Error if writable by group/others (must be 644 or stricter)
if (groupWrite || othersWrite) {
logger.error(
"File %s is writable by group or others. Permissions must be 644 or stricter.",
configFilePath);
throw new SnowflakeSQLException(
String.format(
"File %s is writable by group or others. Permissions must be 644 or stricter.",
configFilePath));
}
// Error if executable by anyone
boolean ownerExec = permissions.contains(PosixFilePermission.OWNER_EXECUTE);
boolean groupExec = permissions.contains(PosixFilePermission.GROUP_EXECUTE);
boolean othersExec = permissions.contains(PosixFilePermission.OTHERS_EXECUTE);
// Executable permission is not allowed
if (ownerExec || groupExec || othersExec) {
logger.error(
"File %s is executable. Executable permission is not allowed.", configFilePath);
throw new SnowflakeSQLException(
String.format(
"File %s is executable. Executable permission is not allowed.", configFilePath));
}
} else {
PosixFileAttributeView posixFileAttributeView =
Files.getFileAttributeView(configFilePath, PosixFileAttributeView.class);
if (!posixFileAttributeView.readAttributes().permissions().stream()
.allMatch(o -> REQUIRED_PERMISSIONS.contains(o))) {
logger.error(
"Reading from file %s is not safe because file permissions are different than read/write for user",
configFilePath);
throw new SnowflakeSQLException(
String.format(
"Reading from file %s is not safe because file permissions are different than read/write for user",
configFilePath));
}
}
}
}
private static String createUrl(Map<String, String> fileConnectionConfiguration)
throws SnowflakeSQLException {
Optional<String> maybeAccount = Optional.ofNullable(fileConnectionConfiguration.get("account"));
Optional<String> maybeHost = Optional.ofNullable(fileConnectionConfiguration.get("host"));
if (maybeAccount.isPresent()
&& maybeHost.isPresent()
&& !maybeHost.get().contains(maybeAccount.get())) {
logger.warn(
String.format(
"Inconsistent host and account values in file configuration. ACCOUNT: {} , HOST: {}. The host value will be used.",
maybeAccount.get(),
maybeHost.get()));
}
String host =
maybeHost.orElse(
maybeAccount
.map(acnt -> String.format("%s.snowflakecomputing.com", acnt))
.orElse(null));
if (host == null || host.isEmpty()) {
logger.warn("Neither host nor account is specified in connection parameters");
throw new SnowflakeSQLException(
"Unable to connect because neither host nor account is specified in connection parameters");
}
logger.debug("Host created using parameters from connection configuration file: {}", host);
String port = fileConnectionConfiguration.get("port");
String protocol = fileConnectionConfiguration.get("protocol");
if (isNullOrEmpty(port)) {
if ("https".equals(protocol)) {
port = "443";
} else {
port = "80";
}
}
return String.format("jdbc:snowflake://%s:%s", host, port);
}
private static void putPropertyIfNotNull(Properties props, Object key, Object value) {
if (key != null && value != null) {
props.put(key, value);
}
}
}