-
Notifications
You must be signed in to change notification settings - Fork 41
/
docker_registry.go
315 lines (271 loc) · 9.79 KB
/
docker_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
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
package testhelpers
import (
"context"
"encoding/base64"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"testing"
"github.com/google/go-containerregistry/pkg/registry"
)
type DockerRegistry struct {
Host string
Port string
Name string
server *httptest.Server
DockerDirectory string
username string
password string
regHandler http.Handler
authnHandler http.Handler
imagePrivileges map[string]ImagePrivileges // map from an imageName to its permissions
}
type RegistryOption func(registry *DockerRegistry)
// WithSharedHandler allows two instances to share the same data by re-using the registry handler.
// Use an authenticated registry to write to a read-only unauthenticated registry.
func WithSharedHandler(handler http.Handler) RegistryOption {
return func(registry *DockerRegistry) {
registry.regHandler = handler
}
}
// WithImagePrivileges enables the execution of read/write access validations based on the image name
func WithImagePrivileges() RegistryOption {
var permissions = make(map[string]ImagePrivileges)
return func(registry *DockerRegistry) {
registry.imagePrivileges = permissions
}
}
// WithAuth adds credentials to registry. Omitting will make the registry read-only
func WithAuth(dockerConfigDir string) RegistryOption {
return func(r *DockerRegistry) {
r.username = RandString(10)
r.password = RandString(10)
r.DockerDirectory = dockerConfigDir
}
}
func NewDockerRegistry(ops ...RegistryOption) *DockerRegistry {
dockerRegistry := &DockerRegistry{
Name: "test-registry-" + RandString(10),
}
for _, op := range ops {
op(dockerRegistry)
}
return dockerRegistry
}
// BasicAuth wraps a handler, allowing requests with matching username and password headers, otherwise rejecting with a 401
func BasicAuth(handler http.Handler, username, password, realm string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || user != username || pass != password {
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
w.WriteHeader(401)
_, _ = w.Write([]byte("Unauthorized.\n"))
return
}
handler.ServeHTTP(w, r)
})
}
// ReadOnly wraps a handler, allowing only GET and HEAD requests, otherwise rejecting with a 405
func ReadOnly(handler http.Handler) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if !isReadRequest(request) {
response.WriteHeader(405)
_, _ = response.Write([]byte("Method Not Allowed.\n"))
return
}
handler.ServeHTTP(response, request)
})
}
func delegator(basicAuthHandler http.Handler, regHandler http.Handler, permissions map[string]ImagePrivileges) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
var (
image ImagePrivileges
ok bool
)
if image, ok = permissions[extractImageName(request.URL.Path)]; !ok {
basicAuthHandler.ServeHTTP(response, request)
return
}
if isReadRequest(request) {
if !image.readable {
response.WriteHeader(401)
_, _ = response.Write([]byte("Unauthorized.\n"))
return
}
} else { // assume write request
if !image.writable {
response.WriteHeader(401)
_, _ = response.Write([]byte("Unauthorized.\n"))
return
}
}
regHandler.ServeHTTP(response, request)
})
}
// Start creates a docker registry following these rules:
// - Shared handler will be used, otherwise a new one will be created
// - By default the shared handler will be wrapped with a read only handler
// - In case credentials are configured, the shared handler will be wrapped with a basic authentication handler and
// if any image privileges were set, then the custom handler will be used to wrap the auth handler.
func (r *DockerRegistry) Start(t *testing.T) {
t.Helper()
r.Host = DockerHostname(t)
// create registry handler, if not re-using a shared one
if r.regHandler == nil {
// change to os.Stderr for verbose output
logger := registry.Logger(log.New(io.Discard, "registry ", log.Lshortfile))
r.regHandler = registry.New(logger)
}
// wrap registry handler with authentication handler, defaulting to read-only
r.authnHandler = ReadOnly(r.regHandler)
if r.username != "" {
if r.imagePrivileges != nil {
// wrap registry handler with basic auth
basicAuthHandler := BasicAuth(r.regHandler, r.username, r.password, "registry")
r.authnHandler = delegator(basicAuthHandler, r.regHandler, r.imagePrivileges)
} else {
// wrap registry handler basic auth
r.authnHandler = BasicAuth(r.regHandler, r.username, r.password, "registry")
}
}
// listen on specific interface with random port, relying on authorization to prevent untrusted writes
listenIP := "127.0.0.1"
if r.Host != "localhost" {
listenIP = r.Host
}
listener, err := net.Listen("tcp", net.JoinHostPort(listenIP, "0"))
AssertNil(t, err)
r.server = &httptest.Server{
Listener: listener,
Config: &http.Server{Handler: r.authnHandler}, //nolint
}
r.server.Start()
tcpAddr := r.server.Listener.Addr().(*net.TCPAddr)
r.Port = strconv.Itoa(tcpAddr.Port)
t.Logf("run registry on %s:%s", r.Host, r.Port)
if r.username != "" {
// Write Docker config and configure auth headers
writeDockerConfig(t, r.DockerDirectory, r.Host, r.Port, r.EncodedAuth())
}
}
func (r *DockerRegistry) Stop(t *testing.T) {
t.Helper()
t.Log("stop registry")
r.server.Close()
}
func (r *DockerRegistry) RepoName(name string) string {
return r.Host + ":" + r.Port + "/" + name
}
func (r *DockerRegistry) EncodedLabeledAuth() string {
return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`{"username":"%s","password":"%s"}`, r.username, r.password)))
}
// setImagePrivileges sets the given image name with the provided ImagePrivileges if WithImagePrivileges was called during registry creation.
// For example SetPrivilegesToImage("my-image", NewImagePrivileges(Readable, Writable)) will save "my-image" as a
// readable and writable image into the registry.
func (r *DockerRegistry) setImagePrivileges(imageName string, privilege ImagePrivileges) {
if r.imagePrivilegesEnabled() {
r.imagePrivileges[imageName] = privilege
}
}
// SetReadOnly set the given image name to be readable when the ImagePrivileges feature was enabled
// Returns RepoName(imageName)
func (r *DockerRegistry) SetReadOnly(imageName string) string {
r.setImagePrivileges(imageName, NewImagePrivileges(Readable))
return r.RepoName(imageName)
}
// SetWriteOnly set the given image name to be writable when the ImagePrivileges feature was enabled
// Returns RepoName(imageName)
func (r *DockerRegistry) SetWriteOnly(imageName string) string {
r.setImagePrivileges(imageName, NewImagePrivileges(Writable))
return r.RepoName(imageName)
}
// SetReadWrite set the given image name to be readable and writable when the ImagePrivileges feature was enabled
// Returns RepoName(imageName)
func (r *DockerRegistry) SetReadWrite(imageName string) string {
r.setImagePrivileges(imageName, NewImagePrivileges(Readable, Writable))
return r.RepoName(imageName)
}
// SetInaccessible set the given image name to do not have any access when the ImagePrivileges feature was enabled
// Returns RepoName(imageName)
func (r *DockerRegistry) SetInaccessible(imageName string) string {
r.setImagePrivileges(imageName, NewImagePrivileges())
return r.RepoName(imageName)
}
func (r *DockerRegistry) imagePrivilegesEnabled() bool {
return r.imagePrivileges != nil
}
func isReadRequest(req *http.Request) bool {
return req.Method == "GET" || req.Method == "HEAD"
}
// DockerHostname discovers the appropriate registry hostname.
// For test to run where "localhost" is not the daemon host, a `insecure-registries` entry of `<host net>/<mask>` with a range that contains the host's non-loopback IP.
// For Docker Desktop, this can be set here: https://docs.docker.com/docker-for-mac/#docker-engine
// Otherwise, its set in the daemon.json: https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file
// If the entry is not found, the fallback is "localhost"
func DockerHostname(t *testing.T) string {
dockerCli := DockerCli(t)
// query daemon for insecure-registry network ranges
var insecureRegistryNets []*net.IPNet
daemonInfo, err := dockerCli.Info(context.TODO())
if err != nil {
t.Fatalf("unable to fetch client.DockerInfo: %s", err)
}
for _, ipnet := range daemonInfo.RegistryConfig.InsecureRegistryCIDRs {
insecureRegistryNets = append(insecureRegistryNets, (*net.IPNet)(ipnet))
}
// search for non-loopback interface IPs contained by a insecure-registry range
ifaces, err := net.Interfaces()
if err != nil {
t.Fatalf("unable to fetch interfaces: %s", err)
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
t.Fatalf("unable to fetch interface address: %s", err)
}
for _, addr := range addrs {
var interfaceIP net.IP
switch interfaceAddr := addr.(type) {
case *net.IPAddr:
interfaceIP = interfaceAddr.IP
case *net.IPNet:
interfaceIP = interfaceAddr.IP
}
// ignore blanks and loopbacks
if interfaceIP == nil || interfaceIP.IsLoopback() {
continue
}
// return first matching interface IP
for _, regNet := range insecureRegistryNets {
if regNet.Contains(interfaceIP) {
return interfaceIP.String()
}
}
}
}
// Fallback to localhost, only works for Linux using --network=host
return "localhost"
}
func (r *DockerRegistry) EncodedAuth() string {
return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", r.username, r.password)))
}
func writeDockerConfig(t *testing.T, configDir, host, port, auth string) {
AssertNil(t, os.WriteFile(
filepath.Join(configDir, "config.json"),
[]byte(fmt.Sprintf(`{
"auths": {
"%s:%s": {
"auth": "%s"
}
}
}
`, host, port, auth)),
0600,
))
}