File: cache_test.go

package info (click to toggle)
gitlab-ci-multi-runner 14.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 31,248 kB
  • sloc: sh: 1,694; makefile: 384; asm: 79; ruby: 68
file content (384 lines) | stat: -rw-r--r-- 10,040 bytes parent folder | download
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
//go:build !integration
// +build !integration

package cache

import (
	"errors"
	"net/url"
	"testing"
	"time"

	"github.com/sirupsen/logrus/hooks/test"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"

	"gitlab.com/gitlab-org/gitlab-runner/common"
	hook "gitlab.com/gitlab-org/gitlab-runner/log/test"
)

type cacheOperationTest struct {
	key                    string
	configExists           bool
	adapterExists          bool
	errorOnAdapterCreation bool
	adapterURL             *url.URL
	expectedURL            *url.URL
	expectedOutput         []string
}

func prepareFakeCreateAdapter(t *testing.T, operationName string, tc cacheOperationTest) func() {
	assertAdapterExpectations := func(t mock.TestingT) bool { return true }

	var cacheAdapter Adapter
	if tc.adapterExists {
		a := new(MockAdapter)

		if tc.adapterURL != nil {
			a.On(operationName).Return(tc.adapterURL)
		}

		assertAdapterExpectations = a.AssertExpectations
		cacheAdapter = a
	}

	var cacheAdapterCreationError error
	if tc.errorOnAdapterCreation {
		cacheAdapterCreationError = errors.New("test error")
	}

	oldCreateAdapter := createAdapter
	createAdapter = func(cacheConfig *common.CacheConfig, timeout time.Duration, objectName string) (Adapter, error) {
		return cacheAdapter, cacheAdapterCreationError
	}

	return func() {
		createAdapter = oldCreateAdapter
		assertAdapterExpectations(t)
	}
}

func prepareFakeBuild(tc cacheOperationTest) *common.Build {
	build := &common.Build{
		Runner: &common.RunnerConfig{
			RunnerSettings: common.RunnerSettings{},
		},
	}

	if tc.configExists {
		build.Runner.Cache = &common.CacheConfig{}
	}

	return build
}

func testCacheOperation(
	t *testing.T,
	operationName string,
	operation func(build *common.Build, key string) *url.URL,
	tc cacheOperationTest,
) {
	t.Run(operationName, func(t *testing.T) {
		hook := test.NewGlobal()

		cleanupCreateAdapter := prepareFakeCreateAdapter(t, operationName, tc)
		defer cleanupCreateAdapter()

		build := prepareFakeBuild(tc)
		generatedURL := operation(build, tc.key)
		assert.Equal(t, tc.expectedURL, generatedURL)

		if len(tc.expectedOutput) == 0 {
			assert.Len(t, hook.AllEntries(), 0)
		} else {
			for _, expectedOutput := range tc.expectedOutput {
				message, err := hook.LastEntry().String()
				require.NoError(t, err)
				assert.Contains(t, message, expectedOutput)
			}
		}
	})
}

func TestCacheOperations(t *testing.T) {
	exampleURL, err := url.Parse("example.com")
	require.NoError(t, err)

	tests := map[string]cacheOperationTest{
		"no-config": {
			key:            "key",
			adapterExists:  true,
			adapterURL:     nil,
			expectedURL:    nil,
			expectedOutput: []string{"Cache config not defined. Skipping cache operation."},
		},
		"key-not-specified": {
			configExists:   true,
			adapterExists:  true,
			adapterURL:     nil,
			expectedURL:    nil,
			expectedOutput: []string{"Empty cache key. Skipping adapter selection."},
		},
		"adapter-doesnt-exists": {
			key:           "key",
			configExists:  true,
			adapterExists: false,
			adapterURL:    exampleURL,
			expectedURL:   nil,
		},
		"adapter-error-on-factorization": {
			key:                    "key",
			configExists:           true,
			errorOnAdapterCreation: true,
			adapterURL:             exampleURL,
			expectedURL:            nil,
			expectedOutput: []string{
				"Could not create cache adapter",
				"test error",
			},
		},
		"adapter-exists": {
			key:           "key",
			configExists:  true,
			adapterExists: true,
			adapterURL:    exampleURL,
			expectedURL:   exampleURL,
		},
	}

	for name, tc := range tests {
		t.Run(name, func(t *testing.T) {
			testCacheOperation(t, "GetDownloadURL", GetCacheDownloadURL, tc)
			testCacheOperation(t, "GetUploadURL", GetCacheUploadURL, tc)
			testCacheOperation(t, "GetGoCloudURL", GetCacheGoCloudURL, tc)
		})
	}
}

func defaultCacheConfig() *common.CacheConfig {
	return &common.CacheConfig{
		Type: "test",
	}
}

func defaultBuild(cacheConfig *common.CacheConfig) *common.Build {
	return &common.Build{
		JobResponse: common.JobResponse{
			JobInfo: common.JobInfo{
				ProjectID: 10,
			},
			RunnerInfo: common.RunnerInfo{
				Timeout: 3600,
			},
		},
		Runner: &common.RunnerConfig{
			RunnerCredentials: common.RunnerCredentials{
				Token: "longtoken",
			},
			RunnerSettings: common.RunnerSettings{
				Cache: cacheConfig,
			},
		},
	}
}

type generateObjectNameTestCase struct {
	cache *common.CacheConfig
	build *common.Build

	key    string
	path   string
	shared bool

	expectedObjectName string
	expectedError      string
}

