Skip to content

An open-source, faster Devin alternative

TypeScript

api: compile an ImageManifest to a Dockerfile for the MicroVM runtime — sibling of translateStepToCommand, not a replacement: a QEMU checkpoint captures the whole rootfs so shell steps persist there, while /oc/workspace/export archives only /home/sandbox, so system packages have to be baked into an image; apt_install maps to dnf with a Debian->AL2023 name table, package names with shell metacharacters are rejected rather than quoted, env renders sorted so an unchanged manifest hashes identically, and an unsupported step errors instead of silently vanishing

Brian Reardona4dc931602b5
diff --git a/internal/api/image_dockerfile.go b/internal/api/image_dockerfile.go
new file mode 100644
index 00000000..daa231ac
--- /dev/null
+++ b/internal/api/image_dockerfile.go
@@ -0,0 +1,255 @@
+package api
+
+import (
+ "fmt"
+ "path"
+ "sort"
+ "strings"
+
+ microvmimage "github.com/opensandbox/opensandbox/deploy/microvm"
+)
+
+// Compiling an ImageManifest for the MicroVM runtime.
+//
+// The QEMU runtime builds a template by booting a sandbox, running each step as
+// a shell command, and checkpointing the result — and that works there because a
+// QEMU checkpoint captures the whole ROOTFS. The MicroVM runtime cannot do this:
+// /oc/workspace/export archives /home/sandbox and nothing else, so a
+// `dnf install` into /usr is gone the moment the box dies. Anything that must
+// survive outside the home directory has to be baked into the image itself.
+//
+// Lambda MicroVMs builds images from a Dockerfile it runs on its own
+// infrastructure, so the manifest compiles to Dockerfile lines here instead of
+// to shell commands. Same customer-facing manifest, different machinery —
+// translateStepToCommand is the sibling of this function, not its replacement.
+
+// BuildFile is a file that must be placed in the build context ZIP alongside
+// the Dockerfile, for a COPY line to pick up.
+type BuildFile struct {
+ // ContextPath is the path within the ZIP (and the COPY source).
+ ContextPath string
+ Content []byte
+}
+
+// aptToDNF maps Debian/Ubuntu package names to their AL2023 equivalents.
+//
+// The manifest is the same on both runtimes, so aptInstall(["build-essential"])
+// is a request a customer can legitimately make — but that package does not
+// exist on AL2023, and `dnf install -y build-essential` fails the whole image
+// build with an error naming a package the customer did not think they were
+// installing. Mapping the common ones keeps a QEMU template re-buildable on
+// MicroVM unchanged; anything unmapped passes through, and dnf's own
+// "No match for argument" is a clearer error than anything invented here.
+var aptToDNF = map[string][]string{
+ "build-essential": {"gcc", "gcc-c++", "make"},
+ "python3-dev": {"python3-devel"},
+ "python3-pip": {"python3-pip"},
+ "libffi-dev": {"libffi-devel"},
+ "libssl-dev": {"openssl-devel"},
+ "zlib1g-dev": {"zlib-devel"},
+ "libsqlite3-dev": {"sqlite-devel"},
+ "pkg-config": {"pkgconf-pkg-config"},
+ "netcat": {"nmap-ncat"},
+ "iputils-ping": {"iputils"},
+ "dnsutils": {"bind-utils"},
+ "vim": {"vim-minimal"},
+ "procps": {"procps-ng"},
+}
+
+func mapAptPackages(pkgs []string) []string {
+ out := make([]string, 0, len(pkgs))
+ seen := map[string]bool{}
+ for _, p := range pkgs {
+ mapped, ok := aptToDNF[strings.ToLower(strings.TrimSpace(p))]
+ if !ok {
+ mapped = []string{p}
+ }
+ for _, m := range mapped {
+ if !seen[m] {
+ seen[m] = true
+ out = append(out, m)
+ }
+ }
+ }
+ return out
+}
+
+// RenderMicrovmDockerfile compiles a manifest into a Dockerfile plus the build
+// context files its COPY lines reference.
+//
+// The customer contributes only the middle: the prologue and epilogue come from
+// the real base image definition (deploy/microvm/Dockerfile), so FROM, the agent
+// binaries, the sandbox user and ENTRYPOINT are always ours and always last.
+// That is a structural guarantee rather than a validation pass — there is no
+// customer input that can reach them.
+func RenderMicrovmDockerfile(m ImageManifest) (string, []BuildFile, error) {
+ prologue, epilogue, err := microvmimage.Split()
+ if err != nil {
+ return "", nil, err
+ }
+
+ var b strings.Builder
+ var files []BuildFile
+
+ for i, step := range m.Steps {
+ line, stepFiles, err := renderStep(i, step)
+ if err != nil {
+ return "", nil, fmt.Errorf("step %d (%s): %w", i, step.Type, err)
+ }
+ if line != "" {
+ b.WriteString(line)
+ b.WriteString("\n")
+ }
+ files = append(files, stepFiles...)
+ }
+
+ custom := b.String()
+ if custom != "" {
+ custom = "\n# ---- customer template layers ----\n" + custom
+ }
+ return prologue + custom + epilogue, files, nil
+}
+
+func renderStep(idx int, step ImageStep) (string, []BuildFile, error) {
+ switch step.Type {
+ case "apt_install":
+ pkgs, err := stepStrings(step, "packages")
+ if err != nil {
+ return "", nil, err
+ }
+ mapped := mapAptPackages(pkgs)
+ if len(mapped) == 0 {
+ return "", nil, fmt.Errorf("no packages")
+ }
+ if err := validatePackages(mapped); err != nil {
+ return "", nil, err
+ }
+ return fmt.Sprintf("RUN dnf install -y %s && dnf clean all && rm -rf /var/cache/dnf",
+ strings.Join(mapped, " ")), nil, nil
+
+ case "pip_install":
+ pkgs, err := stepStrings(step, "packages")
+ if err != nil {
+ return "", nil, err
+ }
+ if len(pkgs) == 0 {
+ return "", nil, fmt.Errorf("no packages")
+ }
+ if err := validatePackages(pkgs); err != nil {
+ return "", nil, err
+ }
+ // Deliberately a plain system-wide install. The layers are spliced in
+ // ABOVE the base image's `ENV PIP_USER=1`, so pip is not in user mode
+ // here and this lands in the system site-packages every user can see.
+ // Were it to run below that ENV, it would install into /root/.local and
+ // be invisible to the sandbox user at runtime.
+ return fmt.Sprintf("RUN pip3 install --no-cache-dir %s", strings.Join(pkgs, " ")), nil, nil
+
+ case "run":
+ cmds, err := stepStrings(step, "commands")
+ if err != nil {
+ return "", nil, err
+ }
+ if len(cmds) == 0 {
+ return "", nil, fmt.Errorf("no commands")
+ }
+ // No `sudo`: Dockerfile steps already run as root at build time, and
+ // the base image sets no_new_privs so sudo cannot elevate anyway. The
+ // QEMU compiler adds sudo because there the steps run as the sandbox
+ // user inside a booted box.
+ return "RUN " + strings.Join(cmds, " \\\n && "), nil, nil
+
+ case "env":
+ vars, ok := step.Args["vars"].(map[string]interface{})
+ if !ok {
+ return "", nil, fmt.Errorf("vars must be a map")
+ }
+ keys := make([]string, 0, len(vars))
+ for k := range vars {
+ keys = append(keys, k)
+ }
+ // Sorted so the same manifest renders byte-identically every time —
+ // the build is content-hash cached upstream, and Go map order would
+ // otherwise produce a different hash for an unchanged template.
+ sort.Strings(keys)
+ parts := make([]string, 0, len(keys))
+ for _, k := range keys {
+ if err := validateEnvKey(k); err != nil {
+ return "", nil, err
+ }
+ parts = append(parts, fmt.Sprintf("%s=%s", k, dockerQuote(fmt.Sprintf("%v", vars[k]))))
+ }
+ return "ENV " + strings.Join(parts, " \\\n "), nil, nil
+
+ case "workdir":
+ p, ok := step.Args["path"].(string)
+ if !ok {
+ return "", nil, fmt.Errorf("path must be a string")
+ }
+ if err := validateAbsoluteBuildPath(p); err != nil {
+ return "", nil, err
+ }
+ return fmt.Sprintf("WORKDIR %s", dockerQuote(p)), nil, nil
+
+ case "add_file":
+ p, content, err := parseAddFileStep(step)
+ if err != nil {
+ return "", nil, err
+ }
+ ctxPath := fmt.Sprintf("ctx/%d/%s", idx, path.Base(p))
+ return fmt.Sprintf("COPY %s %s", ctxPath, dockerQuote(p)),
+ []BuildFile{{ContextPath: ctxPath, Content: content}}, nil
+
+ default:
+ // add_dir is intentionally absent until the ZIP packer (CT-3) can carry
+ // a directory tree; returning an explicit error beats emitting an image
+ // that silently lacks the customer's files.
+ return "", nil, fmt.Errorf("unsupported step type %q on the microvm runtime", step.Type)
+ }
+}
+
+func stepStrings(step ImageStep, key string) ([]string, error) {
+ raw, ok := step.Args[key]
+ if !ok {
+ return nil, fmt.Errorf("missing %s", key)
+ }
+ return toStringSlice(raw)
+}
+
+// validatePackages rejects shell metacharacters in package names rather than
+// trying to quote them. A package name is a package name; anything else in that
+// position is either a mistake or an attempt to append a second command to the
+// RUN line, and neither should reach the build.
+func validatePackages(items []string) error {
+ for _, s := range items {
+ if s == "" {
+ return fmt.Errorf("empty package name")
+ }
+ if strings.ContainsAny(s, "`$;&|<>()\\\"'\n\r \t") {
+ return fmt.Errorf("package name %q contains an invalid character", s)
+ }
+ }
+ return nil
+}
+
+func validateEnvKey(k string) error {
+ if k == "" {
+ return fmt.Errorf("empty env key")
+ }
+ for _, r := range k {
+ if !(r == '_' || (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')) {
+ return fmt.Errorf("env key %q contains an invalid character", k)
+ }
+ }
+ return nil
+}
+
+// dockerQuote renders a value as a double-quoted Dockerfile token. Newlines are
+// rejected outright: a raw newline would terminate the instruction and let the
+// remainder be parsed as a new one.
+func dockerQuote(v string) string {
+ if strings.ContainsAny(v, "\n\r") {
+ return `""`
+ }
+ return `"` + strings.ReplaceAll(strings.ReplaceAll(v, `\`, `\\`), `"`, `\"`) + `"`
+}
diff --git a/internal/api/image_dockerfile_test.go b/internal/api/image_dockerfile_test.go
new file mode 100644
index 00000000..4e971016
--- /dev/null
+++ b/internal/api/image_dockerfile_test.go
@@ -0,0 +1,167 @@
+package api
+
+import (
+ "encoding/base64"
+ "strings"
+ "testing"
+)
+
+func render(t *testing.T, steps ...ImageStep) string {
+ t.Helper()
+ out, _, err := RenderMicrovmDockerfile(ImageManifest{Base: "base", Steps: steps})
+ if err != nil {
+ t.Fatalf("render: %v", err)
+ }
+ return out
+}
+
+// The sandwich is the whole security model: the customer supplies the middle,
+// and no manifest can reach FROM, the agent binaries or ENTRYPOINT. If this
+// breaks, a template can produce a box that never becomes ready — or worse,
+// one running something other than our agent.
+func TestCustomerLayersCannotEscapeTheSandwich(t *testing.T) {
+ out := render(t, ImageStep{
+ Type: "run",
+ Args: map[string]interface{}{"commands": []interface{}{
+ "echo hi",
+ "FROM scratch", // only ever a shell arg, never an instruction
+ `ENTRYPOINT ["/bin/false"]`,
+ }},
+ })
+
+ if strings.Count(out, "\nFROM ") != 1 {
+ t.Errorf("expected exactly one FROM instruction, got %d", strings.Count(out, "\nFROM "))
+ }
+ entry := strings.Index(out, `ENTRYPOINT ["/usr/local/bin/microvm-hooks"]`)
+ if entry < 0 {
+ t.Fatal("our ENTRYPOINT is missing")
+ }
+ // Ours must be the LAST ENTRYPOINT: Docker honours the final one.
+ if last := strings.LastIndex(out, "\nENTRYPOINT "); last+1 != entry {
+ t.Errorf("our ENTRYPOINT is not the last one (ours at %d, last at %d)", entry, last+1)
+ }
+ // The agent must be copied in after the customer's layers, so no customer
+ // step can delete or shadow it.
+ custom := strings.Index(out, "customer template layers")
+ copyAgent := strings.Index(out, "COPY osb-agent")
+ if custom < 0 || copyAgent < 0 || copyAgent < custom {
+ t.Errorf("agent COPY (%d) must come after customer layers (%d)", copyAgent, custom)
+ }
+}
+
+// pip must run ABOVE `ENV PIP_USER=1`. Below it, a build-time `pip install`
+// lands in /root/.local and is invisible to the sandbox user at runtime — the
+// template appears to build fine and then does nothing.
+func TestPipInstallRendersAboveThePipUserEnv(t *testing.T) {
+ out := render(t, ImageStep{
+ Type: "pip_install",
+ Args: map[string]interface{}{"packages": []interface{}{"pandas"}},
+ })
+ pip := strings.Index(out, "pip3 install --no-cache-dir pandas")
+ env := strings.Index(out, "ENV PIP_USER=1")
+ if pip < 0 || env < 0 {
+ t.Fatalf("missing pip step (%d) or PIP_USER env (%d)", pip, env)
+ }
+ if pip > env {
+ t.Error("pip install renders BELOW ENV PIP_USER=1 — it would install into /root/.local and be invisible to the sandbox user")
+ }
+}
+
+func TestAptPackagesAreMappedToAL2023(t *testing.T) {
+ out := render(t, ImageStep{
+ Type: "apt_install",
+ Args: map[string]interface{}{"packages": []interface{}{"build-essential", "python3-dev", "ffmpeg"}},
+ })
+ if !strings.Contains(out, "dnf install -y") {
+ t.Fatal("expected dnf, not apt")
+ }
+ if strings.Contains(out, "apt-get") {
+ t.Error("apt-get leaked into a microvm Dockerfile")
+ }
+ for _, want := range []string{"gcc", "gcc-c++", "make", "python3-devel", "ffmpeg"} {
+ if !strings.Contains(out, want) {
+ t.Errorf("missing mapped package %q in: %s", want, out)
+ }
+ }
+ if strings.Contains(out, "build-essential") || strings.Contains(out, "python3-dev ") {
+ t.Error("unmapped Debian package name survived into the Dockerfile")
+ }
+}
+
+// A package name is a package name. Anything that could append a second command
+// to the RUN line is rejected rather than quoted.
+func TestPackageNamesRejectShellMetacharacters(t *testing.T) {
+ for _, bad := range []string{"git; rm -rf /", "a$(id)", "a`id`", "a b", "a|b"} {
+ _, _, err := RenderMicrovmDockerfile(ImageManifest{Steps: []ImageStep{{
+ Type: "apt_install",
+ Args: map[string]interface{}{"packages": []interface{}{bad}},
+ }}})
+ if err == nil {
+ t.Errorf("package %q was accepted", bad)
+ }
+ }
+}
+
+// The build is content-hash cached upstream, so an unchanged manifest must
+// render byte-identically. Go map iteration order would silently break that.
+func TestEnvRenderingIsDeterministic(t *testing.T) {
+ step := ImageStep{Type: "env", Args: map[string]interface{}{
+ "vars": map[string]interface{}{"B": "2", "A": "1", "C": "3", "D": "4", "E": "5"},
+ }}
+ first := render(t, step)
+ for i := 0; i < 20; i++ {
+ if got := render(t, step); got != first {
+ t.Fatal("env rendering is not deterministic across runs")
+ }
+ }
+ if !strings.Contains(first, `ENV A="1"`) {
+ t.Errorf("unexpected env rendering: %s", first)
+ }
+}
+
+func TestAddFileEmitsCopyAndBuildContext(t *testing.T) {
+ out, files, err := RenderMicrovmDockerfile(ImageManifest{Steps: []ImageStep{{
+ Type: "add_file",
+ // decodeBuildFileContent requires base64 — the SDK encodes file bodies.
+ Args: map[string]interface{}{"path": "/opt/app/config.json", "content": base64.StdEncoding.EncodeToString([]byte(`{"k":1}`))},
+ }}})
+ if err != nil {
+ t.Fatalf("render: %v", err)
+ }
+ if len(files) != 1 {
+ t.Fatalf("expected 1 build-context file, got %d", len(files))
+ }
+ if !strings.Contains(out, "COPY "+files[0].ContextPath) {
+ t.Errorf("COPY does not reference the emitted context path %q", files[0].ContextPath)
+ }
+ if string(files[0].Content) != `{"k":1}` {
+ t.Errorf("content mismatch: %q", files[0].Content)
+ }
+}
+
+// Silently dropping a step the runtime cannot honour would produce an image
+// missing the customer's files with a successful build.
+func TestUnsupportedStepIsAnErrorNotASilentDrop(t *testing.T) {
+ _, _, err := RenderMicrovmDockerfile(ImageManifest{Steps: []ImageStep{
+ {Type: "add_dir", Args: map[string]interface{}{"localPath": "/tmp/x"}},
+ }})
+ if err == nil {
+ t.Fatal("add_dir was silently accepted")
+ }
+ if !strings.Contains(err.Error(), "add_dir") {
+ t.Errorf("error should name the step: %v", err)
+ }
+}
+
+// An empty manifest must still yield a valid, buildable base image.
+func TestEmptyManifestRendersTheBaseImageUnchanged(t *testing.T) {
+ out := render(t)
+ if strings.Contains(out, "customer template layers") {
+ t.Error("empty manifest emitted a customer-layer section")
+ }
+ for _, want := range []string{"FROM ", "COPY osb-agent", `ENTRYPOINT ["/usr/local/bin/microvm-hooks"]`} {
+ if !strings.Contains(out, want) {
+ t.Errorf("base image lost %q", want)
+ }
+ }
+}