-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsysproxy_test.go
More file actions
603 lines (518 loc) · 16.9 KB
/
sysproxy_test.go
File metadata and controls
603 lines (518 loc) · 16.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
package sysproxy
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// ── Get ───────────────────────────────────────────────────────────────────────
func TestGet_NotSet(t *testing.T) {
useMockBackend(t, &mockBackend{
getGlobalFn: func(_ context.Context) (string, error) {
return "", fmt.Errorf("sysproxy: proxy not set")
},
})
_, err := Get()
if err == nil {
t.Error("expected error when proxy not set")
}
}
func TestGet_Set(t *testing.T) {
const want = "http://proxy.example.com:8080"
useMockBackend(t, &mockBackend{
getGlobalFn: func(_ context.Context) (string, error) {
return want, nil
},
})
got, err := Get()
if err != nil {
t.Fatal(err)
}
if got != want {
t.Errorf("Get() = %q, want %q", got, want)
}
}
// ── parse ─────────────────────────────────────────────────────────────────────
func TestParseWithAuth(t *testing.T) {
p, err := parse("http://user:pass@proxy.example.com:8080")
if err != nil {
t.Fatal(err)
}
if p.host != "proxy.example.com" {
t.Errorf("host: got %q, want %q", p.host, "proxy.example.com")
}
if p.port != "8080" {
t.Errorf("port: got %q, want %q", p.port, "8080")
}
if p.user != "user" {
t.Errorf("user: got %q, want %q", p.user, "user")
}
if p.pass != "pass" {
t.Errorf("pass: got %q, want %q", p.pass, "pass")
}
}
func TestParseWithoutAuth(t *testing.T) {
p, err := parse("http://proxy.example.com:3128")
if err != nil {
t.Fatal(err)
}
if p.host != "proxy.example.com" {
t.Errorf("host: got %q, want %q", p.host, "proxy.example.com")
}
if p.user != "" || p.pass != "" {
t.Errorf("expected empty credentials, got user=%q pass=%q", p.user, p.pass)
}
}
func TestParseInvalidURL(t *testing.T) {
_, err := parse("://bad url")
if err == nil {
t.Fatal("expected error for invalid URL, got nil")
}
}
func TestParseEmpty(t *testing.T) {
p, err := parse("")
if err != nil {
t.Fatal(err)
}
if p.host != "" || p.port != "" {
t.Errorf("expected empty host/port, got host=%q port=%q", p.host, p.port)
}
}
func TestParseSocks5(t *testing.T) {
p, err := parse("socks5://user:pass@proxy.example.com:1080")
if err != nil {
t.Fatal(err)
}
if p.host != "proxy.example.com" || p.port != "1080" {
t.Errorf("socks5 parse: host=%q port=%q", p.host, p.port)
}
}
// ── validateProxyURL ──────────────────────────────────────────────────────────
func TestValidateProxyURL(t *testing.T) {
cases := []struct {
url string
want bool // true = valid
wantErrFrag string // non-empty: substring expected in error message
}{
{"http://proxy.example.com:8080", true, ""},
{"https://proxy.example.com:8080", true, ""},
{"socks5://proxy.example.com:1080", true, ""},
{"http://user:pass@proxy.example.com:8080", true, ""},
{"http://localhost:8080", true, ""},
{"://bad url", false, "scheme"},
{"http://", false, "missing host"},
{"http://proxy.example.com:99999", false, "out of range"},
{"http://proxy.example.com:0", false, "out of range"},
{"", false, "missing scheme"},
}
for _, c := range cases {
err := validateProxyURL(c.url)
if (err == nil) != c.want {
t.Errorf("validateProxyURL(%q): got err=%v, want valid=%v", c.url, err, c.want)
continue
}
if !c.want && c.wantErrFrag != "" && !strings.Contains(err.Error(), c.wantErrFrag) {
t.Errorf("validateProxyURL(%q): error = %q, want to contain %q", c.url, err.Error(), c.wantErrFrag)
}
}
}
// ── env vars ──────────────────────────────────────────────────────────────────
func TestSetEnvVars(t *testing.T) {
const proxyURL = "http://proxy.example.com:8080"
t.Cleanup(unsetEnvVars)
setEnvVars(proxyURL)
for _, k := range []string{"http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"} {
if got := os.Getenv(k); got != proxyURL {
t.Errorf("%s = %q, want %q", k, got, proxyURL)
}
}
for _, k := range []string{"no_proxy", "NO_PROXY"} {
if got := os.Getenv(k); got == "" {
t.Errorf("%s should be set, got empty", k)
}
}
}
func TestUnsetEnvVars(t *testing.T) {
setEnvVars("http://proxy.example.com:8080")
unsetEnvVars()
for _, k := range []string{
"http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY",
"all_proxy", "ALL_PROXY", "no_proxy", "NO_PROXY",
} {
if got := os.Getenv(k); got != "" {
t.Errorf("%s should be unset, got %q", k, got)
}
}
}
// ── Set error path ────────────────────────────────────────────────────────────
func TestSetInvalidURL(t *testing.T) {
err := Set("://bad url", ScopeShell)
if err == nil {
t.Fatal("expected error for invalid URL")
}
}
func TestSetScopeShell(t *testing.T) {
t.Cleanup(unsetEnvVars)
if err := Set("http://proxy.example.com:8080", ScopeShell); err != nil {
t.Fatal(err)
}
if got := os.Getenv("http_proxy"); got != "http://proxy.example.com:8080" {
t.Errorf("http_proxy = %q", got)
}
}
func TestUnsetScopeShell(t *testing.T) {
setEnvVars("http://proxy.example.com:8080")
if err := Unset(ScopeShell); err != nil {
t.Fatal(err)
}
if got := os.Getenv("http_proxy"); got != "" {
t.Errorf("http_proxy should be unset, got %q", got)
}
}
func TestInvalidScope(t *testing.T) {
if err := Set("http://proxy.example.com:8080", ProxyScope(99)); err == nil {
t.Error("expected error for invalid scope")
}
if err := Unset(ProxyScope(99)); err == nil {
t.Error("expected error for invalid scope")
}
}
// ── Logger ────────────────────────────────────────────────────────────────────
type testLogger struct{ msgs []string }
func (l *testLogger) Log(msg string) { l.msgs = append(l.msgs, msg) }
func TestSetLogger(t *testing.T) {
l := &testLogger{}
SetLogger(l)
t.Cleanup(func() { SetLogger(nil) })
_ = Set("http://proxy.example.com:8080", ScopeShell)
if len(l.msgs) == 0 {
t.Error("expected at least one log message after Set")
}
}
// ── WriteAppConfig / ClearAppConfig ──────────────────────────────────────────
func setTestHome(t *testing.T) string {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
if volume := filepath.VolumeName(home); volume != "" {
t.Setenv("HOMEDRIVE", volume)
t.Setenv("HOMEPATH", strings.TrimPrefix(home, volume))
}
return home
}
func TestWriteAppConfigCurl(t *testing.T) {
home := setTestHome(t)
if err := WriteAppConfig(AppCurl, "http://proxy.example.com:8080"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join(home, ".curlrc")) //nolint:gosec
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), "proxy = http://proxy.example.com:8080") {
t.Errorf("unexpected content: %s", data)
}
}
func TestClearAppConfigCurl(t *testing.T) {
home := setTestHome(t)
_ = WriteAppConfig(AppCurl, "http://proxy.example.com:8080")
if err := ClearAppConfig(AppCurl); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(home, ".curlrc")) //nolint:gosec
if strings.Contains(string(data), "proxy") {
t.Errorf("proxy should be removed, got: %s", data)
}
}
func TestWriteAppConfigPip(t *testing.T) {
home := setTestHome(t)
if err := WriteAppConfig(AppPip, "http://proxy.example.com:8080"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join(home, ".config", "pip", "pip.conf")) //nolint:gosec
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), "proxy = http://proxy.example.com:8080") {
t.Errorf("unexpected pip.conf content: %s", data)
}
}
func TestWriteAppConfigWget(t *testing.T) {
home := setTestHome(t)
if err := WriteAppConfig(AppWget, "http://proxy.example.com:8080"); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(home, ".wgetrc")) //nolint:gosec
if !strings.Contains(string(data), "http_proxy = http://proxy.example.com:8080") {
t.Errorf("unexpected .wgetrc content: %s", data)
}
}
func TestWriteAppConfigUnsupported(t *testing.T) {
if err := WriteAppConfig("burp", "http://proxy.example.com:8080"); err == nil {
t.Error("expected error for unsupported app")
}
}
// ── ScopeGlobal via mock backend ──────────────────────────────────────────────
func TestSetGlobal_CallsBackend(t *testing.T) {
var called bool
useMockBackend(t, &mockBackend{
setGlobalFn: func(_ context.Context, p *proxy) error {
called = true
if p.host != "proxy.example.com" || p.port != "8080" {
t.Errorf("unexpected proxy: host=%q port=%q", p.host, p.port)
}
return nil
},
})
t.Cleanup(unsetEnvVars)
if err := Set("http://proxy.example.com:8080", ScopeGlobal); err != nil {
t.Fatal(err)
}
if !called {
t.Error("backend.SetGlobal was not called")
}
}
func TestSetGlobal_BackendError(t *testing.T) {
useMockBackend(t, &mockBackend{
setGlobalFn: func(_ context.Context, _ *proxy) error {
return errors.New("backend error")
},
})
t.Cleanup(unsetEnvVars)
if err := Set("http://proxy.example.com:8080", ScopeGlobal); err == nil {
t.Error("expected error from backend")
}
}
func TestUnsetGlobal_CallsBackend(t *testing.T) {
var called bool
useMockBackend(t, &mockBackend{
unsetGlobalFn: func(_ context.Context) error {
called = true
return nil
},
})
t.Cleanup(unsetEnvVars)
if err := Unset(ScopeGlobal); err != nil {
t.Fatal(err)
}
if !called {
t.Error("backend.UnsetGlobal was not called")
}
}
func TestGetContext_PropagatesURL(t *testing.T) {
const want = "http://proxy.example.com:9090"
useMockBackend(t, &mockBackend{
getGlobalFn: func(_ context.Context) (string, error) { return want, nil },
})
got, err := Get()
if err != nil {
t.Fatal(err)
}
if got != want {
t.Errorf("Get() = %q, want %q", got, want)
}
}
func TestSetMultiGlobal_CallsBackend(t *testing.T) {
var got ProxyConfig
useMockBackend(t, &mockBackend{
setGlobalMultiFn: func(_ context.Context, cfg ProxyConfig) error {
got = cfg
return nil
},
})
t.Cleanup(unsetEnvVars)
want := ProxyConfig{
HTTP: "http://http.example.com:8080",
HTTPS: "http://https.example.com:8080",
}
if err := SetMulti(want, ScopeGlobal); err != nil {
t.Fatal(err)
}
if got.HTTP != want.HTTP || got.HTTPS != want.HTTPS {
t.Errorf("SetMulti passed %+v, want %+v", got, want)
}
}
func TestSetPACGlobal_CallsBackend(t *testing.T) {
const pacURL = "http://config.example.com/proxy.pac"
var called bool
useMockBackend(t, &mockBackend{
setGlobalPACFn: func(_ context.Context, u string) error {
called = true
if u != pacURL {
t.Errorf("SetGlobalPAC got %q, want %q", u, pacURL)
}
return nil
},
})
t.Cleanup(unsetEnvVars)
if err := SetPAC(pacURL, ScopeGlobal); err != nil {
t.Fatal(err)
}
if !called {
t.Error("backend.SetGlobalPAC was not called")
}
}
func TestWithProxy_RestoresPrevious(t *testing.T) {
const prev = "http://prev.example.com:8080"
const next = "http://next.example.com:9090"
setLog := []string{}
useMockBackend(t, &mockBackend{
setGlobalFn: func(_ context.Context, p *proxy) error {
setLog = append(setLog, p.rawURL)
return nil
},
unsetGlobalFn: func(_ context.Context) error { return nil },
getGlobalFn: func(_ context.Context) (string, error) { return prev, nil },
})
t.Cleanup(unsetEnvVars)
err := WithProxy(context.Background(), next, ScopeGlobal, func(_ context.Context) error {
return nil
})
if err != nil {
t.Fatal(err)
}
if len(setLog) < 2 {
t.Fatalf("expected at least 2 Set calls, got %d", len(setLog))
}
// last Set call should restore the previous proxy
if setLog[len(setLog)-1] != prev {
t.Errorf("last Set = %q, want %q", setLog[len(setLog)-1], prev)
}
}
// ── SetMultiContext / SetPACContext – ScopeShell ──────────────────────────────
func TestSetMultiContext_ScopeShell(t *testing.T) {
t.Cleanup(unsetEnvVars)
cfg := ProxyConfig{HTTP: "http://proxy.example.com:8080", HTTPS: "http://proxy.example.com:8080"}
if err := SetMulti(cfg, ScopeShell); err != nil {
t.Fatal(err)
}
if got := os.Getenv("http_proxy"); got != cfg.HTTP {
t.Errorf("http_proxy = %q, want %q", got, cfg.HTTP)
}
}
func TestSetPACContext_ScopeShell(t *testing.T) {
t.Cleanup(func() { _ = os.Unsetenv("AUTOPROXY") })
if err := SetPAC("http://config.example.com/proxy.pac", ScopeShell); err != nil {
t.Fatal(err)
}
if got := os.Getenv("AUTOPROXY"); got != "http://config.example.com/proxy.pac" {
t.Errorf("AUTOPROXY = %q", got)
}
}
// ── helpers ───────────────────────────────────────────────────────────────────
func TestHostFromURL(t *testing.T) {
cases := []struct{ url, want string }{
{"http://proxy.example.com:8080", "proxy.example.com"},
{"socks5://user:pass@proxy.example.com:1080", "proxy.example.com"},
{"://bad", ""},
}
for _, c := range cases {
if got := hostFromURL(c.url); got != c.want {
t.Errorf("hostFromURL(%q) = %q, want %q", c.url, got, c.want)
}
}
}
func TestPortFromURL(t *testing.T) {
cases := []struct{ url, want string }{
{"http://proxy.example.com:8080", "8080"},
{"socks5://proxy.example.com:1080", "1080"},
{"://bad", ""},
}
for _, c := range cases {
if got := portFromURL(c.url); got != c.want {
t.Errorf("portFromURL(%q) = %q, want %q", c.url, got, c.want)
}
}
}
// ── normalizeContext ──────────────────────────────────────────────────────────
func TestNormalizeContext_Nil(t *testing.T) {
var nilCtx context.Context // typed nil, avoids SA1012 on literal nil
ctx := normalizeContext(nilCtx)
if ctx == nil {
t.Error("normalizeContext(nil) returned nil")
}
}
func TestNormalizeContext_NonNil(t *testing.T) {
orig := context.Background()
if got := normalizeContext(orig); got != orig {
t.Error("normalizeContext should return the same non-nil context")
}
}
// ── validatePACURL ────────────────────────────────────────────────────────────
func TestValidatePACURL(t *testing.T) {
cases := []struct {
url string
want bool
}{
{"http://config.example.com/proxy.pac", true},
{"https://config.example.com/proxy.pac", true},
{"file:///etc/proxy.pac", true},
{"ftp://bad.example.com/proxy.pac", false},
{"", false},
}
for _, c := range cases {
err := validatePACURL(c.url)
if (err == nil) != c.want {
t.Errorf("validatePACURL(%q): got err=%v, want valid=%v", c.url, err, c.want)
}
}
}
// ── GetConfig via mock backend ────────────────────────────────────────────────
func TestGetConfig_ReturnsFull(t *testing.T) {
want := ProxyConfig{
HTTP: "http://http.example.com:8080",
HTTPS: "http://https.example.com:8080",
SOCKS: "socks5://socks.example.com:1080",
NoProxy: "localhost,10.0.0.0/8",
}
useMockBackend(t, &mockBackend{
getGlobalConfigFn: func(_ context.Context) (ProxyConfig, error) { return want, nil },
})
got, err := GetConfig()
if err != nil {
t.Fatal(err)
}
if got != want {
t.Errorf("GetConfig() = %+v, want %+v", got, want)
}
}
func TestGetConfig_BackendError(t *testing.T) {
useMockBackend(t, &mockBackend{
getGlobalConfigFn: func(_ context.Context) (ProxyConfig, error) {
return ProxyConfig{}, errors.New("proxy not set")
},
})
_, err := GetConfig()
if err == nil {
t.Error("expected error from backend")
}
}
func TestGetConfigContext_CanceledCtx(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := GetConfigContext(ctx)
if err == nil {
t.Error("expected context cancellation error")
}
}
// ── ProxyScope.String ─────────────────────────────────────────────────────────
func TestProxyScopeString(t *testing.T) {
cases := []struct {
scope ProxyScope
want string
}{
{ScopeShell, "shell"},
{ScopeUser, "user"},
{ScopeGlobal, "global"},
{ProxyScope(99), "unknown"},
}
for _, c := range cases {
if got := c.scope.String(); got != c.want {
t.Errorf("ProxyScope(%d).String() = %q, want %q", c.scope, got, c.want)
}
}
}