-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathnegotiator_test.go
More file actions
1622 lines (1397 loc) · 51.6 KB
/
negotiator_test.go
File metadata and controls
1622 lines (1397 loc) · 51.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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package ntlmssp
import (
"bytes"
"encoding/base64"
"encoding/binary"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// seekableBuffer implements io.ReadSeeker to simulate a seekable body like a file
type seekableBuffer struct {
reader *bytes.Reader
seekCalled *bool
}
func newSeekableBuffer(data []byte, seekCalled *bool) *seekableBuffer {
return &seekableBuffer{
reader: bytes.NewReader(data),
seekCalled: seekCalled,
}
}
func (sb *seekableBuffer) Read(p []byte) (n int, err error) {
return sb.reader.Read(p)
}
func (sb *seekableBuffer) Seek(offset int64, whence int) (int64, error) {
if sb.seekCalled != nil {
*sb.seekCalled = true
}
return sb.reader.Seek(offset, whence)
}
func (sb *seekableBuffer) Close() error {
return nil
}
// TestNegotiatorWithSeekableBody tests that seekable bodies work correctly
func TestNegotiatorWithSeekableBody(t *testing.T) {
testData := []byte("test data that would be large in real scenarios")
// Track seek calls to ensure the body is being seeked, not buffered
seekCalled := false
bodyReader := newSeekableBuffer(testData, &seekCalled)
// Create a test server that accepts requests without auth
// (testing the seekable body path without complex NTLM flow)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Read and verify the body was sent correctly
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Failed to read body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !bytes.Equal(body, testData) {
t.Errorf("Body mismatch: expected %q, got %q", testData, body)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}))
defer server.Close()
// Create a request with basic auth
req, err := http.NewRequest("POST", server.URL, bodyReader)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if string(respBody) != "ok" {
t.Errorf("Expected 'ok', got '%s'", string(respBody))
}
// Verify that seek was called (indicating body handling used seek path)
if !seekCalled {
t.Error("Note: Seek was not called - server accepted request without auth negotiation")
}
}
// TestNegotiatorWithPartialSeekableBody tests that seekable bodies starting at non-zero position work correctly
func TestNegotiatorWithPartialSeekableBody(t *testing.T) {
fullData := []byte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
// Simulate a partial read starting at position 10
startPos := int64(10)
expectedData := fullData[startPos:]
// Create a seekable reader and position it at startPos
bodyReader := bytes.NewReader(fullData)
_, err := bodyReader.Seek(startPos, io.SeekStart)
if err != nil {
t.Fatalf("Failed to seek to start position: %v", err)
}
// Create a test server that accepts requests without auth
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Read and verify the body was sent correctly from the offset position
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Failed to read body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !bytes.Equal(body, expectedData) {
t.Errorf("Body mismatch: expected %q, got %q", expectedData, body)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}))
defer server.Close()
// Create a request with basic auth
req, err := http.NewRequest("POST", server.URL, io.NopCloser(bodyReader))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if string(respBody) != "ok" {
t.Errorf("Expected 'ok', got '%s'", string(respBody))
}
}
// TestNegotiatorWithNonSeekableBody tests that non-seekable bodies still work (backward compatibility)
func TestNegotiatorWithNonSeekableBody(t *testing.T) {
testData := []byte("test data")
// Create a test server that immediately returns success without auth
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}))
defer server.Close()
// Use a regular bytes.Buffer which is not seekable
req, err := http.NewRequest("POST", server.URL, io.NopCloser(bytes.NewReader(testData)))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request - should work even with non-seekable body
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if string(body) != "ok" {
t.Errorf("Expected 'ok', got '%s'", string(body))
}
}
// verifyRequestUnmodified checks that the request's headers and properties remain unchanged
func verifyRequestUnmodified(t *testing.T, req *http.Request, originalAuthHeader, originalCustomHeader, originalUserAgent, originalURL, originalMethod string) {
t.Helper()
if got := req.Header.Get("Authorization"); got != originalAuthHeader {
t.Errorf("Authorization header was modified: expected %q, got %q", originalAuthHeader, got)
}
if got := req.Header.Get("X-Custom-Header"); got != originalCustomHeader {
t.Errorf("Custom header was modified: expected %q, got %q", originalCustomHeader, got)
}
if got := req.Header.Get("User-Agent"); got != originalUserAgent {
t.Errorf("User-Agent header was modified: expected %q, got %q", originalUserAgent, got)
}
if got := req.URL.String(); got != originalURL {
t.Errorf("Request URL was modified: expected %q, got %q", originalURL, got)
}
if got := req.Method; got != originalMethod {
t.Errorf("Request method was modified: expected %q, got %q", originalMethod, got)
}
}
// TestNegotiatorDoesNotModifyRequest verifies that Negotiator doesn't modify
// the incoming request, as mandated by the http.RoundTripper contract.
func TestNegotiatorDoesNotModifyRequest(t *testing.T) {
testData := []byte("test request body")
// Create a test server that returns success without auth challenges
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}))
defer server.Close()
// Create a request with basic auth
req, err := http.NewRequest("POST", server.URL, io.NopCloser(bytes.NewReader(testData)))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
req.Header.Set("X-Custom-Header", "custom-value")
req.Header.Set("User-Agent", "test-agent")
// Capture the original request state
originalAuthHeader := req.Header.Get("Authorization")
originalCustomHeader := req.Header.Get("X-Custom-Header")
originalUserAgent := req.Header.Get("User-Agent")
originalURL := req.URL.String()
originalMethod := req.Method
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Verify the original request was NOT modified
verifyRequestUnmodified(t, req, originalAuthHeader, originalCustomHeader, originalUserAgent, originalURL, originalMethod)
// Read response body to ensure request completed successfully
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if string(body) != "ok" {
t.Errorf("Expected 'ok', got '%s'", string(body))
}
}
// TestNegotiatorDoesNotModifyRequestWithAuthChallenge verifies that even when
// auth challenges occur, the original request remains unmodified.
func TestNegotiatorDoesNotModifyRequestWithAuthChallenge(t *testing.T) {
testData := []byte("test request body")
callCount := 0
// Create a test server that returns 401 with NTLM but we won't complete
// the full handshake - we just want to verify the original request isn't modified
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
authHeader := r.Header.Get("Authorization")
if callCount == 1 && authHeader == "" {
// First request: no auth, return 401 with NTLM challenge
w.Header().Set("Www-Authenticate", "NTLM")
w.WriteHeader(http.StatusUnauthorized)
} else if callCount == 2 && authHeader == "Basic dGVzdHVzZXI6dGVzdHBhc3M=" {
// Second request: tries basic auth, we'll just accept it for the test
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok with basic"))
} else {
// Any other scenario
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}
}))
defer server.Close()
// Create a request with basic auth
req, err := http.NewRequest("POST", server.URL, io.NopCloser(bytes.NewReader(testData)))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
req.Header.Set("X-Custom-Header", "custom-value")
req.Header.Set("User-Agent", "test-agent")
// Capture the original request state
originalAuthHeader := req.Header.Get("Authorization")
originalCustomHeader := req.Header.Get("X-Custom-Header")
originalUserAgent := req.Header.Get("User-Agent")
originalURL := req.URL.String()
originalMethod := req.Method
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request - will trigger auth negotiation
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Verify the original request was NOT modified, even after auth negotiation
verifyRequestUnmodified(t, req, originalAuthHeader, originalCustomHeader, originalUserAgent, originalURL, originalMethod)
// Just verify we got a response (don't care about specifics of auth result)
if resp.StatusCode != http.StatusOK {
t.Errorf("Note: Got status %d, but request state is what matters for this test", resp.StatusCode)
}
}
// unseekableReadSeeker implements io.ReadSeeker but fails on Seek (like pipes)
type unseekableReadSeeker struct {
reader *bytes.Reader
}
func (u *unseekableReadSeeker) Read(p []byte) (n int, err error) {
return u.reader.Read(p)
}
func (u *unseekableReadSeeker) Seek(offset int64, whence int) (int64, error) {
// Simulate a pipe or other unseekable stream that implements the interface
// but returns an error when seeking
return 0, io.ErrUnexpectedEOF
}
func (u *unseekableReadSeeker) Close() error {
return nil
}
// TestNegotiatorWithUnseekableReadSeeker tests that bodies implementing io.ReadSeeker
// but failing to seek (like pipes) are handled correctly by falling back to buffering
func TestNegotiatorWithUnseekableReadSeeker(t *testing.T) {
testData := []byte("test data from pipe-like source")
// Create a test server that accepts requests without auth
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Read and verify the body was sent correctly
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Failed to read body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !bytes.Equal(body, testData) {
t.Errorf("Body mismatch: expected %q, got %q", testData, body)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}))
defer server.Close()
// Create an unseekable ReadSeeker (simulating a pipe)
bodyReader := &unseekableReadSeeker{reader: bytes.NewReader(testData)}
// Create a request with basic auth
req, err := http.NewRequest("POST", server.URL, bodyReader)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request - should fallback to buffering and work correctly
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if string(respBody) != "ok" {
t.Errorf("Expected 'ok', got '%s'", string(respBody))
}
}
// asyncRoundTripper simulates a RoundTripper that continues reading the request body
// and headers on background goroutines after RoundTrip returns, which is allowed by
// the http.RoundTripper contract. This tests for race conditions in concurrent access
// to both the request body and headers.
type asyncRoundTripper struct {
// requestCount tracks how many times RoundTrip has been called
requestCount atomic.Int32
t *testing.T
}
func (a *asyncRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
count := a.requestCount.Add(1)
// Simulate async body reading and header access
bodyCopy := &bytes.Buffer{}
if req.Body != nil {
// Start reading the body on a background goroutine
go func() {
defer req.Body.Close()
time.Sleep(30 * time.Millisecond)
// Access request headers in background goroutine
_ = req.Header.Get("Authorization")
_ = req.Header.Get("Content-Type")
_ = req.Header.Get("User-Agent")
// Also access other request fields that might be read
_ = req.Method
_ = req.URL.String()
// Simulate slow reading - this is key to testing the race condition
// Without the closeWaiter fix, this would race with the body being
// seeked and reused in the next request
time.Sleep(50 * time.Millisecond)
_, err := io.Copy(bodyCopy, req.Body)
if err != nil {
a.t.Errorf("Background read error: %v", err)
}
}()
// Return immediately (before background goroutine finishes)
// This simulates the behavior that can cause races
}
authHeader := req.Header.Get("Authorization")
// First request with no auth returns 401 requesting Basic or Negotiate
if count == 1 && authHeader == "" {
return &http.Response{
StatusCode: http.StatusUnauthorized,
Header: http.Header{
"Www-Authenticate": []string{"Basic realm=\"test\"", "Negotiate"},
},
Body: io.NopCloser(bytes.NewReader([]byte{})),
ContentLength: 0,
Request: req,
}, nil
}
// Second request with Basic auth, reject and request Negotiate
if count == 2 && bytes.HasPrefix([]byte(authHeader), []byte("Basic ")) {
return &http.Response{
StatusCode: http.StatusUnauthorized,
Header: http.Header{
"Www-Authenticate": []string{"Negotiate"},
},
Body: io.NopCloser(bytes.NewReader([]byte{})),
ContentLength: 0,
Request: req,
}, nil
}
// Any other request: return success
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{},
Body: io.NopCloser(bytes.NewReader([]byte("success"))),
ContentLength: 7,
Request: req,
}, nil
}
// TestNegotiatorWithAsyncBodyReading tests that the Negotiator correctly handles
// race conditions when the wrapped RoundTripper accesses the request on background
// goroutines after RoundTrip returns, which is allowed by the http.RoundTripper contract.
// This test covers two race conditions:
// 1. Body reading: The wrapped RoundTripper reads the request body on a background
// goroutine. Without the closeWaiter fix, this would race with Negotiator seeking
// and reusing the body for the next request.
// 2. Header reading: The wrapped RoundTripper reads request headers on a background
// goroutine. Without cloning the request, this would race with Negotiator modifying
// headers for the next request.
func TestNegotiatorWithAsyncBodyReading(t *testing.T) {
testData := []byte("test data that will be read asynchronously")
// Create an async RoundTripper that simulates background body reading
asyncRT := &asyncRoundTripper{t: t}
// Create a request with a body
bodyReader := bytes.NewReader(testData)
req, err := http.NewRequest("POST", "http://example.com/test", io.NopCloser(bodyReader))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create Negotiator with the async RoundTripper
negotiator := Negotiator{RoundTripper: asyncRT}
resp, err := negotiator.RoundTrip(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if string(respBody) != "success" {
t.Errorf("Expected 'success', got '%s'", string(respBody))
}
// Verify multiple round trips occurred (testing body reuse)
count := asyncRT.requestCount.Load()
// Should be at least 2 round trips: 1. anonymous, 2. with auth
// This is sufficient to test the critical path where body is reused
if count < 2 {
t.Errorf("Expected at least 2 round trips to test body reuse, got %d", count)
}
// Give background goroutines time to complete
time.Sleep(200 * time.Millisecond)
}
// TestNegotiatorWithEmptyBody tests that requests with nil body work correctly
func TestNegotiatorWithEmptyBody(t *testing.T) {
// Create a test server that accepts requests without auth
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Verify body is nil or empty
if r.Body != nil {
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Failed to read body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(body) != 0 {
t.Errorf("Expected empty body, got %d bytes", len(body))
}
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}))
defer server.Close()
// Create a GET request with nil body
req, err := http.NewRequest("GET", server.URL, nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if string(respBody) != "ok" {
t.Errorf("Expected 'ok', got '%s'", string(respBody))
}
}
// TestNegotiatorWithEmptyBodyAndNTLMChallenge tests that requests with nil body
// work correctly through the full NTLM negotiation
func TestNegotiatorWithEmptyBodyAndNTLMChallenge(t *testing.T) {
callCount := 0
// Create a test server that performs NTLM negotiation
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
authHeader := r.Header.Get("Authorization")
// Verify body is nil or empty on all requests
if r.Body != nil {
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Failed to read body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(body) != 0 {
t.Errorf("Expected empty body on request %d, got %d bytes", callCount, len(body))
}
}
if callCount == 1 && authHeader == "" {
// First request: no auth, return 401 with NTLM challenge
w.Header().Set("Www-Authenticate", "NTLM")
w.WriteHeader(http.StatusUnauthorized)
} else if callCount == 2 && authHeader == "Basic dGVzdHVzZXI6dGVzdHBhc3M=" {
// Second request: tries basic auth, still return 401 with NTLM
w.Header().Set("Www-Authenticate", "NTLM")
w.WriteHeader(http.StatusUnauthorized)
} else {
// Final request or any other: success
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("authenticated"))
}
}))
defer server.Close()
// Create a GET request with nil body
req, err := http.NewRequest("GET", server.URL, nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request - should complete NTLM negotiation without body
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
if string(respBody) != "authenticated" {
t.Errorf("Expected 'authenticated', got '%s'", string(respBody))
}
// The test verifies that NTLM negotiation completes successfully in two round trips
// (anonymous and NTLM negotiate), even with an empty body,
// because the server accepts the NTLM negotiate message without requiring a challenge response.
if callCount != 2 {
t.Errorf("Note: %d round trips occurred (expected 2: anonymous + Basic)", callCount)
}
}
// TestNegotiatorBasicToNTLMUpgrade tests that the Negotiator correctly handles
// servers that initially request Basic auth and then upgrade to NTLM
func TestNegotiatorBasicToNTLMUpgrade(t *testing.T) {
testData := []byte("test request body")
callCount := 0
var negotiateMessageReceived bool
// Create a test server that first accepts Basic auth, then upgrades to NTLM
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
authHeader := r.Header.Get("Authorization")
// Verify body is sent correctly on all requests
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Failed to read body on request %d: %v", callCount, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !bytes.Equal(body, testData) {
t.Errorf("Body mismatch on request %d: expected %q, got %q", callCount, testData, body)
}
if callCount == 1 {
// First request: no auth, return 401 with Basic auth request
w.Header().Set("Www-Authenticate", "Basic realm=\"test\"")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("basic auth required"))
} else if callCount == 2 && bytes.HasPrefix([]byte(authHeader), []byte("Basic ")) {
// Second request: Basic auth provided, but upgrade to NTLM
w.Header().Set("Www-Authenticate", "NTLM")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("upgrading to ntlm"))
} else if callCount == 3 && bytes.HasPrefix([]byte(authHeader), []byte("NTLM ")) {
// Third request: NTLM negotiate message
negotiateMessageReceived = true
// Verify the negotiate message doesn't contain credentials
token := strings.TrimPrefix(authHeader, "NTLM ")
decoded, err := base64.StdEncoding.DecodeString(token)
if err == nil {
if bytes.Contains(decoded, []byte("testuser")) {
t.Error("Negotiate message contains username")
}
if bytes.Contains(decoded, []byte("testpass")) {
t.Error("Negotiate message contains password")
}
}
// Final request: accept (would be NTLM in real scenario)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("authenticated"))
} else {
// Unexpected request
w.WriteHeader(http.StatusBadRequest)
}
}))
defer server.Close()
// Create a POST request with a body
req, err := http.NewRequest("POST", server.URL, io.NopCloser(bytes.NewReader(testData)))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
AllowBasicAuth: true,
},
}
// Make the request - should handle Basic to NTLM upgrade successfully
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
// The upgrade should complete successfully
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
if string(respBody) != "authenticated" {
t.Errorf("Expected 'authenticated', got '%s'", string(respBody))
}
// Verify we went through the expected upgrade flow:
// 1. Initial request (no auth) -> 401 Basic
// 2. Request with Basic auth -> 401 NTLM
// 3. Request with NTLM negotiate -> 200 OK (accepted without challenge in test)
if callCount != 3 {
t.Errorf("Expected exactly 3 round trips for Basic->NTLM upgrade, got %d", callCount)
}
// Verify we received and validated the negotiate message
if !negotiateMessageReceived {
t.Error("NTLM negotiate message was not received during Basic->NTLM upgrade")
}
}
// TestNegotiatorBasicAuthOnly tests that the Negotiator correctly handles
// servers that only request Basic auth and accept it without upgrading to NTLM
func TestNegotiatorBasicAuthOnly(t *testing.T) {
testData := []byte("test request body")
callCount := 0
// Create a test server that only accepts Basic auth
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
authHeader := r.Header.Get("Authorization")
// Verify body is sent correctly on all requests
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Failed to read body on request %d: %v", callCount, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !bytes.Equal(body, testData) {
t.Errorf("Body mismatch on request %d: expected %q, got %q", callCount, testData, body)
}
if callCount == 1 && authHeader == "" {
// First request: no auth, return 401 with Basic auth request
w.Header().Set("Www-Authenticate", "Basic realm=\"test\"")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("basic auth required"))
} else if callCount == 2 && bytes.HasPrefix([]byte(authHeader), []byte("Basic ")) {
// Second request: Basic auth provided, accept it
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("authenticated"))
} else {
// Unexpected scenario
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("unexpected request"))
}
}))
defer server.Close()
// Create a POST request with a body
req, err := http.NewRequest("POST", server.URL, io.NopCloser(bytes.NewReader(testData)))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
AllowBasicAuth: true,
},
}
// Make the request - should succeed with Basic auth only
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
if string(respBody) != "authenticated" {
t.Errorf("Expected 'authenticated', got '%s'", string(respBody))
}
// Verify we went through the expected Basic auth flow:
// 1. Initial request (no auth) -> 401 Basic
// 2. Request with Basic auth -> 200 OK
if callCount != 2 {
t.Errorf("Expected exactly 2 round trips for Basic auth only, got %d", callCount)
}
}
// failingReadSeeker implements io.ReadSeeker but fails on Seek after being read
type failingReadSeeker struct {
reader *bytes.Reader
failOnNext bool
}
func (f *failingReadSeeker) Read(p []byte) (n int, err error) {
n, err = f.reader.Read(p)
if err == nil || err == io.EOF {
// After a successful read, mark to fail on next seek
f.failOnNext = true
}
return n, err
}
func (f *failingReadSeeker) Seek(offset int64, whence int) (int64, error) {
if f.failOnNext {
// Simulate a seek failure (e.g., the underlying file was closed)
return 0, io.ErrUnexpectedEOF
}
return f.reader.Seek(offset, whence)
}
func (f *failingReadSeeker) Close() error {
return nil
}
// TestNegotiatorRewindFailureWithBasicAuth tests that when body.rewind() fails
// during Basic auth flow, the response is returned to the client instead of an error
func TestNegotiatorRewindFailureWithBasicAuth(t *testing.T) {
testData := []byte("test request body")
callCount := 0
// Create a test server that requests Basic auth
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
authHeader := r.Header.Get("Authorization")
// Read body to trigger body consumption
_, _ = io.ReadAll(r.Body)
if callCount == 1 && authHeader == "" {
// First request: no auth, return 401 with Basic auth request
w.Header().Set("Www-Authenticate", "Basic realm=\"test\"")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("basic auth required"))
} else {
// Should not reach here if rewind fails properly
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("authenticated"))
}
}))
defer server.Close()
// Create a body that will fail to rewind after being read
bodyReader := &failingReadSeeker{reader: bytes.NewReader(testData), failOnNext: false}
// Create a POST request with the failing body
req, err := http.NewRequest("POST", server.URL, bodyReader)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.SetBasicAuth("testuser", "testpass")
// Create client with NTLM negotiator
client := &http.Client{
Transport: Negotiator{
RoundTripper: http.DefaultTransport,
},
}
// Make the request - should return the 401 response when rewind fails
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed with error (expected response): %v", err)
}
defer resp.Body.Close()
// Should receive the 401 response since rewind failed
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("Expected status 401 (rewind failed), got %d", resp.StatusCode)
}
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response: %v", err)
}
if string(respBody) != "basic auth required" {
t.Errorf("Expected 'basic auth required', got '%s'", string(respBody))
}
// Should only have made 1 round trip since rewind failed
if callCount != 1 {
t.Errorf("Expected exactly 1 round trip (rewind failed), got %d", callCount)
}
}
// TestNegotiatorRewindFailureWithNTLM tests that when body.rewind() fails
// during NTLM negotiation, the response is returned to the client instead of an error
func TestNegotiatorRewindFailureWithNTLM(t *testing.T) {
testData := []byte("test request body")
callCount := 0