summaryrefslogtreecommitdiff
path: root/auth_test.go
blob: 9b679bf6bac9cd6d2901552958bff7ed9535ef28 (plain)
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
package kate

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

type testData struct {
	UserID int
	Name   string
}

type testSerDes struct{}

func (ts testSerDes) Serialize(w io.Writer, data testData) error {
	_, err := w.Write([]byte(strings.Join([]string{string(rune(data.UserID)), data.Name}, "|")))
	return err
}

func (ts testSerDes) Deserialize(r io.Reader, data *testData) error {
	buf, err := io.ReadAll(r)
	if err != nil {
		return err
	}
	parts := strings.Split(string(buf), "|")
	if len(parts) != 2 {
		return io.ErrUnexpectedEOF
	}
	data.UserID = int(rune(parts[0][0]))
	data.Name = parts[1]
	return nil
}

func createTestAuth() Auth[testData] {
	config := AuthConfig[testData]{
		SerDes:     testSerDes{},
		CookieName: "test_auth",
		URLPath:    "/",
		URLDomain:  "example.com",
		HTTPSOnly:  false,
		MaxAge:     time.Hour,
	}
	return New("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", config)
}

func TestNew(t *testing.T) {
	tests := []struct {
		name    string
		privkey string
		wantErr bool
	}{
		{
			name:    "valid hex key",
			privkey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
			wantErr: false,
		},
		{
			name:    "invalid hex key - too short",
			privkey: "0123456789abcdef",
			wantErr: true,
		},
		{
			name:    "invalid hex key - not hex",
			privkey: "invalid_hex_key_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			config := AuthConfig[testData]{
				SerDes:     testSerDes{},
				CookieName: "test",
			}

			defer func() {
				if r := recover(); r != nil {
					if !tt.wantErr {
						t.Errorf("New() panicked unexpectedly: %v", r)
					}
				} else if tt.wantErr {
					t.Errorf("New() should have panicked but didn't")
				}
			}()

			auth := New(tt.privkey, config)
			if !tt.wantErr && auth.config.CookieName != "test" {
				t.Errorf("New() failed to create auth instance properly")
			}
		})
	}
}

func TestAuth_Set(t *testing.T) {
	auth := createTestAuth()
	data := testData{UserID: 123, Name: "Alice"}

	w := httptest.NewRecorder()
	err := auth.Set(w, data)
	if err != nil {
		t.Fatalf("Set() error = %v", err)
	}

	cookies := w.Result().Cookies()
	if len(cookies) != 1 {
		t.Fatalf("Expected 1 cookie, got %d", len(cookies))
	}

	cookie := cookies[0]
	if cookie.Name != "test_auth" {
		t.Errorf("Expected cookie name 'test_auth', got %s", cookie.Name)
	}
	if cookie.Path != "/" {
		t.Errorf("Expected cookie path '/', got %s", cookie.Path)
	}
	if cookie.Domain != "example.com" {
		t.Errorf("Expected cookie domain 'example.com', got %s", cookie.Domain)
	}
	if !cookie.HttpOnly {
		t.Error("Expected cookie to be HttpOnly")
	}
	if cookie.SameSite != http.SameSiteLaxMode {
		t.Errorf("Expected SameSite to be Lax, got %v", cookie.SameSite)
	}
}

func TestAuth_Required(t *testing.T) {
	auth := createTestAuth()
	data := testData{UserID: 123, Name: "Alice"}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		authData, ok := auth.Get(r.Context())
		if !ok {
			t.Error("Expected to find auth data in context")
			return
		}
		if authData.UserID != 123 || authData.Name != "Alice" {
			t.Errorf("Expected UserID=123, Name=Alice, got UserID=%d, Name=%s", authData.UserID, authData.Name)
		}
		w.WriteHeader(http.StatusOK)
	})

	protectedHandler := auth.Required(handler)

	t.Run("missing cookie", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/", nil)
		w := httptest.NewRecorder()

		protectedHandler.ServeHTTP(w, req)

		if w.Code != http.StatusUnauthorized {
			t.Errorf("Expected status 401, got %d", w.Code)
		}
	})

	t.Run("invalid cookie", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(&http.Cookie{
			Name:  "test_auth",
			Value: "invalid_token",
		})
		w := httptest.NewRecorder()

		protectedHandler.ServeHTTP(w, req)

		if w.Code != http.StatusUnauthorized {
			t.Errorf("Expected status 401, got %d", w.Code)
		}
	})

	t.Run("valid cookie", func(t *testing.T) {
		setW := httptest.NewRecorder()
		if err := auth.Set(setW, data); err != nil {
			t.Fatalf("Set() error = %v", err)
		}
		cookie := setW.Result().Cookies()[0]

		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(cookie)
		w := httptest.NewRecorder()

		protectedHandler.ServeHTTP(w, req)

		if w.Code != http.StatusOK {
			t.Errorf("Expected status 200, got %d", w.Code)
		}
	})
}

