-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
2178 lines (1887 loc) · 60.9 KB
/
main_test.go
File metadata and controls
2178 lines (1887 loc) · 60.9 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
package main
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/tionis/patchwork/internal/metrics"
"golang.org/x/time/rate"
"gopkg.in/yaml.v3"
)
func TestGetClientIP(t *testing.T) {
tests := []struct {
name string
headers map[string]string
remoteAddr string
expectedIP string
}{
{
name: "X-Forwarded-For single IP",
headers: map[string]string{"X-Forwarded-For": "192.168.1.100"},
remoteAddr: "10.0.0.1:12345",
expectedIP: "192.168.1.100",
},
{
name: "X-Forwarded-For multiple IPs",
headers: map[string]string{"X-Forwarded-For": "192.168.1.100, 10.0.0.1, 172.16.0.1"},
remoteAddr: "10.0.0.1:12345",
expectedIP: "192.168.1.100",
},
{
name: "X-Real-IP header",
headers: map[string]string{"X-Real-IP": "203.0.113.1"},
remoteAddr: "10.0.0.1:12345",
expectedIP: "203.0.113.1",
},
{
name: "CF-Connecting-IP header",
headers: map[string]string{"CF-Connecting-IP": "198.51.100.1"},
remoteAddr: "10.0.0.1:12345",
expectedIP: "198.51.100.1",
},
{
name: "RemoteAddr fallback with port",
headers: map[string]string{},
remoteAddr: "172.16.0.50:54321",
expectedIP: "172.16.0.50",
},
{
name: "RemoteAddr fallback without port",
headers: map[string]string{},
remoteAddr: "192.168.1.1",
expectedIP: "192.168.1.1",
},
{
name: "X-Forwarded-For takes precedence",
headers: map[string]string{
"X-Forwarded-For": "192.168.1.100",
"X-Real-IP": "203.0.113.1",
"CF-Connecting-IP": "198.51.100.1",
},
remoteAddr: "10.0.0.1:12345",
expectedIP: "192.168.1.100",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
req.RemoteAddr = tt.remoteAddr
for key, value := range tt.headers {
req.Header.Set(key, value)
}
result := getClientIP(req)
if result != tt.expectedIP {
t.Errorf("Expected IP %q, got %q", tt.expectedIP, result)
}
})
}
}
func TestGenerateUUID(t *testing.T) {
// Test successful UUID generation
uuid1, err := generateUUID()
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
uuid2, err := generateUUID()
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
// UUIDs should be different
if uuid1 == uuid2 {
t.Error("Expected different UUIDs, got the same")
}
// UUID should have the expected format (8-4-4-4-12 hex characters)
parts := strings.Split(uuid1, "-")
if len(parts) != 5 {
t.Errorf("Expected UUID with 5 parts, got %d parts: %s", len(parts), uuid1)
}
expectedLengths := []int{8, 4, 4, 4, 12}
for i, part := range parts {
if len(part) != expectedLengths[i] {
t.Errorf("Expected part %d to have length %d, got %d: %s", i, expectedLengths[i], len(part), part)
}
// Check if it's valid hex
if _, err := hex.DecodeString(part); err != nil {
t.Errorf("Expected part %d to be valid hex, got error: %v", i, err)
}
}
}
func TestServerComputeSecret(t *testing.T) {
secretKey := []byte("test-secret-key-for-testing")
logger := slog.Default()
authCache := NewAuthCache("https://test.example.com", "test-token", 5*time.Minute, logger)
server := &server{
logger: logger,
secretKey: secretKey,
authCache: authCache,
}
// Test secret generation
secret1 := server.computeSecret("test", "channel1")
secret2 := server.computeSecret("test", "channel2")
secret3 := server.computeSecret("other", "channel1")
// Different channels should have different secrets
if secret1 == secret2 {
t.Error("Expected different secrets for different channels")
}
// Different namespaces should have different secrets
if secret1 == secret3 {
t.Error("Expected different secrets for different namespaces")
}
// Same namespace and channel should produce same secret
secret1Again := server.computeSecret("test", "channel1")
if secret1 != secret1Again {
t.Error("Expected same secret for same namespace and channel")
}
// Secret should be hex encoded
if _, err := hex.DecodeString(secret1); err != nil {
t.Errorf("Expected secret to be valid hex, got error: %v", err)
}
}
func TestServerVerifySecret(t *testing.T) {
secretKey := []byte("test-secret-key-for-testing")
logger := slog.Default()
authCache := NewAuthCache("https://test.example.com", "test-token", 5*time.Minute, logger)
server := &server{
logger: logger,
secretKey: secretKey,
authCache: authCache,
}
namespace := "test"
channel := "channel1"
correctSecret := server.computeSecret(namespace, channel)
incorrectSecret := "invalid-secret"
// Test correct secret verification
if !server.verifySecret(namespace, channel, correctSecret) {
t.Error("Expected correct secret to be verified as valid")
}
// Test incorrect secret verification
if server.verifySecret(namespace, channel, incorrectSecret) {
t.Error("Expected incorrect secret to be verified as invalid")
}
// Test empty secret
if server.verifySecret(namespace, channel, "") {
t.Error("Expected empty secret to be verified as invalid")
}
}
func TestHealthCheck(t *testing.T) {
// Test successful health check
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
if _, err := w.Write([]byte("OK")); err != nil {
t.Errorf("Failed to write response: %v", err)
}
}))
defer server.Close()
err := healthCheck(server.URL)
if err != nil {
t.Errorf("Expected no error for successful health check, got %v", err)
}
// Test failed health check (404)
server404 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
if _, err := w.Write([]byte("Not Found")); err != nil {
t.Errorf("Failed to write response: %v", err)
}
}))
defer server404.Close()
err = healthCheck(server404.URL)
if err == nil {
t.Error("Expected error for failed health check, got none")
}
if !strings.Contains(err.Error(), "received status 404") {
t.Errorf("Expected error message about status 404, got: %v", err)
}
// Test health check with invalid URL
err = healthCheck("http://invalid-url-that-does-not-exist.test")
if err == nil {
t.Error("Expected error for invalid URL, got none")
}
if !strings.Contains(err.Error(), "health check failed") {
t.Errorf("Expected error message about health check failure, got: %v", err)
}
}
func TestGetHTTPServer(t *testing.T) {
// Set up environment variables
originalForgejoURL := os.Getenv("FORGEJO_URL")
originalForgejoToken := os.Getenv("FORGEJO_TOKEN")
originalSecretKey := os.Getenv("SECRET_KEY")
defer func() {
if err := os.Setenv("FORGEJO_URL", originalForgejoURL); err != nil {
t.Logf("Failed to restore FORGEJO_URL: %v", err)
}
if err := os.Setenv("FORGEJO_TOKEN", originalForgejoToken); err != nil {
t.Logf("Failed to restore FORGEJO_TOKEN: %v", err)
}
if err := os.Setenv("SECRET_KEY", originalSecretKey); err != nil {
t.Logf("Failed to restore SECRET_KEY: %v", err)
}
}()
t.Run("Missing SECRET_KEY", func(t *testing.T) {
if err := os.Setenv("FORGEJO_URL", "https://test.example.com"); err != nil {
t.Fatalf("Failed to set FORGEJO_URL: %v", err)
}
if err := os.Setenv("FORGEJO_TOKEN", "test-token"); err != nil {
t.Fatalf("Failed to set FORGEJO_TOKEN: %v", err)
}
if err := os.Setenv("SECRET_KEY", ""); err != nil {
t.Fatalf("Failed to set SECRET_KEY: %v", err)
}
logger := slog.Default()
ctx := context.Background()
server := getHTTPServer(logger, ctx, 8080)
if server != nil {
t.Error("Expected nil server when SECRET_KEY is missing")
}
})
t.Run("Missing FORGEJO_TOKEN", func(t *testing.T) {
os.Setenv("FORGEJO_URL", "https://test.example.com")
os.Setenv("FORGEJO_TOKEN", "")
os.Setenv("SECRET_KEY", "test-secret-key")
logger := slog.Default()
ctx := context.Background()
server := getHTTPServer(logger, ctx, 8080)
if server != nil {
t.Error("Expected nil server when FORGEJO_TOKEN is missing")
}
})
t.Run("Valid configuration", func(t *testing.T) {
os.Setenv("FORGEJO_URL", "https://test.example.com")
os.Setenv("FORGEJO_TOKEN", "test-token")
os.Setenv("SECRET_KEY", "test-secret-key")
os.Setenv("ACL_TTL", "10m")
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
ctx := context.Background()
server := getHTTPServer(logger, ctx, 8081)
if server == nil {
t.Fatal("Expected valid server, got nil")
}
expectedAddr := ":8081"
if server.Addr != expectedAddr {
t.Errorf("Expected server address %q, got %q", expectedAddr, server.Addr)
}
if server.Handler == nil {
t.Error("Expected server to have a handler")
}
})
}
func TestServerLogRequest(t *testing.T) {
server := &server{
logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
}
req := httptest.NewRequest("GET", "/test/path?param=value", nil)
req.Header.Set("User-Agent", "test-agent")
req.Header.Set("Referer", "https://example.com")
req.RemoteAddr = "192.168.1.100:12345"
// This test mainly ensures the function doesn't panic
server.logRequest(req, "Test message")
// Since we're using the default logger, we can't easily capture the output
// but we can ensure it doesn't crash
}
func TestStatusHandler(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
server := &server{
logger: logger,
}
req := httptest.NewRequest("GET", "/status", nil)
w := httptest.NewRecorder()
server.statusHandler(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
expectedBody := "OK!\n"
if w.Body.String() != expectedBody {
t.Errorf("Expected body %q, got %q", expectedBody, w.Body.String())
}
}
func TestNotFoundHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/nonexistent", nil)
req.RemoteAddr = "192.168.1.100:12345"
w := httptest.NewRecorder()
notFoundHandler(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("Expected status %d, got %d", http.StatusNotFound, w.Code)
}
}
func TestServeFile(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
t.Run("Existing file", func(t *testing.T) {
// Test with favicon.ico which should exist
handler := serveFile(logger, "assets/favicon.ico", "image/x-icon")
req := httptest.NewRequest("GET", "/favicon.ico", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
contentType := w.Header().Get("Content-Type")
if contentType != "image/x-icon" {
t.Errorf("Expected Content-Type %q, got %q", "image/x-icon", contentType)
}
if w.Body.Len() == 0 {
t.Error("Expected non-empty response body")
}
})
t.Run("Non-existing file", func(t *testing.T) {
handler := serveFile(logger, "assets/nonexistent.txt", "text/plain")
req := httptest.NewRequest("GET", "/nonexistent.txt", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("Expected status %d, got %d", http.StatusNotFound, w.Code)
}
})
}
func TestAuthenticateTokenEdgeCases(t *testing.T) {
server := createTestMainServer()
clientIP := net.ParseIP("192.168.1.100")
t.Run("Public namespace no authentication", func(t *testing.T) {
allowed, reason, err := server.authenticateToken("", "any-token", "/test", "GET", false, clientIP)
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
if !allowed {
t.Error("Expected public namespace to be allowed")
}
if reason != "public" {
t.Errorf("Expected reason 'public', got %q", reason)
}
})
t.Run("No token provided", func(t *testing.T) {
allowed, reason, err := server.authenticateToken("testuser", "", "/test", "GET", false, clientIP)
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
if allowed {
t.Error("Expected access to be denied when no token provided")
}
if reason != "token not found" {
t.Errorf("Expected reason 'token not found', got %q", reason)
}
})
}
func TestTokenInfoMarshalUnmarshalYAML(t *testing.T) {
// Test MarshalYAML
tokenInfo := TokenInfo{
IsAdmin: true,
ExpiresAt: func() *time.Time { t := time.Now(); return &t }(),
}
// Test that MarshalYAML doesn't panic
_, err := tokenInfo.MarshalYAML()
if err != nil {
t.Errorf("Expected no error from MarshalYAML, got %v", err)
}
}
func TestTokenInfoUnmarshalYAML(t *testing.T) {
tests := []struct {
name string
yamlData string
expectedAdmin bool
expectError bool
}{
{
name: "Valid admin token",
yamlData: "is_admin: true",
expectedAdmin: true,
expectError: false,
},
{
name: "Valid non-admin token",
yamlData: "is_admin: false",
expectedAdmin: false,
expectError: false,
},
{
name: "Empty YAML",
yamlData: "",
expectedAdmin: false,
expectError: false,
},
{
name: "Only admin field",
yamlData: "is_admin: true",
expectedAdmin: true,
expectError: false,
},
{
name: "Invalid YAML",
yamlData: "is_admin: [invalid",
expectError: true,
},
{
name: "Admin field with string value",
yamlData: "is_admin: \"true\"",
expectError: true, // String values can't be unmarshaled to bool
},
{
name: "Admin field with string false",
yamlData: "is_admin: \"false\"",
expectError: true, // String values can't be unmarshaled to bool
},
{
name: "Complex YAML with other fields",
yamlData: "is_admin: true\nGET:\n - \"/api/*\"\nPOST:\n - \"/data/*\"",
expectedAdmin: true,
expectError: false,
},
{
name: "YAML with expires_at field",
yamlData: "is_admin: false\nexpires_at: 2024-12-31T23:59:59Z",
expectedAdmin: false,
expectError: false,
},
{
name: "YAML with HTTP method patterns",
yamlData: "is_admin: false\nGET:\n - \"/api/*\"\n - \"/health\"\nPOST:\n - \"/data/*\"\nhuproxy:\n - \"example.com:*\"",
expectedAdmin: false,
expectError: false,
},
{
name: "YAML with all HTTP methods",
yamlData: "is_admin: true\nGET:\n - \"/*\"\nPOST:\n - \"/*\"\nPUT:\n - \"/*\"\nDELETE:\n - \"/*\"\nPATCH:\n - \"/*\"",
expectedAdmin: true,
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var tokenInfo TokenInfo
// Use yaml.Unmarshal to trigger the UnmarshalYAML method
err := yaml.Unmarshal([]byte(tt.yamlData), &tokenInfo)
if tt.expectError {
if err == nil {
t.Error("Expected error from UnmarshalYAML, got none")
}
return
}
if err != nil {
t.Errorf("Expected no error from UnmarshalYAML, got %v", err)
return
}
if tokenInfo.IsAdmin != tt.expectedAdmin {
t.Errorf("Expected IsAdmin %v, got %v", tt.expectedAdmin, tokenInfo.IsAdmin)
}
})
}
}
func TestPatchChannelCreation(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
authCache := NewAuthCache("https://test.example.com", "test-token", 5*time.Minute, logger)
server := &server{
logger: logger,
channels: make(map[string]*patchChannel),
ctx: context.Background(),
authCache: authCache,
}
// Test that channels map is properly initialized
if server.channels == nil {
t.Error("Expected channels map to be initialized")
}
if len(server.channels) != 0 {
t.Errorf("Expected empty channels map, got %d channels", len(server.channels))
}
}
func TestNewAuthCache(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
forgejoURL := "https://test.example.com"
forgejoToken := "test-token"
ttl := 10 * time.Minute
cache := NewAuthCache(forgejoURL, forgejoToken, ttl, logger)
if cache == nil {
t.Fatal("Expected AuthCache to be created, got nil")
}
if cache.forgejoURL != forgejoURL {
t.Errorf("Expected forgejoURL %q, got %q", forgejoURL, cache.forgejoURL)
}
if cache.forgejoToken != forgejoToken {
t.Errorf("Expected forgejoToken %q, got %q", forgejoToken, cache.forgejoToken)
}
if cache.ttl != ttl {
t.Errorf("Expected ttl %v, got %v", ttl, cache.ttl)
}
if cache.data == nil {
t.Error("Expected data map to be initialized")
}
if len(cache.data) != 0 {
t.Errorf("Expected empty data map, got %d entries", len(cache.data))
}
}
func TestConfigDataStruct(t *testing.T) {
// Test ConfigData struct creation
config := ConfigData{
ForgejoURL: "https://test.example.com",
ACLTTL: 5 * time.Minute,
BaseURL: "https://patchwork.example.com",
WebSocketURL: "wss://patchwork.example.com",
}
if config.ForgejoURL != "https://test.example.com" {
t.Errorf("Expected ForgejoURL to be set correctly")
}
if config.ACLTTL != 5*time.Minute {
t.Errorf("Expected ACLTTL to be set correctly")
}
if config.BaseURL != "https://patchwork.example.com" {
t.Errorf("Expected BaseURL to be set correctly")
}
if config.WebSocketURL != "wss://patchwork.example.com" {
t.Errorf("Expected WebSocketURL to be set correctly")
}
}
// Test that server implements the ServerInterface for huproxy
func TestServerInterface(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
authCache := NewAuthCache("https://test.example.com", "test-token", 5*time.Minute, logger)
server := &server{
logger: logger,
authCache: authCache,
}
// Test AuthenticateToken method
clientIP := net.ParseIP("192.168.1.100")
allowed, reason, err := server.AuthenticateToken("", "test-token", "/test", "GET", false, clientIP)
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
if !allowed {
t.Error("Expected public namespace to be allowed")
}
if reason != "public" {
t.Errorf("Expected reason 'public', got %q", reason)
}
// Test GetLogger method
loggerInterface := server.GetLogger()
if loggerInterface == nil {
t.Error("Expected logger interface to be returned")
}
}
// Helper function to create a test server with mock auth cache
func createTestMainServer() *server {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
secretKey := []byte("test-secret-key-for-testing-purposes")
authCache := NewAuthCache("https://test.forgejo.dev", "test-token", 5*time.Minute, logger)
// Create mock auth data to avoid actual HTTP requests
mockUserAuth := &UserAuth{
Tokens: map[string]TokenInfo{
"valid-token": {
IsAdmin: false,
},
"admin-token": {
IsAdmin: true,
},
},
UpdatedAt: time.Now(),
}
authCache.data = map[string]*UserAuth{
"testuser": mockUserAuth,
"admin": mockUserAuth,
}
// Create metrics instance for testing
metricsInstance := metrics.NewMetrics()
return &server{
logger: logger,
channels: make(map[string]*patchChannel),
channelsMutex: sync.RWMutex{},
ctx: context.Background(),
forgejoURL: "https://test.forgejo.dev",
forgejoToken: "test-token",
aclTTL: 5 * time.Minute,
secretKey: secretKey,
authCache: authCache,
metrics: metricsInstance,
publicRateLimiters: make(map[string]*rate.Limiter),
rateLimiterMutex: sync.RWMutex{},
}
}
func TestPublicHandler(t *testing.T) {
tests := []struct {
name string
method string
path string
body string
expectTimeout bool
expectedStatus int
}{
{
name: "GET request - should hang waiting for data",
method: "GET",
path: "unique-path-1",
expectTimeout: true, // GET will wait for data
},
{
name: "POST request with data - should hang waiting for consumer",
method: "POST",
path: "unique-path-2",
body: "test data",
expectTimeout: true, // POST will wait for consumer
},
{
name: "PUT request - should hang waiting for consumer",
method: "PUT",
path: "unique-path-3",
body: "updated data",
expectTimeout: true, // PUT will wait for consumer
},
{
name: "DELETE request - should complete immediately",
method: "DELETE",
path: "any-path",
expectTimeout: false,
expectedStatus: http.StatusMethodNotAllowed,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create fresh server for each test to avoid channel pollution
server := createTestMainServer()
var body io.Reader
if tt.body != "" {
body = strings.NewReader(tt.body)
}
req := httptest.NewRequest(tt.method, "/p/"+tt.path, body)
req = mux.SetURLVars(req, map[string]string{"path": tt.path})
w := httptest.NewRecorder()
if tt.expectTimeout {
done := make(chan bool)
go func() {
server.publicHandler(w, req)
done <- true
}()
select {
case <-done:
t.Errorf("Expected operation to timeout waiting for channel communication, but got status %d with body: %s", w.Code, w.Body.String())
case <-time.After(50 * time.Millisecond):
t.Log("Operation correctly timed out as expected")
}
} else {
server.publicHandler(w, req)
if w.Code != tt.expectedStatus {
t.Errorf("Expected status %d, got %d", tt.expectedStatus, w.Code)
}
}
})
}
}
func TestPublicRateLimiting(t *testing.T) {
server := createTestMainServer()
// Create a mock handler that doesn't block (unlike the real publicHandler)
mockHandler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
// Test rate limiting for public namespace
// The rate limiter allows 10 requests per second with burst of 20
clientIP := "192.168.1.100"
// Create multiple requests from the same IP
for i := 0; i < 25; i++ { // More than the burst limit of 20
req := httptest.NewRequest("GET", "/p/rate-limit-test", nil)
req.RemoteAddr = clientIP + ":12345"
w := httptest.NewRecorder()
// Apply rate limiting middleware with mock handler
rateLimitedHandler := server.rateLimitMiddleware(mockHandler)
rateLimitedHandler(w, req)
if i < 20 {
// First 20 requests should pass (burst limit)
if w.Code == http.StatusTooManyRequests {
t.Errorf("Request %d should not be rate limited, got status %d", i, w.Code)
}
} else {
// Requests beyond burst limit should be rate limited
if w.Code != http.StatusTooManyRequests {
t.Errorf("Request %d should be rate limited, got status %d", i, w.Code)
}
}
}
// Test that different IPs are not affected by each other's rate limits
differentIP := "192.168.1.200"
req := httptest.NewRequest("GET", "/p/different-ip-test", nil)
req.RemoteAddr = differentIP + ":12345"
w := httptest.NewRecorder()
rateLimitedHandler := server.rateLimitMiddleware(mockHandler)
rateLimitedHandler(w, req)
if w.Code == http.StatusTooManyRequests {
t.Error("Different IP should not be rate limited")
}
t.Log("Rate limiting test completed successfully")
}
func TestUserHandler(t *testing.T) {
server := createTestMainServer()
tests := []struct {
name string
method string
username string
path string
token string
body string
expectedStatus int
shouldComplete bool
}{
{
name: "No token provided",
method: "GET",
username: "testuser",
path: "test-path",
token: "",
expectedStatus: http.StatusUnauthorized,
shouldComplete: true, // Auth check happens before channel operations
},
{
name: "Invalid token",
method: "GET",
username: "testuser",
path: "test-path",
token: "invalid-token",
expectedStatus: http.StatusUnauthorized,
shouldComplete: true, // Auth check happens before channel operations
},
{
name: "Valid token but no patterns - POST",
method: "POST",
username: "testuser",
path: "test-path",
token: "valid-token",
body: "test data",
expectedStatus: http.StatusUnauthorized,
shouldComplete: true, // Auth will fail due to no patterns
},
{
name: "Valid token but no patterns - GET",
method: "GET",
username: "testuser",
path: "test-path",
token: "valid-token",
expectedStatus: http.StatusUnauthorized,
shouldComplete: true, // Auth will fail due to no patterns
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var body io.Reader
if tt.body != "" {
body = strings.NewReader(tt.body)
}
req := httptest.NewRequest(tt.method, "/u/"+tt.username+"/"+tt.path, body)
req = mux.SetURLVars(req, map[string]string{
"username": tt.username,
"path": tt.path,
})
if tt.token != "" {
req.Header.Set("Authorization", "Bearer "+tt.token)
}
w := httptest.NewRecorder()
if tt.shouldComplete {
server.userHandler(w, req)
if w.Code != tt.expectedStatus {
t.Errorf("Expected status %d, got %d. Body: %s", tt.expectedStatus, w.Code, w.Body.String())
}
} else {
done := make(chan bool)
go func() {
server.userHandler(w, req)
done <- true
}()
select {
case <-done:
if w.Code != tt.expectedStatus {
t.Errorf("Expected status %d, got %d. Body: %s", tt.expectedStatus, w.Code, w.Body.String())
}
case <-time.After(50 * time.Millisecond):
t.Log("Operation timed out as expected")
}
}
})
}
}
func TestUserAdminHandler(t *testing.T) {
tests := []struct {
name string
username string
adminPath string
token string
expectedStatus int
expectedBody string
}{
{
name: "Valid admin token for cache invalidation",
username: "admin",
adminPath: "invalidate_cache",
token: "admin-token",
expectedStatus: http.StatusOK,
expectedBody: `{"status": "cache invalidated"}`,
},
{
name: "No authorization header",
username: "admin",
adminPath: "invalidate_cache",
token: "",
expectedStatus: http.StatusUnauthorized,
},
{
name: "Invalid admin path",
username: "admin",
adminPath: "unknown-endpoint",
token: "admin-token",
expectedStatus: http.StatusNotFound, // Should get 404 for unknown endpoint
},
{
name: "Non-admin token",
username: "testuser",
adminPath: "invalidate_cache",
token: "valid-token",
expectedStatus: http.StatusForbidden,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := createTestMainServer() // Create fresh server for each test
req := httptest.NewRequest("POST", "/u/"+tt.username+"/_/"+tt.adminPath, nil)
req = mux.SetURLVars(req, map[string]string{
"username": tt.username,
"adminPath": tt.adminPath,
})
if tt.token != "" {
req.Header.Set("Authorization", "Bearer "+tt.token)
}
w := httptest.NewRecorder()
server.userAdminHandler(w, req)
if w.Code != tt.expectedStatus {
t.Errorf("Expected status %d, got %d. Body: %s", tt.expectedStatus, w.Code, w.Body.String())
}
if tt.expectedBody != "" {
if strings.TrimSpace(w.Body.String()) != tt.expectedBody {
t.Errorf("Expected body %q, got %q", tt.expectedBody, strings.TrimSpace(w.Body.String()))
}
}
})
}
}
func TestForwardHookRootHandler(t *testing.T) {
server := createTestMainServer()
t.Run("GET request creates channel", func(t *testing.T) {
req := httptest.NewRequest("GET", "/h", nil)