forked from denisenkom/go-mssqldb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tds_test.go
643 lines (560 loc) · 15.7 KB
/
tds_test.go
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
package mssql
import (
"bytes"
"context"
"database/sql"
"encoding/hex"
"fmt"
"net/url"
"os"
"runtime"
"testing"
)
type MockTransport struct {
bytes.Buffer
}
func (t *MockTransport) Close() error {
return nil
}
func TestSendLogin(t *testing.T) {
memBuf := new(MockTransport)
buf := NewTdsBuffer(1024, memBuf)
login := login{
TDSVersion: verTDS73,
PacketSize: 0x1000,
ClientProgVer: 0x01060100,
ClientPID: 100,
ClientTimeZone: -4 * 60,
ClientID: [6]byte{0x12, 0x34, 0x56, 0x78, 0x90, 0xab},
OptionFlags1: 0xe0,
OptionFlags3: 8,
HostName: "subdev1",
UserName: "test",
// file deepcode ignore HardcodedPassword/test: This is a test file
Password: "testpwd",
AppName: "appname",
ServerName: "servername",
CtlIntName: "library",
Language: "en",
Database: "database",
ClientLCID: 0x204,
AtchDBFile: "filepath",
}
err := sendLogin(buf, login)
if err != nil {
t.Error("sendLogin should succeed")
}
ref := []byte{
16, 1, 0, 222, 0, 0, 1, 0, 198 + 16, 0, 0, 0, 3, 0, 10, 115, 0, 16, 0, 0, 0, 1,
6, 1, 100, 0, 0, 0, 0, 0, 0, 0, 224, 0, 0, 8, 16, 255, 255, 255, 4, 2, 0,
0, 94, 0, 7, 0, 108, 0, 4, 0, 116, 0, 7, 0, 130, 0, 7, 0, 144, 0, 10, 0, 164,
0, 0, 0, 164, 0, 7, 0, 178, 0, 2, 0, 182, 0, 8, 0, 18, 52, 86, 120, 144, 171,
198, 0, 0, 0, 198, 0, 8, 0, 214, 0, 0, 0, 0, 0, 0, 0, 115, 0, 117, 0, 98,
0, 100, 0, 101, 0, 118, 0, 49, 0, 116, 0, 101, 0, 115, 0, 116, 0, 226, 165,
243, 165, 146, 165, 226, 165, 162, 165, 210, 165, 227, 165, 97, 0, 112,
0, 112, 0, 110, 0, 97, 0, 109, 0, 101, 0, 115, 0, 101, 0, 114, 0, 118, 0,
101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 108, 0, 105, 0, 98, 0, 114,
0, 97, 0, 114, 0, 121, 0, 101, 0, 110, 0, 100, 0, 97, 0, 116, 0, 97, 0, 98,
0, 97, 0, 115, 0, 101, 0, 102, 0, 105, 0, 108, 0, 101, 0, 112, 0, 97, 0,
116, 0, 104, 0}
out := memBuf.Bytes()
if !bytes.Equal(ref, out) {
fmt.Println("Expected:")
fmt.Print(hex.Dump(ref))
fmt.Println("Returned:")
fmt.Print(hex.Dump(out))
t.Error("input output don't match")
}
}
func TestReadLogin(t *testing.T) {
fail := func (name string, expected, actual interface{}) {
// file deepcode ignore ClearTextLogging/test: This is a test file
fmt.Println("Expected:", expected)
fmt.Println("Returned:", actual)
t.Errorf("input output don't match for %s", name)
}
buf := NewTdsBuffer(1024, new(MockTransport))
expectedLogin := login{
TDSVersion: verTDS73,
PacketSize: 0x1000,
ClientProgVer: 0x01060100,
ClientPID: 100,
ConnectionID: 1111,
OptionFlags1: 0xe0,
OptionFlags2: 0xe2,
TypeFlags: 0xa0,
OptionFlags3: 0xe5,
ClientTimeZone: -4 * 60,
ClientLCID: 0x204,
HostName: "subdev1",
UserName: "test",
Password: "testpwd",
AppName: "appname",
ServerName: "servername",
CtlIntName: "library",
Language: "en",
Database: "database",
ClientID: [6]byte{0x12, 0x34, 0x56, 0x78, 0x90, 0xab},
SSPI: []byte{1, 2, 3},
AtchDBFile: "filepath",
ChangePassword: "meow",
}
err := sendLogin(buf, expectedLogin)
if err != nil {
t.Error("sendLogin should succeed")
return
}
actualLogin, err := ReadLoginRequest(buf)
if err != nil {
t.Error("ReadLoginRequest should succeed")
return
}
// reset password because on sendLogin the password gets mangled before being sent
// over the wire
expectedLogin.Password = ""
actualLogin.Password = ""
if actualLogin.TDSVersion != expectedLogin.TDSVersion {
fail("TDSVersion", expectedLogin.TDSVersion, actualLogin.TDSVersion)
}
if actualLogin.PacketSize != expectedLogin.PacketSize {
fail("PacketSize", expectedLogin.PacketSize, actualLogin.PacketSize)
}
if actualLogin.ClientProgVer != expectedLogin.ClientProgVer {
fail(
"ClientProgVer",
expectedLogin.ClientProgVer,
actualLogin.ClientProgVer)
}
if actualLogin.ClientPID != expectedLogin.ClientPID {
fail("ClientPID", expectedLogin.ClientPID, actualLogin.ClientPID)
}
if actualLogin.ConnectionID != expectedLogin.ConnectionID {
fail("ConnectionID", expectedLogin.ConnectionID, actualLogin.ConnectionID)
}
if actualLogin.OptionFlags1 != expectedLogin.OptionFlags1 {
fail("OptionFlags1", expectedLogin.OptionFlags1, actualLogin.OptionFlags1)
}
if actualLogin.OptionFlags2 != expectedLogin.OptionFlags2 {
fail("OptionFlags2", expectedLogin.OptionFlags2, actualLogin.OptionFlags2)
}
if actualLogin.TypeFlags != expectedLogin.TypeFlags {
fail("TypeFlags", expectedLogin.TypeFlags, actualLogin.TypeFlags)
}
if actualLogin.OptionFlags3 != expectedLogin.OptionFlags3 {
fail("OptionFlags3", expectedLogin.OptionFlags3, actualLogin.OptionFlags3)
}
if actualLogin.ClientTimeZone != expectedLogin.ClientTimeZone {
fail(
"ClientTimeZone",
expectedLogin.ClientTimeZone,
actualLogin.ClientTimeZone)
}
if actualLogin.ClientLCID != expectedLogin.ClientLCID {
fail("ClientLCID", expectedLogin.ClientLCID, actualLogin.ClientLCID)
}
if actualLogin.HostName != expectedLogin.HostName {
fail("HostName", expectedLogin.HostName, actualLogin.HostName)
}
if actualLogin.UserName != expectedLogin.UserName {
fail("UserName", expectedLogin.UserName, actualLogin.UserName)
}
if actualLogin.Password != expectedLogin.Password {
fail("Password", expectedLogin.Password, actualLogin.Password)
}
if actualLogin.AppName != expectedLogin.AppName {
fail("AppName", expectedLogin.AppName, actualLogin.AppName)
}
if actualLogin.ServerName != expectedLogin.ServerName {
fail("ServerName", expectedLogin.ServerName, actualLogin.ServerName)
}
if actualLogin.CtlIntName != expectedLogin.CtlIntName {
fail("CtlIntName", expectedLogin.CtlIntName, actualLogin.CtlIntName)
}
if actualLogin.Language != expectedLogin.Language {
fail("Language", expectedLogin.Language, actualLogin.Language)
}
if actualLogin.Database != expectedLogin.Database {
fail("Database", expectedLogin.Database, actualLogin.Database)
}
if actualLogin.ClientID != expectedLogin.ClientID {
fail("ClientID", expectedLogin.ClientID, actualLogin.ClientID)
}
if !bytes.Equal(actualLogin.SSPI, expectedLogin.SSPI) {
fail("SSPI", expectedLogin.SSPI, actualLogin.SSPI)
}
if actualLogin.AtchDBFile != expectedLogin.AtchDBFile {
fail("AtchDBFile", expectedLogin.AtchDBFile, actualLogin.AtchDBFile)
}
if actualLogin.ChangePassword != expectedLogin.ChangePassword {
fail(
"ChangePassword",
expectedLogin.ChangePassword,
actualLogin.ChangePassword,
)
}
}
func TestSendSqlBatch(t *testing.T) {
checkConnStr(t)
p, err := parseConnectParams(makeConnStr(t).String())
if err != nil {
t.Error("parseConnectParams failed:", err.Error())
return
}
conn, err := connect(context.Background(), nil, optionalLogger{testLogger{t}}, p)
if err != nil {
t.Error("Open connection failed:", err.Error())
return
}
defer conn.buf.transport.Close()
headers := []headerStruct{
{hdrtype: dataStmHdrTransDescr,
data: transDescrHdr{0, 1}.pack()},
}
err = sendSqlBatch72(conn.buf, "select 1", headers, true)
if err != nil {
t.Error("Sending sql batch failed", err.Error())
return
}
ch := make(chan tokenStruct, 5)
go processResponse(context.Background(), conn, ch, nil)
var lastRow []interface{}
loop:
for tok := range ch {
switch token := tok.(type) {
case doneStruct:
break loop
case []columnStruct:
conn.columns = token
case []interface{}:
lastRow = token
default:
fmt.Println("unknown token", tok)
}
}
if len(lastRow) == 0 {
t.Fatal("expected row but no row set")
}
switch value := lastRow[0].(type) {
case int32:
if value != 1 {
t.Error("Invalid value returned, should be 1", value)
return
}
}
}
func checkConnStr(t *testing.T) {
if len(os.Getenv("SQLSERVER_DSN")) > 0 {
return
}
if len(os.Getenv("HOST")) > 0 && len(os.Getenv("DATABASE")) > 0 {
return
}
t.Skip("no database connection string")
}
// makeConnStr returns a URL struct so it may be modified by various
// tests before used as a DSN.
func makeConnStr(t *testing.T) *url.URL {
dsn := os.Getenv("SQLSERVER_DSN")
if len(dsn) > 0 {
parsed, err := url.Parse(dsn)
if err != nil {
t.Fatal("unable to parse SQLSERVER_DSN as URL", err)
}
values := parsed.Query()
if values.Get("log") == "" {
values.Set("log", "127")
}
parsed.RawQuery = values.Encode()
return parsed
}
values := url.Values{}
values.Set("log", "127")
values.Set("database", os.Getenv("DATABASE"))
return &url.URL{
Scheme: "sqlserver",
Host: os.Getenv("HOST"),
Path: os.Getenv("INSTANCE"),
User: url.UserPassword(os.Getenv("SQLUSER"), os.Getenv("SQLPASSWORD")),
RawQuery: values.Encode(),
}
}
type testLogger struct {
t *testing.T
}
func (l testLogger) Printf(format string, v ...interface{}) {
l.t.Logf(format, v...)
}
func (l testLogger) Println(v ...interface{}) {
l.t.Log(v...)
}
func TestConnect(t *testing.T) {
checkConnStr(t)
SetLogger(testLogger{t})
conn, err := sql.Open("mssql", makeConnStr(t).String())
if err != nil {
t.Error("Open connection failed:", err.Error())
return
}
defer conn.Close()
}
func simpleQuery(conn *sql.DB, t *testing.T) (stmt *sql.Stmt) {
stmt, err := conn.Prepare("select 1 as a")
if err != nil {
t.Error("Prepare failed:", err.Error())
return nil
}
return stmt
}
func checkSimpleQuery(rows *sql.Rows, t *testing.T) {
numrows := 0
for rows.Next() {
var val int
err := rows.Scan(&val)
if err != nil {
t.Error("Scan failed:", err.Error())
}
if val != 1 {
t.Error("query should return 1")
}
numrows++
}
if numrows != 1 {
t.Error("query should return 1 row, returned", numrows)
}
}
func TestQuery(t *testing.T) {
conn := open(t)
if conn == nil {
return
}
defer conn.Close()
stmt := simpleQuery(conn, t)
if stmt == nil {
return
}
defer stmt.Close()
rows, err := stmt.Query()
if err != nil {
t.Error("Query failed:", err.Error())
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
t.Error("getting columns failed", err.Error())
}
if len(columns) != 1 && columns[0] != "a" {
t.Error("returned incorrect columns (expected ['a']):", columns)
}
checkSimpleQuery(rows, t)
}
func TestMultipleQueriesSequentialy(t *testing.T) {
conn := open(t)
defer conn.Close()
stmt, err := conn.Prepare("select 1 as a")
if err != nil {
t.Error("Prepare failed:", err.Error())
return
}
defer stmt.Close()
rows, err := stmt.Query()
if err != nil {
t.Error("Query failed:", err.Error())
return
}
defer rows.Close()
checkSimpleQuery(rows, t)
rows, err = stmt.Query()
if err != nil {
t.Error("Query failed:", err.Error())
return
}
defer rows.Close()
checkSimpleQuery(rows, t)
}
func TestMultipleQueryClose(t *testing.T) {
conn := open(t)
defer conn.Close()
stmt, err := conn.Prepare("select 1 as a")
if err != nil {
t.Error("Prepare failed:", err.Error())
return
}
defer stmt.Close()
rows, err := stmt.Query()
if err != nil {
t.Error("Query failed:", err.Error())
return
}
rows.Close()
rows, err = stmt.Query()
if err != nil {
t.Error("Query failed:", err.Error())
return
}
defer rows.Close()
checkSimpleQuery(rows, t)
}
func TestPing(t *testing.T) {
conn := open(t)
defer conn.Close()
conn.Ping()
}
func TestSecureWithInvalidHostName(t *testing.T) {
checkConnStr(t)
SetLogger(testLogger{t})
dsn := makeConnStr(t)
dsnParams := dsn.Query()
dsnParams.Set("encrypt", "true")
dsnParams.Set("TrustServerCertificate", "false")
dsnParams.Set("hostNameInCertificate", "foo.bar")
dsn.RawQuery = dsnParams.Encode()
conn, err := sql.Open("mssql", dsn.String())
if err != nil {
t.Fatal("Open connection failed:", err.Error())
}
defer conn.Close()
err = conn.Ping()
if err == nil {
t.Fatal("Connected to fake foo.bar server")
}
}
func TestSecureConnection(t *testing.T) {
checkConnStr(t)
SetLogger(testLogger{t})
dsn := makeConnStr(t)
dsnParams := dsn.Query()
dsnParams.Set("encrypt", "true")
dsnParams.Set("TrustServerCertificate", "true")
dsn.RawQuery = dsnParams.Encode()
conn, err := sql.Open("mssql", dsn.String())
if err != nil {
t.Fatal("Open connection failed:", err.Error())
}
defer conn.Close()
var msg string
err = conn.QueryRow("select 'secret'").Scan(&msg)
if err != nil {
t.Fatal("cannot scan value", err)
}
if msg != "secret" {
t.Fatal("expected secret, got: ", msg)
}
var secure bool
err = conn.QueryRow("select encrypt_option from sys.dm_exec_connections where session_id=@@SPID").Scan(&secure)
if err != nil {
t.Fatal("cannot scan value", err)
}
if !secure {
t.Fatal("connection is not encrypted")
}
}
func TestBadConnect(t *testing.T) {
checkConnStr(t)
SetLogger(testLogger{t})
connURL := makeConnStr(t)
connURL.User = url.UserPassword("baduser", "badpwd")
badDSN := connURL.String()
conn, err := sql.Open("mssql", badDSN)
if err != nil {
t.Error("Open connection failed:", err.Error())
}
defer conn.Close()
err = conn.Ping()
if err == nil {
t.Error("Ping should fail for connection: ", badDSN)
}
}
func TestSSPIAuth(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Only on windows")
}
checkConnStr(t)
connStr := makeConnStr(t)
params := connStr.Query()
params.Set("Integrated Security", "sspi")
connStr.RawQuery = params.Encode()
db, err := sql.Open("mssql", connStr.String())
if err != nil {
t.Error("Open failed", err)
}
defer db.Close()
row := db.QueryRow("select 1, 'abc'")
var somenumber int64
var somechars string
err = row.Scan(&somenumber, &somechars)
if err != nil {
t.Error("scan failed", err)
}
if somenumber != int64(1) || somechars != "abc" {
t.Errorf("Invalid values from query: want {%d,'%s'}, got {%d,'%s'}", int64(1), "abc", somenumber, somechars)
}
}
func TestUcs22Str(t *testing.T) {
// Test valid input
s, err := ucs22str([]byte{0x31, 0, 0x32, 0, 0x33, 0}) // 123 in UCS2 encoding
if err != nil {
t.Errorf("ucs22str should not fail for valid ucs2 byte sequence: %s", err)
}
if s != "123" {
t.Errorf("ucs22str expected to return 123 but it returned %s", s)
}
// Test invalid input
_, err = ucs22str([]byte{0})
if err == nil {
t.Error("ucs22str should fail on single byte input, but it didn't")
}
}
func TestReadUcs2(t *testing.T) {
buf := bytes.NewBuffer([]byte{0x31, 0, 0x32, 0, 0x33, 0}) // 123 in UCS2 encoding
s, err := readUcs2(buf, 3)
if err != nil {
t.Errorf("readUcs2 should not fail for valid ucs2 byte sequence: %s", err)
}
if s != "123" {
t.Errorf("readUcs2 expected to return 123 but it returned %s", s)
}
buf = bytes.NewBuffer([]byte{0})
_, err = readUcs2(buf, 1)
if err == nil {
t.Error("readUcs2 should fail on single byte input, but it didn't")
}
}
func TestReadUsVarChar(t *testing.T) {
// should succeed for valid buffer
buf := bytes.NewBuffer([]byte{3, 0, 0x31, 0, 0x32, 0, 0x33, 0}) // 123 in UCS2 encoding with length prefix 3 uint16
s, err := readUsVarChar(buf)
if err != nil {
t.Errorf("readUsVarChar should not fail for valid ucs2 byte sequence: %s", err)
}
if s != "123" {
t.Errorf("readUsVarChar expected to return 123 but it returned %s", s)
}
// should fail for empty buffer
buf = bytes.NewBuffer([]byte{})
_, err = readUsVarChar(buf)
if err == nil {
t.Error("readUsVarChar should fail on empty buffer, but it didn't")
}
}
func TestReadBVarByte(t *testing.T) {
memBuf := bytes.NewBuffer([]byte{3, 1, 2, 3})
s, err := readBVarByte(memBuf)
if err != nil {
t.Errorf("readUsVarByte should not fail for valid buffer: %s", err)
}
if !bytes.Equal(s, []byte{1, 2, 3}) {
t.Errorf("readUsVarByte expected to return [1 2 3] but it returned %v", s)
}
// test empty buffer
memBuf = bytes.NewBuffer([]byte{})
s, err = readBVarByte(memBuf)
if err == nil {
t.Error("readUsVarByte should fail on empty buffer, but it didn't")
}
// test short buffer
memBuf = bytes.NewBuffer([]byte{1})
s, err = readBVarByte(memBuf)
if err == nil {
t.Error("readUsVarByte should fail on short buffer, but it didn't")
}
}