func TestAuth_Optional(t *testing.T) {
	auth := createTestAuth()
	data := testData{UserID: 123, Name: "Alice"}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		authData, ok := auth.Get(r.Context())
		if ok {
			if authData.UserID != 123 || authData.Name != "Alice" {
				t.Errorf("Expected UserID=123, Name=Alice, got UserID=%d, Name=%s", authData.UserID, authData.Name)
			}
		}
		w.WriteHeader(http.StatusOK)
	})

	optionalHandler := auth.Optional(handler)

	t.Run("missing cookie - should allow", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/", nil)
		w := httptest.NewRecorder()

		optionalHandler.ServeHTTP(w, req)

		if w.Code != http.StatusOK {
			t.Errorf("Expected status 200, got %d", w.Code)
		}
	})

	t.Run("invalid cookie - should allow", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(&http.Cookie{
			Name:  "test_auth",
			Value: "invalid_token",
		})
		w := httptest.NewRecorder()

		optionalHandler.ServeHTTP(w, req)

		if w.Code != http.StatusOK {
			t.Errorf("Expected status 200, got %d", w.Code)
		}
	})

	t.Run("valid cookie", func(t *testing.T) {
		setW := httptest.NewRecorder()
		if err := auth.Set(setW, data); err != nil {
			t.Fatalf("Set() error = %v", err)
		}
		cookie := setW.Result().Cookies()[0]

		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(cookie)
		w := httptest.NewRecorder()

		optionalHandler.ServeHTTP(w, req)

		if w.Code != http.StatusOK {
			t.Errorf("Expected status 200, got %d", w.Code)
		}
	})
}

func TestAuth_Get(t *testing.T) {
	auth := createTestAuth()
	data := testData{UserID: 123, Name: "Alice"}

	t.Run("no data in context", func(t *testing.T) {
		ctx := context.Background()
		result, ok := auth.Get(ctx)
		if ok {
			t.Error("Expected Get to return false for empty context")
		}
		if result.UserID != 0 || result.Name != "" {
			t.Error("Expected zero value for missing data")
		}
	})

	t.Run("data in context", func(t *testing.T) {
		ctx := context.WithValue(context.Background(), key, data)
		result, ok := auth.Get(ctx)
		if !ok {
			t.Error("Expected Get to return true for context with data")
		}
		if result.UserID != 123 || result.Name != "Alice" {
			t.Errorf("Expected UserID=123, Name=Alice, got UserID=%d, Name=%s", result.UserID, result.Name)
		}
	})

	t.Run("wrong type in context", func(t *testing.T) {
		ctx := context.WithValue(context.Background(), key, "wrong_type")
		result, ok := auth.Get(ctx)
		if ok {
			t.Error("Expected Get to return false for wrong type in context")
		}
		if result.UserID != 0 || result.Name != "" {
			t.Error("Expected zero value for wrong type")
		}
	})
}

type failingSerDes struct {
	failSerialize   bool
	failDeserialize bool
}

func (f failingSerDes) Serialize(w io.Writer, data testData) error {
	if f.failSerialize {
		return io.ErrClosedPipe
	}
	return testSerDes{}.Serialize(w, data)
}

func (f failingSerDes) Deserialize(r io.Reader, data *testData) error {
	if f.failDeserialize {
		return io.ErrUnexpectedEOF
	}
	return testSerDes{}.Deserialize(r, data)
}

