/
ocitester.go
293 lines (261 loc) · 8.74 KB
/
ocitester.go
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
package oci
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
"time"
"github.com/containerd/containerd/remotes/docker"
"github.com/distribution/distribution/v3/configuration"
"github.com/distribution/distribution/v3/registry"
"oras.land/oras-go/pkg/content"
"oras.land/oras-go/pkg/oras"
"github.com/bitnami/charts-syncer/api"
"github.com/bitnami/charts-syncer/internal/cache/cachedisk"
"github.com/bitnami/charts-syncer/internal/utils"
"github.com/bitnami/charts-syncer/pkg/client/repo/helmclassic"
)
var (
ociPing = regexp.MustCompile(`(?m)\/v2\/(.*)`)
ociIndexRegex = regexp.MustCompile(`(?m)\/v2\/(.*)\/index\/manifests\/latest`)
ociTagManifestRegex = regexp.MustCompile(`(?m)\/v2\/(.*)\/manifests\/(.*)`)
ociBlobsRegex = regexp.MustCompile(`(?m)\/v2\/(.*)\/blobs\/sha256:(.*)`)
ociTagsListRegex = regexp.MustCompile(`(?m)\/v2\/(.*)\/tags\/list`)
username = "user"
password = "password"
)
// RepoTester allows to unit test each repo implementation
type RepoTester struct {
url *url.URL
username string
password string
t *testing.T
// Map of chart name to indexed versions, as returned by the charts API.
index map[string][]*helmclassic.ChartVersion
// Whether the repo should load an empty index or not
emptyIndex bool
// index.yaml to be loaded for testing purposes
indexFile string
}
func PushFileToOCI(t *testing.T, filepath string, ref string) {
ctx := context.Background()
resolver := docker.NewResolver(docker.ResolverOptions{PlainHTTP: true})
fileContent, err := os.ReadFile(filepath)
if err != nil {
t.Fatal(err)
}
filename := path.Base(filepath)
customMediaType := "my.custom.media.type"
memoryStore := content.NewMemory()
blobDesc, err := memoryStore.Add(filename, customMediaType, fileContent)
if err != nil {
t.Fatal(err)
}
manifest, manifestDesc, config, configDesc, err := content.GenerateManifestAndConfig(nil, nil, blobDesc)
if err != nil {
t.Fatal(err)
}
memoryStore.Set(configDesc, config)
if err := memoryStore.StoreManifest(ref, manifestDesc, manifest); err != nil {
t.Fatal(err)
}
if _, err := oras.Copy(ctx, memoryStore, ref, resolver, ref, oras.WithNameValidation(nil)); err != nil {
t.Fatal(err)
}
}
func PrepareTest(t *testing.T, ociRepo *api.Repo) *Repo {
t.Helper()
// Define cache dir
cacheDir, err := os.MkdirTemp("", "client")
if err != nil {
t.Fatal(err)
}
cache, err := cachedisk.New(cacheDir, ociRepo.GetUrl())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(cacheDir) })
// Create oci client
client, err := New(ociRepo, cache, false)
if err != nil {
t.Fatal(err)
}
return client
}
// Creates an HTTP server that knows how to reply to all OCI related request except PUSH one.
func PrepareHttpServer(t *testing.T, ociRepo *api.Repo) *Repo {
t.Helper()
// Create HTTP server
tester := NewTester(t, ociRepo)
ociRepo.Url = tester.GetURL() + "/someproject/charts"
return PrepareTest(t, ociRepo)
}
// Starts an OCI compliant server (docker-registry) so our push command based on oras cli works out-of-the-box.
// This way we don't have to mimic all the low-level HTTP requests made by oras.
func PrepareOciServer(t *testing.T, ociRepo *api.Repo) {
t.Helper()
// Create OCI server as docker registry
config := &configuration.Configuration{}
addr, err := utils.GetListenAddress()
if err != nil {
t.Fatal(err)
}
dockerRegistryHost := "http://" + addr
config.HTTP.Addr = fmt.Sprintf(addr)
config.HTTP.DrainTimeout = time.Duration(10) * time.Second
config.Storage = map[string]configuration.Parameters{"inmemory": map[string]interface{}{}}
dockerRegistry, err := registry.NewRegistry(context.Background(), config)
if err != nil {
t.Fatal(err)
}
go dockerRegistry.ListenAndServe()
ociRepo.Url = dockerRegistryHost + "/someproject/charts"
}
// NewTester creates fake HTTP server to handle requests and return a RepoTester object with useful info for testing
func NewTester(t *testing.T, repo *api.Repo) *RepoTester {
t.Helper()
tester := &RepoTester{
t: t,
username: username,
password: password,
index: make(map[string][]*helmclassic.ChartVersion),
}
s := httptest.NewServer(tester)
u, err := url.Parse(s.URL)
if err != nil {
t.Fatal(err)
}
t.Cleanup(s.Close)
tester.url = u
return tester
}
func testBasicAuth(t *testing.T, r *http.Request) {
// Check basic auth credentals.
username, password, ok := r.BasicAuth()
if got, want := ok, true; got != want {
t.Fatalf("got: %t, want: %t", got, want)
}
if got, want := username, username; got != want {
t.Fatalf("got: %q, want: %q", got, want)
}
if got, want := password, password; got != want {
t.Fatalf("got: %q, want: %q", got, want)
}
}
// ServeHTTP implements the http Handler type
func (rt *RepoTester) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Handle recognized requests.
if ociIndexRegex.Match([]byte(r.URL.Path)) && r.Method == "HEAD" {
rt.HeadManifest404(w)
return
}
if ociBlobsRegex.Match([]byte(r.URL.Path)) && r.Method == "GET" {
testBasicAuth(rt.t, r)
name := strings.Split(r.URL.Path, "/")[4]
fullDigest := strings.Split(r.URL.Path, "/")[6]
digest := strings.Split(fullDigest, ":")[1]
rt.GetChartPackage(w, r, name, digest)
return
}
if ociTagManifestRegex.Match([]byte(r.URL.Path)) && r.Method == "HEAD" {
testBasicAuth(rt.t, r)
rt.HeadManifest200(w)
return
}
if ociTagManifestRegex.Match([]byte(r.URL.Path)) && r.Method == "GET" {
testBasicAuth(rt.t, r)
name := strings.Split(r.URL.Path, "/")[4]
version := strings.Split(r.URL.Path, "/")[6]
rt.GetTagManifest(w, r, name, version)
return
}
if ociTagsListRegex.Match([]byte(r.URL.Path)) && r.Method == "GET" {
testBasicAuth(rt.t, r)
name := strings.Split(r.URL.Path, "/")[4]
rt.GetTagsList(w, r, name)
return
}
if ociPing.Match([]byte(r.URL.Path)) && r.Method == "GET" {
rt.ReplyPing(w)
return
}
rt.t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
}
// GetURL returns the URL of the server
func (rt *RepoTester) GetURL() string {
return rt.url.String()
}
// GetTagManifest returns the oci manifest of a specific tag
func (rt *RepoTester) GetTagManifest(w http.ResponseWriter, r *http.Request, name, version string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, filename, _, _ := runtime.Caller(1)
testdataPath := path.Join(path.Dir(filename), "../../../../testdata/oci")
// Get oci manifest from testdata folder
manifestFileName := fmt.Sprintf("%s-%s-oci-manifest.json", name, version)
manifestFile := filepath.Join(testdataPath, manifestFileName)
manifest, err := os.ReadFile(manifestFile)
if err != nil {
rt.t.Fatal(err)
}
w.Write(manifest)
}
// GetTagsList returns the list of available tags for the specified asset
func (rt *RepoTester) GetTagsList(w http.ResponseWriter, r *http.Request, name string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, filename, _, _ := runtime.Caller(1)
testdataPath := path.Join(path.Dir(filename), "../../../../testdata/oci")
// Get oci manifest from testdata folder
tagsListFileName := fmt.Sprintf("%s-oci-tags-list.json", name)
tagsListFile := filepath.Join(testdataPath, tagsListFileName)
tagsList, err := os.ReadFile(tagsListFile)
if err != nil {
rt.t.Fatal(err)
}
w.Write(tagsList)
}
// HeadManifest200 return if a manifests exists or not
func (rt *RepoTester) HeadManifest200(w http.ResponseWriter) {
w.WriteHeader(200)
}
// HeadManifest404 return if a manifests exists or not
func (rt *RepoTester) HeadManifest404(w http.ResponseWriter) {
w.WriteHeader(404)
}
// ReplyPing reply to a ping operation done by remote.Head to guess some connection parameters
// https://github.com/google/go-containerregistry/blob/main/pkg/v1/remote/transport/transport.go#L51
func (rt *RepoTester) ReplyPing(w http.ResponseWriter) {
w.WriteHeader(200)
}
// GetChartPackage returns a packaged helm chart
func (rt *RepoTester) GetChartPackage(w http.ResponseWriter, r *http.Request, name, digest string) {
w.WriteHeader(200)
_, filename, _, _ := runtime.Caller(1)
chartPackageName := fmt.Sprintf("%s-%s.tgz", name, digest)
testdataPath := path.Join(path.Dir(filename), "../../../../testdata/oci")
// Get chart from testdata folder
chartPackageFile := path.Join(testdataPath, "charts", chartPackageName)
chartPackage, err := os.ReadFile(chartPackageFile)
if err != nil {
rt.t.Fatal(err)
}
w.Write(chartPackage)
}
// GetIndex returns an index file
func (rt *RepoTester) GetIndex(_ http.ResponseWriter, _ *http.Request) {
}
// GetChart returns the chart info from the index
func (rt *RepoTester) GetChart(_ http.ResponseWriter, _ *http.Request, _ string) {
}
// PostChart push a packaged chart
func (rt *RepoTester) PostChart(_ http.ResponseWriter, _ *http.Request) {
}