-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathauth_test.go
More file actions
466 lines (391 loc) · 12.3 KB
/
auth_test.go
File metadata and controls
466 lines (391 loc) · 12.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
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
package imap
import (
"bufio"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
type mockIMAPServer struct {
listener net.Listener
address string
authAttempts int32
validUser string
validPass string
failAuth bool
failConnection bool
responses map[string]string
failCommands map[string]bool // commands that should return NO (keyed by uppercase command name)
tlsConfig *tls.Config
}
func newMockIMAPServer(validUser, validPass string) (*mockIMAPServer, error) {
// Generate a certificate for testing
cert, err := generateSelfSignedCertificate()
if err != nil {
return nil, fmt.Errorf("failed to generate certificate: %v", err)
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
listener, err := tls.Listen("tcp", "127.0.0.1:0", tlsConfig)
if err != nil {
return nil, fmt.Errorf("failed to create TLS listener: %v", err)
}
server := &mockIMAPServer{
listener: listener,
address: listener.Addr().String(),
validUser: validUser,
validPass: validPass,
responses: make(map[string]string),
failCommands: make(map[string]bool),
tlsConfig: tlsConfig,
}
go server.serve()
return server, nil
}
func (s *mockIMAPServer) serve() {
for {
conn, err := s.listener.Accept()
if err != nil {
return
}
go s.handleConnection(conn)
}
}
func (s *mockIMAPServer) handleConnection(conn net.Conn) {
defer conn.Close()
if s.failConnection {
// Simulate connection failure
return
}
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
writer.WriteString("* OK IMAP4rev1 Mock Server Ready\r\n")
writer.Flush()
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
parts := strings.Fields(line)
if len(parts) < 2 {
continue
}
tag := parts[0]
command := strings.ToUpper(parts[1])
switch command {
case "LOGIN":
atomic.AddInt32(&s.authAttempts, 1)
if s.failAuth {
writer.WriteString(fmt.Sprintf("%s NO LOGIN failed\r\n", tag))
} else if len(parts) >= 4 {
// Extract username and password (removing quotes)
username := strings.Trim(parts[2], `"`)
password := strings.Trim(parts[3], `"`)
if username == s.validUser && password == s.validPass {
writer.WriteString(fmt.Sprintf("%s OK LOGIN completed\r\n", tag))
} else {
writer.WriteString(fmt.Sprintf("%s NO [AUTHENTICATIONFAILED] Authentication failed\r\n", tag))
}
} else {
writer.WriteString(fmt.Sprintf("%s BAD Invalid LOGIN command\r\n", tag))
}
case "AUTHENTICATE":
atomic.AddInt32(&s.authAttempts, 1)
if s.failAuth {
writer.WriteString(fmt.Sprintf("%s NO AUTHENTICATE failed\r\n", tag))
} else {
// Simplified XOAUTH2 handling
writer.WriteString(fmt.Sprintf("%s OK AUTHENTICATE completed\r\n", tag))
}
case "CAPABILITY":
writer.WriteString("* CAPABILITY IMAP4rev1 LOGIN AUTHENTICATE\r\n")
writer.WriteString(fmt.Sprintf("%s OK CAPABILITY completed\r\n", tag))
case "APPEND":
// Two-phase APPEND literal continuation protocol
literalSize := 0
if idx := strings.LastIndex(line, "{"); idx != -1 {
if endIdx := strings.LastIndex(line, "}"); endIdx > idx {
sizeStr := strings.TrimSuffix(line[idx+1:endIdx], "+")
literalSize, _ = strconv.Atoi(sizeStr)
}
}
writer.WriteString("+ Ready for literal data\r\n")
writer.Flush()
if literalSize > 0 {
buf := make([]byte, literalSize)
if _, err := io.ReadFull(reader, buf); err != nil {
return
}
}
if _, err := reader.ReadString('\n'); err != nil {
return
}
writer.WriteString(fmt.Sprintf("%s OK [APPENDUID 1 100] APPEND completed\r\n", tag))
case "SELECT":
writer.WriteString("* 0 EXISTS\r\n* 0 RECENT\r\n")
writer.WriteString(fmt.Sprintf("%s OK SELECT completed\r\n", tag))
case "EXAMINE":
writer.WriteString("* 0 EXISTS\r\n* 0 RECENT\r\n")
writer.WriteString(fmt.Sprintf("%s OK EXAMINE completed\r\n", tag))
case "LOGOUT":
writer.WriteString("* BYE IMAP4rev1 Server logging out\r\n")
writer.WriteString(fmt.Sprintf("%s OK LOGOUT completed\r\n", tag))
writer.Flush()
return
default:
if s.failCommands[command] {
writer.WriteString(fmt.Sprintf("%s NO %s failed\r\n", tag, command))
} else {
writer.WriteString(fmt.Sprintf("%s OK %s completed\r\n", tag, command))
}
}
writer.Flush()
}
}
func (s *mockIMAPServer) GetAuthAttempts() int {
return int(atomic.LoadInt32(&s.authAttempts))
}
func (s *mockIMAPServer) ResetAuthAttempts() {
atomic.StoreInt32(&s.authAttempts, 0)
}
func (s *mockIMAPServer) Close() {
s.listener.Close()
}
func (s *mockIMAPServer) GetHost() string {
host, _, _ := net.SplitHostPort(s.address)
return host
}
func (s *mockIMAPServer) GetPort() int {
_, portStr, _ := net.SplitHostPort(s.address)
var port int
fmt.Sscanf(portStr, "%d", &port)
return port
}
func generateSelfSignedCertificate() (tls.Certificate, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return tls.Certificate{}, err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Test Co"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return tls.Certificate{}, err
}
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
return tls.X509KeyPair(certPEM, keyPEM)
}
// TestAuthenticationNoRecursion verifies that authentication failures don't cause recursion
func TestAuthenticationNoRecursion(t *testing.T) {
// Save original settings
originalVerbose := Verbose
originalRetryCount := RetryCount
originalTLSSkipVerify := TLSSkipVerify
// Configure for testing
Verbose = false
RetryCount = 3 // Set retry count to verify it's not used for auth
TLSSkipVerify = true // Skip verification for test cert
defer func() {
Verbose = originalVerbose
RetryCount = originalRetryCount
TLSSkipVerify = originalTLSSkipVerify
}()
server, err := newMockIMAPServer("testuser", "testpass")
if err != nil {
t.Fatalf("Failed to create mock server: %v", err)
}
defer server.Close()
// Test 1: Successful authentication
t.Run("SuccessfulAuth", func(t *testing.T) {
server.ResetAuthAttempts()
d, err := New("testuser", "testpass", server.GetHost(), server.GetPort())
if err != nil {
t.Errorf("Expected successful connection, got error: %v", err)
}
if d != nil {
d.Close()
}
// Should only attempt auth once
if attempts := server.GetAuthAttempts(); attempts != 1 {
t.Errorf("Expected 1 auth attempt, got %d", attempts)
}
})
// Test 2: Failed authentication should not retry
t.Run("FailedAuthNoRetry", func(t *testing.T) {
server.ResetAuthAttempts()
// Use a channel to detect if the function returns in reasonable time
done := make(chan bool, 1)
var connErr error
go func() {
_, connErr = New("testuser", "wrongpass", server.GetHost(), server.GetPort())
done <- true
}()
select {
case <-done:
// Good, function returned
if connErr == nil {
t.Error("Expected authentication error, got nil")
}
case <-time.After(2 * time.Second):
t.Error("Authentication appears to be stuck in recursion")
}
// Should only attempt auth once despite RetryCount being 3
attempts := server.GetAuthAttempts()
if attempts != 1 {
t.Errorf("Expected 1 auth attempt (no retry), got %d", attempts)
}
})
// Test 3: XOAUTH2 authentication should also not retry
t.Run("XOAuth2NoRetry", func(t *testing.T) {
server.ResetAuthAttempts()
server.failAuth = true
defer func() { server.failAuth = false }()
done := make(chan bool, 1)
var connErr error
go func() {
_, connErr = NewWithOAuth2("testuser", "token", server.GetHost(), server.GetPort())
done <- true
}()
select {
case <-done:
if connErr == nil {
t.Error("Expected authentication error, got nil")
}
case <-time.After(2 * time.Second):
t.Error("XOAUTH2 authentication appears to be stuck in recursion")
}
// Should only attempt auth once
attempts := server.GetAuthAttempts()
if attempts != 1 {
t.Errorf("Expected 1 XOAUTH2 auth attempt (no retry), got %d", attempts)
}
})
}
// TestConnectionRetry verifies that connection failures still retry
func TestConnectionRetry(t *testing.T) {
// Save original settings
originalVerbose := Verbose
originalRetryCount := RetryCount
originalTLSSkipVerify := TLSSkipVerify
// Configure for testing
Verbose = false
RetryCount = 2 // Reduce for faster test
TLSSkipVerify = true
defer func() {
Verbose = originalVerbose
RetryCount = originalRetryCount
TLSSkipVerify = originalTLSSkipVerify
}()
start := time.Now()
_, err := New("user", "pass", "127.0.0.1", 59999) // Use unlikely port
elapsed := time.Since(start)
if err == nil {
t.Error("Expected connection error, got nil")
}
// With retries, it should take some time (but not too long)
// Each retry has a delay, so it should take at least a second
if elapsed < 100*time.Millisecond {
t.Error("Connection failed too quickly, retries may not be working")
}
// But it shouldn't take forever (indicates no infinite loop)
if elapsed > 30*time.Second {
t.Error("Connection took too long, possible infinite loop")
}
}
// TestReconnectWithBadCredentials verifies Reconnect handles auth failures properly
func TestReconnectWithBadCredentials(t *testing.T) {
// Save original settings
originalVerbose := Verbose
originalTLSSkipVerify := TLSSkipVerify
// Configure for testing
Verbose = false
TLSSkipVerify = true
defer func() {
Verbose = originalVerbose
TLSSkipVerify = originalTLSSkipVerify
}()
server, err := newMockIMAPServer("testuser", "testpass")
if err != nil {
t.Fatalf("Failed to create mock server: %v", err)
}
defer server.Close()
d, err := New("testuser", "testpass", server.GetHost(), server.GetPort())
if err != nil {
t.Fatalf("Failed to create initial connection: %v", err)
}
defer d.Close()
// Change password to simulate bad credentials on reconnect
d.Password = "wrongpass"
server.ResetAuthAttempts()
// Attempt reconnect with bad credentials
err = d.Reconnect()
if err == nil {
t.Error("Expected reconnect to fail with bad credentials")
}
// Should only attempt auth once
attempts := server.GetAuthAttempts()
if attempts != 1 {
t.Errorf("Expected 1 auth attempt on reconnect, got %d", attempts)
}
// Connection should be closed after failed auth
if d.Connected {
t.Error("Connection should be closed after failed reconnect")
}
}
// TestSimpleAuthRecursionCheck does a simple test without mock server
func TestSimpleAuthRecursionCheck(t *testing.T) {
// Save original settings
originalVerbose := Verbose
originalRetryCount := RetryCount
originalDialTimeout := DialTimeout
// Configure for testing
Verbose = false
RetryCount = 2 // Reduce retry count for faster test
DialTimeout = 1 * time.Second // Set short timeout to avoid long waits
defer func() {
Verbose = originalVerbose
RetryCount = originalRetryCount
DialTimeout = originalDialTimeout
}()
// Try to connect to localhost on a port that's definitely not listening
// This should fail quickly and retry according to RetryCount
start := time.Now()
_, err := New("test", "test", "127.0.0.1", 54321) // Use localhost with random port
elapsed := time.Since(start)
if err == nil {
t.Error("Expected error connecting to non-listening port")
}
// Connection failure should retry, so it should take more than immediate
if elapsed < 100*time.Millisecond {
t.Error("Failed too quickly, connection retry might not be working")
}
// Should complete within reasonable time (not stuck in recursion)
// With 2 retries and 1 second timeout, should be done in under 10 seconds
if elapsed > 10*time.Second {
t.Error("Took too long, might be stuck in recursion")
}
}