func TestAuth_Set_SerializationError(t *testing.T) {
	config := AuthConfig[testData]{
		SerDes:     failingSerDes{failSerialize: true},
		CookieName: "test_auth",
	}
	auth := New("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", config)

	data := testData{UserID: 123, Name: "Alice"}
	w := httptest.NewRecorder()

	err := auth.Set(w, data)
	if err == nil {
		t.Error("Expected Set to return error for serialization failure")
	}
}

func TestAuth_Required_DeserializationError(t *testing.T) {
	config := AuthConfig[testData]{
		SerDes:     failingSerDes{failDeserialize: true},
		CookieName: "test_auth",
	}
	goodAuth := createTestAuth()
	badAuth := New("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", config)

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	protectedHandler := badAuth.Required(handler)

	data := testData{UserID: 123, Name: "Alice"}
	setW := httptest.NewRecorder()
	if err := goodAuth.Set(setW, data); err != nil {
		t.Fatalf("Set() error = %v", err)
	}
	cookie := setW.Result().Cookies()[0]

	req := httptest.NewRequest("GET", "/", nil)
	req.AddCookie(cookie)
	w := httptest.NewRecorder()

	protectedHandler.ServeHTTP(w, req)

	if w.Code != http.StatusInternalServerError {
		t.Errorf("Expected status 500 for deserialization error, got %d", w.Code)
	}
}

func TestAuth_Optional_DeserializationError(t *testing.T) {
	config := AuthConfig[testData]{
		SerDes:     failingSerDes{failDeserialize: true},
		CookieName: "test_auth",
	}
	goodAuth := createTestAuth()
	badAuth := New("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", config)

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	optionalHandler := badAuth.Optional(handler)

	data := testData{UserID: 123, Name: "Alice"}
	setW := httptest.NewRecorder()
	if err := goodAuth.Set(setW, data); err != nil {
		t.Fatalf("Set() error = %v", err)
	}
	cookie := setW.Result().Cookies()[0]

	req := httptest.NewRequest("GET", "/", nil)
	req.AddCookie(cookie)
	w := httptest.NewRecorder()

	optionalHandler.ServeHTTP(w, req)

	if w.Code != http.StatusInternalServerError {
		t.Errorf("Expected status 500 for deserialization error, got %d", w.Code)
	}
}

func TestAuth_Clear(t *testing.T) {
	auth := createTestAuth()

	t.Run("clear cookie properties", func(t *testing.T) {
		w := httptest.NewRecorder()
		auth.Clear(w)

		cookies := w.Result().Cookies()
		if len(cookies) != 1 {
			t.Fatalf("Expected 1 cookie, got %d", len(cookies))
		}

		cookie := cookies[0]
		if cookie.Name != "test_auth" {
			t.Errorf("Expected cookie name 'test_auth', got %s", cookie.Name)
		}
		if cookie.Value != "" {
			t.Errorf("Expected empty cookie value, got %s", cookie.Value)
		}
		if cookie.Path != "/" {
			t.Errorf("Expected cookie path '/', got %s", cookie.Path)
		}
		if cookie.Domain != "example.com" {
			t.Errorf("Expected cookie domain 'example.com', got %s", cookie.Domain)
		}
		if cookie.MaxAge != -1 {
			t.Errorf("Expected cookie MaxAge -1, got %d", cookie.MaxAge)
		}
		if !cookie.HttpOnly {
			t.Error("Expected cookie to be HttpOnly")
		}
		if cookie.SameSite != http.SameSiteLaxMode {
			t.Errorf("Expected SameSite to be Lax, got %v", cookie.SameSite)
		}
	})
}

