Repository navigation
Expand file tree
/
Copy pathintegration_test.go
More file actions
240 lines (236 loc) · 6.86 KB
/
Copy pathintegration_test.go
File metadata and controls
240 lines (236 loc) · 6.86 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
package proxykit_test
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/colduction/proxykit-go"
"github.com/colduction/proxykit-go/proxyparser"
"github.com/colduction/proxykit-go/proxypool"
)
// TestPoolParseHTTPProxy checks pooled parsing and authenticated requests through HTTP and HTTPS proxies.
func TestPoolParseHTTPProxy(t *testing.T) {
const (
username = "user@name"
password = "p:ss/?#%"
target = "http://target.invalid:8080/resource?q=1"
)
wantAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.RequestURI != target || r.URL.String() != target || r.Host != "target.invalid:8080" {
http.Error(w, "wrong proxy target", http.StatusBadRequest)
return
}
if r.Header.Get("Proxy-Authorization") != wantAuth {
http.Error(w, "wrong proxy credentials", http.StatusProxyAuthRequired)
return
}
if r.TLS == nil {
_, _ = io.WriteString(w, "http proxy")
} else {
_, _ = io.WriteString(w, "https proxy")
}
})
plain := httptest.NewServer(handler)
t.Cleanup(plain.Close)
secure := httptest.NewTLSServer(handler)
t.Cleanup(secure.Close)
roots := x509.NewCertPool()
roots.AddCert(secure.Certificate())
var lines []string
for _, endpoint := range []string{plain.URL, secure.URL} {
scheme, host, ok := strings.Cut(endpoint, "://")
if !ok {
t.Fatalf("unexpected test proxy URL %q", endpoint)
}
lines = append(lines, scheme+"|"+host+"|"+username+"|"+password)
}
path := filepath.Join(t.TempDir(), "proxies.txt")
if err := os.WriteFile(path, []byte(strings.Join(lines, "\r\n")), 0600); err != nil {
t.Fatal(err)
}
pool, err := proxypool.Open(path, proxypool.Options{SequentialBufferBytes: 32, MaxLineBytes: 256})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := pool.Close(); err != nil {
t.Error(err)
}
})
parser, err := proxyparser.New("%t|%h:%d|%u|%p", true)
if err != nil {
t.Fatal(err)
}
var batch proxypool.Batch
var count int
for {
if err := pool.NextBatch(&batch); err != nil {
if errors.Is(err, io.EOF) {
break
}
t.Fatal(err)
}
for line := range batch.Lines() {
var proxy proxykit.Proxy
if err := parser.ParseBytes(line, &proxy); err != nil {
t.Fatal(err)
}
exported := proxy.ExportURL().String()
if !strings.Contains(exported, "user%40name:p%3Ass%2F%3F%23%25@") {
t.Fatalf("credentials not percent-escaped: %q", exported)
}
proxyURL, err := url.Parse(exported)
if err != nil {
t.Fatal(err)
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
TLSClientConfig: &tls.Config{RootCAs: roots},
TLSHandshakeTimeout: 2 * time.Second,
ResponseHeaderTimeout: 2 * time.Second,
}
defer transport.CloseIdleConnections()
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
request, err := http.NewRequestWithContext(t.Context(), http.MethodGet, target, nil)
if err != nil {
t.Fatal(err)
}
response, err := client.Do(request)
if err != nil {
t.Fatal(err)
}
body, readErr := io.ReadAll(response.Body)
closeErr := response.Body.Close()
if readErr != nil || closeErr != nil {
t.Fatalf("response read: %v; close: %v", readErr, closeErr)
}
if response.StatusCode != http.StatusOK || string(body) != string(proxy.Scheme)+" proxy" {
t.Fatalf("proxy response = %d %q", response.StatusCode, body)
}
count++
}
}
if count != len(lines) {
t.Fatalf("sent %d proxy requests, want %d", count, len(lines))
}
}
// BenchmarkPoolParse measures sequential and shuffled pool iteration with proxy parsing.
func BenchmarkPoolParse(b *testing.B) {
const lineCount = 4096
var source strings.Builder
want := make(map[string]proxykit.Proxy, lineCount)
var wantHostBytes int
for i := range lineCount {
number := strconv.Itoa(i)
var host string
switch i % 4 {
case 0:
host = "proxy-" + number + ".zone" + strconv.Itoa(i%64) + ":8080"
case 1:
host = "192.0." + strconv.Itoa(i/256) + "." + strconv.Itoa(i%256) + ":8080"
case 2:
host = "proxy-" + number + ".example.com:8080"
default:
host = "[2001:db8::" + strconv.FormatInt(int64(i), 16) + "]:8080"
}
line := "http://user:pass@" + host
source.WriteString(line)
source.WriteByte('\n')
want[line] = proxykit.Proxy{Scheme: proxykit.HTTP, Host: host, Username: "user", Password: "pass"}
wantHostBytes += len(host)
}
path := filepath.Join(b.TempDir(), "proxies.txt")
if err := os.WriteFile(path, []byte(source.String()), 0600); err != nil {
b.Fatal(err)
}
parser, err := proxyparser.New("%t://%u:%p@%h:%d", true)
if err != nil {
b.Fatal(err)
}
for _, mode := range []struct {
name string
value proxypool.Mode
}{
{name: "Sequential", value: proxypool.ModeSequential},
{name: "Shuffled", value: proxypool.ModeShuffled},
} {
for _, method := range []string{"NextBytes", "Batch"} {
b.Run(mode.name+"/"+method, func(b *testing.B) {
pool, err := proxypool.Open(path, proxypool.Options{
Mode: mode.value,
Reuse: true,
SequentialBufferBytes: 16 << 10,
BlockBytes: 16 << 10,
RegionBytes: 64 << 10,
MaxLineBytes: 256,
Seed: 123,
})
if err != nil {
b.Fatal(err)
}
defer pool.Close()
var buffer []byte
var batch proxypool.Batch
var proxy proxykit.Proxy
verify := true
scan := func() {
var count, hostBytes int
if method == "NextBytes" {
for count < lineCount {
buffer, err = pool.NextBytes(buffer[:0])
if err != nil {
b.Fatal(err)
}
if err := parser.ParseBytes(buffer, &proxy); err != nil {
b.Fatal(err)
}
if verify && proxy != want[string(buffer)] {
b.Fatalf("parsed proxy differs for %q", buffer)
}
hostBytes += len(proxy.Host)
count++
}
} else {
for count < lineCount {
if err := pool.NextBatch(&batch); err != nil {
b.Fatal(err)
}
for line := range batch.Lines() {
if err := parser.ParseBytes(line, &proxy); err != nil {
b.Fatal(err)
}
if verify && proxy != want[string(line)] {
b.Fatalf("parsed proxy differs for %q", line)
}
hostBytes += len(proxy.Host)
count++
}
}
}
if count != lineCount || hostBytes != wantHostBytes {
b.Fatalf("parsed %d lines / %d host bytes, want %d / %d", count, hostBytes, lineCount, wantHostBytes)
}
}
scan()
verify = false
b.SetBytes(int64(source.Len()))
b.ReportAllocs()
for b.Loop() {
scan()
}
b.ReportMetric(float64(b.Elapsed().Nanoseconds())/float64(b.N*lineCount), "ns/line")
})
}
}
}