forked from testcontainers/testcontainers-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker_auth_test.go
382 lines (312 loc) · 10.8 KB
/
docker_auth_test.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
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
package testcontainers
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/cpuguy83/dockercfg"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go/internal/core"
"github.com/testcontainers/testcontainers-go/wait"
)
const exampleAuth = "https://example-auth.com"
var testDockerConfigDirPath = filepath.Join("testdata", ".docker")
var indexDockerIO = core.IndexDockerIO
func TestGetDockerConfig(t *testing.T) {
const expectedErrorMessage = "Expected to find %s in auth configs"
// Verify that the default docker config file exists before any test in this suite runs.
// Then, we can safely run the tests that rely on it.
defaultCfg, err := dockercfg.LoadDefaultConfig()
require.NoError(t, err)
require.NotEmpty(t, defaultCfg)
t.Run("without DOCKER_CONFIG env var retrieves default", func(t *testing.T) {
t.Setenv("DOCKER_CONFIG", "")
cfg, err := getDockerConfig()
require.NoError(t, err)
require.NotEmpty(t, cfg)
assert.Equal(t, defaultCfg, cfg)
})
t.Run("with DOCKER_CONFIG env var pointing to a non-existing file raises error", func(t *testing.T) {
t.Setenv("DOCKER_CONFIG", filepath.Join(testDockerConfigDirPath, "non-existing"))
cfg, err := getDockerConfig()
require.Error(t, err)
require.Empty(t, cfg)
})
t.Run("with DOCKER_CONFIG env var", func(t *testing.T) {
t.Setenv("DOCKER_CONFIG", testDockerConfigDirPath)
cfg, err := getDockerConfig()
require.NoError(t, err)
require.NotEmpty(t, cfg)
assert.Len(t, cfg.AuthConfigs, 3)
authCfgs := cfg.AuthConfigs
if _, ok := authCfgs[indexDockerIO]; !ok {
t.Errorf(expectedErrorMessage, indexDockerIO)
}
if _, ok := authCfgs["https://example.com"]; !ok {
t.Errorf(expectedErrorMessage, "https://example.com")
}
if _, ok := authCfgs["https://my.private.registry"]; !ok {
t.Errorf(expectedErrorMessage, "https://my.private.registry")
}
})
t.Run("DOCKER_AUTH_CONFIG env var takes precedence", func(t *testing.T) {
t.Setenv("DOCKER_AUTH_CONFIG", `{
"auths": {
"`+exampleAuth+`": {}
},
"credsStore": "desktop"
}`)
t.Setenv("DOCKER_CONFIG", testDockerConfigDirPath)
cfg, err := getDockerConfig()
require.NoError(t, err)
require.NotEmpty(t, cfg)
assert.Len(t, cfg.AuthConfigs, 1)
authCfgs := cfg.AuthConfigs
if _, ok := authCfgs[indexDockerIO]; ok {
t.Errorf("Not expected to find %s in auth configs", indexDockerIO)
}
if _, ok := authCfgs[exampleAuth]; !ok {
t.Errorf(expectedErrorMessage, exampleAuth)
}
})
t.Run("retrieve auth with DOCKER_AUTH_CONFIG env var", func(t *testing.T) {
base64 := "Z29waGVyOnNlY3JldA==" // gopher:secret
t.Setenv("DOCKER_AUTH_CONFIG", `{
"auths": {
"`+exampleAuth+`": { "username": "gopher", "password": "secret", "auth": "`+base64+`" }
},
"credsStore": "desktop"
}`)
registry, cfg, err := DockerImageAuth(context.Background(), exampleAuth+"/my/image:latest")
require.NoError(t, err)
require.NotEmpty(t, cfg)
assert.Equal(t, exampleAuth, registry)
assert.Equal(t, "gopher", cfg.Username)
assert.Equal(t, "secret", cfg.Password)
assert.Equal(t, base64, cfg.Auth)
})
t.Run("match registry authentication by host", func(t *testing.T) {
base64 := "Z29waGVyOnNlY3JldA==" // gopher:secret
imageReg := "example-auth.com"
imagePath := "/my/image:latest"
t.Setenv("DOCKER_AUTH_CONFIG", `{
"auths": {
"`+exampleAuth+`": { "username": "gopher", "password": "secret", "auth": "`+base64+`" }
},
"credsStore": "desktop"
}`)
registry, cfg, err := DockerImageAuth(context.Background(), imageReg+imagePath)
require.NoError(t, err)
require.NotEmpty(t, cfg)
assert.Equal(t, imageReg, registry)
assert.Equal(t, "gopher", cfg.Username)
assert.Equal(t, "secret", cfg.Password)
assert.Equal(t, base64, cfg.Auth)
})
t.Run("fail to match registry authentication due to invalid host", func(t *testing.T) {
base64 := "Z29waGVyOnNlY3JldA==" // gopher:secret
imageReg := "example-auth.com"
imagePath := "/my/image:latest"
invalidRegistryURL := "://invalid-host"
t.Setenv("DOCKER_AUTH_CONFIG", `{
"auths": {
"`+invalidRegistryURL+`": { "username": "gopher", "password": "secret", "auth": "`+base64+`" }
},
"credsStore": "desktop"
}`)
registry, cfg, err := DockerImageAuth(context.Background(), imageReg+imagePath)
require.ErrorIs(t, err, dockercfg.ErrCredentialsNotFound)
require.Empty(t, cfg)
assert.Equal(t, imageReg, registry)
})
t.Run("fail to match registry authentication by host with empty URL scheme creds and missing default", func(t *testing.T) {
origDefaultRegistryFn := defaultRegistryFn
t.Cleanup(func() {
defaultRegistryFn = origDefaultRegistryFn
})
defaultRegistryFn = func(ctx context.Context) string {
return ""
}
base64 := "Z29waGVyOnNlY3JldA==" // gopher:secret
imageReg := ""
imagePath := "image:latest"
t.Setenv("DOCKER_AUTH_CONFIG", `{
"auths": {
"example-auth.com": { "username": "gopher", "password": "secret", "auth": "`+base64+`" }
},
"credsStore": "desktop"
}`)
registry, cfg, err := DockerImageAuth(context.Background(), imageReg+imagePath)
require.ErrorIs(t, err, dockercfg.ErrCredentialsNotFound)
require.Empty(t, cfg)
assert.Equal(t, imageReg, registry)
})
}
func TestBuildContainerFromDockerfile(t *testing.T) {
ctx := context.Background()
req := ContainerRequest{
FromDockerfile: FromDockerfile{
Context: "./testdata",
},
AlwaysPullImage: true, // make sure the authentication takes place
ExposedPorts: []string{"6379/tcp"},
WaitingFor: wait.ForLog("Ready to accept connections"),
}
redisC, err := prepareRedisImage(ctx, req, t)
require.NoError(t, err)
terminateContainerOnEnd(t, ctx, redisC)
}
// removeImageFromLocalCache removes the image from the local cache
func removeImageFromLocalCache(t *testing.T, img string) {
ctx := context.Background()
testcontainersClient, err := NewDockerClientWithOpts(ctx, client.WithVersion(daemonMaxVersion))
if err != nil {
t.Log("could not create client to cleanup registry: ", err)
}
defer testcontainersClient.Close()
_, err = testcontainersClient.ImageRemove(ctx, img, image.RemoveOptions{
Force: true,
PruneChildren: true,
})
if err != nil {
t.Logf("could not remove image %s: %v\n", img, err)
}
}
func TestBuildContainerFromDockerfileWithDockerAuthConfig(t *testing.T) {
mappedPort := prepareLocalRegistryWithAuth(t)
// using the same credentials as in the Docker Registry
base64 := "dGVzdHVzZXI6dGVzdHBhc3N3b3Jk" // testuser:testpassword
t.Setenv("DOCKER_AUTH_CONFIG", `{
"auths": {
"localhost:`+mappedPort+`": { "username": "testuser", "password": "testpassword", "auth": "`+base64+`" }
},
"credsStore": "desktop"
}`)
ctx := context.Background()
req := ContainerRequest{
FromDockerfile: FromDockerfile{
Context: "./testdata",
Dockerfile: "auth.Dockerfile",
BuildArgs: map[string]*string{
"REGISTRY_PORT": &mappedPort,
},
},
AlwaysPullImage: true, // make sure the authentication takes place
ExposedPorts: []string{"6379/tcp"},
WaitingFor: wait.ForLog("Ready to accept connections"),
}
redisC, err := prepareRedisImage(ctx, req, t)
require.NoError(t, err)
terminateContainerOnEnd(t, ctx, redisC)
}
func TestBuildContainerFromDockerfileShouldFailWithWrongDockerAuthConfig(t *testing.T) {
mappedPort := prepareLocalRegistryWithAuth(t)
// using different credentials than in the Docker Registry
base64 := "Zm9vOmJhcg==" // foo:bar
t.Setenv("DOCKER_AUTH_CONFIG", `{
"auths": {
"localhost:`+mappedPort+`": { "username": "foo", "password": "bar", "auth": "`+base64+`" }
},
"credsStore": "desktop"
}`)
ctx := context.Background()
req := ContainerRequest{
FromDockerfile: FromDockerfile{
Context: "./testdata",
Dockerfile: "auth.Dockerfile",
BuildArgs: map[string]*string{
"REGISTRY_PORT": &mappedPort,
},
},
AlwaysPullImage: true, // make sure the authentication takes place
ExposedPorts: []string{"6379/tcp"},
WaitingFor: wait.ForLog("Ready to accept connections"),
}
redisC, err := prepareRedisImage(ctx, req, t)
require.Error(t, err)
terminateContainerOnEnd(t, ctx, redisC)
}
func TestCreateContainerFromPrivateRegistry(t *testing.T) {
mappedPort := prepareLocalRegistryWithAuth(t)
// using the same credentials as in the Docker Registry
base64 := "dGVzdHVzZXI6dGVzdHBhc3N3b3Jk" // testuser:testpassword
t.Setenv("DOCKER_AUTH_CONFIG", `{
"auths": {
"localhost:`+mappedPort+`": { "username": "testuser", "password": "testpassword", "auth": "`+base64+`" }
},
"credsStore": "desktop"
}`)
ctx := context.Background()
req := ContainerRequest{
Image: "localhost:" + mappedPort + "/redis:5.0-alpine",
AlwaysPullImage: true, // make sure the authentication takes place
ExposedPorts: []string{"6379/tcp"},
WaitingFor: wait.ForLog("Ready to accept connections"),
}
redisContainer, err := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
require.NoError(t, err)
terminateContainerOnEnd(t, ctx, redisContainer)
}
func prepareLocalRegistryWithAuth(t *testing.T) string {
ctx := context.Background()
wd, err := os.Getwd()
require.NoError(t, err)
// copyDirectoryToContainer {
req := ContainerRequest{
Image: "registry:2",
ExposedPorts: []string{"5000/tcp"},
Env: map[string]string{
"REGISTRY_AUTH": "htpasswd",
"REGISTRY_AUTH_HTPASSWD_REALM": "Registry",
"REGISTRY_AUTH_HTPASSWD_PATH": "/auth/htpasswd",
"REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY": "/data",
},
Files: []ContainerFile{
{
HostFilePath: fmt.Sprintf("%s/testdata/auth", wd),
ContainerFilePath: "/auth",
},
{
HostFilePath: fmt.Sprintf("%s/testdata/data", wd),
ContainerFilePath: "/data",
},
},
WaitingFor: wait.ForExposedPort(),
}
// }
genContainerReq := GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: req,
Started: true,
}
registryC, err := GenericContainer(ctx, genContainerReq)
require.NoError(t, err)
mappedPort, err := registryC.MappedPort(ctx, "5000/tcp")
require.NoError(t, err)
mp := mappedPort.Port()
t.Cleanup(func() {
removeImageFromLocalCache(t, "localhost:"+mp+"/redis:5.0-alpine")
})
t.Cleanup(func() {
require.NoError(t, registryC.Terminate(context.Background()))
})
_, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
return mp
}
func prepareRedisImage(ctx context.Context, req ContainerRequest, t *testing.T) (Container, error) {
genContainerReq := GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: req,
Started: true,
}
redisC, err := GenericContainer(ctx, genContainerReq)
return redisC, err
}