func TestAuth_Clear_RemovesExistingHeaders(t *testing.T) {
	auth := createTestAuth()
	data := testData{UserID: 123, Name: "Alice"}

	t.Run("clear removes existing Set-Cookie headers for same cookie", func(t *testing.T) {
		w := httptest.NewRecorder()
		
		// Set the auth cookie first
		err := auth.Set(w, data)
		if err != nil {
			t.Fatalf("Set() error = %v", err)
		}
		
		// Verify we have one Set-Cookie header
		setCookieHeaders := w.Header()["Set-Cookie"]
		if len(setCookieHeaders) != 1 {
			t.Fatalf("Expected 1 Set-Cookie header after Set(), got %d", len(setCookieHeaders))
		}
		
		// Clear the auth cookie
		auth.Clear(w)
		
		// Verify we still have only one Set-Cookie header (the clear one)
		setCookieHeaders = w.Header()["Set-Cookie"]
		if len(setCookieHeaders) != 1 {
			t.Fatalf("Expected 1 Set-Cookie header after Clear(), got %d", len(setCookieHeaders))
		}
		
		// Parse the remaining cookie to verify it's the clear cookie
		cookies := w.Result().Cookies()
		if len(cookies) != 1 {
			t.Fatalf("Expected 1 parseable cookie, got %d", len(cookies))
		}
		
		cookie := cookies[0]
		if cookie.Name != "test_auth" {
			t.Errorf("Expected cookie name 'test_auth', got %s", cookie.Name)
		}
		if cookie.MaxAge != -1 {
			t.Errorf("Expected cookie MaxAge -1, got %d", cookie.MaxAge)
		}
		if cookie.Value != "" {
			t.Errorf("Expected empty cookie value, got %s", cookie.Value)
		}
	})
	
	t.Run("clear does not affect other cookies", func(t *testing.T) {
		w := httptest.NewRecorder()
		
		// Add a different cookie manually
		otherCookie := &http.Cookie{
			Name:  "other_cookie",
			Value: "other_value",
		}
		w.Header().Add("Set-Cookie", otherCookie.String())
		
		// Set the auth cookie
		err := auth.Set(w, data)
		if err != nil {
			t.Fatalf("Set() error = %v", err)
		}
		
		// Clear the auth cookie
		auth.Clear(w)
		
		// Verify we have two cookies: the other cookie and the clear auth cookie
		cookies := w.Result().Cookies()
		if len(cookies) != 2 {
			t.Fatalf("Expected 2 cookies after Clear(), got %d", len(cookies))
		}
		
		// Find the other cookie
		var foundOtherCookie bool
		var foundClearCookie bool
		for _, cookie := range cookies {
			if cookie.Name == "other_cookie" && cookie.Value == "other_value" {
				foundOtherCookie = true
			}
			if cookie.Name == "test_auth" && cookie.MaxAge == -1 {
				foundClearCookie = true
			}
		}
		
		if !foundOtherCookie {
			t.Error("Expected to find other_cookie in response")
		}
		if !foundClearCookie {
			t.Error("Expected to find clear auth cookie in response")
		}
	})
	
	t.Run("clear works when no existing headers", func(t *testing.T) {
		w := httptest.NewRecorder()
		
		// Clear without setting first
		auth.Clear(w)
		
		// Verify we have one Set-Cookie header (the clear one)
		cookies := w.Result().Cookies()
		if len(cookies) != 1 {
			t.Fatalf("Expected 1 cookie after Clear(), got %d", len(cookies))
		}
		
		cookie := cookies[0]
		if cookie.Name != "test_auth" {
			t.Errorf("Expected cookie name 'test_auth', got %s", cookie.Name)
		}
		if cookie.MaxAge != -1 {
			t.Errorf("Expected cookie MaxAge -1, got %d", cookie.MaxAge)
		}
	})
}

func TestRemoveSetCookieHeaders(t *testing.T) {
	t.Run("removes matching cookie headers", func(t *testing.T) {
		w := httptest.NewRecorder()
		
		// Add multiple cookies
		w.Header().Add("Set-Cookie", "test_auth=value1; Path=/")
		w.Header().Add("Set-Cookie", "other_cookie=value2; Path=/")
		w.Header().Add("Set-Cookie", "test_auth=value3; Path=/; Domain=example.com")
		
		removeSetCookieHeaders(w, "test_auth")
		
		cookies := w.Result().Cookies()
		if len(cookies) != 1 {
			t.Fatalf("Expected 1 cookie after removal, got %d", len(cookies))
		}
		
		if cookies[0].Name != "other_cookie" {
			t.Errorf("Expected other_cookie to remain, got %s", cookies[0].Name)
		}
	})
	
	t.Run("handles empty headers", func(t *testing.T) {
		w := httptest.NewRecorder()
		
		removeSetCookieHeaders(w, "test_auth")
		
		cookies := w.Result().Cookies()
		if len(cookies) != 0 {
			t.Fatalf("Expected 0 cookies, got %d", len(cookies))
		}
	})
	
	t.Run("handles malformed headers", func(t *testing.T) {
		w := httptest.NewRecorder()
		
		// Add a malformed header (no = sign)
		w.Header().Add("Set-Cookie", "malformed_header")
		w.Header().Add("Set-Cookie", "test_auth=value")
		
		removeSetCookieHeaders(w, "test_auth")
		
		// The malformed header should be preserved (check raw headers)
		setCookieHeaders := w.Header()["Set-Cookie"]
		if len(setCookieHeaders) != 1 || setCookieHeaders[0] != "malformed_header" {
			t.Errorf("Expected malformed header to be preserved, got %v", setCookieHeaders)
		}
		
		// The malformed header won't be parsed into a valid cookie by Go's parser
		cookies := w.Result().Cookies()
		if len(cookies) != 0 {
			t.Errorf("Expected 0 parseable cookies (malformed header), got %d", len(cookies))
		}
	})
}

