Repository navigation
Expand file tree
/
Copy pathproxy_test.go
More file actions
2373 lines (1984 loc) · 69.4 KB
/
Copy pathproxy_test.go
File metadata and controls
2373 lines (1984 loc) · 69.4 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 (
"bufio"
"bytes"
"compress/gzip"
"crypto/sha1"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/andybalholm/brotli"
"ublproxy/internal/blocklist"
"ublproxy/internal/ca"
"ublproxy/internal/store"
)
// testEnv holds everything needed to run a proxy e2e test.
type testEnv struct {
proxyURL string
httpURL string
httpsURL string
caPool *x509.CertPool
upstreamPool *x509.CertPool
handler *proxyHandler
}
// startTestEnv spins up an upstream HTTP server, an upstream HTTPS server, and
// the proxy itself. The CA is generated in-memory — no disk I/O.
// Pass nil for rules to create a proxy without blocking.
func startTestEnv(t *testing.T, upstreamHandler http.Handler, rules *blocklist.RuleSet) *testEnv {
t.Helper()
// Upstream servers
httpServer := httptest.NewServer(upstreamHandler)
httpsServer := httptest.NewTLSServer(upstreamHandler)
// In-memory CA
caCert, caKey, err := ca.Generate()
if err != nil {
t.Fatalf("ca.Generate: %v", err)
}
certs := ca.NewCache(caCert, caKey)
caCertPEM := ca.EncodeCertPEM(caCert)
handler := newProxyHandler(certs, caCertPEM)
if rules != nil {
handler.baselineRules.Store(rules)
}
// Trust the test HTTPS server's certificate so the proxy can validate
// upstream TLS connections (proxy validates upstream certs in production)
upstreamCAPool := x509.NewCertPool()
upstreamCAPool.AddCert(httpsServer.Certificate())
handler.transport.TLSClientConfig = &tls.Config{
RootCAs: upstreamCAPool,
}
// The proxy needs a real http.Server (not httptest) so that Hijack works
// on the ResponseWriter. httptest.NewServer wraps net/http.Server, which
// does support Hijack, so this is fine.
proxyServer := httptest.NewServer(handler)
// Build a CertPool that trusts our test CA so the HTTP client validates
// the MITM certificates the proxy presents.
caPool := x509.NewCertPool()
caPool.AddCert(caCert)
t.Cleanup(func() {
proxyServer.Close()
httpServer.Close()
httpsServer.Close()
})
return &testEnv{
proxyURL: proxyServer.URL,
httpURL: httpServer.URL,
httpsURL: httpsServer.URL,
caPool: caPool,
upstreamPool: upstreamCAPool,
handler: handler,
}
}
// httpsHost returns the host:port of the HTTPS upstream server.
func (e *testEnv) httpsHost() string {
u, _ := url.Parse(e.httpsURL)
return u.Host
}
// httpClient returns an *http.Client configured to route through the proxy.
// For HTTPS requests, it trusts the test CA (MITM certs).
func (e *testEnv) httpClient(t *testing.T) *http.Client {
t.Helper()
proxyURL, err := url.Parse(e.proxyURL)
if err != nil {
t.Fatalf("parse proxy URL: %v", err)
}
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
TLSClientConfig: &tls.Config{
RootCAs: e.caPool,
},
},
}
}
// passthroughClient returns an *http.Client configured to route through the
// proxy but trusting the upstream server's TLS cert (not the proxy CA).
// Used for testing passthrough tunnels where no MITM occurs.
func (e *testEnv) passthroughClient(t *testing.T) *http.Client {
t.Helper()
proxyURL, err := url.Parse(e.proxyURL)
if err != nil {
t.Fatalf("parse proxy URL: %v", err)
}
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
TLSClientConfig: &tls.Config{
RootCAs: e.upstreamPool,
},
},
}
}
func TestHTTPProxy(t *testing.T) {
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("hello from upstream"))
}), nil)
client := env.httpClient(t)
resp, err := client.Get(env.httpURL + "/test")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK)
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "hello from upstream" {
t.Errorf("body = %q, want %q", body, "hello from upstream")
}
}
func TestHTTPProxyHeaders(t *testing.T) {
var receivedHeaders http.Header
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHeaders = r.Header.Clone()
w.Header().Set("X-Upstream-Header", "present")
w.WriteHeader(http.StatusOK)
}), nil)
client := env.httpClient(t)
req, err := http.NewRequest("GET", env.httpURL+"/headers", nil)
if err != nil {
t.Fatalf("new request: %v", err)
}
req.Header.Set("X-Custom-Header", "test-value")
req.Header.Set("Connection", "keep-alive")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
// Custom header should be forwarded to upstream
if got := receivedHeaders.Get("X-Custom-Header"); got != "test-value" {
t.Errorf("upstream X-Custom-Header = %q, want %q", got, "test-value")
}
// Hop-by-hop headers should be stripped before forwarding
if got := receivedHeaders.Get("Connection"); got != "" {
t.Errorf("upstream Connection header = %q, want it stripped", got)
}
// Response headers from upstream should be forwarded to client
if got := resp.Header.Get("X-Upstream-Header"); got != "present" {
t.Errorf("response X-Upstream-Header = %q, want %q", got, "present")
}
}
func TestHTTPSProxy(t *testing.T) {
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("hello from tls upstream"))
}), nil)
client := env.httpClient(t)
resp, err := client.Get(env.httpsURL + "/secure")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK)
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "hello from tls upstream" {
t.Errorf("body = %q, want %q", body, "hello from tls upstream")
}
}
func TestHTTPSHTMLRewriting(t *testing.T) {
rs := blocklist.NewRuleSet()
rs.AddLine("||ads.tracker.com^")
rs.AddLine("##.ad-banner")
upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`<html><head>` +
`<script src="https://ads.tracker.com/serve.js"></script>` +
`</head><body>` +
`<div class="ad-banner">Ad</div>` +
`<p>Content</p>` +
`</body></html>`))
})
env := startTestEnv(t, upstream, rs)
client := env.httpClient(t)
resp, err := client.Get(env.httpsURL + "/page.html")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
if !strings.Contains(bodyStr, "<!-- ublproxy: blocked script") {
t.Errorf("blocked script should be stripped over HTTPS, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, "<style>") {
t.Errorf("element hiding CSS should be injected over HTTPS, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, ".ad-banner") {
t.Errorf("CSS should contain .ad-banner selector, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, "Content") {
t.Errorf("page content should be preserved, got:\n%s", bodyStr)
}
}
func TestHTTPProxyPOST(t *testing.T) {
var receivedBody string
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
receivedBody = string(body)
w.WriteHeader(http.StatusCreated)
w.Write([]byte("created"))
}), nil)
client := env.httpClient(t)
resp, err := client.Post(env.httpURL+"/create", "text/plain", strings.NewReader("request body"))
if err != nil {
t.Fatalf("POST: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusCreated)
}
if receivedBody != "request body" {
t.Errorf("upstream body = %q, want %q", receivedBody, "request body")
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "created" {
t.Errorf("response body = %q, want %q", body, "created")
}
}
func TestPortalPage(t *testing.T) {
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}), nil)
// Direct request to the proxy (not through it as a proxy)
resp, err := http.Get(env.proxyURL + "/")
if err != nil {
t.Fatalf("GET /: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK)
}
contentType := resp.Header.Get("Content-Type")
if !strings.Contains(contentType, "text/html") {
t.Errorf("Content-Type = %q, want it to contain %q", contentType, "text/html")
}
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
for _, want := range []string{"ublproxy", "ca.crt", "Install"} {
if !strings.Contains(bodyStr, want) {
t.Errorf("body does not contain %q", want)
}
}
}
func TestPortalCACertDownload(t *testing.T) {
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}), nil)
// Direct request to download the CA cert
resp, err := http.Get(env.proxyURL + "/ca.crt")
if err != nil {
t.Fatalf("GET /ca.crt: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK)
}
contentType := resp.Header.Get("Content-Type")
if contentType != "application/x-pem-file" {
t.Errorf("Content-Type = %q, want %q", contentType, "application/x-pem-file")
}
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
if !strings.HasPrefix(bodyStr, "-----BEGIN CERTIFICATE-----") {
t.Errorf("body does not start with PEM header, got %q", bodyStr[:min(len(bodyStr), 40)])
}
// Verify the PEM can be decoded and parsed as a valid certificate
block, _ := pem.Decode(body)
if block == nil {
t.Fatal("failed to decode PEM block from response body")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
t.Fatalf("failed to parse certificate: %v", err)
}
if !cert.IsCA {
t.Error("downloaded certificate is not a CA certificate")
}
if cert.Subject.CommonName != "ublproxy CA" {
t.Errorf("certificate CN = %q, want %q", cert.Subject.CommonName, "ublproxy CA")
}
}
func TestProxyPAC(t *testing.T) {
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}), nil)
// Set portalOrigin so the PAC template can extract host:port
env.handler.portalOrigin = "https://myhost:9443"
resp, err := http.Get(env.proxyURL + "/proxy.pac")
if err != nil {
t.Fatalf("GET /proxy.pac: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK)
}
contentType := resp.Header.Get("Content-Type")
if contentType != "application/x-ns-proxy-autoconfig" {
t.Errorf("Content-Type = %q, want %q", contentType, "application/x-ns-proxy-autoconfig")
}
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
if !strings.Contains(bodyStr, "FindProxyForURL") {
t.Error("PAC body does not contain FindProxyForURL function")
}
if !strings.Contains(bodyStr, "HTTPS myhost:9443") {
t.Errorf("PAC body does not contain expected proxy directive, got:\n%s", bodyStr)
}
}
func TestPACBypassesPrivateNetworks(t *testing.T) {
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}), nil)
env.handler.portalOrigin = "https://myhost.local:9443"
env.handler.httpOrigin = "http://192.168.1.100:8080"
// Desktop PAC should bypass private networks
resp, err := http.Get(env.proxyURL + "/proxy.pac")
if err != nil {
t.Fatalf("GET /proxy.pac: %v", err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
pac := string(body)
privateRanges := []struct {
pattern string
desc string
}{
{`isInNet(host, "10.0.0.0", "255.0.0.0")`, "10.0.0.0/8"},
{`isInNet(host, "172.16.0.0", "255.240.0.0")`, "172.16.0.0/12"},
{`isInNet(host, "192.168.0.0", "255.255.0.0")`, "192.168.0.0/16"},
{`isInNet(host, "169.254.0.0", "255.255.0.0")`, "169.254.0.0/16"},
{`*.local`, ".local mDNS"},
}
for _, r := range privateRanges {
if !strings.Contains(pac, r.pattern) {
t.Errorf("desktop PAC missing bypass for %s (%s)", r.desc, r.pattern)
}
}
// Mobile PAC should also bypass private networks
resp, err = http.Get(env.proxyURL + "/mobile.pac")
if err != nil {
t.Fatalf("GET /mobile.pac: %v", err)
}
body, _ = io.ReadAll(resp.Body)
resp.Body.Close()
mobilePac := string(body)
for _, r := range privateRanges {
if !strings.Contains(mobilePac, r.pattern) {
t.Errorf("mobile PAC missing bypass for %s (%s)", r.desc, r.pattern)
}
}
}
func TestBlocksHTTPByHostname(t *testing.T) {
var upstreamHit atomic.Bool
rs := blocklist.NewRuleSet()
rs.AddHostname("127.0.0.1")
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upstreamHit.Store(true)
w.WriteHeader(http.StatusOK)
w.Write([]byte("should not see this"))
}), rs)
client := env.httpClient(t)
resp, err := client.Get(env.httpURL + "/tracking.js")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusNoContent)
}
body, _ := io.ReadAll(resp.Body)
if len(body) != 0 {
t.Errorf("body = %q, want empty (blocked)", body)
}
if upstreamHit.Load() {
t.Error("upstream was hit, but request should have been blocked")
}
}
func TestBlocksHTTPSByHostname(t *testing.T) {
var upstreamHit atomic.Bool
rs := blocklist.NewRuleSet()
rs.AddHostname("127.0.0.1")
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upstreamHit.Store(true)
w.WriteHeader(http.StatusOK)
w.Write([]byte("should not see this"))
}), rs)
client := env.httpClient(t)
// HTTPS request to a blocked host — the CONNECT tunnel should be blocked
// before any TLS handshake occurs, so the client will get an error.
_, err := client.Get(env.httpsURL + "/secure-tracking.js")
if err == nil {
t.Error("expected error for blocked HTTPS host, got nil")
}
if upstreamHit.Load() {
t.Error("upstream was hit, but request should have been blocked")
}
}
func TestBlocksHTTPByURLPattern(t *testing.T) {
var lastPath string
rs := blocklist.NewRuleSet()
rs.AddRule("/ads/banner*.gif")
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lastPath = r.URL.Path
w.WriteHeader(http.StatusOK)
w.Write([]byte("upstream response"))
}), rs)
client := env.httpClient(t)
// Matching URL pattern should be blocked
resp, err := client.Get(env.httpURL + "/ads/banner123.gif")
if err != nil {
t.Fatalf("GET blocked URL: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Errorf("blocked status = %d, want %d", resp.StatusCode, http.StatusNoContent)
}
// Non-matching URL should pass through
resp, err = client.Get(env.httpURL + "/page.html")
if err != nil {
t.Fatalf("GET allowed URL: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("allowed status = %d, want %d", resp.StatusCode, http.StatusOK)
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "upstream response" {
t.Errorf("body = %q, want %q", body, "upstream response")
}
if lastPath != "/page.html" {
t.Errorf("upstream saw path = %q, want %q", lastPath, "/page.html")
}
}
func TestBlocksHTTPSByURLPattern(t *testing.T) {
var requestPaths []string
rs := blocklist.NewRuleSet()
rs.AddRule("/ads/tracking.js")
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestPaths = append(requestPaths, r.URL.Path)
w.WriteHeader(http.StatusOK)
w.Write([]byte("upstream response"))
}), rs)
client := env.httpClient(t)
// Non-matching path should pass through (CONNECT succeeds, MITM proxies request)
resp, err := client.Get(env.httpsURL + "/page.html")
if err != nil {
t.Fatalf("GET allowed HTTPS URL: %v", err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("allowed status = %d, want %d", resp.StatusCode, http.StatusOK)
}
if string(body) != "upstream response" {
t.Errorf("body = %q, want %q", body, "upstream response")
}
// Matching URL pattern should be blocked after MITM (CONNECT succeeds,
// but the individual request inside the tunnel is blocked)
resp, err = client.Get(env.httpsURL + "/ads/tracking.js")
if err != nil {
t.Fatalf("GET blocked HTTPS URL: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Errorf("blocked status = %d, want %d", resp.StatusCode, http.StatusNoContent)
}
// Only the allowed request should have reached upstream
if len(requestPaths) != 1 || requestPaths[0] != "/page.html" {
t.Errorf("upstream saw paths = %v, want [/page.html]", requestPaths)
}
}
func TestExceptionAllowsBlockedHTTPPath(t *testing.T) {
var requestPaths []string
rs := blocklist.NewRuleSet()
rs.AddRule("/ads/*")
rs.AddException("@@/ads/approved*")
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestPaths = append(requestPaths, r.URL.Path)
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}), rs)
client := env.httpClient(t)
// Blocked by /ads/* rule
resp, err := client.Get(env.httpURL + "/ads/tracking.js")
if err != nil {
t.Fatalf("GET blocked URL: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Errorf("blocked status = %d, want %d", resp.StatusCode, http.StatusNoContent)
}
// Exception allows /ads/approved*
resp, err = client.Get(env.httpURL + "/ads/approved-banner.gif")
if err != nil {
t.Fatalf("GET excepted URL: %v", err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("excepted status = %d, want %d", resp.StatusCode, http.StatusOK)
}
if string(body) != "ok" {
t.Errorf("excepted body = %q, want %q", body, "ok")
}
// Only the excepted request should have reached upstream
if len(requestPaths) != 1 || requestPaths[0] != "/ads/approved-banner.gif" {
t.Errorf("upstream saw paths = %v, want [/ads/approved-banner.gif]", requestPaths)
}
}
func TestThirdPartyOption(t *testing.T) {
var requestPaths []string
rs := blocklist.NewRuleSet()
// Only block /ads/* when the request is cross-origin
rs.AddRule("/ads/*$third-party")
env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestPaths = append(requestPaths, r.URL.Path)
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}), rs)
client := env.httpClient(t)
// Same-origin request (Referer matches request host): should NOT be blocked.
// The upstream runs on 127.0.0.1, so use a Referer from the same host.
req, _ := http.NewRequest("GET", env.httpURL+"/ads/banner.gif", nil)
req.Header.Set("Referer", env.httpURL+"/page.html")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("GET same-origin: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("same-origin status = %d, want %d (should not be blocked)", resp.StatusCode, http.StatusOK)
}
// Cross-origin request (Referer from different domain): should be blocked.
req, _ = http.NewRequest("GET", env.httpURL+"/ads/banner.gif", nil)
req.Header.Set("Referer", "http://differentdomain.com/page.html")
resp, err = client.Do(req)
if err != nil {
t.Fatalf("GET cross-origin: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Errorf("cross-origin status = %d, want %d (should be blocked)", resp.StatusCode, http.StatusNoContent)
}
// Only the same-origin request should have reached upstream
if len(requestPaths) != 1 || requestPaths[0] != "/ads/banner.gif" {
t.Errorf("upstream saw paths = %v, want [/ads/banner.gif]", requestPaths)
}
}
func TestElementHidingCSSInjection(t *testing.T) {
rs := blocklist.NewRuleSet()
rs.AddLine("##.ad-banner")
rs.AddLine("##.tracking-pixel")
upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`<html><head><title>Test</title></head><body>` +
`<div class="ad-banner">Ad content</div>` +
`<img class="tracking-pixel" src="pixel.gif">` +
`<p>Real content</p>` +
`</body></html>`))
})
env := startTestEnv(t, upstream, rs)
client := env.httpClient(t)
resp, err := client.Get(env.httpURL + "/page.html")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
// CSS should be injected to hide matching elements
if !strings.Contains(bodyStr, "<style>") {
t.Errorf("should contain injected style tag, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, ".ad-banner") {
t.Errorf("CSS should contain .ad-banner selector, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, ".tracking-pixel") {
t.Errorf("CSS should contain .tracking-pixel selector, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, "display: none !important") {
t.Errorf("CSS should use display:none, got:\n%s", bodyStr)
}
// Content elements should remain in DOM (hidden by CSS, not stripped)
if !strings.Contains(bodyStr, "Ad content") {
t.Errorf("ad element should remain in DOM (CSS hides it), got:\n%s", bodyStr)
}
// Non-ad content should be preserved
if !strings.Contains(bodyStr, "<title>Test</title>") {
t.Errorf("title should be preserved, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, "Real content") {
t.Errorf("real content should be preserved, got:\n%s", bodyStr)
}
}
func TestElementHidingSkipsNonHTML(t *testing.T) {
rs := blocklist.NewRuleSet()
rs.AddLine("##.ad-banner")
upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status": "ok"}`))
})
env := startTestEnv(t, upstream, rs)
client := env.httpClient(t)
resp, err := client.Get(env.httpURL + "/api/data")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
// JSON response should not be modified
if strings.Contains(bodyStr, "<style>") {
t.Errorf("non-HTML response should not be modified, got:\n%s", bodyStr)
}
if bodyStr != `{"status": "ok"}` {
t.Errorf("body = %q, want %q", bodyStr, `{"status": "ok"}`)
}
}
func TestNonHTMLPreservesCompression(t *testing.T) {
rs := blocklist.NewRuleSet()
rs.AddLine("##.ad-banner")
svgContent := `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><circle cx="50" cy="50" r="40"/></svg>`
// Upstream serves gzip-compressed SVG when client accepts gzip
upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
gz.Write([]byte(svgContent))
gz.Close()
w.Header().Set("Content-Type", "image/svg+xml")
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
w.WriteHeader(http.StatusOK)
w.Write(buf.Bytes())
return
}
w.Header().Set("Content-Type", "image/svg+xml")
w.WriteHeader(http.StatusOK)
w.Write([]byte(svgContent))
})
env := startTestEnv(t, upstream, rs)
client := env.httpClient(t)
client.Transport.(*http.Transport).DisableCompression = true
req, _ := http.NewRequest("GET", env.httpsURL+"/icon.svg", nil)
req.Header.Set("Accept-Encoding", "gzip")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// The proxy must not corrupt non-HTML resources. The gzip body and
// Content-Encoding header should arrive intact at the client.
if resp.Header.Get("Content-Encoding") != "gzip" {
t.Errorf("Content-Encoding = %q, want %q", resp.Header.Get("Content-Encoding"), "gzip")
}
gr, err := gzip.NewReader(bytes.NewReader(body))
if err != nil {
t.Fatalf("body is not valid gzip: %v", err)
}
decoded, _ := io.ReadAll(gr)
gr.Close()
if string(decoded) != svgContent {
t.Errorf("decoded SVG = %q, want %q", decoded, svgContent)
}
}
func TestElementHidingBrotli(t *testing.T) {
rs := blocklist.NewRuleSet()
rs.AddLine("##.ad-banner")
htmlBody := `<html><head></head><body><div class="ad-banner">Ad</div><p>Hello</p></body></html>`
upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
bw := brotli.NewWriter(&buf)
bw.Write([]byte(htmlBody))
bw.Close()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Content-Encoding", "br")
w.WriteHeader(http.StatusOK)
w.Write(buf.Bytes())
})
env := startTestEnv(t, upstream, rs)
client := env.httpClient(t)
resp, err := client.Get(env.httpURL + "/page.html")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
if !strings.Contains(bodyStr, "<style>") {
t.Errorf("brotli HTML should have CSS injected, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, ".ad-banner") {
t.Errorf("CSS should contain .ad-banner selector, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, "Hello") {
t.Errorf("non-ad content should be preserved, got:\n%s", bodyStr)
}
}
func TestElementHidingNestedContent(t *testing.T) {
rs := blocklist.NewRuleSet()
rs.AddLine("##.ad-container")
upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`<html><body>` +
`<div class="ad-container">` +
`<div class="inner"><script src="ad.js"></script>` +
`<iframe src="ad-network.com/serve"></iframe></div>` +
`</div>` +
`<p>Keep this</p>` +
`</body></html>`))
})
env := startTestEnv(t, upstream, rs)
client := env.httpClient(t)
resp, err := client.Get(env.httpURL + "/page.html")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
// Element hiding is CSS-only — container stays in DOM but is hidden
if !strings.Contains(bodyStr, "<style>") {
t.Errorf("should contain CSS injection, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, ".ad-container") {
t.Errorf("CSS should contain .ad-container selector, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, "Keep this") {
t.Errorf("non-ad content should be preserved, got:\n%s", bodyStr)
}
}
func TestElementHidingAllSelectorsCSS(t *testing.T) {
rs := blocklist.NewRuleSet()
rs.AddLine("##div .ad-child") // complex selector
rs.AddLine("##.ad-banner") // simple selector
upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`<html><head></head><body>` +
`<div class="ad-banner">Ad</div>` +
`<div><span class="ad-child">Nested ad</span></div>` +
`</body></html>`))
})
env := startTestEnv(t, upstream, rs)
client := env.httpClient(t)
resp, err := client.Get(env.httpURL + "/page.html")
if err != nil {
t.Fatalf("GET: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
// Both simple and complex selectors should be in CSS
if !strings.Contains(bodyStr, "<style>") {
t.Errorf("should contain injected style tag, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, ".ad-banner") {
t.Errorf("CSS should contain simple selector, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, "div .ad-child") {
t.Errorf("CSS should contain complex selector, got:\n%s", bodyStr)
}
if !strings.Contains(bodyStr, "display: none !important") {
t.Errorf("CSS should use display:none, got:\n%s", bodyStr)
}
// Content elements stay in DOM (CSS hides them)
if !strings.Contains(bodyStr, `class="ad-banner"`) {
t.Errorf("ad element should remain in DOM, got:\n%s", bodyStr)
}
}
func TestElementHidingByID(t *testing.T) {
rs := blocklist.NewRuleSet()
rs.AddLine("###sidebar-ad")
upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`<html><body>` +
`<div id="sidebar-ad"><a href="sponsor.html">Sponsor</a></div>` +
`<div id="content">Main</div>` +
`</body></html>`))
})
env := startTestEnv(t, upstream, rs)
client := env.httpClient(t)