-
Notifications
You must be signed in to change notification settings - Fork 279
/
registry.go
270 lines (222 loc) · 7.85 KB
/
registry.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
package testhelpers
import (
"context"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"testing"
"time"
dockertypes "github.com/docker/docker/api/types"
dockercontainer "github.com/docker/docker/api/types/container"
"github.com/docker/go-connections/nat"
"golang.org/x/crypto/bcrypt"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"github.com/buildpacks/pack/internal/archive"
)
var registryContainerNames = map[string]string{
"linux": "library/registry:2",
"windows": "micahyoung/registry:latest",
}
type TestRegistryConfig struct {
runRegistryName string
RunRegistryHost string
RunRegistryPort string
DockerConfigDir string
username string
password string
}
func RegistryHost(host, port string) string {
return fmt.Sprintf("%s:%s", host, port)
}
func CreateRegistryFixture(t *testing.T, tmpDir, fixturePath string) string {
// copy fixture to temp dir
registryFixtureCopy := filepath.Join(tmpDir, "registryCopy")
RecursiveCopyNow(t, fixturePath, registryFixtureCopy)
// git init that dir
repository, err := git.PlainInit(registryFixtureCopy, false)
AssertNil(t, err)
// git add . that dir
worktree, err := repository.Worktree()
AssertNil(t, err)
_, err = worktree.Add(".")
AssertNil(t, err)
// git commit that dir
commit, err := worktree.Commit("first", &git.CommitOptions{
Author: &object.Signature{
Name: "John Doe",
Email: "john@doe.org",
When: time.Now(),
},
})
AssertNil(t, err)
_, err = repository.CommitObject(commit)
AssertNil(t, err)
return registryFixtureCopy
}
func RunRegistry(t *testing.T) *TestRegistryConfig {
t.Log("run registry")
t.Helper()
runRegistryName := "test-registry-" + RandString(10)
username := RandString(10)
password := RandString(10)
runRegistryHost, runRegistryPort := startRegistry(t, runRegistryName, username, password)
dockerConfigDir := setupDockerConfigWithAuth(t, username, password, runRegistryHost, runRegistryPort)
registryConfig := &TestRegistryConfig{
runRegistryName: runRegistryName,
RunRegistryHost: runRegistryHost,
RunRegistryPort: runRegistryPort,
DockerConfigDir: dockerConfigDir,
username: username,
password: password,
}
waitForRegistryToBeAvailable(t, registryConfig)
return registryConfig
}
func waitForRegistryToBeAvailable(t *testing.T, registryConfig *TestRegistryConfig) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for {
_, err := registryConfig.RegistryCatalog()
if err == nil {
break
}
ctxErr := ctx.Err()
if ctxErr != nil {
t.Fatal("registry not ready:", ctxErr.Error(), ":", err.Error())
}
time.Sleep(500 * time.Microsecond)
}
}
func (rc *TestRegistryConfig) AuthConfig() dockertypes.AuthConfig {
return dockertypes.AuthConfig{
Username: rc.username,
Password: rc.password,
ServerAddress: RegistryHost(rc.RunRegistryHost, rc.RunRegistryPort),
}
}
func (rc *TestRegistryConfig) Login(t *testing.T, username string, password string) {
Eventually(t, func() bool {
_, err := dockerCli(t).RegistryLogin(context.Background(), dockertypes.AuthConfig{
Username: username,
Password: password,
ServerAddress: RegistryHost(rc.RunRegistryHost, rc.RunRegistryPort),
})
return err == nil
}, 100*time.Millisecond, 10*time.Second)
}
func startRegistry(t *testing.T, runRegistryName, username, password string) (string, string) {
ctx := context.Background()
daemonInfo, err := dockerCli(t).Info(ctx)
AssertNil(t, err)
registryContainerName := registryContainerNames[daemonInfo.OSType]
AssertNil(t, PullImageWithAuth(dockerCli(t), registryContainerName, ""))
htpasswdTar := generateHtpasswd(t, username, password)
defer htpasswdTar.Close()
ctr, err := dockerCli(t).ContainerCreate(ctx, &dockercontainer.Config{
Image: registryContainerName,
Labels: map[string]string{"author": "pack"},
Env: []string{
"REGISTRY_AUTH=htpasswd",
"REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm",
"REGISTRY_AUTH_HTPASSWD_PATH=/registry_test_htpasswd",
},
}, &dockercontainer.HostConfig{
AutoRemove: true,
PortBindings: nat.PortMap{
"5000/tcp": []nat.PortBinding{{}},
},
}, nil, runRegistryName)
AssertNil(t, err)
err = dockerCli(t).CopyToContainer(ctx, ctr.ID, "/", htpasswdTar, dockertypes.CopyToContainerOptions{})
AssertNil(t, err)
err = dockerCli(t).ContainerStart(ctx, ctr.ID, dockertypes.ContainerStartOptions{})
AssertNil(t, err)
inspect, err := dockerCli(t).ContainerInspect(context.TODO(), ctr.ID)
AssertNil(t, err)
runRegistryPort := inspect.NetworkSettings.Ports["5000/tcp"][0].HostPort
runRegistryHost := DockerHostname(t)
return runRegistryHost, runRegistryPort
}
func DockerHostname(t *testing.T) string {
dockerCli := dockerCli(t)
daemonHost := dockerCli.DaemonHost()
u, err := url.Parse(daemonHost)
if err != nil {
t.Fatalf("unable to parse URI client.DaemonHost: %s", err)
}
switch u.Scheme {
// DOCKER_HOST is usually remote so always use its hostname/IP
// Note: requires "insecure-registries" CIDR entry on Daemon config
case "tcp":
return u.Hostname()
// if DOCKER_HOST is non-tcp, we assume that we are
// talking to the daemon over a local pipe.
default:
daemonInfo, err := dockerCli.Info(context.TODO())
if err != nil {
t.Fatalf("unable to fetch client.DockerInfo: %s", err)
}
if daemonInfo.OSType == "windows" {
// try to lookup the host IP by helper domain name (https://docs.docker.com/docker-for-windows/networking/#use-cases-and-workarounds)
// Note: pack appears to not support /etc/hosts-based insecure-registries
addrs, err := net.LookupHost("host.docker.internal")
if err != nil {
t.Fatalf("unknown address response: %+v %s", addrs, err)
}
if len(addrs) != 1 {
t.Fatalf("ambiguous address response: %v", addrs)
}
return addrs[0]
}
// Linux can use --network=host so always use "localhost"
return "localhost"
}
}
func generateHtpasswd(t *testing.T, username string, password string) io.ReadCloser {
// https://docs.docker.com/registry/deploying/#restricting-access
// HTPASSWD format: https://github.com/foomo/htpasswd/blob/e3a90e78da9cff06a83a78861847aa9092cbebdd/hashing.go#L23
passwordBytes, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
reader := archive.CreateSingleFileTarReader("/registry_test_htpasswd", username+":"+string(passwordBytes))
return reader
}
func setupDockerConfigWithAuth(t *testing.T, username string, password string, runRegistryHost string, runRegistryPort string) string {
dockerConfigDir, err := ioutil.TempDir("", "pack.test.docker.config.dir")
AssertNil(t, err)
AssertNil(t, ioutil.WriteFile(filepath.Join(dockerConfigDir, "config.json"), []byte(fmt.Sprintf(`{
"auths": {
"%s": {
"auth": "%s"
}
}
}
`, RegistryHost(runRegistryHost, runRegistryPort), encodedUserPass(username, password))), 0666))
return dockerConfigDir
}
func encodedUserPass(username string, password string) string {
return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password)))
}
func (rc *TestRegistryConfig) StopRegistry(t *testing.T) {
t.Log("stop registry")
t.Helper()
err := dockerCli(t).ContainerKill(context.Background(), rc.runRegistryName, "SIGKILL")
AssertNil(t, err)
err = os.RemoveAll(rc.DockerConfigDir)
AssertNil(t, err)
}
func (rc *TestRegistryConfig) RepoName(name string) string {
return RegistryHost(rc.RunRegistryHost, rc.RunRegistryPort) + "/" + name
}
func (rc *TestRegistryConfig) RegistryAuth() string {
return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`{"username":"%s","password":"%s"}`, rc.username, rc.password)))
}
func (rc *TestRegistryConfig) RegistryCatalog() (string, error) {
return HTTPGetE(fmt.Sprintf("http://%s/v2/_catalog", RegistryHost(rc.RunRegistryHost, rc.RunRegistryPort)), map[string]string{
"Authorization": "Basic " + encodedUserPass(rc.username, rc.password),
})
}