func TestAuth_Required_ClearsInvalidCookies(t *testing.T) {
	auth := createTestAuth()
	
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	protectedHandler := auth.Required(handler)

	t.Run("clears invalid cookie on decryption failure", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(&http.Cookie{
			Name:  "test_auth",
			Value: "invalid_encrypted_value",
		})
		w := httptest.NewRecorder()

		protectedHandler.ServeHTTP(w, req)

		if w.Code != http.StatusUnauthorized {
			t.Errorf("Expected status 401, got %d", w.Code)
		}

		// Verify that a clear cookie was set
		cookies := w.Result().Cookies()
		if len(cookies) != 1 {
			t.Fatalf("Expected 1 clear cookie to be set, got %d", len(cookies))
		}

		cookie := cookies[0]
		if cookie.Name != "test_auth" {
			t.Errorf("Expected cookie name 'test_auth', got %s", cookie.Name)
		}
		if cookie.MaxAge != -1 {
			t.Errorf("Expected cookie MaxAge -1, got %d", cookie.MaxAge)
		}
	})

	t.Run("clears invalid cookie on deserialization failure", func(t *testing.T) {
		// Create a cookie with a different auth instance that will deserialize differently
		config := AuthConfig[testData]{
			SerDes:     failingSerDes{failDeserialize: true},
			CookieName: "test_auth",
		}
		goodAuth := createTestAuth()
		badAuth := New("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", config)

		// Set a cookie with the good auth
		data := testData{UserID: 123, Name: "Alice"}
		setW := httptest.NewRecorder()
		if err := goodAuth.Set(setW, data); err != nil {
			t.Fatalf("Set() error = %v", err)
		}
		validCookie := setW.Result().Cookies()[0]

		// Try to use it with the bad auth (will fail deserialization)
		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(validCookie)
		w := httptest.NewRecorder()

		badAuth.Required(handler).ServeHTTP(w, req)

		if w.Code != http.StatusInternalServerError {
			t.Errorf("Expected status 500, got %d", w.Code)
		}

		// Verify that a clear cookie was set
		cookies := w.Result().Cookies()
		if len(cookies) != 1 {
			t.Fatalf("Expected 1 clear cookie to be set, got %d", len(cookies))
		}

		cookie := cookies[0]
		if cookie.Name != "test_auth" {
			t.Errorf("Expected cookie name 'test_auth', got %s", cookie.Name)
		}
		if cookie.MaxAge != -1 {
			t.Errorf("Expected cookie MaxAge -1, got %d", cookie.MaxAge)
		}
	})
}

