banger/internal/daemon/images_pull_test.go
Thales Maciel 43982a4ae3
Phase B-1: ownership fixup via debugfs pass
imagepull.Flatten now captures per-file uid/gid/mode/type from the
tar headers as it walks layers, returning a Metadata map alongside
the extracted tree. Whiteouts correctly drop the victim's metadata.
The returned Metadata feeds the new imagepull.ApplyOwnership, which
pipes a batched `set_inode_field` script to `debugfs -w -f -`.

Why: mkfs.ext4 -d copies the runner's on-disk uids verbatim, so
without this pass setuid binaries become setuid-nonroot and sshd
refuses to start on the resulting image. With the pass, a pulled
debian:bookworm has /usr/bin/sudo with uid=0 + setuid bit surviving
intact.

imagepull.BuildExt4 signature unchanged; ownership is applied as a
separate step by the daemon orchestrator between BuildExt4 and
StageBootArtifacts, keeping each helper focused. The seam
(d.pullAndFlatten) now returns (Metadata, error) for test stubs to
feed synthetic metadata.

StdinRunner is a new duck-typed extension next to CommandRunner;
the real system.Runner implements RunStdin, test mocks don't need
to unless they exercise stdin. Prevents every existing mock from
growing a new method.

Tests:
 - TestFlattenCapturesHeaderMetadata: setuid bit + mode survive the
   tar-header walk
 - TestApplyOwnershipRewritesUidGidMode: real debugfs round-trip —
   create ext4 with runner's uid, apply synthetic metadata setting
   uid=0 + setuid mode, verify via `debugfs -R stat` that the
   inode now has uid=0 and mode 04755
 - TestBuildOwnershipScriptDeterministic: sorted, well-formed
   sif script output

Debugfs and mkfs.ext4 tests skip if the binaries aren't on PATH.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-16 18:04:22 -03:00

197 lines
6 KiB
Go

