diff --git a/internal/container/kit.go b/internal/container/kit.go new file mode 100644 index 000000000..53499d6bc --- /dev/null +++ b/internal/container/kit.go @@ -0,0 +1,179 @@ +package container + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "path" + "strings" + + "github.com/moby/moby/api/pkg/stdcopy" + "github.com/moby/moby/api/types/container" + "github.com/moby/moby/api/types/mount" + "github.com/moby/moby/client" + + "github.com/samcharles93/archie-core/internal/infrastructure/kit" +) + +const hookOutputTail = 2000 + +// KitSpec is one Kit task container: the workload image running archie's +// worker as root, on the task's sandbox network, with the Kit's launch. +type KitSpec struct { + Name string + Image string + Network string + // Worker is the entrypoint that runs archie-agent as the container's + // root process, and WorkerEnv its environment, credentials included. + Worker []string + WorkerEnv []string + Binds []string + Labels map[string]string + Launch kit.Launch +} + +// StartKit creates and starts a Kit container, then brings it to the state +// a harness may run in: install hooks run as their users, the Kit's files +// written as the harness user, and startup hooks run. A failing install or +// foreground startup hook removes the container and returns the hook's +// output. +func StartKit(ctx context.Context, cli *client.Client, s KitSpec) (string, error) { + var mounts []mount.Mount + for _, v := range s.Launch.Volumes { + if _, err := cli.VolumeCreate(ctx, client.VolumeCreateOptions{Name: v.Name, Labels: s.Labels}); err != nil { + return "", fmt.Errorf("create kit volume %s: %w", v.Name, err) + } + mounts = append(mounts, mount.Mount{Type: mount.TypeVolume, Source: v.Name, Target: v.Path}) + } + created, err := cli.ContainerCreate(ctx, client.ContainerCreateOptions{ + Name: s.Name, + Config: &container.Config{ + Image: s.Image, + Entrypoint: s.Worker, + Cmd: []string{}, + User: "0", + Env: s.WorkerEnv, + WorkingDir: kit.WorkspaceDir, + Labels: s.Labels, + }, + HostConfig: &container.HostConfig{ + NetworkMode: container.NetworkMode(s.Network), + Binds: s.Binds, + Mounts: mounts, + }, + }) + if err != nil { + return "", fmt.Errorf("create kit container: %w", err) + } + fail := func(err error) (string, error) { + _, rmErr := cli.ContainerRemove(context.WithoutCancel(ctx), created.ID, client.ContainerRemoveOptions{Force: true}) + return "", errors.Join(err, rmErr) + } + if _, err := cli.ContainerStart(ctx, created.ID, client.ContainerStartOptions{}); err != nil { + return fail(fmt.Errorf("start kit container: %w", err)) + } + for i, h := range s.Launch.Install { + if err := runHook(ctx, cli, created.ID, h); err != nil { + return fail(fmt.Errorf("install hook %d: %w", i+1, err)) + } + } + for _, f := range s.Launch.Files { + if err := writeKitFile(ctx, cli, created.ID, s.Launch.Harness.User, f.Path, f.Content, f.Mode, f.Overwrite); err != nil { + return fail(fmt.Errorf("write kit file %s: %w", f.Path, err)) + } + } + for i, h := range s.Launch.Startup { + if err := runHook(ctx, cli, created.ID, h); err != nil { + return fail(fmt.Errorf("startup hook %d: %w", i+1, err)) + } + } + return created.ID, nil +} + +// RemoveKitVolumes removes an execution's Kit volumes once the execution +// has ended; a retry of the same execution reuses them until then. +func RemoveKitVolumes(ctx context.Context, cli *client.Client, volumes []kit.Volume) error { + var errs []error + for _, v := range volumes { + if _, err := cli.VolumeRemove(ctx, v.Name, client.VolumeRemoveOptions{Force: true}); err != nil { + errs = append(errs, fmt.Errorf("remove kit volume %s: %w", v.Name, err)) + } + } + return errors.Join(errs...) +} + +func runHook(ctx context.Context, cli *client.Client, id string, h kit.Hook) error { + if h.Background { + exec, err := cli.ExecCreate(ctx, id, client.ExecCreateOptions{User: h.User, Env: h.Env, Cmd: h.Argv, WorkingDir: kit.WorkspaceDir}) + if err != nil { + return err + } + _, err = cli.ExecStart(ctx, exec.ID, client.ExecStartOptions{Detach: true}) + return err + } + code, out, err := ExecIn(ctx, cli, id, h.User, h.Env, h.Argv) + if err != nil { + return err + } + if code != 0 { + return fmt.Errorf("%s exited %d: %s", strings.Join(h.Argv, " "), code, out) + } + return nil +} + +// writeKitFile writes a lifecycle file as the harness user, so the file +// belongs to the agent as the Kit spec requires. +func writeKitFile(ctx context.Context, cli *client.Client, id, user, target, content, mode string, overwrite *bool) error { + script := `mkdir -p "$(dirname "$KIT_PATH")" && printf %s "$KIT_CONTENT" | base64 -d > "$KIT_PATH"` + if mode != "" { + script += ` && chmod "$KIT_MODE" "$KIT_PATH"` + } + if overwrite != nil && !*overwrite { + script = `[ -e "$KIT_PATH" ] || { ` + script + `; }` + } + env := []string{ + "KIT_PATH=" + path.Clean(target), + "KIT_CONTENT=" + base64.StdEncoding.EncodeToString([]byte(content)), + "KIT_MODE=" + mode, + } + code, out, err := ExecIn(ctx, cli, id, user, env, []string{"sh", "-c", script}) + if err != nil { + return err + } + if code != 0 { + return fmt.Errorf("exited %d: %s", code, out) + } + return nil +} + +// ExecIn runs argv in a container as user with exactly env, and returns its +// exit code and the tail of its combined output. +func ExecIn(ctx context.Context, cli *client.Client, id, user string, env, argv []string) (int, string, error) { + exec, err := cli.ExecCreate(ctx, id, client.ExecCreateOptions{ + User: user, Env: env, Cmd: argv, WorkingDir: kit.WorkspaceDir, + AttachStdout: true, AttachStderr: true, + }) + if err != nil { + return 0, "", err + } + attached, err := cli.ExecAttach(ctx, exec.ID, client.ExecAttachOptions{}) + if err != nil { + return 0, "", err + } + defer attached.Close() + var out bytes.Buffer + if _, err := stdcopy.StdCopy(&out, &out, attached.Reader); err != nil { + return 0, "", err + } + inspected, err := cli.ExecInspect(ctx, exec.ID, client.ExecInspectOptions{}) + if err != nil { + return 0, "", err + } + text := strings.TrimSpace(out.String()) + if len(text) > hookOutputTail { + text = text[len(text)-hookOutputTail:] + } + return inspected.ExitCode, text, nil +} diff --git a/internal/container/kit_test.go b/internal/container/kit_test.go new file mode 100644 index 000000000..15de2c74f --- /dev/null +++ b/internal/container/kit_test.go @@ -0,0 +1,141 @@ +package container + +import ( + "context" + "fmt" + "io" + "strings" + "testing" + "time" + + "github.com/docker/sandbox-kit-spec/v3/spec" + "github.com/moby/moby/client" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/infrastructure/kit" +) + +const kitProbeImage = "alpine:3" + +func kitClient(t *testing.T) *client.Client { + t.Helper() + cli, err := client.New(client.FromEnv) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cli.Close() }) + if _, err := cli.ImageInspect(t.Context(), kitProbeImage); err != nil { + rc, err := cli.ImagePull(t.Context(), kitProbeImage, client.ImagePullOptions{}) + if err != nil { + t.Fatal(err) + } + _, _ = io.Copy(io.Discard, rc) + _ = rc.Close() + } + return cli +} + +func kitSpec(t *testing.T, install ...kit.Hook) KitSpec { + t.Helper() + name := fmt.Sprintf("archie-kit-test-%d", time.Now().UnixNano()) + overwrite := false + return KitSpec{ + Name: name, + Image: kitProbeImage, + Network: "none", + Worker: []string{"sleep", "300"}, + WorkerEnv: []string{"STATE_STORE_TOKEN=worker-secret", "NATS_TOKEN=worker-secret"}, + Labels: map[string]string{"archie-kit-test": name}, + Launch: kit.Launch{ + Harness: agentexec.HarnessSpec{User: kit.DefaultHarnessUser}, + Install: install, + Startup: []kit.Hook{{Argv: []string{"sh", "-c", "id -u > /tmp/startup-uid"}, User: kit.DefaultHarnessUser}}, + Files: []spec.File{ + {Path: "/tmp/kit/settings.json", Content: `{"theme":1}`, Mode: "0600"}, + {Path: "/tmp/kit/keep.json", Content: "second", Overwrite: &overwrite}, + }, + Volumes: []kit.Volume{{Name: name + "-state", Path: "/data"}}, + }, + } +} + +func startKit(t *testing.T, cli *client.Client, s KitSpec) string { + t.Helper() + id, err := StartKit(t.Context(), cli, s) + t.Cleanup(func() { + ctx := context.WithoutCancel(t.Context()) + if id != "" { + _, _ = cli.ContainerRemove(ctx, id, client.ContainerRemoveOptions{Force: true}) + } + _ = RemoveKitVolumes(ctx, cli, s.Launch.Volumes) + }) + if err != nil { + t.Fatalf("StartKit: %v", err) + } + return id +} + +func run(t *testing.T, cli *client.Client, id, user string, argv ...string) (int, string) { + t.Helper() + code, out, err := ExecIn(t.Context(), cli, id, user, []string{"PATH=/usr/bin:/bin"}, argv) + if err != nil { + t.Fatal(err) + } + return code, out +} + +// TestKitContainerSeparatesTheHarnessFromTheWorker proves the one-container +// design's boundary on a real container: the worker's credentials are in +// its environment, and the harness user cannot read them. +func TestKitContainerSeparatesTheHarnessFromTheWorker(t *testing.T) { + cli := kitClient(t) + id := startKit(t, cli, kitSpec(t, kit.Hook{ + Argv: []string{"sh", "-c", `echo "$WORKSPACE_DIR" > /etc/seeded; echo first > /tmp/kit-keep-seed`}, + User: "0", Env: []string{"WORKSPACE_DIR=/workspace"}, + })) + + inspected, err := cli.ContainerInspect(t.Context(), id, client.ContainerInspectOptions{}) + if err != nil { + t.Fatal(err) + } + workerUser := inspected.Container.Config.User + if code, out := run(t, cli, id, workerUser, "cat", "/proc/1/environ"); code != 0 || !strings.Contains(out, "worker-secret") { + t.Fatalf("the worker's own user cannot see its environment (%d %q); the probe below would prove nothing", code, out) + } + if code, out := run(t, cli, id, kit.DefaultHarnessUser, "cat", "/proc/1/environ"); code == 0 || strings.Contains(out, "worker-secret") { + t.Fatalf("the harness user read the worker's environment: %q", out) + } + + if _, out := run(t, cli, id, "0", "cat", "/etc/seeded"); out != "/workspace" { + t.Errorf("install hook did not run as root with its declared env: /etc/seeded = %q", out) + } + if _, out := run(t, cli, id, "0", "cat", "/tmp/startup-uid"); out != kit.DefaultHarnessUser { + t.Errorf("startup hook ran as uid %q, want %s", out, kit.DefaultHarnessUser) + } + if _, out := run(t, cli, id, "0", "stat", "-c", "%u %a", "/tmp/kit/settings.json"); out != kit.DefaultHarnessUser+" 600" { + t.Errorf("kit file owner and mode %q, want the harness user and 600", out) + } + if _, out := run(t, cli, id, "0", "cat", "/tmp/kit/keep.json"); out != "second" { + t.Errorf("kit file content %q", out) + } +} + +func TestKitContainerFailingInstallHookIsRemoved(t *testing.T) { + cli := kitClient(t) + s := kitSpec(t, kit.Hook{Argv: []string{"sh", "-c", "echo broken registry >&2; exit 3"}, User: "0"}) + id, err := StartKit(t.Context(), cli, s) + t.Cleanup(func() { _ = RemoveKitVolumes(context.WithoutCancel(t.Context()), cli, s.Launch.Volumes) }) + if err == nil || !strings.Contains(err.Error(), "install hook 1") || !strings.Contains(err.Error(), "broken registry") { + t.Fatalf("StartKit error %v, want the failing hook and its output", err) + } + if id != "" { + t.Fatalf("StartKit returned container %s for a failed start", id) + } + list, err := cli.ContainerList(t.Context(), client.ContainerListOptions{All: true, Filters: client.Filters{}.Add("label", "archie-kit-test="+s.Name)}) + if err != nil { + t.Fatal(err) + } + if len(list.Items) != 0 { + t.Fatalf("a failed Kit start left %d container(s) behind", len(list.Items)) + } +}