Debian Codegraph @

remotehttp_test.go

raw
1 package desync
2
3 import (
4 "bytes"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "net/url"
9 "testing"
10 "time"
11
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14 )
15
16 func TestHTTPStoreURL(t *testing.T) {
17 var requestURI string
18 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
19 requestURI = r.RequestURI
20 }))
21 defer ts.Close()
22 u, _ := url.Parse(ts.URL)
23
24 chunkID := ChunkID{1, 2, 3, 4}
25 tests := map[string]struct {
26 storePath string
27 serverPath string
28 }{
29 "no path": {"", "/0102/0102030400000000000000000000000000000000000000000000000000000000.cacnk"},
30 "slash only": {"/", "/0102/0102030400000000000000000000000000000000000000000000000000000000.cacnk"},
31 "no trailing slash": {"/path", "/path/0102/0102030400000000000000000000000000000000000000000000000000000000.cacnk"},
32 "with trailing slash": {"/path/", "/path/0102/0102030400000000000000000000000000000000000000000000000000000000.cacnk"},
33 "long path": {"/path1/path2", "/path1/path2/0102/0102030400000000000000000000000000000000000000000000000000000000.cacnk"},
34 }
35 for name, test := range tests {
36 t.Run(name, func(t *testing.T) {
37 u.Path = test.storePath
38 s, err := NewRemoteHTTPStore(u, StoreOptions{})
39 require.NoError(t, err)
40 s.GetChunk(chunkID)
41 require.Equal(t, test.serverPath, requestURI)
42 })
43 }
44 }
45
46 func TestHasChunk(t *testing.T) {
47 var attemptCount int
48
49 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
50 attemptCount++
51 switch r.URL.String() {
52 case "/0000/0000000100000000000000000000000000000000000000000000000000000000.cacnk":
53 w.WriteHeader(http.StatusOK)
54 case "/0000/0000000200000000000000000000000000000000000000000000000000000000.cacnk":
55 w.WriteHeader(http.StatusNotFound)
56 case "/0000/0000000300000000000000000000000000000000000000000000000000000000.cacnk":
57 w.WriteHeader(http.StatusBadRequest)
58 case "/0000/0000000400000000000000000000000000000000000000000000000000000000.cacnk":
59 w.WriteHeader(http.StatusForbidden)
60 case "/0000/0000000500000000000000000000000000000000000000000000000000000000.cacnk":
61 w.WriteHeader(http.StatusBadGateway)
62 io.WriteString(w, "Bad Gateway")
63 case "/0000/0000000600000000000000000000000000000000000000000000000000000000.cacnk":
64 if attemptCount >= 2 {
65 w.WriteHeader(http.StatusOK)
66 } else {
67 w.WriteHeader(http.StatusBadGateway)
68 io.WriteString(w, "Bad Gateway")
69 }
70 case "/0000/0000000700000000000000000000000000000000000000000000000000000000.cacnk":
71 if attemptCount >= 3 {
72 w.WriteHeader(http.StatusNotFound)
73 } else {
74 w.WriteHeader(http.StatusBadGateway)
75 io.WriteString(w, "Bad Gateway")
76 }
77 default:
78 w.WriteHeader(http.StatusBadRequest)
79 }
80 }))
81 defer ts.Close()
82 u, _ := url.Parse(ts.URL)
83
84 tests := map[string]struct {
85 chunkId ChunkID
86 hasChunk bool
87 hasError bool
88 attemptCount int
89 }{
90 // The default case is a successful chunk test operation
91 "chunk exists": {ChunkID{0, 0, 0, 1}, true, false, 1},
92 // HTTP 404 Not Found - Testing a chunk that does not exist should result in an immediate 'does not exist' response
93 "chunk does not exist": {ChunkID{0, 0, 0, 2}, false, false, 1},
94 // HTTP 400 Bad Request - should fail immediately
95 "bad request": {ChunkID{0, 0, 0, 3}, false, true, 1},
96 // HTTP 403 Forbidden - should fail immediately
97 "forbidden": {ChunkID{0, 0, 0, 4}, false, true, 1},
98 // HTTP 503 Bad Gateway - should retry, but ultimately fail
99 "permanent 503": {ChunkID{0, 0, 0, 5}, false, true, 5},
100 // HTTP 503 Bad Gateway - should retry, and a subsequent successful call should return that the chunk exists
101 "temporary 503, then chunk exists": {ChunkID{0, 0, 0, 6}, true, false, 2},
102 // HTTP 503 Bad Gateway - should retry, and a subsequent successful call should report that the chunk does not exist immediately
103 "temporary 503, then chunk does not exist": {ChunkID{0, 0, 0, 7}, false, false, 3},
104 }
105 for name, test := range tests {
106 t.Run(name, func(t *testing.T) {
107 u.Path = "/"
108 s, err := NewRemoteHTTPStore(u, StoreOptions{ErrorRetry: 5, ErrorRetryBaseInterval: time.Microsecond})
109 require.NoError(t, err)
110
111 attemptCount = 0
112 hasChunk, err := s.HasChunk(test.chunkId)
113 assert.Equal(t, test.hasChunk, hasChunk)
114 if test.hasError {
115 assert.Error(t, err)
116 } else {
117 assert.NoError(t, err)
118 }
119 assert.Equal(t, test.attemptCount, attemptCount)
120 })
121 }
122 }
123
124 func TestGetChunk(t *testing.T) {
125 var attemptCount int
126
127 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
128 attemptCount++
129 switch r.URL.String() {
130 case "/3bc8/3bc8e3230df5515b1b40e938e49ebc765c6157d4cf4e2b9d5f9c272571365395":
131 w.WriteHeader(http.StatusOK)
132 io.WriteString(w, "Chunk Content String 1")
133 case "/0000/0000000100000000000000000000000000000000000000000000000000000000":
134 w.WriteHeader(http.StatusOK)
135 io.WriteString(w, "Chunk Content With hash mismatch")
136 case "/0000/0000000200000000000000000000000000000000000000000000000000000000":
137 w.WriteHeader(http.StatusNotFound)
138 case "/0000/0000000300000000000000000000000000000000000000000000000000000000":
139 w.WriteHeader(http.StatusBadRequest)
140 io.WriteString(w, "BadRequest")
141 case "/0000/0000000400000000000000000000000000000000000000000000000000000000":
142 w.WriteHeader(http.StatusForbidden)
143 io.WriteString(w, "Forbidden")
144 case "/0000/0000000500000000000000000000000000000000000000000000000000000000":
145 w.WriteHeader(http.StatusBadGateway)
146 io.WriteString(w, "Bad Gateway")
147 case "/65a1/65a128d0658c4cf0941771c7090fea6d9c6f981810659c24c91ba23edd71574b":
148 if attemptCount >= 2 {
149 w.WriteHeader(http.StatusOK)
150 io.WriteString(w, "Chunk Content String 6")
151 } else {
152 w.WriteHeader(http.StatusBadGateway)
153 io.WriteString(w, "Bad Gateway")
154 }
155 case "/0000/0000000700000000000000000000000000000000000000000000000000000000":
156 if attemptCount >= 3 {
157 w.WriteHeader(http.StatusNotFound)
158 } else {
159 w.WriteHeader(http.StatusBadGateway)
160 io.WriteString(w, "Bad Gateway")
161 }
162 default:
163 w.WriteHeader(http.StatusBadRequest)
164 }
165 }))
166 defer ts.Close()
167 u, _ := url.Parse(ts.URL)
168
169 tests := map[string]struct {
170 chunkId ChunkID
171 content string
172 hasError bool
173 attemptCount int
174 }{
175
176 // The default case is a successful get chunk operation
177 "chunk exists": {ChunkID{0x3b, 0xc8, 0xe3, 0x23, 0x0d, 0xf5, 0x51, 0x5b, 0x1b, 0x40, 0xe9, 0x38, 0xe4, 0x9e, 0xbc, 0x76, 0x5c, 0x61, 0x57, 0xd4, 0xcf, 0x4e, 0x2b, 0x9d, 0x5f, 0x9c, 0x27, 0x25, 0x71, 0x36, 0x53, 0x95}, "Chunk Content String 1", false, 1},
178 // Fetching a chunk where the hash does not match the contents should fail for a store where verification is enabled
179 "chunk exists, but invalid hash": {ChunkID{0, 0, 0, 1}, "", true, 1},
180 // HTTP 404 Not Found - Fetching a chunk that does not exist should fail immediately
181 "chunk does not exist": {ChunkID{0, 0, 0, 2}, "", true, 1},
182 // HTTP 400 Bad Request - should fail immediately
183 "bad request": {ChunkID{0, 0, 0, 3}, "", true, 1},
184 // HTTP 403 Forbidden - should fail immediately
185 "forbidden": {ChunkID{0, 0, 0, 4}, "", true, 1},
186 // HTTP 503 Bad Gateway - should retry, but ultimately fail
187 "permanent 503": {ChunkID{0, 0, 0, 5}, "", true, 5},
188 // HTTP 503 Bad Gateway - should retry, and a subsequent successful call should return a successful chunk
189 "temporary 503, then chunk exists": {ChunkID{0x65, 0xa1, 0x28, 0xd0, 0x65, 0x8c, 0x4c, 0xf0, 0x94, 0x17, 0x71, 0xc7, 0x09, 0x0f, 0xea, 0x6d, 0x9c, 0x6f, 0x98, 0x18, 0x10, 0x65, 0x9c, 0x24, 0xc9, 0x1b, 0xa2, 0x3e, 0xdd, 0x71, 0x57, 0x4b}, "Chunk Content String 6", false, 2},
190 // HTTP 503 Bad Gateway - should retry, and a subsequent successful call should report that the chunk does not exist, thereby failing immediately
191 "temporary 503, then chunk does not exist": {ChunkID{0, 0, 0, 7}, "", true, 3},
192 }
193 for name, test := range tests {
194 t.Run(name, func(t *testing.T) {
195 u.Path = "/"
196 s, err := NewRemoteHTTPStore(u, StoreOptions{ErrorRetry: 5, ErrorRetryBaseInterval: time.Microsecond, Uncompressed: true})
197 require.NoError(t, err)
198
199 attemptCount = 0
200 content, err := s.GetChunk(test.chunkId)
201 content_string := ""
202 if content != nil {
203 uncompressedContent, _ := content.Data()
204 content_string = string(uncompressedContent)
205 }
206 assert.Equal(t, test.content, content_string)
207 if test.hasError {
208 assert.Error(t, err)
209 } else {
210 assert.NoError(t, err)
211 }
212 assert.Equal(t, test.attemptCount, attemptCount)
213 })
214 }
215 }
216
217 func TestPutChunk(t *testing.T) {
218 var attemptCount int
219 var writtenContent []byte
220
221 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
222 attemptCount++
223 switch r.URL.String() {
224 case "/3bc8/3bc8e3230df5515b1b40e938e49ebc765c6157d4cf4e2b9d5f9c272571365395":
225 content, err := io.ReadAll(r.Body)
226 if err != nil {
227 w.WriteHeader(http.StatusBadRequest)
228 io.WriteString(w, err.Error())
229 } else {
230 writtenContent = content
231 w.WriteHeader(http.StatusOK)
232 }
233 case "/3cc8/3cc8e3230df5515b1b40e938e49ebc765c6157d4cf4e2b9d5f9c272571365395":
234 content, err := io.ReadAll(r.Body)
235 if err != nil {
236 w.WriteHeader(http.StatusBadRequest)
237 io.WriteString(w, err.Error())
238 } else {
239 writtenContent = content
240 w.WriteHeader(http.StatusCreated)
241 }
242 case "/0000/0000000300000000000000000000000000000000000000000000000000000000":
243 w.WriteHeader(http.StatusBadRequest)
244 io.WriteString(w, "BadRequest")
245 case "/0000/0000000400000000000000000000000000000000000000000000000000000000":
246 w.WriteHeader(http.StatusForbidden)
247 io.WriteString(w, "Forbidden")
248 case "/0000/0000000500000000000000000000000000000000000000000000000000000000":
249 w.WriteHeader(http.StatusBadGateway)
250 io.WriteString(w, "Bad Gateway")
251 case "/65a1/65a128d0658c4cf0941771c7090fea6d9c6f981810659c24c91ba23edd71574b":
252 if attemptCount >= 2 {
253 content, err := io.ReadAll(r.Body)
254 if err != nil {
255 w.WriteHeader(http.StatusBadRequest)
256 io.WriteString(w, err.Error())
257 } else {
258 writtenContent = content
259 w.WriteHeader(http.StatusOK)
260 }
261 } else {
262 w.WriteHeader(http.StatusBadGateway)
263 io.WriteString(w, "Bad Gateway")
264 }
265 default:
266 w.WriteHeader(http.StatusBadRequest)
267 }
268 }))
269 defer ts.Close()
270 u, _ := url.Parse(ts.URL)
271
272 tests := map[string]struct {
273 chunkId ChunkID
274 content string
275 writtenContent string
276 hasError bool
277 attemptCount int
278 }{
279 // The typical path is a successful store operation
280 "store chunk successful": {ChunkID{0x3b, 0xc8, 0xe3, 0x23, 0x0d, 0xf5, 0x51, 0x5b, 0x1b, 0x40, 0xe9, 0x38, 0xe4, 0x9e, 0xbc, 0x76, 0x5c, 0x61, 0x57, 0xd4, 0xcf, 0x4e, 0x2b, 0x9d, 0x5f, 0x9c, 0x27, 0x25, 0x71, 0x36, 0x53, 0x95}, "Chunk Content String 1", "Chunk Content String 1", false, 1},
281 // Some servers return 201/StatusCreated for a PUT
282 "store chunk successful - created": {ChunkID{0x3c, 0xc8, 0xe3, 0x23, 0x0d, 0xf5, 0x51, 0x5b, 0x1b, 0x40, 0xe9, 0x38, 0xe4, 0x9e, 0xbc, 0x76, 0x5c, 0x61, 0x57, 0xd4, 0xcf, 0x4e, 0x2b, 0x9d, 0x5f, 0x9c, 0x27, 0x25, 0x71, 0x36, 0x53, 0x95}, "Chunk Content String 1", "Chunk Content String 1", false, 1},
283 // Attempting to store a chunk with null content will be errored by the library itself, and will not result in any HTTP requests
284 "store chunk not allowed with no chunk content": {ChunkID{0, 0, 0, 2}, "", "", true, 0},
285 // HTTP 400 Bad Request - should fail immediately
286 "bad request": {ChunkID{0, 0, 0, 3}, "3", "", true, 1},
287 // HTTP 403 Forbidden - should fail immediately
288 "forbidden": {ChunkID{0, 0, 0, 4}, "4", "", true, 1},
289 // HTTP 503 Bad Gateway - should retry, but ultimately fail
290 "permanent 503": {ChunkID{0, 0, 0, 5}, "5", "", true, 5},
291 // HTTP 503 Bad Gateway - should retry, and a subsequent successful call should make the entire operation succeed
292 "temporary 503, then store chunk successful": {ChunkID{0x65, 0xa1, 0x28, 0xd0, 0x65, 0x8c, 0x4c, 0xf0, 0x94, 0x17, 0x71, 0xc7, 0x09, 0x0f, 0xea, 0x6d, 0x9c, 0x6f, 0x98, 0x18, 0x10, 0x65, 0x9c, 0x24, 0xc9, 0x1b, 0xa2, 0x3e, 0xdd, 0x71, 0x57, 0x4b}, "Chunk Content String 6", "Chunk Content String 6", false, 2},
293 }
294 for name, test := range tests {
295 t.Run(name, func(t *testing.T) {
296 u.Path = "/"
297 s, err := NewRemoteHTTPStore(u, StoreOptions{ErrorRetry: 5, ErrorRetryBaseInterval: time.Microsecond, Uncompressed: true})
298 require.NoError(t, err)
299
300 attemptCount = 0
301 writtenContent = nil
302 chunk, _ := NewChunkWithID(test.chunkId, []byte(test.content), true)
303 err = s.StoreChunk(chunk)
304 writtenContentString := ""
305 if writtenContent != nil {
306 writtenContentString = string(writtenContent)
307 }
308 assert.Equal(t, test.writtenContent, writtenContentString)
309 if test.hasError {
310 assert.Error(t, err)
311 } else {
312 assert.NoError(t, err)
313 }
314 assert.Equal(t, test.attemptCount, attemptCount)
315 })
316 }
317 }
318
319 // When retries are exhausted on a server error, the returned error must
320 // reflect the actual status code and response body, not a synthetic status
321 // code 0 or an empty message.
322 func TestRetryExhaustedError(t *testing.T) {
323 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
324 w.WriteHeader(http.StatusServiceUnavailable)
325 io.WriteString(w, "service down for maintenance")
326 }))
327 defer ts.Close()
328 u, _ := url.Parse(ts.URL)
329
330 s, err := NewRemoteHTTPStore(u, StoreOptions{ErrorRetry: 2, ErrorRetryBaseInterval: time.Microsecond, Uncompressed: true})
331 require.NoError(t, err)
332
333 // GetChunk reports the real status code
334 _, err = s.GetChunk(ChunkID{0, 0, 0, 1})
335 require.Error(t, err)
336 assert.Contains(t, err.Error(), "503")
337
338 // HasChunk reports the real status code
339 _, err = s.HasChunk(ChunkID{0, 0, 0, 1})
340 require.Error(t, err)
341 assert.Contains(t, err.Error(), "503")
342
343 // StoreChunk reports the response body
344 chunk, err := NewChunkWithID(ChunkID{0, 0, 0, 1}, []byte("data"), true)
345 require.NoError(t, err)
346 err = s.StoreChunk(chunk)
347 require.Error(t, err)
348 assert.Contains(t, err.Error(), "service down for maintenance")
349 }
350
351 func TestRemoteHTTPPutEncrypted(t *testing.T) {
352 body := new(bytes.Buffer)
353
354 // Setup a dummy server that records the request body (raw chunk data)
355 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
356 io.Copy(body, r.Body)
357 }))
358 defer ts.Close()
359 u, _ := url.Parse(ts.URL)
360
361 // HTTP client store with encryption and compression
362 httpStore, err := NewRemoteHTTPStore(u, StoreOptions{
363 Uncompressed: false,
364 Encryption: true,
365 EncryptionKey: testEncryptionKey,
366 })
367 require.NoError(t, err)
368
369 // Prep a test chunk
370 dataIn := []byte("some data")
371 chunkIn := NewChunk(dataIn)
372
373 // Send the chunk over HTTP
374 err = httpStore.StoreChunk(chunkIn)
375 require.NoError(t, err)
376
377 // If everything worked, the request body should be the chunk data, first
378 // compressed, then encrypted. Unwind it manually to check the layers are in order.
379 dec, err := NewXChaCha20Poly1305(testKey(t, testEncryptionKey))
380 require.NoError(t, err)
381 decrypted, err := dec.fromStorage(body.Bytes())
382 require.NoError(t, err)
383 uncompressed, err := Decompress(nil, decrypted)
384 require.NoError(t, err)
385 require.Equal(t, dataIn, uncompressed)
386 }