func TestAuth_Optional_ClearsInvalidCookies(t *testing.T) {
	auth := createTestAuth()
	
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	optionalHandler := auth.Optional(handler)

	t.Run("clears invalid cookie on decryption failure and continues", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(&http.Cookie{
			Name:  "test_auth",
			Value: "invalid_encrypted_value",
		})
		w := httptest.NewRecorder()

		optionalHandler.ServeHTTP(w, req)

		// Should continue processing (200 OK)
		if w.Code != http.StatusOK {
			t.Errorf("Expected status 200, got %d", w.Code)
		}

		// Verify that a clear cookie was set
		cookies := w.Result().Cookies()
		if len(cookies) != 1 {
			t.Fatalf("Expected 1 clear cookie to be set, got %d", len(cookies))
		}

		cookie := cookies[0]
		if cookie.Name != "test_auth" {
			t.Errorf("Expected cookie name 'test_auth', got %s", cookie.Name)
		}
		if cookie.MaxAge != -1 {
			t.Errorf("Expected cookie MaxAge -1, got %d", cookie.MaxAge)
		}
	})

	t.Run("clears invalid cookie on deserialization failure", func(t *testing.T) {
		// Create a cookie with a different auth instance that will deserialize differently
		config := AuthConfig[testData]{
			SerDes:     failingSerDes{failDeserialize: true},
			CookieName: "test_auth",
		}
		goodAuth := createTestAuth()
		badAuth := New("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", config)

		// Set a cookie with the good auth
		data := testData{UserID: 123, Name: "Alice"}
		setW := httptest.NewRecorder()
		if err := goodAuth.Set(setW, data); err != nil {
			t.Fatalf("Set() error = %v", err)
		}
		validCookie := setW.Result().Cookies()[0]

		// Try to use it with the bad auth (will fail deserialization)
		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(validCookie)
		w := httptest.NewRecorder()

		badAuth.Optional(handler).ServeHTTP(w, req)

		if w.Code != http.StatusInternalServerError {
			t.Errorf("Expected status 500, got %d", w.Code)
		}

		// Verify that a clear cookie was set
		cookies := w.Result().Cookies()
		if len(cookies) != 1 {
			t.Fatalf("Expected 1 clear cookie to be set, got %d", len(cookies))
		}

		cookie := cookies[0]
		if cookie.Name != "test_auth" {
			t.Errorf("Expected cookie name 'test_auth', got %s", cookie.Name)
		}
		if cookie.MaxAge != -1 {
			t.Errorf("Expected cookie MaxAge -1, got %d", cookie.MaxAge)
		}
	})
}

func TestAuth_Clear_Integration(t *testing.T) {
	auth := createTestAuth()
	data := testData{UserID: 123, Name: "Alice"}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		authData, ok := auth.Get(r.Context())
		if !ok {
			t.Error("Expected to find auth data in context")
			return
		}
		if authData.UserID != 123 || authData.Name != "Alice" {
			t.Errorf("Expected UserID=123, Name=Alice, got UserID=%d, Name=%s", authData.UserID, authData.Name)
		}
		w.WriteHeader(http.StatusOK)
	})

	protectedHandler := auth.Required(handler)

	t.Run("authentication works before clear", func(t *testing.T) {
		setW := httptest.NewRecorder()
		if err := auth.Set(setW, data); err != nil {
			t.Fatalf("Set() error = %v", err)
		}
		cookie := setW.Result().Cookies()[0]

		req := httptest.NewRequest("GET", "/", nil)
		req.AddCookie(cookie)
		w := httptest.NewRecorder()

		protectedHandler.ServeHTTP(w, req)

		if w.Code != http.StatusOK {
			t.Errorf("Expected status 200, got %d", w.Code)
		}
	})

	t.Run("authentication fails after clear", func(t *testing.T) {
		setW := httptest.NewRecorder()
		if err := auth.Set(setW, data); err != nil {
			t.Fatalf("Set() error = %v", err)
		}
		originalCookie := setW.Result().Cookies()[0]

		clearW := httptest.NewRecorder()
		auth.Clear(clearW)
		clearCookie := clearW.Result().Cookies()[0]

		if clearCookie.MaxAge != -1 {
			t.Errorf("Expected clear cookie to have MaxAge -1, got %d", clearCookie.MaxAge)
		}

		req := httptest.NewRequest("GET", "/", nil)
		w := httptest.NewRecorder()

		protectedHandler.ServeHTTP(w, req)

		if w.Code != http.StatusUnauthorized {
			t.Errorf("Expected status 401 when no cookie is present (simulating browser behavior after clear), got %d", w.Code)
		}

		req2 := httptest.NewRequest("GET", "/", nil)
		req2.AddCookie(originalCookie)
		w2 := httptest.NewRecorder()

		protectedHandler.ServeHTTP(w2, req2)

		if w2.Code != http.StatusOK {
			t.Errorf("Expected original cookie to still work, got %d", w2.Code)
		}
	})
}