Debian Codegraph @

pkg/server/server_test.go

raw
1 // Copyright 2024 The Archivista Contributors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package server
16
17 import (
18 "bytes"
19 "context"
20 "errors"
21 "io"
22 "net/http"
23 "net/http/httptest"
24 "os"
25 "path/filepath"
26 "strings"
27 "testing"
28
29 "github.com/gorilla/mux"
30 "github.com/in-toto/archivista/pkg/api"
31 "github.com/in-toto/archivista/pkg/artifactstore"
32 "github.com/in-toto/archivista/pkg/config"
33 "github.com/stretchr/testify/mock"
34 "github.com/stretchr/testify/suite"
35 )
36
37 // Mock StorerMock
38 type StorerMock struct {
39 mock.Mock
40 Storer
41 }
42
43 func (m *StorerMock) Store(context.Context, string, []byte) error {
44 args := m.Called()
45 return args.Error(0)
46 }
47
48 type StorerGetterMock struct {
49 mock.Mock
50 StorerGetter
51 }
52
53 // Mock StorerGetter
54 func (m *StorerGetterMock) Store(context.Context, string, []byte) error {
55 args := m.Called()
56 return args.Error(0)
57 }
58
59 func (m *StorerGetterMock) Get(context.Context, string) (io.ReadCloser, error) {
60 args := m.Called()
61 stringReader := strings.NewReader("testData")
62 stringReadCloser := io.NopCloser(stringReader)
63 return stringReadCloser, args.Error(0)
64 }
65
66 // Mock ResponseRecorderMock
67 type ResponseRecorderMock struct {
68 mock.Mock
69 Code int
70 HeaderMap http.Header
71 Body *bytes.Buffer
72 Flushed bool
73 }
74
75 func (m *ResponseRecorderMock) Write([]byte) (int, error) {
76 args := m.Called()
77 return args.Int(0), args.Error(1)
78 }
79
80 func (rw *ResponseRecorderMock) Header() http.Header {
81 return http.Header{}
82 }
83
84 func (rw *ResponseRecorderMock) WriteHeader(code int) {
85 rw.Code = code
86 }
87
88 func (rw *ResponseRecorderMock) WriteString(str string) (int, error) {
89 return 0, nil
90 }
91
92 // Define test Suite
93 type UTServerSuite struct {
94 suite.Suite
95 mockedStorer *StorerMock
96 mockedStorerGetter *StorerGetterMock
97 mockedResposeRecorder *ResponseRecorderMock
98 testServer Server
99 }
100
101 func TestUTServerSuite(t *testing.T) {
102 suite.Run(t, new(UTServerSuite))
103 }
104
105 func (ut *UTServerSuite) SetupTest() {
106 ut.mockedStorer = new(StorerMock)
107 ut.mockedStorerGetter = new(StorerGetterMock)
108 ut.mockedResposeRecorder = new(ResponseRecorderMock)
109 ut.testServer = Server{
110 metadataStore: ut.mockedStorer,
111 objectStore: ut.mockedStorerGetter,
112 artifactStore: ut.testArtifactStore(),
113 }
114 }
115
116 func (ut *UTServerSuite) Test_New() {
117 cfg := new(config.Config)
118 cfg.EnableGraphql = true
119 cfg.GraphqlWebClientEnable = true
120 cfg.EnableSQLStore = true
121 var err error
122 ut.testServer, err = New(cfg, WithMetadataStore(ut.mockedStorer), WithObjectStore(ut.mockedStorerGetter))
123 ut.NoError(err)
124 ut.NotNil(ut.testServer)
125 router := ut.testServer.Router()
126 ut.NotNil(router)
127
128 allPaths := []string{}
129 err = router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
130 pathTemplate, err := route.GetPathTemplate()
131 if err != nil {
132 ut.FailNow(err.Error())
133 }
134 allPaths = append(allPaths, pathTemplate)
135 return nil
136 })
137 if err != nil {
138 ut.FailNow(err.Error())
139 }
140 ut.Contains(allPaths, "/download/{gitoid}")
141 ut.Contains(allPaths, "/upload")
142 ut.Contains(allPaths, "/query")
143 ut.Contains(allPaths, "/v1/download/{gitoid}")
144 ut.Contains(allPaths, "/v1/upload")
145 ut.Contains(allPaths, "/v1/query")
146 ut.Contains(allPaths, "/")
147 ut.Contains(allPaths, "/swagger/")
148 }
149
150 func (ut *UTServerSuite) Test_New_EnableGraphQL_False() {
151 cfg := new(config.Config)
152 cfg.EnableGraphql = false
153 cfg.GraphqlWebClientEnable = true
154 cfg.EnableSQLStore = true
155 var err error
156 ut.testServer, err = New(cfg, WithMetadataStore(ut.mockedStorer), WithObjectStore(ut.mockedStorerGetter))
157 ut.NoError(err)
158 ut.NotNil(ut.testServer)
159 router := ut.testServer.Router()
160 ut.NotNil(router)
161
162 allPaths := []string{}
163 err = router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
164 pathTemplate, err := route.GetPathTemplate()
165 if err != nil {
166 ut.FailNow(err.Error())
167 }
168 allPaths = append(allPaths, pathTemplate)
169 return nil
170 })
171 if err != nil {
172 ut.FailNow(err.Error())
173 }
174 ut.Contains(allPaths, "/download/{gitoid}")
175 ut.Contains(allPaths, "/upload")
176 ut.NotContains(allPaths, "/query")
177 ut.Contains(allPaths, "/v1/download/{gitoid}")
178 ut.Contains(allPaths, "/v1/upload")
179 ut.NotContains(allPaths, "/v1/query")
180 ut.Contains(allPaths, "/swagger/")
181 }
182
183 func (ut *UTServerSuite) Test_New_GraphqlWebClientEnable_False() {
184 cfg := new(config.Config)
185 cfg.EnableGraphql = true
186 cfg.GraphqlWebClientEnable = false
187 cfg.EnableSQLStore = true
188 var err error
189 ut.testServer, err = New(cfg, WithMetadataStore(ut.mockedStorer), WithObjectStore(ut.mockedStorerGetter))
190 ut.NoError(err)
191 ut.NotNil(ut.testServer)
192 router := ut.testServer.Router()
193 ut.NotNil(router)
194
195 allPaths := []string{}
196 err = router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
197 pathTemplate, err := route.GetPathTemplate()
198 if err != nil {
199 ut.FailNow(err.Error())
200 }
201 allPaths = append(allPaths, pathTemplate)
202 return nil
203 })
204 if err != nil {
205 ut.FailNow(err.Error())
206 }
207 ut.Contains(allPaths, "/download/{gitoid}")
208 ut.Contains(allPaths, "/upload")
209 ut.Contains(allPaths, "/query")
210 ut.Contains(allPaths, "/v1/download/{gitoid}")
211 ut.Contains(allPaths, "/v1/upload")
212 ut.Contains(allPaths, "/v1/query")
213 ut.NotContains(allPaths, "/")
214 ut.Contains(allPaths, "/swagger/")
215 }
216
217 func (ut *UTServerSuite) Test_Upload() {
218 ctx := context.TODO()
219 r := strings.NewReader("fakeTestData")
220
221 ut.mockedStorerGetter.On("Store").Return(nil) // mock Get() to return nil
222 ut.mockedStorer.On("Store").Return(nil) // mock Store() to return nil
223
224 resp, err := ut.testServer.Upload(ctx, r)
225 ut.NoError(err)
226 ut.NotEqual("", resp.Gitoid)
227 }
228
229 func (ut *UTServerSuite) Test_Upload_NoObjectStorage() {
230 ctx := context.TODO()
231 r := strings.NewReader("fakeTestData")
232
233 ut.testServer.objectStore = nil
234 ut.mockedStorer.On("Store").Return(nil) // mock Store() to return nil
235
236 resp, err := ut.testServer.Upload(ctx, r)
237 ut.NoError(err)
238 ut.NotEqual("", resp.Gitoid)
239 }
240
241 func (ut *UTServerSuite) Test_Upload_FailedObjectStorage() {
242 ctx := context.TODO()
243 r := strings.NewReader("fakeTestData")
244
245 ut.mockedStorerGetter.On("Store").Return(errors.New("Bad S3")) // mock Get() to return err
246 ut.mockedStorer.On("Store").Return(nil) // mock Store() to return nil
247
248 resp, err := ut.testServer.Upload(ctx, r)
249 ut.ErrorContains(err, "Bad S3")
250 ut.Equal(api.UploadResponse{}, resp)
251 }
252
253 func (ut *UTServerSuite) Test_Upload_FailedMetadatStprage() {
254 ctx := context.TODO()
255 r := strings.NewReader("fakeTestData")
256
257 ut.mockedStorerGetter.On("Store").Return(nil) // mock Get() to return nil
258 ut.mockedStorer.On("Store").Return(errors.New("Bad SQL")) // mock Store() to return err
259
260 resp, err := ut.testServer.Upload(ctx, r)
261 ut.ErrorContains(err, "Bad SQL")
262 ut.Equal(api.UploadResponse{}, resp)
263 }
264
265 func (ut *UTServerSuite) Test_UploadHandler() {
266 w := httptest.NewRecorder()
267 requestBody := []byte("fakePayload")
268 request := httptest.NewRequest(http.MethodPost, "/v1/upload", bytes.NewBuffer(requestBody))
269
270 ut.mockedStorerGetter.On("Store").Return(nil) // mock Get() to return nil
271 ut.mockedStorer.On("Store").Return(nil) // mock Store() to return nil
272
273 ut.testServer.UploadHandler(w, request)
274 ut.Equal(http.StatusOK, w.Code)
275 }
276
277 func (ut *UTServerSuite) Test_UploadHandler_WrongMethod() {
278 w := httptest.NewRecorder()
279 requestBody := []byte("fakePayload")
280 request := httptest.NewRequest(http.MethodGet, "/upload", bytes.NewBuffer(requestBody))
281
282 ut.mockedStorerGetter.On("Store").Return(nil) // mock Get() to return nil
283 ut.mockedStorer.On("Store").Return(nil) // mock Store() to return nil
284
285 ut.testServer.UploadHandler(w, request)
286 ut.Equal(http.StatusBadRequest, w.Code)
287 ut.Contains(w.Body.String(), "is an unsupported method")
288 }
289
290 func (ut *UTServerSuite) Test_UploadHandler_FailureUpload() {
291 w := httptest.NewRecorder()
292 requestBody := []byte("fakePayload")
293 request := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewBuffer(requestBody))
294
295 ut.mockedStorerGetter.On("Store").Return(errors.New("BAD S3")) // mock Get() to return nil
296 ut.mockedStorer.On("Store").Return(nil) // mock Store() to return nil
297
298 ut.testServer.UploadHandler(w, request)
299 ut.Equal(http.StatusInternalServerError, w.Code)
300 ut.Contains(w.Body.String(), "BAD S3")
301 }
302
303 func (ut *UTServerSuite) Test_Download() {
304 ctx := context.TODO()
305 ut.mockedStorerGetter.On("Get").Return(nil) // mock Get() to return nil
306
307 resp, err := ut.testServer.Download(ctx, "fakeGitoid")
308 ut.NoError(err)
309 data, _ := io.ReadAll(resp)
310 ut.Equal("testData", string(data))
311 }
312
313 func (ut *UTServerSuite) Test_Download_NoObjectStorage() {
314 ctx := context.TODO()
315 ut.testServer.objectStore = nil
316
317 _, err := ut.testServer.Download(ctx, "fakeGitoid")
318 ut.ErrorContains(err, "object store unavailable")
319 }
320
321 func (ut *UTServerSuite) Test_Download_ObjectStorageError() {
322 ctx := context.TODO()
323 ut.mockedStorerGetter.On("Get").Return(errors.New("BAD S3")) // mock Get() to return nil
324
325 _, err := ut.testServer.Download(ctx, "fakeGitoid")
326 ut.ErrorContains(err, "BAD S3")
327 }
328
329 func (ut *UTServerSuite) Test_DownloadHandler() {
330 w := httptest.NewRecorder()
331 request := httptest.NewRequest(http.MethodGet, "/v1/download", nil)
332 request = mux.SetURLVars(request, map[string]string{"gitoid": "fakeGitoid"})
333
334 ut.mockedStorerGetter.On("Get").Return(nil) // mock Get() to return nil
335
336 ut.testServer.DownloadHandler(w, request)
337 ut.Equal(http.StatusOK, w.Code)
338 ut.Equal("testData", w.Body.String())
339 }
340
341 func (ut *UTServerSuite) Test_DownloadHandler_BadMethod() {
342 w := httptest.NewRecorder()
343 request := httptest.NewRequest(http.MethodPost, "/v1/download", nil)
344 request = mux.SetURLVars(request, map[string]string{"gitoid": "fakeGitoid"})
345
346 ut.mockedStorerGetter.On("Get").Return(nil) // mock Get() to return nil
347
348 ut.testServer.DownloadHandler(w, request)
349 ut.Equal(http.StatusBadRequest, w.Code)
350 ut.Contains(w.Body.String(), "POST is an unsupported method")
351 }
352
353 func (ut *UTServerSuite) Test_DownloadHandler_MissingGitOID() {
354 w := httptest.NewRecorder()
355 request := httptest.NewRequest(http.MethodGet, "/v1/download", nil)
356
357 ut.mockedStorerGetter.On("Get").Return(nil) // mock Get() to return nil
358
359 ut.testServer.DownloadHandler(w, request)
360 ut.Equal(http.StatusBadRequest, w.Code)
361 ut.Contains(w.Body.String(), "gitoid parameter is required")
362 }
363
364 func (ut *UTServerSuite) Test_DownloadHandler_GitOIDEmpty() {
365 w := httptest.NewRecorder()
366 request := httptest.NewRequest(http.MethodGet, "/v1/download", nil)
367 request = mux.SetURLVars(request, map[string]string{"gitoid": ""})
368
369 ut.mockedStorerGetter.On("Get").Return(nil) // mock Get() to return nil
370
371 ut.testServer.DownloadHandler(w, request)
372 ut.Equal(http.StatusBadRequest, w.Code)
373 ut.Contains(w.Body.String(), "gitoid parameter is required")
374 }
375
376 func (ut *UTServerSuite) Test_DownloadHandler_ObjectStorageFailed() {
377 w := httptest.NewRecorder()
378 request := httptest.NewRequest(http.MethodGet, "/v1/download", nil)
379 request = mux.SetURLVars(request, map[string]string{"gitoid": "fakeGitoid"})
380
381 ut.mockedStorerGetter.On("Get").Return(errors.New("BAD S3")) // mock Get() to return nil
382
383 ut.testServer.DownloadHandler(w, request)
384 ut.Equal(http.StatusInternalServerError, w.Code)
385 ut.Contains(w.Body.String(), "BAD S3")
386 }
387
388 func (ut *UTServerSuite) Test_DownloadHandler_NotFound() {
389 request := httptest.NewRequest(http.MethodGet, "/v1/download", nil)
390 request = mux.SetURLVars(request, map[string]string{"gitoid": "fakeGitoid"})
391
392 ut.mockedStorerGetter.On("Get").Return(nil) // mock Get() to return nil
393 ut.mockedResposeRecorder.On("Write").Return(404, errors.New("Not Found"))
394
395 ut.testServer.DownloadHandler(ut.mockedResposeRecorder, request)
396 ut.Equal(http.StatusNotFound, ut.mockedResposeRecorder.Code)
397 ut.Nil(ut.mockedResposeRecorder.Body)
398 }
399
400 func (ut *UTServerSuite) Test_AllArtifactsHandler() {
401 w := httptest.NewRecorder()
402 request := httptest.NewRequest(http.MethodGet, "/v1/artifacts", nil)
403
404 ut.testServer.AllArtifactsHandler(w, request)
405 ut.Equal(http.StatusOK, w.Code)
406 ut.Contains(w.Body.String(), "witness")
407 ut.Contains(w.Body.String(), "v0.1.0")
408 ut.Contains(w.Body.String(), "linux-x64")
409 }
410
411 func (ut *UTServerSuite) Test_ArtifactAllVersionsHandler() {
412 w := httptest.NewRecorder()
413 request := httptest.NewRequest(http.MethodGet, "/v1/artifacts/witness", nil)
414 request = mux.SetURLVars(request, map[string]string{"name": "witness"})
415
416 ut.testServer.ArtifactAllVersionsHandler(w, request)
417 ut.Equal(http.StatusOK, w.Code)
418 ut.Contains(w.Body.String(), "v0.1.0")
419 ut.Contains(w.Body.String(), "linux-x64")
420 }
421
422 func (ut *UTServerSuite) Test_ArtifactVersionHandler() {
423 w := httptest.NewRecorder()
424 request := httptest.NewRequest(http.MethodGet, "/v1/artifacts/witness/v0.1.0", nil)
425 request = mux.SetURLVars(request, map[string]string{"name": "witness", "version": "v0.1.0"})
426
427 ut.testServer.ArtifactVersionHandler(w, request)
428 ut.Equal(http.StatusOK, w.Code)
429 ut.Contains(w.Body.String(), "linux-x64")
430 }
431
432 func (ut *UTServerSuite) Test_ArtifactVersionHandler_NotFound() {
433 w := httptest.NewRecorder()
434 request := httptest.NewRequest(http.MethodGet, "/v1/artifacts/witness/v0.3.0", nil)
435 request = mux.SetURLVars(request, map[string]string{"name": "witness", "version": "v0.3.0"})
436
437 ut.testServer.ArtifactVersionHandler(w, request)
438 ut.Equal(http.StatusNotFound, w.Code)
439 ut.Contains(w.Body.String(), "version not found")
440 }
441
442 func (ut *UTServerSuite) Test_DownloadArtifactHandler() {
443 w := httptest.NewRecorder()
444 request := httptest.NewRequest(http.MethodGet, "/v1/download/artifact/witness/v0.1.0/linux-x64", nil)
445 request = mux.SetURLVars(request, map[string]string{"name": "witness", "version": "v0.1.0", "distribution": "linux-x64"})
446
447 ut.testServer.DownloadArtifactHandler(w, request)
448 ut.Equal(http.StatusOK, w.Code)
449 ut.Contains(w.Body.String(), "test")
450 }
451
452 func (ut *UTServerSuite) Test_DownloadArtifactHandler_NotFound() {
453 w := httptest.NewRecorder()
454 request := httptest.NewRequest(http.MethodGet, "/v1/download/artifact/witness/v0.1.0/linux-arm", nil)
455 request = mux.SetURLVars(request, map[string]string{"name": "witness", "version": "v0.1.0", "distribution": "linux-arm"})
456
457 ut.testServer.DownloadArtifactHandler(w, request)
458 ut.Equal(http.StatusNotFound, w.Code)
459 ut.Contains(w.Body.String(), "distribution of artifact not found")
460 }
461
462 func (ut *UTServerSuite) testArtifactStore() artifactstore.Store {
463 testDir := ut.T().TempDir()
464 testDistroFilePath := filepath.Join(testDir, "witness-v0.1.0-linux-x64")
465 ut.NoError(os.WriteFile(testDistroFilePath, []byte("test"), 0644))
466
467 config := artifactstore.Config{
468 Artifacts: map[string]artifactstore.Artifact{
469 "witness": {
470 Versions: map[string]artifactstore.Version{
471 "v0.1.0": {
472 Description: "some description",
473 Distributions: map[string]artifactstore.Distribution{
474 "linux-x64": {
475 SHA256Digest: "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
476 FileLocation: testDistroFilePath,
477 },
478 },
479 },
480 },
481 },
482 },
483 }
484
485 wds, err := artifactstore.New(artifactstore.WithConfig(config))
486 ut.NoError(err)
487 return wds
488 }