Repository navigation
Expand file tree
/
Copy pathfetchurl_test.go
More file actions
386 lines (354 loc) · 10.3 KB
/
Copy pathfetchurl_test.go
File metadata and controls
386 lines (354 loc) · 10.3 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
package fetchurl
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/shogo82148/go-sfv"
)
func sha256Sum(b []byte) string {
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}
func TestFetcher(t *testing.T) {
content := []byte("test content")
hash := sha256Sum(content)
t.Run("Direct Download Success", func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write(content); err != nil {
t.Errorf("failed to write response: %v", err)
}
}))
defer ts.Close()
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: []string{ts.URL},
Out: &out,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out.String() != string(content) {
t.Errorf("got %q, want %q", out.String(), string(content))
}
})
t.Run("Direct Download Success Uppercase Hash", func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write(content); err != nil {
t.Errorf("failed to write response: %v", err)
}
}))
defer ts.Close()
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "SHA-256",
Hash: strings.ToUpper(hash),
URLs: []string{ts.URL},
Out: &out,
})
if err != nil {
t.Fatalf("unexpected error for uppercase hash: %v", err)
}
if out.String() != string(content) {
t.Errorf("got %q, want %q", out.String(), string(content))
}
})
t.Run("Direct Download Hash Mismatch", func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write([]byte("wrong content")); err != nil {
t.Errorf("failed to write response: %v", err)
}
}))
defer ts.Close()
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: []string{ts.URL},
Out: &out,
})
if err == nil {
t.Fatal("expected error, got nil")
}
if !errors.Is(err, ErrPartialWrite) {
t.Errorf("expected ErrPartialWrite, got %v", err)
}
if !errors.Is(err, ErrHashMismatch) {
t.Errorf("expected ErrHashMismatch, got %v", err)
}
})
t.Run("Server Fetch Success", func(t *testing.T) {
// Mock Source
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Error("Should not hit source if server succeeds")
}))
defer source.Close()
// Mock FetchURL Server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != fmt.Sprintf("/api/fetchurl/sha256/%s", hash) {
t.Errorf("unexpected path: %s", r.URL.Path)
w.WriteHeader(404)
return
}
// Verify X-Source-Urls header
val := r.Header.Get("X-Source-Urls")
list, err := sfv.DecodeList([]string{val})
if err != nil {
t.Errorf("failed to decode X-Source-Urls: %v", err)
}
found := false
for _, item := range list {
if s, ok := item.Value.(string); ok && s == source.URL {
found = true
}
}
if !found {
t.Errorf("X-Source-Urls missing source URL, got %v", val)
}
if _, err := w.Write(content); err != nil {
t.Errorf("failed to write response: %v", err)
}
}))
defer server.Close()
t.Setenv("FETCHURL_SERVER", fmt.Sprintf("\"%s/api/fetchurl\"", server.URL))
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: []string{source.URL},
Out: &out,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out.String() != string(content) {
t.Errorf("got %q, want %q", out.String(), string(content))
}
})
t.Run("Server Fail Fallback", func(t *testing.T) {
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write(content); err != nil {
t.Errorf("failed to write response: %v", err)
}
}))
defer source.Close()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
defer server.Close()
t.Setenv("FETCHURL_SERVER", fmt.Sprintf("\"%s/api/fetchurl\"", server.URL))
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: []string{source.URL},
Out: &out,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out.String() != string(content) {
t.Errorf("got %q, want %q", out.String(), string(content))
}
})
t.Run("Partial Download No Fallback", func(t *testing.T) {
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write(content); err != nil {
t.Errorf("failed to write response: %v", err)
}
}))
defer source.Close()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write([]byte("partial")); err != nil {
t.Errorf("failed to write response: %v", err)
}
}))
defer server.Close()
t.Setenv("FETCHURL_SERVER", fmt.Sprintf("\"%s/api/fetchurl\"", server.URL))
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: []string{source.URL},
Out: &out,
})
if err == nil {
t.Fatal("expected error, got nil")
}
if !errors.Is(err, ErrPartialWrite) {
t.Errorf("expected ErrPartialWrite, got %v", err)
}
if out.String() != "partial" {
t.Errorf("got %q, want %q", out.String(), "partial")
}
})
t.Run("Unsupported Algorithm", func(t *testing.T) {
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "md4",
Hash: "abc",
URLs: []string{"http://example.com"},
Out: &out,
})
if !errors.Is(err, ErrUnsupportedAlgorithm) {
t.Errorf("expected ErrUnsupportedAlgorithm, got %v", err)
}
})
t.Run("Invalid Digest Rejected Before Network", func(t *testing.T) {
// Path-escaping or wrong-length digests must not be dialed: they are
// interpolated into the CAS request path on FETCHURL_SERVER.
var dialed bool
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
dialed = true
t.Errorf("unexpected request for invalid digest: %s", r.URL.Path)
w.WriteHeader(http.StatusTeapot)
}))
defer ts.Close()
t.Setenv("FETCHURL_SERVER", ts.URL+"/api/fetchurl")
f := NewFetcher(nil)
var out bytes.Buffer
for _, bad := range []string{
"..",
"deadbeef",
"../../../etc/passwd",
hash + "aa",
"gg" + hash[2:], // non-hex
} {
out.Reset()
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: bad,
URLs: []string{ts.URL + "/source"},
Out: &out,
})
if !errors.Is(err, ErrInvalidDigest) {
t.Errorf("hash %q: want ErrInvalidDigest, got %v", bad, err)
}
if out.Len() != 0 {
t.Errorf("hash %q: wrote %d bytes, want none", bad, out.Len())
}
}
if dialed {
t.Error("invalid digests triggered network I/O")
}
})
t.Run("Missing Source URLs", func(t *testing.T) {
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: nil,
Out: &out,
})
if !errors.Is(err, ErrMissingSourceURLs) {
t.Errorf("expected ErrMissingSourceURLs, got %v", err)
}
})
t.Run("All Sources Failed", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
}))
defer server.Close()
t.Setenv("FETCHURL_SERVER", fmt.Sprintf("\"%s/api/fetchurl\"", server.URL))
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: []string{server.URL},
Out: &out,
})
if !errors.Is(err, ErrAllSourcesFailed) {
t.Errorf("expected ErrAllSourcesFailed, got %v", err)
}
})
t.Run("HTTP Status Error", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(403)
}))
defer server.Close()
t.Setenv("FETCHURL_SERVER", fmt.Sprintf("\"%s/api/fetchurl\"", server.URL))
f := NewFetcher(nil)
var out bytes.Buffer
err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: []string{server.URL},
Out: &out,
})
var httpErr *HTTPStatusError
if !errors.As(err, &httpErr) {
t.Fatalf("expected HTTPStatusError, got %T: %v", err, err)
}
if httpErr.StatusCode != 403 {
t.Errorf("expected status 403, got %d", httpErr.StatusCode)
}
})
// Non-OK responses must drain a bounded body so HTTP/1 keep-alive can
// reuse the TCP connection for the next server/source attempt.
t.Run("NonOK drains body for connection reuse", func(t *testing.T) {
var newConns atomic.Int32
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/api/fetchurl/") {
w.WriteHeader(http.StatusForbidden)
// Body large enough that skipping drain would typically
// prevent reuse (and larger than a tiny error page).
if _, err := w.Write(bytes.Repeat([]byte("e"), 8192)); err != nil {
t.Errorf("write error body: %v", err)
}
return
}
if _, err := w.Write(content); err != nil {
t.Errorf("write content: %v", err)
}
}))
ts.Config.ConnState = func(_ net.Conn, state http.ConnState) {
if state == http.StateNew {
newConns.Add(1)
}
}
ts.Start()
defer ts.Close()
t.Setenv("FETCHURL_SERVER", ts.URL+"/api/fetchurl")
// Explicit transport: keep-alive on, single idle conn per host so a
// second dial is visible if the first response was not drained.
f := NewFetcher(&http.Client{
Transport: &http.Transport{
DisableKeepAlives: false,
MaxIdleConnsPerHost: 1,
},
})
var out bytes.Buffer
if err := f.Fetch(t.Context(), FetchOptions{
Algo: "sha256",
Hash: hash,
URLs: []string{ts.URL + "/source"},
Out: &out,
}); err != nil {
t.Fatalf("Fetch: %v", err)
}
if out.String() != string(content) {
t.Fatalf("content = %q, want %q", out.String(), content)
}
if n := newConns.Load(); n != 1 {
t.Fatalf("new TCP connections = %d, want 1 (keep-alive reuse after non-OK drain)", n)
}
})
}