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
|
package container
import (
"archive/tar"
"bytes"
"context"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
cerrdefs "github.com/containerd/errdefs"
"github.com/docker/docker/api/types/build"
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/integration/internal/container"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/testutil/fakecontext"
"github.com/moby/go-archive"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/skip"
)
func TestCopyFromContainerPathDoesNotExist(t *testing.T) {
ctx := setupTest(t)
apiClient := testEnv.APIClient()
cid := container.Create(ctx, t, apiClient)
_, _, err := apiClient.CopyFromContainer(ctx, cid, "/dne")
assert.Check(t, is.ErrorType(err, cerrdefs.IsNotFound))
assert.Check(t, is.ErrorContains(err, "Could not find the file /dne in container "+cid))
}
// TestCopyFromContainerPathIsNotDir tests that an error is returned when
// trying to create a directory on a path that's a file.
func TestCopyFromContainerPathIsNotDir(t *testing.T) {
skip.If(t, testEnv.UsingSnapshotter(), "FIXME: https://github.com/moby/moby/issues/47107")
ctx := setupTest(t)
apiClient := testEnv.APIClient()
cid := container.Create(ctx, t, apiClient)
// Pick a path that already exists as a file; on Linux "/etc/passwd"
// is expected to be there, so we pick that for convenience.
existingFile := "/etc/passwd/"
expected := []string{"not a directory"}
if testEnv.DaemonInfo.OSType == "windows" {
existingFile = "c:/windows/system32/drivers/etc/hosts/"
// Depending on the version of Windows, this produces a "ERROR_INVALID_NAME" (Windows < 2025),
// or a "ERROR_DIRECTORY" (Windows 2025); https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
expected = []string{
"The directory name is invalid.", // ERROR_DIRECTORY
"The filename, directory name, or volume label syntax is incorrect.", // ERROR_INVALID_NAME
}
}
_, _, err := apiClient.CopyFromContainer(ctx, cid, existingFile)
var found bool
for _, expErr := range expected {
if err != nil && strings.Contains(err.Error(), expErr) {
found = true
break
}
}
assert.Check(t, found, "Expected error to be one of %v, but got %v", expected, err)
}
func TestCopyToContainerPathDoesNotExist(t *testing.T) {
ctx := setupTest(t)
apiClient := testEnv.APIClient()
cid := container.Create(ctx, t, apiClient)
err := apiClient.CopyToContainer(ctx, cid, "/dne", nil, containertypes.CopyToContainerOptions{})
assert.Check(t, is.ErrorType(err, cerrdefs.IsNotFound))
assert.Check(t, is.ErrorContains(err, "Could not find the file /dne in container "+cid))
}
func TestCopyEmptyFile(t *testing.T) {
ctx := setupTest(t)
apiClient := testEnv.APIClient()
cid := container.Create(ctx, t, apiClient)
// empty content
dstDir, _ := makeEmptyArchive(t)
err := apiClient.CopyToContainer(ctx, cid, dstDir, bytes.NewReader([]byte("")), containertypes.CopyToContainerOptions{})
assert.NilError(t, err)
// tar with empty file
dstDir, preparedArchive := makeEmptyArchive(t)
err = apiClient.CopyToContainer(ctx, cid, dstDir, preparedArchive, containertypes.CopyToContainerOptions{})
assert.NilError(t, err)
// tar with empty file archive mode
dstDir, preparedArchive = makeEmptyArchive(t)
err = apiClient.CopyToContainer(ctx, cid, dstDir, preparedArchive, containertypes.CopyToContainerOptions{
CopyUIDGID: true,
})
assert.NilError(t, err)
// copy from empty file
rdr, _, err := apiClient.CopyFromContainer(ctx, cid, dstDir)
assert.NilError(t, err)
defer rdr.Close()
}
func TestCopyToContainerCopyUIDGID(t *testing.T) {
skip.If(t, testEnv.DaemonInfo.OSType == "windows")
ctx := setupTest(t)
apiClient := testEnv.APIClient()
imageID := makeTestImage(ctx, t)
tests := []struct {
doc string
user string
expected string
}{
{
doc: "image default",
expected: "2375:2376",
},
{
// Align with behavior of docker run, which treats a UID with
// empty groupname as default (0 (root)).
//
// docker run --rm --user "7777:" alpine id
// uid=7777 gid=0(root) groups=0(root)
doc: "trailing colon",
user: "7777:",
expected: "7777:0",
},
{
// Align with behavior of docker run, which treats a GID with
// empty username as default (0 (root)).
//
// docker run --rm --user ":7777" alpine id
// uid=0(root) gid=7777 groups=7777
doc: "leading colon",
user: ":7777",
expected: "0:7777",
},
{
doc: "known UID",
user: "2375",
expected: "2375:2376",
},
{
doc: "unknown UID",
user: "7777",
expected: "7777:0",
},
{
doc: "UID and GID",
user: "2375:2376",
expected: "2375:2376",
},
{
doc: "username and groupname",
user: "testuser:testgroup",
expected: "2375:2376",
},
{
doc: "username",
user: "testuser",
expected: "2375:2376",
},
{
doc: "username and GID",
user: "testuser:7777",
expected: "2375:7777",
},
{
doc: "UID and groupname",
user: "7777:testgroup",
expected: "7777:2376",
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
cID := container.Run(ctx, t, apiClient, container.WithImage(imageID), container.WithUser(tc.user))
defer container.Remove(ctx, t, apiClient, cID, containertypes.RemoveOptions{Force: true})
// tar with empty file
dstDir, preparedArchive := makeEmptyArchive(t)
err := apiClient.CopyToContainer(ctx, cID, dstDir, preparedArchive, containertypes.CopyToContainerOptions{
CopyUIDGID: true,
})
assert.NilError(t, err)
res, err := container.Exec(ctx, apiClient, cID, []string{"stat", "-c", "%u:%g", "/empty-file.txt"})
assert.NilError(t, err)
assert.Equal(t, res.ExitCode, 0)
assert.Equal(t, strings.TrimSpace(res.Stdout()), tc.expected)
})
}
}
func makeTestImage(ctx context.Context, t *testing.T) (imageID string) {
t.Helper()
apiClient := testEnv.APIClient()
tmpDir := t.TempDir()
buildCtx := fakecontext.New(t, tmpDir, fakecontext.WithDockerfile(`
FROM busybox
RUN addgroup -g 2376 testgroup && adduser -D -u 2375 -G testgroup testuser
USER testuser:testgroup
`))
defer buildCtx.Close()
resp, err := apiClient.ImageBuild(ctx, buildCtx.AsTarReader(t), build.ImageBuildOptions{})
assert.NilError(t, err)
defer resp.Body.Close()
err = jsonmessage.DisplayJSONMessagesStream(resp.Body, io.Discard, 0, false, func(msg jsonmessage.JSONMessage) {
var r build.Result
assert.NilError(t, json.Unmarshal(*msg.Aux, &r))
imageID = r.ID
})
assert.NilError(t, err)
assert.Assert(t, imageID != "")
return imageID
}
func makeEmptyArchive(t *testing.T) (string, io.ReadCloser) {
tmpDir := t.TempDir()
srcPath := filepath.Join(tmpDir, "empty-file.txt")
err := os.WriteFile(srcPath, []byte(""), 0o400)
assert.NilError(t, err)
// TODO(thaJeztah) Add utilities to the client to make steps below less complicated.
// Code below is taken from copyToContainer() in docker/cli.
srcInfo, err := archive.CopyInfoSourcePath(srcPath, false)
assert.NilError(t, err)
srcArchive, err := archive.TarResource(srcInfo)
assert.NilError(t, err)
t.Cleanup(func() {
srcArchive.Close()
})
ctrPath := "/empty-file.txt"
dstInfo := archive.CopyInfo{Path: ctrPath}
dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
assert.NilError(t, err)
t.Cleanup(func() {
preparedArchive.Close()
})
return dstDir, preparedArchive
}
func TestCopyToContainerPathIsNotDir(t *testing.T) {
ctx := setupTest(t)
apiClient := testEnv.APIClient()
cid := container.Create(ctx, t, apiClient)
path := "/etc/passwd/"
if testEnv.DaemonInfo.OSType == "windows" {
path = "c:/windows/system32/drivers/etc/hosts/"
}
err := apiClient.CopyToContainer(ctx, cid, path, nil, containertypes.CopyToContainerOptions{})
assert.Check(t, is.ErrorContains(err, "not a directory"))
}
func TestCopyFromContainer(t *testing.T) {
skip.If(t, testEnv.DaemonInfo.OSType == "windows")
ctx := setupTest(t)
apiClient := testEnv.APIClient()
dir, err := os.MkdirTemp("", t.Name())
assert.NilError(t, err)
defer os.RemoveAll(dir)
buildCtx := fakecontext.New(t, dir, fakecontext.WithFile("foo", "hello"), fakecontext.WithFile("baz", "world"), fakecontext.WithDockerfile(`
FROM busybox
COPY foo /foo
COPY baz /bar/quux/baz
RUN ln -s notexist /bar/notarget && ln -s quux/baz /bar/filesymlink && ln -s quux /bar/dirsymlink && ln -s / /bar/root
CMD /fake
`))
defer buildCtx.Close()
resp, err := apiClient.ImageBuild(ctx, buildCtx.AsTarReader(t), build.ImageBuildOptions{})
assert.NilError(t, err)
defer resp.Body.Close()
var imageID string
err = jsonmessage.DisplayJSONMessagesStream(resp.Body, io.Discard, 0, false, func(msg jsonmessage.JSONMessage) {
var r build.Result
assert.NilError(t, json.Unmarshal(*msg.Aux, &r))
imageID = r.ID
})
assert.NilError(t, err)
assert.Assert(t, imageID != "")
cid := container.Create(ctx, t, apiClient, container.WithImage(imageID))
for _, x := range []struct {
src string
expect map[string]string
}{
{"/", map[string]string{"/": "", "/foo": "hello", "/bar/quux/baz": "world", "/bar/filesymlink": "", "/bar/dirsymlink": "", "/bar/notarget": ""}},
{".", map[string]string{"./": "", "./foo": "hello", "./bar/quux/baz": "world", "./bar/filesymlink": "", "./bar/dirsymlink": "", "./bar/notarget": ""}},
{"/.", map[string]string{"./": "", "./foo": "hello", "./bar/quux/baz": "world", "./bar/filesymlink": "", "./bar/dirsymlink": "", "./bar/notarget": ""}},
{"./", map[string]string{"./": "", "./foo": "hello", "./bar/quux/baz": "world", "./bar/filesymlink": "", "./bar/dirsymlink": "", "./bar/notarget": ""}},
{"/./", map[string]string{"./": "", "./foo": "hello", "./bar/quux/baz": "world", "./bar/filesymlink": "", "./bar/dirsymlink": "", "./bar/notarget": ""}},
{"/bar/root", map[string]string{"root": ""}},
{"/bar/root/", map[string]string{"root/": "", "root/foo": "hello", "root/bar/quux/baz": "world", "root/bar/filesymlink": "", "root/bar/dirsymlink": "", "root/bar/notarget": ""}},
{"/bar/root/.", map[string]string{"./": "", "./foo": "hello", "./bar/quux/baz": "world", "./bar/filesymlink": "", "./bar/dirsymlink": "", "./bar/notarget": ""}},
{"bar/quux", map[string]string{"quux/": "", "quux/baz": "world"}},
{"bar/quux/", map[string]string{"quux/": "", "quux/baz": "world"}},
{"bar/quux/.", map[string]string{"./": "", "./baz": "world"}},
{"bar/quux/baz", map[string]string{"baz": "world"}},
{"bar/filesymlink", map[string]string{"filesymlink": ""}},
{"bar/dirsymlink", map[string]string{"dirsymlink": ""}},
{"bar/dirsymlink/", map[string]string{"dirsymlink/": "", "dirsymlink/baz": "world"}},
{"bar/dirsymlink/.", map[string]string{"./": "", "./baz": "world"}},
{"bar/notarget", map[string]string{"notarget": ""}},
} {
t.Run(x.src, func(t *testing.T) {
rdr, _, err := apiClient.CopyFromContainer(ctx, cid, x.src)
assert.NilError(t, err)
defer rdr.Close()
found := make(map[string]bool, len(x.expect))
var numFound int
tr := tar.NewReader(rdr)
for numFound < len(x.expect) {
h, err := tr.Next()
if errors.Is(err, io.EOF) {
break
}
assert.NilError(t, err)
expected, exists := x.expect[h.Name]
if !exists {
// this archive will have extra stuff in it since we are copying from root
// and docker adds a bunch of stuff
continue
}
numFound++
found[h.Name] = true
buf, err := io.ReadAll(tr)
if err == nil {
assert.Check(t, is.Equal(string(buf), expected))
}
}
for f := range x.expect {
assert.Check(t, found[f], f+" not found in archive")
}
})
}
}
|