func TestGenerateObjectName(t *testing.T) {
	cache := defaultCacheConfig()
	cacheBuild := defaultBuild(cache)

	tests := map[string]generateObjectNameTestCase{
		"default usage": {
			cache:              cache,
			build:              cacheBuild,
			key:                "key",
			expectedObjectName: "runner/longtoke/project/10/key",
		},
		"empty key": {
			cache:              cache,
			build:              cacheBuild,
			key:                "",
			expectedObjectName: "",
		},
		"short path is set": {
			cache:              cache,
			build:              cacheBuild,
			key:                "key",
			path:               "whatever",
			expectedObjectName: "whatever/runner/longtoke/project/10/key",
		},
		"multiple segment path is set": {
			cache:              cache,
			build:              cacheBuild,
			key:                "key",
			path:               "some/other/path/goes/here",
			expectedObjectName: "some/other/path/goes/here/runner/longtoke/project/10/key",
		},
		"path is empty": {
			cache:              cache,
			build:              cacheBuild,
			key:                "key",
			path:               "",
			expectedObjectName: "runner/longtoke/project/10/key",
		},
		"shared flag is set to true": {
			cache:              cache,
			build:              cacheBuild,
			key:                "key",
			shared:             true,
			expectedObjectName: "project/10/key",
		},
		"shared flag is set to false": {
			cache:              cache,
			build:              cacheBuild,
			key:                "key",
			shared:             false,
			expectedObjectName: "runner/longtoke/project/10/key",
		},
		"path traversal but within base path": {
			cache:              cache,
			build:              cacheBuild,
			key:                "../10/key",
			expectedObjectName: "runner/longtoke/project/10/key",
		},
		"path traversal resolves to empty key": {
			cache:         cache,
			build:         cacheBuild,
			key:           "../10",
			expectedError: "computed cache path outside of project bucket. Please remove `../` from cache key",
		},
		"path traversal escapes project namespace": {
			cache:         cache,
			build:         cacheBuild,
			key:           "../10-outside",
			expectedError: "computed cache path outside of project bucket. Please remove `../` from cache key",
		},
	}

	for name, test := range tests {
		t.Run(name, func(t *testing.T) {
			cache.Path = test.path
			cache.Shared = test.shared

			objectName, err := generateObjectName(test.build, test.cache, test.key)

			assert.Equal(t, test.expectedObjectName, objectName)
			if test.expectedError == "" {
				assert.NoError(t, err)
			} else {
				assert.EqualError(t, err, test.expectedError)
			}
		})
	}
}

func TestCacheUploadEnv(t *testing.T) {
	tests := map[string]struct {
		key                   string
		cacheConfig           *common.CacheConfig
		createCacheAdapter    bool
		createCacheAdapterErr error
		getUploadEnvResult    interface{}
		expectedEnvs          map[string]string
		expectedLogEntry      string
	}{
		"full map": {
			key:                "key",
			cacheConfig:        &common.CacheConfig{},
			createCacheAdapter: true,
			getUploadEnvResult: map[string]string{"TEST1": "123", "TEST2": "456"},
			expectedEnvs:       map[string]string{"TEST1": "123", "TEST2": "456"},
		},
		"nil": {
			key:                "key",
			cacheConfig:        &common.CacheConfig{},
			createCacheAdapter: true,
			getUploadEnvResult: nil,
			expectedEnvs:       nil,
		},
		"no cache config": {
			key:                "key",
			cacheConfig:        nil,
			createCacheAdapter: true,
			getUploadEnvResult: nil,
			expectedEnvs:       nil,
			expectedLogEntry:   "Cache config not defined",
		},
		"no key": {
			key:                "",
			cacheConfig:        &common.CacheConfig{},
			createCacheAdapter: true,
			getUploadEnvResult: nil,
			expectedEnvs:       nil,
		},
		"adapter not exists": {
			cacheConfig:        &common.CacheConfig{},
			createCacheAdapter: false,
			getUploadEnvResult: nil,
			expectedEnvs:       nil,
		},
		"adapter creation error": {
			cacheConfig:           &common.CacheConfig{},
			createCacheAdapter:    true,
			createCacheAdapterErr: errors.New("test error"),
			getUploadEnvResult:    nil,
			expectedEnvs:          nil,
			expectedLogEntry:      `Could not create cache adapter" error="test error`,
		},
	}

	for name, tc := range tests {
		t.Run(name, func(t *testing.T) {
			cacheAdapter := new(MockAdapter)
			defer cacheAdapter.AssertExpectations(t)

			logs, cleanUpHooks := hook.NewHook()
			defer cleanUpHooks()

			build := &common.Build{
				Runner: &common.RunnerConfig{
					RunnerSettings: common.RunnerSettings{
						Cache: tc.cacheConfig,
					},
				},
			}

			oldCreateAdapter := createAdapter
			createAdapter = func(_ *common.CacheConfig, timeout time.Duration, objectName string) (Adapter, error) {
				if tc.createCacheAdapter {
					return cacheAdapter, tc.createCacheAdapterErr
				}

				return nil, nil
			}
			defer func() {
				createAdapter = oldCreateAdapter
			}()

			if tc.cacheConfig != nil && tc.createCacheAdapter {
				cacheAdapter.On("GetUploadEnv").Return(tc.getUploadEnvResult)
			}

			envs := GetCacheUploadEnv(build, "key")
			assert.Equal(t, tc.expectedEnvs, envs)

			if tc.expectedLogEntry != "" {
				lastLogMsg, err := logs.LastEntry().String()
				require.NoError(t, err)
				assert.Contains(t, lastLogMsg, tc.expectedLogEntry)
			}
		})
	}
}