forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection_configuration_test.go
More file actions
471 lines (394 loc) · 16.6 KB
/
connection_configuration_test.go
File metadata and controls
471 lines (394 loc) · 16.6 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package gosnowflake
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"database/sql"
"fmt"
"io/fs"
"os"
path "path/filepath"
"strconv"
"testing"
"time"
toml "github.com/BurntSushi/toml"
)
func TestTokenFilePermission(t *testing.T) {
if isWindows {
return
}
os.Setenv(snowflakeHome, "./test_data")
connectionsStat, err := os.Stat("./test_data/connections.toml")
assertNilF(t, err, "The error should not occur")
tokenStat, err := os.Stat("./test_data/snowflake/session/token")
assertNilF(t, err, "The error should not occur")
defer func() {
err = os.Chmod("./test_data/connections.toml", connectionsStat.Mode())
assertNilF(t, err, "The error should not occur")
err = os.Chmod("./test_data/snowflake/session/token", tokenStat.Mode())
assertNilF(t, err, "The error should not occur")
}()
t.Run("test warning logger for readable outside owner", func(t *testing.T) {
var originalLogger = logger
logger = CreateDefaultLogger()
buf := &bytes.Buffer{}
logger.SetOutput(buf)
defer func() {
logger = originalLogger
}()
err = os.Chmod("./test_data/connections.toml", 0644)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
_, err = loadConnectionConfig()
assertNilF(t, err, "The error should not occur")
connectionsAbsolutePath, err2 := path.Abs("./test_data/connections.toml")
assertNilF(t, err2, "The error should not occur")
expectedWarn := fmt.Sprintf("level=warning msg=\"file '%v' is readable by someone other than the owner. "+
"Your Permission: -rw-r--r--. If you want to disable this warning, either remove read permissions from group "+
"and others or set the environment variable SF_SKIP_WARNING_FOR_READ_PERMISSIONS_ON_CONFIG_FILE to true\"", connectionsAbsolutePath)
assertStringContainsF(t, buf.String(), expectedWarn)
})
t.Run("test warning skipped logger for readable outside owner", func(t *testing.T) {
os.Setenv(skipWarningForReadPermissionsEnv, "true")
defer func() {
os.Unsetenv(skipWarningForReadPermissionsEnv)
}()
var originalLogger = logger
logger = CreateDefaultLogger()
buf := &bytes.Buffer{}
logger.SetOutput(buf)
defer func() {
logger = originalLogger
}()
err = os.Chmod("./test_data/connections.toml", 0644)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
_, err = loadConnectionConfig()
assertNilF(t, err, "The error should not occur")
})
t.Run("test writable connection file other than owner", func(t *testing.T) {
err = os.Chmod("./test_data/connections.toml", 0666)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
_, err := loadConnectionConfig()
assertNotNilF(t, err, "The error should occur because the file is writable by anyone but the owner")
driverErr, ok := err.(*SnowflakeError)
assertTrueF(t, ok, "This should be a Snowflake Error")
assertEqualF(t, driverErr.Number, ErrCodeInvalidFilePermission)
})
t.Run("test writable token file other than owner", func(t *testing.T) {
err = os.Chmod("./test_data/snowflake/session/token", 0666)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
_, err := readToken("./test_data/snowflake/session/token")
assertNotNilF(t, err, "The error should occur because the file is writable by anyone but the owner")
driverErr, ok := err.(*SnowflakeError)
assertTrueF(t, ok, "This should be a Snowflake Error")
assertEqualF(t, driverErr.Number, ErrCodeInvalidFilePermission)
})
t.Run("test executable connection file", func(t *testing.T) {
err = os.Chmod("./test_data/connections.toml", 0100)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
_, err := loadConnectionConfig()
assertNotNilF(t, err, "The error should occur because the file is executable")
driverErr, ok := err.(*SnowflakeError)
assertTrueF(t, ok, "This should be a Snowflake Error")
assertEqualF(t, driverErr.Number, ErrCodeInvalidFilePermission)
})
t.Run("test executable token file", func(t *testing.T) {
err = os.Chmod("./test_data/snowflake/session/token", 0010)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
_, err := readToken("./test_data/snowflake/session/token")
assertNotNilF(t, err, "The error should occur because the file is executable")
driverErr, ok := err.(*SnowflakeError)
assertTrueF(t, ok, "This should be a Snowflake Error")
assertEqualF(t, driverErr.Number, ErrCodeInvalidFilePermission)
})
t.Run("test valid file permission for connection config and token file", func(t *testing.T) {
err = os.Chmod("./test_data/connections.toml", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
err = os.Chmod("./test_data/snowflake/session/token", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
_, err := loadConnectionConfig()
assertNilF(t, err, "The error occurred because the permission is not 0600")
_, err = readToken("./test_data/snowflake/session/token")
assertNilF(t, err, "The error occurred because the permission is not 0600")
})
}
func TestLoadConnectionConfigForStandardAuth(t *testing.T) {
err := os.Chmod("./test_data/connections.toml", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
os.Setenv(snowflakeHome, "./test_data")
cfg, err := loadConnectionConfig()
assertNilF(t, err, "The error should not occur")
assertEqualF(t, cfg.Account, "snowdriverswarsaw.us-west-2.aws")
assertEqualF(t, cfg.User, "test_default_user")
assertEqualF(t, cfg.Password, "test_default_pass")
assertEqualF(t, cfg.Warehouse, "testw_default")
assertEqualF(t, cfg.Database, "test_default_db")
assertEqualF(t, cfg.Schema, "test_default_go")
assertEqualF(t, cfg.Protocol, "https")
assertEqualF(t, cfg.Port, 300)
}
func TestLoadConnectionConfigForOAuth(t *testing.T) {
err := os.Chmod("./test_data/connections.toml", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
os.Setenv(snowflakeHome, "./test_data")
os.Setenv(snowflakeConnectionName, "aws-oauth")
cfg, err := loadConnectionConfig()
assertNilF(t, err, "The error should not occur")
assertEqualF(t, cfg.Account, "snowdriverswarsaw.us-west-2.aws")
assertEqualF(t, cfg.User, "test_oauth_user")
assertEqualF(t, cfg.Password, "test_oauth_pass")
assertEqualF(t, cfg.Warehouse, "testw_oauth")
assertEqualF(t, cfg.Database, "test_oauth_db")
assertEqualF(t, cfg.Schema, "test_oauth_go")
assertEqualF(t, cfg.Protocol, "https")
assertEqualF(t, cfg.Authenticator, AuthTypeOAuth)
assertEqualF(t, cfg.Token, "token_value")
assertEqualF(t, cfg.Port, 443)
assertEqualE(t, cfg.DisableOCSPChecks, true)
}
func TestLoadConnectionConfigForSnakeCaseConfiguration(t *testing.T) {
err := os.Chmod("./test_data/connections.toml", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
os.Setenv(snowflakeHome, "./test_data")
os.Setenv(snowflakeConnectionName, "snake-case")
cfg, err := loadConnectionConfig()
assertNilF(t, err, "The error should not occur")
assertEqualE(t, cfg.OCSPFailOpen, OCSPFailOpenTrue)
}
func TestReadTokenValueWithTokenFilePath(t *testing.T) {
err := os.Chmod("./test_data/connections.toml", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
err = os.Chmod("./test_data/snowflake/session/token", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
os.Setenv(snowflakeHome, "./test_data")
os.Setenv(snowflakeConnectionName, "read-token")
cfg, err := loadConnectionConfig()
assertNilF(t, err, "The error should not occur")
assertEqualF(t, cfg.Authenticator, AuthTypeOAuth)
assertEqualF(t, cfg.Token, "mock_token123456")
assertEqualE(t, cfg.InsecureMode, true)
}
func TestLoadConnectionConfigWitNonExistingDSN(t *testing.T) {
err := os.Chmod("./test_data/connections.toml", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
os.Setenv(snowflakeHome, "./test_data")
os.Setenv(snowflakeConnectionName, "unavailableDSN")
_, err = loadConnectionConfig()
assertNotNilF(t, err, "The error should occur")
driverErr, ok := err.(*SnowflakeError)
assertTrueF(t, ok, "This should be a Snowflake Error")
assertEqualF(t, driverErr.Number, ErrCodeFailedToFindDSNInToml)
}
func TestLoadConnectionConfigWithTokenFileNotExist(t *testing.T) {
err := os.Chmod("./test_data/connections.toml", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
os.Setenv(snowflakeHome, "./test_data")
os.Setenv(snowflakeConnectionName, "aws-oauth-file")
_, err = loadConnectionConfig()
assertNotNilF(t, err, "The error should occur")
_, ok := err.(*(fs.PathError))
assertTrueF(t, ok, "This error should be a path error")
}
func TestParseInt(t *testing.T) {
var i interface{}
i = 20
num, err := parseInt(i)
assertNilF(t, err, "This value should be parsed")
assertEqualF(t, num, 20)
i = "40"
num, err = parseInt(i)
assertNilF(t, err, "This value should be parsed")
assertEqualF(t, num, 40)
i = "wrong_num"
_, err = parseInt(i)
assertNotNilF(t, err, "should have failed")
}
func TestParseBool(t *testing.T) {
var i interface{}
i = true
b, err := parseBool(i)
assertNilF(t, err, "This value should be parsed")
assertEqualF(t, b, true)
i = "false"
b, err = parseBool(i)
assertNilF(t, err, "This value should be parsed")
assertEqualF(t, b, false)
i = "wrong_bool"
_, err = parseInt(i)
assertNotNilF(t, err, "should have failed")
}
func TestParseDuration(t *testing.T) {
var i interface{}
i = 300
dur, err := parseDuration(i)
assertNilF(t, err, "This value should be parsed")
assertEqualF(t, dur, time.Duration(300*int64(time.Second)))
i = "30"
dur, err = parseDuration(i)
assertNilF(t, err, "This value should be parsed")
assertEqualF(t, dur, time.Duration(int64(time.Minute)/2))
i = false
_, err = parseDuration(i)
assertNotNilF(t, err, "should have failed")
}
type paramList struct {
testParams []string
values []interface{}
}
func TestParseToml(t *testing.T) {
// Generate a fresh private key for this unit test only
localTestKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("Failed to generate test private key: %s", err.Error())
}
testCases := []paramList{
{
testParams: []string{"user", "password", "host", "account", "warehouse", "database",
"schema", "role", "region", "protocol", "passcode", "application", "token",
"tracing", "tmpDirPath", "tmp_dir_path", "clientConfigFile", "client_config_file", "oauth_authorization_url", "oauth_client_id",
"oauth_client_secret", "oauth_token_request_url", "oauth_redirect_uri", "oauth_scope",
"workload_identity_provider", "workload_identity_entra_resource", "proxyHost", "noProxy", "proxyUser", "proxyPassword", "proxyProtocol"},
values: []interface{}{"value"},
},
{
testParams: []string{"privatekey", "private_key"},
values: []interface{}{generatePKCS8StringSupress(localTestKey)},
},
{
testParams: []string{"port", "maxRetryCount", "max_retry_count", "clientTimeout", "client_timeout", "jwtClientTimeout", "jwt_client_timeout", "loginTimeout",
"login_timeout", "requestTimeout", "request_timeout", "jwtTimeout", "jwt_timeout", "externalBrowserTimeout", "external_browser_timeout", "proxyPort"},
values: []interface{}{"300", 500},
},
{
testParams: []string{"ocspFailOpen", "ocsp_fail_open", "insecureMode", "insecure_mode", "PasscodeInPassword", "passcode_in_password", "validateDEFAULTParameters", "validate_default_parameters",
"clientRequestMFAtoken", "client_request_mfa_token", "clientStoreTemporaryCredential", "client_store_temporary_credential", "disableQueryContextCache", "disable_query_context_cache", "disable_ocsp_checks",
"includeRetryReason", "include_retry_reason", "disableConsoleLogin", "disable_console_login", "disableSamlUrlCheck", "disable_saml_url_check"},
values: []interface{}{true, "true", false, "false"},
},
{
testParams: []string{"connectionDiagnosticsEnabled", "connection_diagnostics_enabled"},
values: []interface{}{true, false},
},
{
testParams: []string{"connectionDiagnosticsAllowlistFile", "connection_diagnostics_allowlist_file"},
values: []interface{}{"myallowlist.json"},
},
}
for _, testCase := range testCases {
for _, param := range testCase.testParams {
for _, value := range testCase.values {
t.Run(param, func(t *testing.T) {
cfg := &Config{}
connectionMap := make(map[string]interface{})
connectionMap[param] = value
err := parseToml(cfg, connectionMap)
assertNilF(t, err, "The value should be parsed")
})
}
}
}
}
func TestParseTomlWithWrongValue(t *testing.T) {
testCases := []paramList{
{
testParams: []string{"user", "password", "host", "account", "warehouse", "database",
"schema", "role", "region", "protocol", "passcode", "application", "token", "privateKey",
"tracing", "tmpDirPath", "clientConfigFile", "wrongParams", "token_file_path", "proxyhost", "noproxy", "proxyUser", "proxyPassword", "proxyProtocol"},
values: []interface{}{1, false},
},
{
testParams: []string{"port", "maxRetryCount", "clientTimeout", "jwtClientTimeout", "loginTimeout",
"requestTimeout", "jwtTimeout", "externalBrowserTimeout", "authenticator"},
values: []interface{}{"wrong_value", false},
},
{
testParams: []string{"ocspFailOpen", "insecureMode", "PasscodeInPassword", "validateDEFAULTParameters", "clientRequestMFAtoken",
"clientStoreTemporaryCredential", "disableQueryContextCache", "includeRetryReason", "disableConsoleLogin", "disableSamlUrlCheck"},
values: []interface{}{"wrong_value", 1},
},
}
for _, testCase := range testCases {
for _, param := range testCase.testParams {
for _, value := range testCase.values {
t.Run(param, func(t *testing.T) {
cfg := &Config{}
connectionMap := make(map[string]interface{})
connectionMap[param] = value
err := parseToml(cfg, connectionMap)
assertNotNilF(t, err, "should have failed")
driverErr, ok := err.(*SnowflakeError)
assertTrueF(t, ok, "This should be a Snowflake Error")
assertEqualF(t, driverErr.Number, ErrCodeTomlFileParsingFailed)
})
}
}
}
}
func TestGetTomlFilePath(t *testing.T) {
skipOnMissingHome(t)
dir, err := getTomlFilePath("")
assertNilF(t, err, "should not have failed")
homeDir, err := os.UserHomeDir()
assertNilF(t, err, "The connection cannot find the user home directory")
assertEqualF(t, dir, path.Join(homeDir, ".snowflake"))
location := "../user//somelocation///b"
dir, err = getTomlFilePath(location)
assertNilF(t, err, "should not have failed")
result, err := path.Abs(location)
assertNilF(t, err, "should not have failed")
assertEqualF(t, dir, result)
//Absolute path for windows can be varied depend on which disk the driver is located.
// As a result, this test is available on non-Window machines.
if !isWindows {
result = "/user/somelocation/b"
location = "/user//somelocation///b"
dir, err = getTomlFilePath(location)
assertNilF(t, err, "should not have failed")
assertEqualF(t, dir, result)
}
}
func TestTomlConnection(t *testing.T) {
os.Setenv(snowflakeHome, "./test_data/")
os.Setenv(snowflakeConnectionName, "toml-connection")
defer os.Unsetenv(snowflakeHome)
wiremock.registerMappings(t,
wiremockMapping{filePath: "auth/password/successful_flow.json"},
wiremockMapping{filePath: "select1.json", params: map[string]string{
"%AUTHORIZATION_HEADER%": "session token",
}},
)
type Connection struct {
Account string `toml:"account"`
User string `toml:"user"`
Password string `toml:"password"`
Host string `toml:"host"`
Port string `toml:"port"`
Protocol string `toml:"protocol"`
}
type TomlStruct struct {
Connection Connection `toml:"toml-connection"`
}
cfg := wiremock.connectionConfig()
connection := &TomlStruct{
Connection: Connection{
Account: cfg.Account,
User: cfg.User,
Password: cfg.Password,
Host: cfg.Host,
Port: strconv.Itoa(cfg.Port),
Protocol: cfg.Protocol,
},
}
f, err := os.OpenFile("./test_data/connections.toml", os.O_APPEND|os.O_WRONLY, 0600)
assertNilF(t, err, "Failed to create connections.toml file")
defer f.Close()
encoder := toml.NewEncoder(f)
err = encoder.Encode(connection)
assertNilF(t, err, "Failed to parse the config to toml structure")
if !isWindows {
err = os.Chmod("./test_data/connections.toml", 0600)
assertNilF(t, err, "The error occurred because you cannot change the file permission")
}
db, err := sql.Open("snowflake", "autoConfig")
assertNilF(t, err, "The error occurred because the db cannot be established")
runSmokeQuery(t, db)
}