Debian Codegraph @

pkg/objectstorage/filestore/file_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 package filestore_test
15
16 import (
17 "context"
18 "io"
19 "os"
20 "path/filepath"
21 "testing"
22
23 "github.com/in-toto/archivista/pkg/objectstorage/filestore"
24 "github.com/stretchr/testify/suite"
25 )
26
27 // Test Suite: UT FileStoreSuite
28 type UTFileStoreSuite struct {
29 suite.Suite
30 tempDir string
31 payload []byte
32 }
33
34 func TestUTFileStoreSuite(t *testing.T) {
35 suite.Run(t, new(UTFileStoreSuite))
36 }
37
38 func (ut *UTFileStoreSuite) SetupTest() {
39 // Create a temporary directory for testing
40 tempDir, err := os.MkdirTemp("", "filestore_test")
41 if err != nil {
42 ut.FailNow(err.Error())
43 }
44 ut.tempDir = tempDir
45 ut.payload = []byte("test payload")
46 }
47
48 func (ut *UTFileStoreSuite) TearDownTest() {
49 os.RemoveAll(ut.tempDir)
50 }
51 func (ut *UTFileStoreSuite) Test_Get() {
52
53 store, _, err := filestore.New(context.Background(), ut.tempDir, ":50025")
54 if err != nil {
55 ut.FailNow(err.Error())
56 }
57
58 // Define a test payload
59 payload := []byte("test payload")
60
61 // Store the payload
62 err = store.Store(context.Background(), "test_gitoid", payload)
63 if err != nil {
64 ut.FailNow(err.Error())
65 }
66
67 // Attempt storing at malicious payload location
68 err = store.Store(context.Background(), "../../test_gitoid", payload)
69 if err != nil && err != filepath.ErrBadPattern {
70 ut.FailNowf("Failed to detect bad path: %v", err.Error())
71 }
72
73 // Retrieve the payload
74 reader, err := store.Get(context.Background(), "test_gitoid")
75 if err != nil {
76 ut.FailNowf("Failed to retrieve payload: %v", err.Error())
77 }
78 defer reader.Close()
79
80 // Read the payload from the reader
81 retrievedPayload, err := io.ReadAll(reader)
82 if err != nil {
83 ut.FailNowf("Failed to read payload: %v", err.Error())
84 }
85
86 // Compare the retrieved payload with the original payload
87 ut.Equal(string(retrievedPayload), string(payload))
88
89 // Attempt to retrieve non-local payload
90 _, err = store.Get(context.Background(), "/etc/passwd")
91 if err != nil && err != filepath.ErrBadPattern {
92 ut.FailNowf("Failed to detect bad path: %v", err.Error())
93 }
94
95 }