package daemon
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"banger/internal/api"
"banger/internal/imagepull"
"banger/internal/model"
"banger/internal/paths"
"banger/internal/system"
"github.com/google/go-containerregistry/pkg/name"
)
func writeFakeKernelTriple(t *testing.T) (kernelPath, initrdPath, modulesDir string) {
t.Helper()
dir := t.TempDir()
kernelPath = filepath.Join(dir, "vmlinux")
if err := os.WriteFile(kernelPath, []byte("kernel"), 0o644); err != nil {
t.Fatal(err)
}
initrdPath = filepath.Join(dir, "initrd.img")
if err := os.WriteFile(initrdPath, []byte("initrd"), 0o644); err != nil {
t.Fatal(err)
}
modulesDir = filepath.Join(dir, "modules")
if err := os.MkdirAll(modulesDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(modulesDir, "modules.dep"), []byte(""), 0o644); err != nil {
t.Fatal(err)
}
return
}
// stubPullAndFlatten writes a fixed file tree into destDir, simulating a
// successful OCI pull without the network or tarball machinery.
func stubPullAndFlatten(_ context.Context, _ string, _ string, destDir string) (imagepull.Metadata, error) {
if err := os.MkdirAll(filepath.Join(destDir, "etc"), 0o755); err != nil {
return imagepull.Metadata{}, err
}
if err := os.WriteFile(filepath.Join(destDir, "etc", "hello"), []byte("world"), 0o644); err != nil {
return imagepull.Metadata{}, err
}
if err := os.WriteFile(filepath.Join(destDir, "marker"), []byte("ok"), 0o644); err != nil {
return imagepull.Metadata{}, err
}
// Tiny synthetic metadata — daemon-level tests exercise the seam
// plumbing, not the ownership pass itself.
return imagepull.Metadata{Entries: map[string]imagepull.FileMeta{}}, nil
}
func TestPullImageHappyPath(t *testing.T) {
if _, err := exec.LookPath("mkfs.ext4"); err != nil {
t.Skip("mkfs.ext4 not available; skipping")
}
imagesDir := t.TempDir()
cacheDir := t.TempDir()
kernel, initrd, modules := writeFakeKernelTriple(t)
d := &Daemon{
layout: paths.Layout{ImagesDir: imagesDir, OCICacheDir: cacheDir},
store: openDaemonStore(t),
runner: system.NewRunner(),
pullAndFlatten: stubPullAndFlatten,
}
image, err := d.PullImage(context.Background(), api.ImagePullParams{
Ref: "docker.io/library/debian:bookworm",
KernelPath: kernel,
InitrdPath: initrd,
ModulesDir: modules,
})
if err != nil {
t.Fatalf("PullImage: %v", err)
}
if image.Name != "debian-bookworm" {
t.Errorf("Name = %q, want debian-bookworm", image.Name)
}
if !image.Managed {
t.Errorf("expected Managed=true")
}
if image.ArtifactDir == "" || !strings.HasPrefix(image.ArtifactDir, imagesDir) {
t.Errorf("ArtifactDir = %q, want under %q", image.ArtifactDir, imagesDir)
}
for _, rel := range []string{"rootfs.ext4", "kernel", "initrd.img", "modules"} {
if _, err := os.Stat(filepath.Join(image.ArtifactDir, rel)); err != nil {
t.Errorf("missing artifact %s: %v", rel, err)
}
}
// Staging dir should be gone after publish.
stagings, _ := filepath.Glob(filepath.Join(imagesDir, "*.staging"))
if len(stagings) != 0 {
t.Errorf("staging dirs left behind: %v", stagings)
}
}
func TestPullImageRejectsExistingName(t *testing.T) {
imagesDir := t.TempDir()
kernel, _, _ := writeFakeKernelTriple(t)
d := &Daemon{
layout: paths.Layout{ImagesDir: imagesDir, OCICacheDir: t.TempDir()},
store: openDaemonStore(t),
runner: system.NewRunner(),
pullAndFlatten: stubPullAndFlatten,
}
// Seed a preexisting image with the would-be derived name.
id, _ := model.NewID()
if err := d.store.UpsertImage(context.Background(), model.Image{
ID: id,
Name: "debian-bookworm",
CreatedAt: model.Now(),
UpdatedAt: model.Now(),
}); err != nil {
t.Fatal(err)
}
_, err := d.PullImage(context.Background(), api.ImagePullParams{
Ref: "docker.io/library/debian:bookworm",
KernelPath: kernel,
})
if err == nil || !strings.Contains(err.Error(), "already exists") {
t.Fatalf("expected already-exists error, got %v", err)
}
}
func TestPullImageRequiresKernel(t *testing.T) {
d := &Daemon{
layout: paths.Layout{ImagesDir: t.TempDir(), OCICacheDir: t.TempDir()},
store: openDaemonStore(t),
runner: system.NewRunner(),
pullAndFlatten: stubPullAndFlatten,
}
_, err := d.PullImage(context.Background(), api.ImagePullParams{
Ref: "docker.io/library/debian:bookworm",
})
if err == nil || !strings.Contains(err.Error(), "kernel") {
t.Fatalf("expected kernel-required error, got %v", err)
}
}
func TestPullImageCleansStagingOnFailure(t *testing.T) {
imagesDir := t.TempDir()
kernel, _, _ := writeFakeKernelTriple(t)
failureSeam := func(_ context.Context, _ string, _ string, _ string) (imagepull.Metadata, error) {
return imagepull.Metadata{}, errors.New("network borked")
}
d := &Daemon{
layout: paths.Layout{ImagesDir: imagesDir, OCICacheDir: t.TempDir()},
store: openDaemonStore(t),
runner: system.NewRunner(),
pullAndFlatten: failureSeam,
}
_, err := d.PullImage(context.Background(), api.ImagePullParams{
Ref: "docker.io/library/debian:bookworm",
KernelPath: kernel,
})
if err == nil || !strings.Contains(err.Error(), "network borked") {
t.Fatalf("expected propagated pull error, got %v", err)
}
stagings, _ := filepath.Glob(filepath.Join(imagesDir, "*.staging"))
if len(stagings) != 0 {
t.Errorf("staging dir left behind on failure: %v", stagings)
}
}
func TestDefaultImageNameFromRef(t *testing.T) {
cases := []struct {
in string
want string
}{
{"docker.io/library/debian:bookworm", "debian-bookworm"},
{"alpine:3.20", "alpine-3-20"},
{"docker.io/library/debian", "debian"},
{"ghcr.io/some/org/my-image:v2.1", "my-image-v2-1"},
}
for _, tc := range cases {
ref, err := name.ParseReference(tc.in)
if err != nil {
t.Fatalf("parse %s: %v", tc.in, err)
}
if got := defaultImageNameFromRef(ref); got != tc.want {
t.Errorf("defaultImageNameFromRef(%s) = %q, want %q", tc.in, got, tc.want)
}
}
}