carlos / platform Public

media: authenticate the image's inputs and harden its build

Astra's review of the image tool, fix round 1.

lock verifies each suite's InRelease with gpgv against the committed
Debian archive keyring, then checks the Packages index's size and sha256
against that signed release before parsing it. Validity is judged at the
snapshot's time. The committed lock regenerates unchanged through this
chain (snapshot 20261117T000000Z).

push keeps credentials on the configured registry: every request, upload
Location and redirect must keep its scheme and authority. A repeat push
now reads the tag and digest back, as a first push does.

The final image holds no setuid or setgid path, and the build fails if
one remains. dpkg's status file records every locked package from its
verified control file.

The build id comes from the full commit hash, so core.abbrev cannot
change the image, and build refuses any Go but the release pin.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev add7bc3369715cef73744c54b9aa9f5b80e27888 parent ca373e8
12 files changed, +1,281 −126
  • Makefile +14 −6
  • cmd/mediaimage/build.go +149 −25
  • cmd/mediaimage/deb.go +107 −8
  • cmd/mediaimage/lock.go +29 −29
  • cmd/mediaimage/main.go +1 −0
  • cmd/mediaimage/mediaimage_test.go +638 −32
  • cmd/mediaimage/oci.go +47 −5
  • cmd/mediaimage/push.go +26 −13
  • cmd/mediaimage/release.go +254 −0
  • deploy/media-image/README.md +7 −5
  • deploy/media-image/debian-archive-keyring.gpg binary
  • docs/superpowers/notes/media-conversion-copy-deck.md +9 −3
diff --git a/Makefile b/Makefile
index 59eceed3a..be8f47683 100644
--- a/Makefile
+++ b/Makefile
@@ -7,7 +7,7 @@ LDFLAGS := -s -w -X github.com/carlosframework/platform/internal/version.Build=$
GOOS ?=
GOARCH ?=
-.PHONY: test build build-console fmt staticcheck govulncheck census-card census-propose code-health code-health-record console-mockup-kit parity-doc media-image media-image-lock
+.PHONY: test build build-console fmt staticcheck govulncheck census-card census-propose code-health code-health-record console-mockup-kit parity-doc media-image media-image-binary media-image-lock
# The build gate: vet, format, tests. `.amadan/ci.d/10-gate` runs this same
# target, so what CI checks and what you check are one definition.
@@ -30,21 +30,29 @@ build-console:
CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) go build -trimpath -ldflags "$(LDFLAGS)" -o console ./cmd/console
# The media engine's arm64 image (deploy/media-image/README.md). The image's
-# time is the commit's, so a commit builds the same image every time.
+# time is the commit's and its build id is cut from the full commit hash, so
+# a commit builds the same image on any machine, whatever core.abbrev says.
+# Go is the release pin; mediaimage refuses any other.
MEDIA_IMAGE_LOCK := deploy/media-image/debs.lock
+MEDIA_IMAGE_KEYRING := deploy/media-image/debian-archive-keyring.gpg
+MEDIA_IMAGE_BINARY ?= dist/carlos-media
+MEDIA_IMAGE_GO = $(shell sed -n 's/^GOTOOLCHAIN=\(go[0-9.]*\).*/\1/p' .amadan/go-toolchain.sh)
+MEDIA_IMAGE_LDFLAGS = -s -w -X github.com/carlosframework/platform/internal/version.Build=$(shell git rev-parse HEAD | cut -c1-12) -X github.com/carlosframework/platform/internal/version.Commit=$(shell git rev-parse HEAD)
MEDIA_IMAGE_CACHE ?= dist/media-image-cache
MEDIA_IMAGE_CREATED ?= $(shell TZ=UTC git log -1 --format=%cd --date=format-local:%Y-%m-%dT%H:%M:%SZ)
MEDIA_IMAGE_SNAPSHOT ?= $(shell date -u +%Y%m%dT000000Z)
MEDIA_IMAGE_BASE ?= $(shell sed -n 's/^\# base //p' $(MEDIA_IMAGE_LOCK))
-media-image:
- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -buildvcs=false -ldflags "$(LDFLAGS)" -o dist/carlos-media ./cmd/carlos-media
- GOOS= GOARCH= go run ./cmd/mediaimage build --lock $(MEDIA_IMAGE_LOCK) --binary dist/carlos-media --created $(MEDIA_IMAGE_CREATED) --cache $(MEDIA_IMAGE_CACHE) --out dist/media-image
+media-image-binary:
+ GOTOOLCHAIN=$(MEDIA_IMAGE_GO) CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -buildvcs=false -ldflags "$(MEDIA_IMAGE_LDFLAGS)" -o $(MEDIA_IMAGE_BINARY) ./cmd/carlos-media
+
+media-image: media-image-binary
+ GOTOOLCHAIN=$(MEDIA_IMAGE_GO) GOOS= GOARCH= go run ./cmd/mediaimage build --lock $(MEDIA_IMAGE_LOCK) --binary $(MEDIA_IMAGE_BINARY) --created $(MEDIA_IMAGE_CREATED) --cache $(MEDIA_IMAGE_CACHE) --out dist/media-image
# Pins the newest packages at today's snapshot, on the base the lock already
# names. MEDIA_IMAGE_BASE=docker.io/library/debian@sha256:... moves the base.
media-image-lock:
- GOOS= GOARCH= go run ./cmd/mediaimage lock --snapshot $(MEDIA_IMAGE_SNAPSHOT) --base $(MEDIA_IMAGE_BASE) --cache $(MEDIA_IMAGE_CACHE) --out $(MEDIA_IMAGE_LOCK)
+ GOTOOLCHAIN=$(MEDIA_IMAGE_GO) GOOS= GOARCH= go run ./cmd/mediaimage lock --snapshot $(MEDIA_IMAGE_SNAPSHOT) --base $(MEDIA_IMAGE_BASE) --keyring $(MEDIA_IMAGE_KEYRING) --cache $(MEDIA_IMAGE_CACHE) --out $(MEDIA_IMAGE_LOCK)
fmt:
gofmt -w .
diff --git a/cmd/mediaimage/build.go b/cmd/mediaimage/build.go
index 0db45805f..cbce6b1fd 100644
--- a/cmd/mediaimage/build.go
+++ b/cmd/mediaimage/build.go
@@ -6,6 +6,7 @@ import (
"compress/gzip"
"context"
"crypto/sha256"
+ "debug/buildinfo"
"debug/elf"
"encoding/hex"
"encoding/json"
@@ -16,6 +17,7 @@ import (
"os"
"path"
"path/filepath"
+ "runtime"
"slices"
"strings"
"sync"
@@ -34,10 +36,15 @@ var (
// errMissingExecutable is a program the engine runs that the image
// does not hold for arm64.
errMissingExecutable = errors.New("missing executable")
+ // errPrivilegedMode is a setuid or setgid path left in the final image.
+ errPrivilegedMode = errors.New("setuid or setgid path in the image")
+ // errToolchain is an image built with another Go than releases use.
+ errToolchain = errors.New("wrong Go toolchain")
)
const (
- scratchPath = "scratch"
+ scratchPath = "scratch"
+ dpkgStatusPath = "var/lib/dpkg/status"
// scratchID is the numeric user and group the engine runs as.
scratchID = 65534
imageUser = "65534:65534"
@@ -48,6 +55,45 @@ const (
labelDebsLock = "io.carlosframework.debs-lock"
)
+// releaseGoVersion is the Go every release is built with, the pin in
+// .amadan/go-toolchain.sh. Layer bytes depend on it through compress/flate,
+// and carlos-media's bytes through the compiler.
+const releaseGoVersion = "go1.26.10"
+
+// privilegeBits are the mode bits that change who a program runs as. The
+// engine never needs them, so the image holds none. The sticky bit grants
+// nothing and stays.
+const privilegeBits = 0o6000
+
+// toolchain reads the two Go versions a build depends on.
+var toolchain = struct {
+ tool func() string
+ binary func(string) (string, error)
+}{runtime.Version, binaryGoVersion}
+
+func binaryGoVersion(file string) (string, error) {
+ info, err := buildinfo.ReadFile(file)
+ if err != nil {
+ return "", err
+ }
+ return info.GoVersion, nil
+}
+
+// checkToolchain refuses a build that could not reproduce a release.
+func checkToolchain(binary string) error {
+ if got := toolchain.tool(); got != releaseGoVersion {
+ return fmt.Errorf("%w: mediaimage runs on %s, releases use %s", errToolchain, got, releaseGoVersion)
+ }
+ got, err := toolchain.binary(binary)
+ if err != nil {
+ return fmt.Errorf("%w: %s names no Go version: %w", errToolchain, binary, err)
+ }
+ if got != releaseGoVersion {
+ return fmt.Errorf("%w: %s was built with %s, releases use %s", errToolchain, binary, got, releaseGoVersion)
+ }
+ return nil
+}
+
// libraryDirs is the arm64 loader's default search path on Debian.
var libraryDirs = []string{"lib/aarch64-linux-gnu", "usr/lib/aarch64-linux-gnu", "lib", "usr/lib"}
@@ -100,6 +146,9 @@ func buildImage(ctx context.Context, o buildOptions) (media.ImageInfo, error) {
if o.Out == "" || o.Binary == "" || o.Cache == "" {
return media.ImageInfo{}, errors.New("--out, --binary and --cache are required")
}
+ if err := checkToolchain(o.Binary); err != nil {
+ return media.ImageInfo{}, err
+ }
ref, err := parseImageRef(lock.Base)
if err != nil {
return media.ImageInfo{}, err
@@ -136,7 +185,7 @@ func buildImage(ctx context.Context, o buildOptions) (media.ImageInfo, error) {
var layers []ociDescriptor
diffIDs := slices.Clone(base.Config.RootFS.DiffIDs)
for _, layer := range base.Manifest.Layers {
- if err := scanLayerBlob(store.path(layer.Digest), root); err != nil {
+ if err := scanLayerBlob(store.path(layer.Digest), root, spool); err != nil {
return media.ImageInfo{}, fmt.Errorf("base layer %s: %w", layer.Digest, err)
}
if err := copyFile(store.path(layer.Digest), filepath.Join(layout, "blobs", "sha256", strings.TrimPrefix(layer.Digest, "sha256:"))); err != nil {
@@ -145,24 +194,34 @@ func buildImage(ctx context.Context, o buildOptions) (media.ImageInfo, error) {
layers = append(layers, ociDescriptor{MediaType: mediaTypeOCILayer, Digest: layer.Digest, Size: layer.Size})
}
- plan, err := planDebs(ctx, store, lock, root, spool)
+ statusFile, err := baseStatusFile(store, base)
if err != nil {
return media.ImageInfo{}, err
}
- top, err := planTopLayer(o.Binary, root, spool)
+ plan, err := planDebs(ctx, store, lock, statusFile, root, spool)
if err != nil {
return media.ImageInfo{}, err
}
- for _, items := range [][]layerItem{plan, top} {
+ addLayer := func(items []layerItem) error {
desc, diffID, err := writeLayer(layout, spool, items, created)
if err != nil {
- return media.ImageInfo{}, err
- }
- if err := scanLayerBlob(filepath.Join(layout, "blobs", "sha256", strings.TrimPrefix(desc.Digest, "sha256:")), root); err != nil {
- return media.ImageInfo{}, err
+ return err
}
layers = append(layers, desc)
diffIDs = append(diffIDs, diffID)
+ return scanLayerBlob(filepath.Join(layout, "blobs", "sha256", strings.TrimPrefix(desc.Digest, "sha256:")), root, spool)
+ }
+ if err := addLayer(plan); err != nil {
+ return media.ImageInfo{}, err
+ }
+ // The top layer is planned last: it covers whatever privileged paths
+ // the layers below it left.
+ top, err := planTopLayer(o.Binary, root, spool)
+ if err != nil {
+ return media.ImageInfo{}, err
+ }
+ if err := addLayer(top); err != nil {
+ return media.ImageInfo{}, err
}
if err := checkImage(root); err != nil {
return media.ImageInfo{}, err
@@ -496,7 +555,7 @@ func (p *debPlan) readEntry(h *tar.Header, r io.Reader, regular map[string]layer
if err != nil || clean == "" || unloadableFiles[clean] {
return nil, err
}
- item := layerItem{path: clean, typ: h.Typeflag, mode: h.Mode & 0o7777}
+ item := layerItem{path: clean, typ: h.Typeflag, mode: h.Mode & 0o7777 &^ privilegeBits}
switch h.Typeflag {
case tar.TypeDir:
case tar.TypeReg:
@@ -612,12 +671,25 @@ func sortedItems(items map[string]layerItem) []layerItem {
}
// planDebs builds the package layer's entries from every locked package.
-func planDebs(ctx context.Context, store blobStore, lock lockFile, root *tree, spool string) ([]layerItem, error) {
+func planDebs(ctx context.Context, store blobStore, lock lockFile, baseStatus []byte, root *tree, spool string) ([]layerItem, error) {
plan := &debPlan{entries: map[string]layerItem{}, spool: spool}
+ installed := map[string]string{}
for _, e := range lock.Entries {
if err := plan.addDeb(ctx, store.path(e.SHA256), e.Package); err != nil {
return nil, err
}
+ control, err := readControl(ctx, store.path(e.SHA256), e)
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", e.Package, err)
+ }
+ installed[e.Package] = statusRecord(control)
+ }
+ sum, size, err := spoolFile(spool, bytes.NewReader(mergeStatus(baseStatus, installed)))
+ if err != nil {
+ return nil, err
+ }
+ if err := plan.add(layerItem{path: dpkgStatusPath, typ: tar.TypeReg, mode: 0o644, sum: sum, size: size}); err != nil {
+ return nil, err
}
for _, alt := range alternativeLinks {
if _, ok := lock.version(alt.pkg); !ok {
@@ -638,7 +710,8 @@ func planDebs(ctx context.Context, store blobStore, lock lockFile, root *tree, s
return sortedItems(plan.entries), nil
}
-// planTopLayer is the binary and the scratch directory the engine writes to.
+// planTopLayer is the binary, the scratch directory the engine writes to,
+// and an unprivileged copy of every setuid or setgid path below it.
func planTopLayer(binary string, root *tree, spool string) ([]layerItem, error) {
f, err := os.Open(binary)
if err != nil {
@@ -654,6 +727,21 @@ func planTopLayer(binary string, root *tree, spool string) ([]layerItem, error)
entry: {path: entry, typ: tar.TypeReg, mode: 0o755, sum: sum, size: size},
scratchPath: {path: scratchPath, typ: tar.TypeDir, mode: 0o700, uid: scratchID, gid: scratchID},
}
+ for name, n := range root.nodes {
+ if _, taken := items[name]; taken || n.mode&privilegeBits == 0 {
+ continue
+ }
+ item := layerItem{path: name, mode: n.mode &^ privilegeBits, uid: n.uid, gid: n.gid}
+ switch {
+ case n.kind == kindDir:
+ item.typ = tar.TypeDir
+ case n.kind == kindFile && n.sum != "":
+ item.typ, item.sum, item.size = tar.TypeReg, n.sum, n.size
+ default:
+ continue // checkImage refuses what cannot be copied
+ }
+ items[name] = item
+ }
addParents(items, root)
return sortedItems(items), nil
}
@@ -747,9 +835,13 @@ type elfInfo struct {
// node is one path of the layered image.
type node struct {
- kind nodeKind
- link string
- elf *elfInfo
+ kind nodeKind
+ link string
+ elf *elfInfo
+ mode int64
+ uid, gid int
+ sum string // spool file of a privileged regular file
+ size int64
}
// tree is the image's file system as its layers build it up.
@@ -811,7 +903,7 @@ func (t *tree) removeChildren(name string) {
}
// scanLayerBlob applies a gzip layer to the tree.
-func scanLayerBlob(file string, t *tree) error {
+func scanLayerBlob(file string, t *tree, spool string) error {
f, err := os.Open(file)
if err != nil {
return err
@@ -822,12 +914,13 @@ func scanLayerBlob(file string, t *tree) error {
return err
}
defer gz.Close()
- return scanLayer(gz, t)
+ return scanLayer(gz, t, spool)
}
// scanLayer applies one layer: its whiteouts first, as they only ever hide
-// what lower layers hold, then its entries.
-func scanLayer(r io.Reader, t *tree) error {
+// what lower layers hold, then its entries. A privileged regular file's
+// bytes go to the spool, for the unprivileged copy above it.
+func scanLayer(r io.Reader, t *tree, spool string) error {
type entry struct {
name, hardlink string
node *node
@@ -854,19 +947,19 @@ func scanLayer(r io.Reader, t *tree) error {
e := entry{name: name}
switch h.Typeflag {
case tar.TypeDir:
- e.node = &node{kind: kindDir}
+ e.node = &node{kind: kindDir, mode: h.Mode & 0o7777, uid: h.Uid, gid: h.Gid}
case tar.TypeSymlink:
e.node = &node{kind: kindLink, link: h.Linkname}
case tar.TypeLink:
e.hardlink = strings.TrimSuffix(strings.TrimPrefix(h.Linkname, "./"), "/")
case tar.TypeReg:
- info, err := readELF(tr)
+ n, err := scanFile(h, tr, spool)
if err != nil {
return fmt.Errorf("%s: %w", name, err)
}
- e.node = &node{kind: kindFile, elf: info}
+ e.node = n
default:
- e.node = &node{kind: kindFile}
+ e.node = &node{kind: kindFile, mode: h.Mode & 0o7777}
}
entries = append(entries, e)
}
@@ -900,6 +993,26 @@ func scanLayer(r io.Reader, t *tree) error {
return nil
}
+// scanFile reads one regular file of a layer.
+func scanFile(h *tar.Header, r io.Reader, spool string) (*node, error) {
+ n := &node{kind: kindFile, mode: h.Mode & 0o7777, uid: h.Uid, gid: h.Gid}
+ if n.mode&privilegeBits != 0 {
+ var err error
+ if n.sum, n.size, err = spoolFile(spool, r); err != nil {
+ return nil, err
+ }
+ f, err := os.Open(filepath.Join(spool, n.sum))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ r = f
+ }
+ info, err := readELF(r)
+ n.elf = info
+ return n, err
+}
+
// readELF parses a file that starts with the ELF magic; anything else, and
// a file debug/elf cannot read, is plain data.
func readELF(r io.Reader) (*elfInfo, error) {
@@ -974,9 +1087,20 @@ func (t *tree) findLibrary(owner string, info *elfInfo, lib string) bool {
return false
}
-// checkImage fails unless the engine's programs are present for arm64 and
-// every arm64 ELF's libraries resolve inside the image.
+// checkImage fails unless the engine's programs are present for arm64,
+// every arm64 ELF's libraries resolve inside the image, and no path is
+// setuid or setgid.
func checkImage(t *tree) error {
+ var privileged []string
+ for name, n := range t.nodes {
+ if n.kind != kindLink && n.mode&privilegeBits != 0 {
+ privileged = append(privileged, "/"+name)
+ }
+ }
+ if len(privileged) > 0 {
+ slices.Sort(privileged)
+ return fmt.Errorf("%w: %s", errPrivilegedMode, strings.Join(privileged, ", "))
+ }
for _, name := range requiredExecutables {
if !t.isArm64(name) {
return fmt.Errorf("%w: /%s is not an arm64 program", errMissingExecutable, name)
diff --git a/cmd/mediaimage/deb.go b/cmd/mediaimage/deb.go
index debb9924f..1662426f5 100644
--- a/cmd/mediaimage/deb.go
+++ b/cmd/mediaimage/deb.go
@@ -1,13 +1,18 @@
package main
import (
+ "archive/tar"
"bytes"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
+ "maps"
+ "os"
"os/exec"
+ "path"
+ "slices"
"strconv"
"strings"
)
@@ -17,9 +22,15 @@ var errBadDeb = errors.New("bad deb")
const arMagic = "!<arch>\n"
-// readDeb finds the data member of a .deb (an ar archive) and returns its
-// tar stream, decompressed. The caller closes it.
+// readDeb returns a .deb's data tar stream, decompressed. The caller
+// closes it.
func readDeb(ctx context.Context, r io.Reader) (io.ReadCloser, error) {
+ return readDebMember(ctx, r, "data.tar")
+}
+
+// readDebMember finds a tar member of a .deb (an ar archive) by its name
+// before the compression suffix.
+func readDebMember(ctx context.Context, r io.Reader, member string) (io.ReadCloser, error) {
magic := make([]byte, len(arMagic))
if _, err := io.ReadFull(r, magic); err != nil || string(magic) != arMagic {
return nil, fmt.Errorf("%w: not an ar archive", errBadDeb)
@@ -27,7 +38,7 @@ func readDeb(ctx context.Context, r io.Reader) (io.ReadCloser, error) {
for {
var header [60]byte
if _, err := io.ReadFull(r, header[:]); err != nil {
- return nil, fmt.Errorf("%w: no data member", errBadDeb)
+ return nil, fmt.Errorf("%w: no %s member", errBadDeb, member)
}
if string(header[58:60]) != "`\n" {
return nil, fmt.Errorf("%w: a member header is damaged", errBadDeb)
@@ -37,7 +48,7 @@ func readDeb(ctx context.Context, r io.Reader) (io.ReadCloser, error) {
if err != nil || size < 0 {
return nil, fmt.Errorf("%w: a member size is damaged", errBadDeb)
}
- if strings.HasPrefix(name, "data.tar") {
+ if name == member || strings.HasPrefix(name, member+".") {
return decompressMember(ctx, name, io.LimitReader(r, size))
}
if _, err := io.CopyN(io.Discard, r, size+size%2); err != nil {
@@ -47,21 +58,109 @@ func readDeb(ctx context.Context, r io.Reader) (io.ReadCloser, error) {
}
func decompressMember(ctx context.Context, name string, r io.Reader) (io.ReadCloser, error) {
- switch name {
- case "data.tar":
+ switch path.Ext(name) {
+ case ".tar":
return io.NopCloser(r), nil
- case "data.tar.gz":
+ case ".gz":
gz, err := gzip.NewReader(r)
if err != nil {
return nil, fmt.Errorf("%w: %s: %w", errBadDeb, name, err)
}
return gz, nil
- case "data.tar.xz":
+ case ".xz":
return xzReader(ctx, r)
}
return nil, fmt.Errorf("%w: %s is not a compression this tool reads", errBadDeb, name)
}
+// maxControlBytes bounds a package's control file.
+const maxControlBytes = 1 << 20
+
+// readControl returns a verified package's control file, refusing one
+// that does not describe the package the lock pins.
+func readControl(ctx context.Context, file string, e lockEntry) (string, error) {
+ f, err := os.Open(file)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ member, err := readDebMember(ctx, f, "control.tar")
+ if err != nil {
+ return "", err
+ }
+ defer member.Close()
+ r := tar.NewReader(member)
+ for {
+ h, err := r.Next()
+ if errors.Is(err, io.EOF) {
+ return "", fmt.Errorf("%w: no control file", errBadDeb)
+ }
+ if err != nil {
+ return "", fmt.Errorf("%w: %w", errBadDeb, err)
+ }
+ if strings.TrimPrefix(h.Name, "./") != "control" {
+ continue
+ }
+ data, err := io.ReadAll(io.LimitReader(r, maxControlBytes))
+ if err != nil {
+ return "", fmt.Errorf("%w: %w", errBadDeb, err)
+ }
+ return checkControl(string(data), e)
+ }
+}
+
+// checkControl compares a control file with the lock's pin.
+func checkControl(control string, e lockEntry) (string, error) {
+ var fields map[string]string
+ err := stanzas(strings.NewReader(control), func(f map[string]string) error {
+ fields = f
+ return nil
+ })
+ if err != nil {
+ return "", fmt.Errorf("%w: %w", errBadDeb, err)
+ }
+ arch := fields["Architecture"]
+ if fields["Package"] != e.Package || fields["Version"] != e.Version || (arch != "arm64" && arch != "all") {
+ return "", fmt.Errorf("%w: the control file of %s says %s %s for %s", errBadDeb, e.Package, fields["Package"], fields["Version"], arch)
+ }
+ return control, nil
+}
+
+// statusRecord is a control file as dpkg records an installed package.
+func statusRecord(control string) string {
+ first, rest, _ := strings.Cut(strings.TrimRight(control, "\n")+"\n", "\n")
+ return first + "\nStatus: install ok installed\n" + rest
+}
+
+// statusPackage names the package of a status record.
+func statusPackage(record string) string {
+ for _, line := range strings.Split(record, "\n") {
+ if name, ok := strings.CutPrefix(line, "Package:"); ok {
+ return strings.TrimSpace(name)
+ }
+ }
+ return ""
+}
+
+// mergeStatus adds the installed records to a dpkg status file. A record
+// replaces the base's record of the same package, and the file is sorted
+// by package so that it is the same on every build.
+func mergeStatus(base []byte, installed map[string]string) []byte {
+ records := map[string]string{}
+ for _, record := range strings.Split(string(base), "\n\n") {
+ if name := statusPackage(record); name != "" {
+ records[name] = strings.TrimRight(record, "\n") + "\n"
+ }
+ }
+ maps.Copy(records, installed)
+ var out strings.Builder
+ for _, name := range slices.Sorted(maps.Keys(records)) {
+ out.WriteString(records[name])
+ out.WriteString("\n")
+ }
+ return []byte(out.String())
+}
+
// xzStream is the output of an xz -dc child. Reading it to the end reports
// the child's failure, so a damaged stream is never a short success.
type xzStream struct {
diff --git a/cmd/mediaimage/lock.go b/cmd/mediaimage/lock.go
index 7eabaaa29..0a18ee105 100644
--- a/cmd/mediaimage/lock.go
+++ b/cmd/mediaimage/lock.go
@@ -3,6 +3,7 @@ package main
import (
"archive/tar"
"bufio"
+ "bytes"
"compress/gzip"
"context"
"errors"
@@ -10,11 +11,13 @@ import (
"io"
"net/url"
"os"
+ "os/exec"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
+ "time"
)
var (
@@ -440,17 +443,25 @@ func sign(n int) int {
return 0
}
-// lockOptions are the lock command's flags. Archive replaces
+// lockOptions are the lock command's flags. Keyring holds the Debian
+// archive keys that authenticate the snapshot. Archive replaces
// snapshot.debian.org's archive root in tests.
type lockOptions struct {
- Snapshot, Base, Out, Cache, Archive string
+ Snapshot, Base, Out, Cache, Keyring, Archive string
}
// writeLock resolves the closure at a snapshot and writes the lock.
func writeLock(ctx context.Context, o lockOptions) error {
- if !snapshotPattern.MatchString(o.Snapshot) {
+ if _, err := exec.LookPath("gpgv"); err != nil {
+ return fmt.Errorf("%w: %w", errNoGPGV, err)
+ }
+ snapshot, err := time.Parse("20060102T150405Z", o.Snapshot)
+ if err != nil || !snapshotPattern.MatchString(o.Snapshot) {
return fmt.Errorf("%w: --snapshot is not YYYYMMDDTHHMMSSZ", errBadLock)
}
+ if _, err := os.Stat(o.Keyring); err != nil {
+ return fmt.Errorf("%w: --keyring must name a keyring file: %w", errBadLock, err)
+ }
if o.Out == "" {
return fmt.Errorf("%w: --out is required", errBadLock)
}
@@ -484,7 +495,7 @@ func writeLock(ctx context.Context, o lockOptions) error {
var index []debPackage
for _, s := range suites {
origin := archive + "/" + s.archive + "/" + o.Snapshot + "/"
- packages, err := fetchPackages(ctx, origin, s.suite)
+ packages, err := fetchPackages(ctx, origin, s.suite, o.Keyring, snapshot)
if err != nil {
return fmt.Errorf("%s: %w", s.suite, err)
}
@@ -505,30 +516,19 @@ func writeLock(ctx context.Context, o lockOptions) error {
return writeFileAtomic(o.Out, data)
}
-// fetchPackages downloads and parses one suite's index.
-func fetchPackages(ctx context.Context, origin, suite string) ([]debPackage, error) {
- var packages []debPackage
- err := withRetry(ctx, func() error {
- body, err := httpGet(ctx, origin+"dists/"+suite+"/main/binary-arm64/Packages.xz")
- if err != nil {
- return err
- }
- defer body.Close()
- xz, err := xzReader(ctx, body)
- if err != nil {
- return err
- }
- defer xz.Close()
- packages, err = parsePackages(xz, origin)
- return err
- })
- return packages, err
+// baseStatus reads the base image's installed packages.
+func baseStatus(store blobStore, base baseImage) (map[string]string, error) {
+ data, err := baseStatusFile(store, base)
+ if err != nil {
+ return nil, err
+ }
+ return parseStatus(bytes.NewReader(data))
}
-// baseStatus reads var/lib/dpkg/status from the base image's layers; the
-// last layer that holds it wins.
-func baseStatus(store blobStore, base baseImage) (map[string]string, error) {
- var status map[string]string
+// baseStatusFile returns var/lib/dpkg/status from the base image's layers;
+// the last layer that holds it wins.
+func baseStatusFile(store blobStore, base baseImage) ([]byte, error) {
+ var status []byte
for _, layer := range base.Manifest.Layers {
found, err := layerStatus(store.path(layer.Digest))
if err != nil {
@@ -544,7 +544,7 @@ func baseStatus(store blobStore, base baseImage) (map[string]string, error) {
return status, nil
}
-func layerStatus(path string) (map[string]string, error) {
+func layerStatus(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
@@ -556,7 +556,7 @@ func layerStatus(path string) (map[string]string, error) {
}
defer gz.Close()
r := tar.NewReader(gz)
- var status map[string]string
+ var status []byte
for {
h, err := r.Next()
if errors.Is(err, io.EOF) {
@@ -566,7 +566,7 @@ func layerStatus(path string) (map[string]string, error) {
return nil, err
}
if strings.TrimPrefix(h.Name, "./") == "var/lib/dpkg/status" {
- if status, err = parseStatus(r); err != nil {
+ if status, err = io.ReadAll(r); err != nil {
return nil, err
}
}
diff --git a/cmd/mediaimage/main.go b/cmd/mediaimage/main.go
index ea9ff3479..86e59da7a 100644
--- a/cmd/mediaimage/main.go
+++ b/cmd/mediaimage/main.go
@@ -78,6 +78,7 @@ func runLock(ctx context.Context, args []string, stdout, stderr io.Writer) error
fs.StringVar(&o.Snapshot, "snapshot", "", "snapshot.debian.org timestamp, YYYYMMDDTHHMMSSZ")
fs.StringVar(&o.Base, "base", "", "base image, docker.io/library/debian@sha256:<digest>")
fs.StringVar(&o.Out, "out", "", "lock file to write")
+ fs.StringVar(&o.Keyring, "keyring", "", "Debian archive keyring that authenticates the snapshot")
fs.StringVar(&o.Cache, "cache", "", "directory that keeps downloads between runs")
if err := parseFlags(fs, args, stderr); err != nil {
return err
diff --git a/cmd/mediaimage/mediaimage_test.go b/cmd/mediaimage/mediaimage_test.go
index bc2db9e4c..0274fea8d 100644
--- a/cmd/mediaimage/mediaimage_test.go
+++ b/cmd/mediaimage/mediaimage_test.go
@@ -4,6 +4,7 @@ import (
"archive/tar"
"bytes"
"compress/gzip"
+ "crypto"
"crypto/sha256"
"debug/elf"
"encoding/base64"
@@ -15,20 +16,35 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "net/url"
"os"
"os/exec"
"path/filepath"
+ "runtime"
"slices"
"strconv"
"strings"
"sync"
+ "sync/atomic"
"testing"
+ "golang.org/x/crypto/openpgp"
+ "golang.org/x/crypto/openpgp/clearsign"
+ "golang.org/x/crypto/openpgp/packet"
+
"github.com/carlosframework/platform/internal/media"
)
const testCreated = "2026-11-16T10:00:00Z"
+// The fixtures' carlos-media is a hand-made ELF with no Go build record,
+// and this test binary may run on any Go. TestBuildEnforcesTheReleaseToolchain
+// puts the real checks back.
+func init() {
+ toolchain.tool = func() string { return releaseGoVersion }
+ toolchain.binary = func(string) (string, error) { return releaseGoVersion, nil }
+}
+
// fx is one entry of a fixture tar.
type fx struct {
name string
@@ -92,11 +108,11 @@ func arBytes(members ...fx) []byte {
return buf.Bytes()
}
-func debBytes(t *testing.T, files []fx) []byte {
+func debBytes(t *testing.T, control string, files []fx) []byte {
t.Helper()
return arBytes(
fx{name: "debian-binary", body: []byte("2.0\n")},
- fx{name: "control.tar.gz", body: gzipBytes(t, tarBytes(t, nil))},
+ fx{name: "control.tar.gz", body: gzipBytes(t, tarBytes(t, []fx{file("./control", []byte(control))}))},
fx{name: "data.tar.gz", body: gzipBytes(t, tarBytes(t, files))},
)
}
@@ -220,6 +236,14 @@ type fixture struct {
cache, lock, binary, out string
base []fx
debs map[string][]fx
+ control map[string]string // replaces a package's control file
+}
+
+const fixtureVersion = "7:7.1.5-0+deb13u1"
+
+func fixtureControl(name string) string {
+ return "Package: " + name + "\nSource: src-" + name + "\nVersion: " + fixtureVersion +
+ "\nArchitecture: arm64\nMaintainer: Debian\nDescription: a fixture\n spread over two lines\n"
}
func ffmpegDebs(t *testing.T) map[string][]fx {
@@ -259,9 +283,13 @@ func (f *fixture) write(t *testing.T) lockFile {
t.Helper()
l := lockFile{Snapshot: "20261116T000000Z", Base: putBase(t, f.cache, f.base)}
for name, files := range f.debs {
- data := debBytes(t, files)
+ control, ok := f.control[name]
+ if !ok {
+ control = fixtureControl(name)
+ }
+ data := debBytes(t, control, files)
l.Entries = append(l.Entries, lockEntry{
- Package: name, Version: "7:7.1.5-0+deb13u1",
+ Package: name, Version: fixtureVersion,
URL: "https://deb.invalid/" + name + ".deb",
SHA256: putBlob(t, f.cache, data), Size: int64(len(data)),
})
@@ -634,14 +662,17 @@ func TestResolveClosureRefusesAnUnresolvedDependency(t *testing.T) {
// fakeRegistry is a registry v2 on 127.0.0.1, for pulls and pushes.
type fakeRegistry struct {
- mu sync.Mutex
- blobs map[string][]byte
- manifests map[string][]byte
- uploads map[string][]byte
- puts []string
- password string
- tamper bool
- srv *httptest.Server
+ mu sync.Mutex
+ blobs map[string][]byte
+ manifests map[string][]byte
+ uploads map[string][]byte
+ puts []string
+ password string
+ tamper bool
+ failDigest bool // a manifest read by digest answers 500
+ redirect string // every request is sent here instead
+ location func(stage string) string // replaces an upload's Location
+ srv *httptest.Server
}
func newFakeRegistry(t *testing.T) *fakeRegistry {
@@ -664,18 +695,29 @@ func (r *fakeRegistry) ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}
}
+ if r.redirect != "" {
+ w.Header().Set("Location", r.redirect)
+ w.WriteHeader(http.StatusTemporaryRedirect)
+ return
+ }
+ locate := func(stage, normal string) {
+ w.Header().Set("Location", normal)
+ if r.location != nil {
+ w.Header().Set("Location", r.location(stage))
+ }
+ }
path := strings.TrimPrefix(req.URL.Path, "/v2/engine/")
switch {
case strings.HasPrefix(path, "blobs/uploads/") && req.Method == http.MethodPost:
id := strconv.Itoa(len(r.uploads) + 1)
r.uploads[id] = nil
- w.Header().Set("Location", "/v2/engine/blobs/uploads/"+id+"?state=s")
+ locate("start", "/v2/engine/blobs/uploads/"+id+"?state=s")
w.WriteHeader(http.StatusAccepted)
case strings.HasPrefix(path, "blobs/uploads/") && req.Method == http.MethodPatch:
id := strings.TrimPrefix(path, "blobs/uploads/")
body, _ := io.ReadAll(req.Body)
r.uploads[id] = append(r.uploads[id], body...)
- w.Header().Set("Location", "/v2/engine/blobs/uploads/"+id+"?state=t")
+ locate("data", "/v2/engine/blobs/uploads/"+id+"?state=t")
w.WriteHeader(http.StatusAccepted)
case strings.HasPrefix(path, "blobs/uploads/") && req.Method == http.MethodPut:
id := strings.TrimPrefix(path, "blobs/uploads/")
@@ -704,6 +746,8 @@ func (r *fakeRegistry) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.manifests["sha256:"+digestOf(body)] = body
w.Header().Set("Docker-Content-Digest", "sha256:"+digestOf(body))
w.WriteHeader(http.StatusCreated)
+ case strings.HasPrefix(path, "manifests/sha256:") && r.failDigest:
+ w.WriteHeader(http.StatusInternalServerError)
case strings.HasPrefix(path, "manifests/"):
data, ok := r.manifests[strings.TrimPrefix(path, "manifests/")]
if !ok {
@@ -721,8 +765,70 @@ func (r *fakeRegistry) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}
}
-func TestLockCommandEndToEnd(t *testing.T) {
+// testSnapshot is long past, so a release valid at the snapshot has expired
+// by any wall clock.
+const testSnapshot = "20200115T000000Z"
+
+var signingKeys = sync.OnceValues(func() (*openpgp.Entity, *openpgp.Entity) {
+ make := func(name string) *openpgp.Entity {
+ key, err := openpgp.NewEntity(name, "", name+"@example.invalid", &packet.Config{RSABits: 2048})
+ if err != nil {
+ panic(err)
+ }
+ return key
+ }
+ return make("archive"), make("stranger")
+})
+
+func clearsigned(t *testing.T, key *openpgp.Entity, text string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ w, err := clearsign.Encode(&buf, key.PrivateKey, &packet.Config{DefaultHash: crypto.SHA256})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.WriteString(w, text); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func releaseText(codename, date, until string, index []byte) string {
+ text := "Origin: Debian\nCodename: " + codename + "\nDate: " + date + "\n"
+ if until != "" {
+ text += "Valid-Until: " + until + "\n"
+ }
+ return text + fmt.Sprintf("SHA256:\n %s %d %s\n", digestOf(index), len(index), packagesIndex)
+}
+
+const (
+ testReleaseDate = "Wed, 01 Jan 2020 00:00:00 UTC"
+ testReleaseUntil = "Wed, 22 Jan 2020 00:00:00 UTC"
+)
+
+// signedArchive is a snapshot.debian.org on 127.0.0.1, with a base image in
+// a fake registry.
+type signedArchive struct {
+ files map[string][]byte
+ hits atomic.Int32
+ url string
+ keyring string
+ base string
+ index []byte // trixie's Packages.xz
+}
+
+const (
+ trixieRelease = "/debian/" + testSnapshot + "/dists/trixie/InRelease"
+ trixieIndex = "/debian/" + testSnapshot + "/dists/trixie/" + packagesIndex
+)
+
+func newSignedArchive(t *testing.T) *signedArchive {
+ t.Helper()
requireXZ(t)
+ requireGPGV(t)
reg := newFakeRegistry(t)
status := "Package: libbase1\nStatus: install ok installed\nVersion: 2.0-1\n\n"
layer := gzipBytes(t, tarBytes(t, []fx{dir("var/"), dir("var/lib/"), dir("var/lib/dpkg/"), file("var/lib/dpkg/status", []byte(status))}))
@@ -741,38 +847,193 @@ func TestLockCommandEndToEnd(t *testing.T) {
reg.manifests["sha256:"+digestOf(manifest)] = manifest
reg.manifests["sha256:"+digestOf(index)] = index
- packages := map[string]string{
- "/debian/20261116T000000Z/dists/trixie/main/binary-arm64/Packages.xz": "Package: ffmpeg\nVersion: 1\nArchitecture: arm64\nDepends: libbase1\nFilename: pool/main/f/ffmpeg.deb\nSize: 3\nSHA256: " + strings.Repeat("1", 64) + "\n\nPackage: libbase1\nVersion: 2.0-1\nArchitecture: arm64\nFilename: pool/main/l/libbase1.deb\nSize: 4\nSHA256: " + strings.Repeat("2", 64) + "\n\n",
- "/debian/20261116T000000Z/dists/trixie-updates/main/binary-arm64/Packages.xz": "",
- "/debian-security/20261116T000000Z/dists/trixie-security/main/binary-arm64/Packages.xz": "Package: ffmpeg\nVersion: 2\nArchitecture: arm64\nDepends: libbase1\nFilename: pool/updates/main/f/ffmpeg.deb\nSize: 5\nSHA256: " + strings.Repeat("3", 64) + "\n\n",
+ key, _ := signingKeys()
+ var ring bytes.Buffer
+ if err := key.Serialize(&ring); err != nil {
+ t.Fatal(err)
+ }
+ a := &signedArchive{files: map[string][]byte{}, base: reg.host() + "/engine@sha256:" + digestOf(index)}
+ a.keyring = filepath.Join(t.TempDir(), "archive.gpg")
+ if err := os.WriteFile(a.keyring, ring.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ for _, s := range []struct{ archive, suite, packages string }{
+ {"debian", "trixie", "Package: ffmpeg\nVersion: 1\nArchitecture: arm64\nDepends: libbase1\nFilename: pool/main/f/ffmpeg.deb\nSize: 3\nSHA256: " + strings.Repeat("1", 64) + "\n\nPackage: libbase1\nVersion: 2.0-1\nArchitecture: arm64\nFilename: pool/main/l/libbase1.deb\nSize: 4\nSHA256: " + strings.Repeat("2", 64) + "\n\n"},
+ {"debian", "trixie-updates", ""},
+ {"debian-security", "trixie-security", "Package: ffmpeg\nVersion: 2\nArchitecture: arm64\nDepends: libbase1\nFilename: pool/updates/main/f/ffmpeg.deb\nSize: 5\nSHA256: " + strings.Repeat("3", 64) + "\n\n"},
+ } {
+ compressed := xzBytes(t, []byte(s.packages))
+ root := "/" + s.archive + "/" + testSnapshot + "/dists/" + s.suite + "/"
+ a.files[root+packagesIndex] = compressed
+ a.files[root+"InRelease"] = clearsigned(t, key, releaseText(s.suite, testReleaseDate, testReleaseUntil, compressed))
+ if s.suite == "trixie" {
+ a.index = compressed
+ }
}
- archive := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- body, ok := packages[req.URL.Path]
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ a.hits.Add(1)
+ body, ok := a.files[req.URL.Path]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
- _, _ = w.Write(xzBytes(t, []byte(body)))
+ _, _ = w.Write(body)
}))
- defer archive.Close()
+ t.Cleanup(srv.Close)
+ a.url = srv.URL
+ return a
+}
+
+func (a *signedArchive) options(out string) lockOptions {
+ return lockOptions{Snapshot: testSnapshot, Base: a.base, Out: out, Keyring: a.keyring, Archive: a.url}
+}
+func TestLockCommandEndToEnd(t *testing.T) {
+ a := newSignedArchive(t)
out := filepath.Join(t.TempDir(), "debs.lock")
- ref := reg.host() + "/engine@sha256:" + digestOf(index)
- err := writeLock(t.Context(), lockOptions{Snapshot: "20261116T000000Z", Base: ref, Out: out, Archive: archive.URL})
- if err != nil {
+ if err := writeLock(t.Context(), a.options(out)); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(out)
if err != nil {
t.Fatal(err)
}
- want := "# snapshot 20261116T000000Z\n# base " + ref + "\n" +
- "ffmpeg\t2\t" + archive.URL + "/debian-security/20261116T000000Z/pool/updates/main/f/ffmpeg.deb\t" + strings.Repeat("3", 64) + "\t5\n"
+ want := "# snapshot " + testSnapshot + "\n# base " + a.base + "\n" +
+ "ffmpeg\t2\t" + a.url + "/debian-security/" + testSnapshot + "/pool/updates/main/f/ffmpeg.deb\t" + strings.Repeat("3", 64) + "\t5\n"
if string(data) != want {
t.Fatalf("lock:\n%s\nwant:\n%s", data, want)
}
}
+// TestLockRefusesAnUnauthenticatedIndex: nothing reaches the package
+// resolver unless Debian's keys vouch for the release and the release for
+// the index's exact bytes.
+func TestLockRefusesAnUnauthenticatedIndex(t *testing.T) {
+ key, stranger := signingKeys()
+ signed := func(a *signedArchive, text string) { a.files[trixieRelease] = clearsigned(t, key, text) }
+ for name, c := range map[string]struct {
+ mutate func(a *signedArchive)
+ want error
+ }{
+ "a changed release": {func(a *signedArchive) {
+ a.files[trixieRelease] = bytes.Replace(a.files[trixieRelease], []byte("Origin: Debian"), []byte("Origin: Debiam"), 1)
+ }, errBadRelease},
+ "another key's signature": {func(a *signedArchive) {
+ a.files[trixieRelease] = clearsigned(t, stranger, releaseText("trixie", testReleaseDate, testReleaseUntil, a.index))
+ }, errBadRelease},
+ "no signature": {func(a *signedArchive) {
+ a.files[trixieRelease] = []byte(releaseText("trixie", testReleaseDate, testReleaseUntil, a.index))
+ }, errBadRelease},
+ "text before the signed message": {func(a *signedArchive) {
+ a.files[trixieRelease] = append([]byte("Codename: trixie\n\n"), a.files[trixieRelease]...)
+ }, errBadRelease},
+ "text after the signature": {func(a *signedArchive) {
+ a.files[trixieRelease] = append(slices.Clone(a.files[trixieRelease]), []byte("Codename: trixie\n")...)
+ }, errBadRelease},
+ "another suite's release": {func(a *signedArchive) {
+ signed(a, releaseText("bookworm", testReleaseDate, testReleaseUntil, a.index))
+ }, errBadRelease},
+ "expired at the snapshot": {func(a *signedArchive) {
+ signed(a, releaseText("trixie", testReleaseDate, "Fri, 10 Jan 2020 00:00:00 UTC", a.index))
+ }, errBadRelease},
+ "dated after the snapshot": {func(a *signedArchive) {
+ signed(a, releaseText("trixie", "Mon, 20 Jan 2020 00:00:00 UTC", testReleaseUntil, a.index))
+ }, errBadRelease},
+ "a release that omits the index": {func(a *signedArchive) {
+ signed(a, "Origin: Debian\nCodename: trixie\nDate: "+testReleaseDate+"\nSHA256:\n "+strings.Repeat("a", 64)+" 1 other/Packages.xz\n")
+ }, errBadRelease},
+ "a substituted index of the same size": {func(a *signedArchive) {
+ forged := slices.Clone(a.index)
+ forged[len(forged)/2] ^= 0xff
+ a.files[trixieIndex] = forged
+ }, errBadHash},
+ "an index of another size": {func(a *signedArchive) {
+ a.files[trixieIndex] = append(slices.Clone(a.index), 0)
+ }, errBadHash},
+ } {
+ t.Run(name, func(t *testing.T) {
+ a := newSignedArchive(t)
+ c.mutate(a)
+ out := filepath.Join(t.TempDir(), "debs.lock")
+ if err := writeLock(t.Context(), a.options(out)); !errors.Is(err, c.want) {
+ t.Fatalf("writeLock = %v, want %v", err, c.want)
+ }
+ if _, err := os.Stat(out); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("a refused run wrote the lock")
+ }
+ })
+ }
+}
+
+// TestLockAcceptsAReleaseWithNoExpiry: Debian's stable suite has no
+// Valid-Until. TestLockCommandEndToEnd covers one that expired in 2020,
+// long before today but after its snapshot.
+func TestLockAcceptsAReleaseWithNoExpiry(t *testing.T) {
+ key, _ := signingKeys()
+ a := newSignedArchive(t)
+ a.files[trixieRelease] = clearsigned(t, key, releaseText("trixie", testReleaseDate, "", a.index))
+ if err := writeLock(t.Context(), a.options(filepath.Join(t.TempDir(), "debs.lock"))); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestCheckGPGVStatus: Debian signs with several keys. One key we do not
+// hold is normal; one signature that fails is not.
+func TestCheckGPGVStatus(t *testing.T) {
+ const good = "[GNUPG:] GOODSIG AAAA Debian\n[GNUPG:] VALIDSIG BBBB 2026-11-16\n"
+ for name, c := range map[string]struct {
+ status string
+ ok bool
+ }{
+ "one good signature": {good, true},
+ "a good one and an unknown": {"[GNUPG:] ERRSIG CCCC 1 8 01 0 9\n[GNUPG:] NO_PUBKEY CCCC\n" + good, true},
+ "a good one and a bad one": {good + "[GNUPG:] BADSIG DDDD Debian\n", false},
+ "only an unknown key": {"[GNUPG:] ERRSIG CCCC 1 8 01 0 9\n[GNUPG:] NO_PUBKEY CCCC\n", false},
+ "an expired key": {"[GNUPG:] EXPKEYSIG AAAA Debian\n[GNUPG:] VALIDSIG BBBB 2026-11-16\n", false},
+ "a revoked key": {"[GNUPG:] REVKEYSIG AAAA Debian\n[GNUPG:] VALIDSIG BBBB 2026-11-16\n", false},
+ "good without a valid line": {"[GNUPG:] GOODSIG AAAA Debian\n", false},
+ "nothing": {"", false},
+ "a status word in other text": {"GOODSIG AAAA\nVALIDSIG BBBB\n", false},
+ } {
+ t.Run(name, func(t *testing.T) {
+ err := checkGPGVStatus([]byte(c.status))
+ if c.ok && err != nil {
+ t.Fatalf("refused: %v", err)
+ }
+ if !c.ok && !errors.Is(err, errBadRelease) {
+ t.Fatalf("checkGPGVStatus = %v, want errBadRelease", err)
+ }
+ })
+ }
+}
+
+func TestLockRefusesToRunWithoutGPGV(t *testing.T) {
+ a := newSignedArchive(t)
+ t.Setenv("PATH", t.TempDir())
+ out := filepath.Join(t.TempDir(), "debs.lock")
+ if err := writeLock(t.Context(), a.options(out)); !errors.Is(err, errNoGPGV) {
+ t.Fatalf("writeLock = %v, want errNoGPGV", err)
+ }
+ if got := a.hits.Load(); got != 0 {
+ t.Fatalf("the archive saw %d requests", got)
+ }
+}
+
+func TestLockRefusesToRunWithoutAKeyring(t *testing.T) {
+ requireGPGV(t)
+ a := newSignedArchive(t)
+ o := a.options(filepath.Join(t.TempDir(), "debs.lock"))
+ for _, keyring := range []string{"", filepath.Join(t.TempDir(), "absent.gpg")} {
+ o.Keyring = keyring
+ if err := writeLock(t.Context(), o); !errors.Is(err, errBadLock) {
+ t.Fatalf("writeLock(keyring %q) = %v, want errBadLock", keyring, err)
+ }
+ }
+ if got := a.hits.Load(); got != 0 {
+ t.Fatalf("the archive saw %d requests", got)
+ }
+}
+
// TestRegistryAnswersAnAnonymousChallenge: Docker Hub answers a first pull
// 401 and names the token service to ask.
func TestRegistryAnswersAnAnonymousChallenge(t *testing.T) {
@@ -808,10 +1069,14 @@ func TestRegistryAnswersAnAnonymousChallenge(t *testing.T) {
func requireXZ(t *testing.T) {
t.Helper()
if _, err := exec.LookPath("xz"); err != nil {
- if os.Getenv("CI") != "" {
- t.Fatal("xz is required in CI")
- }
- t.Skip("no xz on this machine")
+ t.Skip("skipped: xz is not installed here (real image builds still need it)")
+ }
+}
+
+func requireGPGV(t *testing.T) {
+ t.Helper()
+ if _, err := exec.LookPath("gpgv"); err != nil {
+ t.Skip("skipped: gpgv is not installed here (mediaimage lock still needs it)")
}
}
@@ -1170,6 +1435,207 @@ func TestBuildNeverWritesADirectoryOverABaseSymlink(t *testing.T) {
}
}
+// TestImageHoldsNoPrivilegedPaths: setuid and setgid are gone from the
+// image as it runs, in the base's files as well as the packages'.
+func TestImageHoldsNoPrivilegedPaths(t *testing.T) {
+ f := newFixture(t)
+ su := arm(t, "libc.so.6")
+ f.base = append(f.base,
+ fx{name: "usr/bin/su", typ: tar.TypeReg, mode: 0o4755, body: su},
+ fx{name: "usr/bin/su-alias", typ: tar.TypeLink, mode: 0o4755, link: "usr/bin/su"},
+ fx{name: "usr/bin/chage", typ: tar.TypeReg, mode: 0o2755, body: []byte("chage")},
+ fx{name: "var/mail/", typ: tar.TypeDir, mode: 0o2775},
+ fx{name: "tmp/", typ: tar.TypeDir, mode: 0o1777},
+ )
+ f.debs["libsetuid"] = []fx{{name: "./usr/bin/from-a-package", typ: tar.TypeReg, mode: 0o6755, body: []byte("pkg")}}
+ f.build(t)
+ debs, top := builtEntries(t, f.out)
+ for name, want := range map[string]int64{"usr/bin/su": 0o755, "usr/bin/su-alias": 0o755, "usr/bin/chage": 0o755, "var/mail/": 0o775} {
+ e, ok := top[name]
+ if !ok {
+ t.Errorf("%s has no unprivileged copy", name)
+ continue
+ }
+ if e.hdr.Mode != want || e.hdr.Uid != 1000 || e.hdr.Gid != 1000 {
+ t.Errorf("%s = mode %o owner %d:%d", name, e.hdr.Mode, e.hdr.Uid, e.hdr.Gid)
+ }
+ }
+ if !bytes.Equal(top["usr/bin/su"].body, su) {
+ t.Error("the copy of su does not hold su's bytes")
+ }
+ if e := debs["usr/bin/from-a-package"]; e.hdr.Mode != 0o755 {
+ t.Errorf("the package's file has mode %o", e.hdr.Mode)
+ }
+ if _, ok := top["tmp/"]; ok {
+ t.Error("the sticky /tmp was rewritten")
+ }
+}
+
+func TestCheckImageRefusesAPrivilegedPath(t *testing.T) {
+ for name, n := range map[string]*node{
+ "setuid file": {kind: kindFile, mode: 0o4755},
+ "setgid file": {kind: kindFile, mode: 0o2755},
+ "setgid dir": {kind: kindDir, mode: 0o2775},
+ } {
+ root := newTree()
+ root.nodes["usr/bin/left-behind"] = n
+ if err := checkImage(root); !errors.Is(err, errPrivilegedMode) {
+ t.Errorf("%s: checkImage = %v, want errPrivilegedMode", name, err)
+ }
+ }
+}
+
+// TestStatusRecordsEveryLockedPackage: scanners and dpkg read this file to
+// learn what the image holds.
+func TestStatusRecordsEveryLockedPackage(t *testing.T) {
+ f := newFixture(t)
+ f.debs["libc6"] = []fx{file("./usr/share/doc/libc6/copyright", []byte("c"))}
+ for i, entry := range f.base {
+ if entry.name == "var/lib/dpkg/status" {
+ f.base[i].body = []byte("Package: libc6\nStatus: install ok installed\nArchitecture: arm64\nVersion: 2.41-12\n\n" +
+ "Package: base-files\nStatus: install ok installed\nArchitecture: arm64\nVersion: 13.8\n\n")
+ }
+ }
+ l := f.write(t)
+ if _, err := buildImage(t.Context(), f.options()); err != nil {
+ t.Fatal(err)
+ }
+ debs, _ := builtEntries(t, f.out)
+ text := string(debs["var/lib/dpkg/status"].body)
+ installed, err := parseStatus(strings.NewReader(text))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range l.Entries {
+ if installed[e.Package] != e.Version {
+ t.Errorf("%s is recorded at %q, want %q", e.Package, installed[e.Package], e.Version)
+ }
+ for _, field := range []string{"Package: " + e.Package + "\nStatus: install ok installed\n", "Source: src-" + e.Package + "\n"} {
+ if !strings.Contains(text, field) {
+ t.Errorf("no %q in the status file", field)
+ }
+ }
+ }
+ if !strings.Contains(text, "Architecture: arm64\nMaintainer: Debian\nDescription: a fixture\n spread over two lines\n") {
+ t.Errorf("the control fields did not survive:\n%s", text)
+ }
+ if installed["base-files"] != "13.8" {
+ t.Error("a base record that nothing replaced is gone")
+ }
+ if strings.Contains(text, "2.41-12") || strings.Count(text, "Package: libc6\n") != 1 {
+ t.Errorf("the superseded base record survived:\n%s", text)
+ }
+}
+
+func TestBuildRefusesAControlFileThatIsNotTheLockedPackage(t *testing.T) {
+ for name, control := range map[string]string{
+ "another package": strings.Replace(fixtureControl("ffmpeg"), "Package: ffmpeg", "Package: evil", 1),
+ "another version": strings.Replace(fixtureControl("ffmpeg"), fixtureVersion, "1.0", 1),
+ "another architecture": strings.Replace(fixtureControl("ffmpeg"), "Architecture: arm64", "Architecture: amd64", 1),
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFixture(t)
+ f.control = map[string]string{"ffmpeg": control}
+ if err := f.buildErr(t); !errors.Is(err, errBadDeb) {
+ t.Fatalf("build = %v, want errBadDeb", err)
+ }
+ })
+ }
+}
+
+func TestBuildEnforcesTheReleaseToolchain(t *testing.T) {
+ f := newFixture(t)
+ f.write(t)
+ saved := toolchain
+ t.Cleanup(func() { toolchain = saved })
+ toolchain.tool = func() string { return "go1.26.9" }
+ if _, err := buildImage(t.Context(), f.options()); !errors.Is(err, errToolchain) {
+ t.Fatalf("a build on another Go = %v, want errToolchain", err)
+ }
+ toolchain.tool = saved.tool
+ toolchain.binary = func(string) (string, error) { return "go1.26.11", nil }
+ if _, err := buildImage(t.Context(), f.options()); !errors.Is(err, errToolchain) {
+ t.Fatalf("a binary from another Go = %v, want errToolchain", err)
+ }
+ toolchain.binary = binaryGoVersion
+ if _, err := buildImage(t.Context(), f.options()); !errors.Is(err, errToolchain) {
+ t.Fatalf("a binary with no Go version = %v, want errToolchain", err)
+ }
+}
+
+func TestBinaryGoVersionReadsARealBinary(t *testing.T) {
+ self, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := binaryGoVersion(self)
+ if err != nil || got != runtime.Version() {
+ t.Fatalf("binaryGoVersion = %q, %v, want %q", got, err, runtime.Version())
+ }
+}
+
+// TestReleaseGoVersionIsTheCIPin: one Go for CI, releases and this image.
+func TestReleaseGoVersionIsTheCIPin(t *testing.T) {
+ data, err := os.ReadFile(filepath.Join("..", "..", ".amadan", "go-toolchain.sh"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(data), "\nGOTOOLCHAIN="+releaseGoVersion+"+auto\n") {
+ t.Fatalf("releaseGoVersion %s is not the pin in .amadan/go-toolchain.sh", releaseGoVersion)
+ }
+}
+
+// TestCoreAbbrevDoesNotChangeTheBinary builds carlos-media through make
+// under two core.abbrev settings and compares the bytes.
+func TestCoreAbbrevDoesNotChangeTheBinary(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipped in -short: it cross-compiles carlos-media")
+ }
+ for _, tool := range []string{"make", "git"} {
+ if _, err := exec.LookPath(tool); err != nil {
+ t.Skipf("skipped: %s is not installed here", tool)
+ }
+ }
+ root := filepath.Join("..", "..")
+ env := func(abbrev string) []string {
+ var out []string
+ for _, kv := range os.Environ() {
+ if !strings.HasPrefix(kv, "MAKE") && !strings.HasPrefix(kv, "GIT_CONFIG") {
+ out = append(out, kv)
+ }
+ }
+ return append(out, "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=core.abbrev", "GIT_CONFIG_VALUE_0="+abbrev)
+ }
+ short := func(abbrev string) string {
+ cmd := exec.Command("git", "-C", root, "rev-parse", "--short", "HEAD")
+ cmd.Env = env(abbrev)
+ out, err := cmd.Output()
+ if err != nil {
+ t.Skipf("skipped: this is not a git checkout: %v", err)
+ }
+ return strings.TrimSpace(string(out))
+ }
+ if short("7") == short("20") {
+ t.Fatal("core.abbrev did not reach git, so this test proves nothing")
+ }
+ build := func(abbrev string) []byte {
+ out := filepath.Join(t.TempDir(), "carlos-media")
+ cmd := exec.Command("make", "-C", root, "media-image-binary", "MEDIA_IMAGE_BINARY="+out)
+ cmd.Env = env(abbrev)
+ if log, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("make: %v\n%s", err, log)
+ }
+ data, err := os.ReadFile(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+ }
+ if !bytes.Equal(build("7"), build("20")) {
+ t.Fatal("core.abbrev changed carlos-media's bytes")
+ }
+}
+
func TestBuildMaterialisesHardlinks(t *testing.T) {
f := newFixture(t)
f.debs["libhard"] = []fx{
@@ -1438,6 +1904,146 @@ func TestPushVerifiesTheDigestTheRegistryHolds(t *testing.T) {
}
}
+// TestRepeatPushVerifiesTheDigest: a tag that already holds this image is
+// not taken on trust. The digest must read back too.
+func TestRepeatPushVerifiesTheDigest(t *testing.T) {
+ f := newFixture(t)
+ info := f.build(t)
+ reg := newFakeRegistry(t)
+ if _, err := pushImage(t.Context(), pushOptionsFor(reg, f.out, "v0.40.0")); err != nil {
+ t.Fatal(err)
+ }
+ reg.failDigest = true
+ _, err := pushImage(t.Context(), pushOptionsFor(reg, f.out, "v0.40.0"))
+ var status *statusError
+ if !errors.As(err, &status) || status.Code != http.StatusInternalServerError {
+ t.Fatalf("repeat push with a failing digest lookup = %v", err)
+ }
+ reg.failDigest = false
+ delete(reg.manifests, info.Digest)
+ if _, err := pushImage(t.Context(), pushOptionsFor(reg, f.out, "v0.40.0")); !errors.Is(err, errDigestMismatch) {
+ t.Fatalf("repeat push with the digest gone = %v, want errDigestMismatch", err)
+ }
+ if len(reg.puts) != 1 {
+ t.Fatalf("a repeat push wrote the tag: %v", reg.puts)
+ }
+}
+
+// credentialTrap is another origin that records every request it gets.
+func credentialTrap(t *testing.T) (*httptest.Server, *atomic.Int32) {
+ t.Helper()
+ var hits atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ hits.Add(1)
+ w.WriteHeader(http.StatusAccepted)
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &hits
+}
+
+func TestPushKeepsCredentialsOnTheRegistry(t *testing.T) {
+ f := newFixture(t)
+ f.build(t)
+ trap, hits := credentialTrap(t)
+ for name, arrange := range map[string]func(reg *fakeRegistry){
+ "an upload session elsewhere": func(reg *fakeRegistry) {
+ reg.location = func(stage string) string {
+ if stage == "start" {
+ return trap.URL + "/v2/engine/blobs/uploads/1"
+ }
+ return "/v2/engine/blobs/uploads/1"
+ }
+ },
+ "an upload's next step elsewhere": func(reg *fakeRegistry) {
+ reg.location = func(stage string) string {
+ if stage == "data" {
+ return trap.URL + "/v2/engine/blobs/uploads/1"
+ }
+ return "/v2/engine/blobs/uploads/1"
+ }
+ },
+ "a location with its own credentials": func(reg *fakeRegistry) {
+ reg.location = func(string) string { return "http://user:pass@" + reg.host() + "/v2/engine/blobs/uploads/1" }
+ },
+ "no location": func(reg *fakeRegistry) {
+ reg.location = func(string) string { return "" }
+ },
+ "a redirect elsewhere": func(reg *fakeRegistry) { reg.redirect = trap.URL + "/stolen" },
+ } {
+ t.Run(name, func(t *testing.T) {
+ reg := newFakeRegistry(t)
+ arrange(reg)
+ _, err := pushImage(t.Context(), pushOptionsFor(reg, f.out, "v0.40.0"))
+ if !errors.Is(err, errUnsafeLocation) {
+ t.Fatalf("push = %v, want errUnsafeLocation", err)
+ }
+ if got := hits.Load(); got != 0 {
+ t.Fatalf("the other origin got %d requests", got)
+ }
+ if len(reg.puts) != 0 {
+ t.Fatalf("the manifest was written: %v", reg.puts)
+ }
+ })
+ }
+}
+
+// TestUploadRefusesADowngradeToHTTP: same host and port, but in the clear.
+func TestUploadRefusesADowngradeToHTTP(t *testing.T) {
+ f := newFixture(t)
+ f.build(t)
+ m, _ := readLayout(t, f.out)
+ var hits atomic.Int32
+ var srv *httptest.Server
+ srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ hits.Add(1)
+ switch req.Method {
+ case http.MethodHead:
+ w.WriteHeader(http.StatusNotFound)
+ default:
+ w.Header().Set("Location", "http://"+strings.TrimPrefix(srv.URL, "https://")+"/v2/engine/blobs/uploads/1")
+ w.WriteHeader(http.StatusAccepted)
+ }
+ }))
+ defer srv.Close()
+ saved := httpClient
+ httpClient = srv.Client()
+ t.Cleanup(func() { httpClient = saved })
+ reg := &registry{base: srv.URL, repo: "engine", basic: "Basic secret"}
+ if err := uploadBlob(t.Context(), reg, f.out, m.Layers[2]); !errors.Is(err, errUnsafeLocation) {
+ t.Fatalf("uploadBlob = %v, want errUnsafeLocation", err)
+ }
+ if got := hits.Load(); got != 2 {
+ t.Fatalf("the registry got %d requests, want the check and the session only", got)
+ }
+}
+
+func TestCheckOrigin(t *testing.T) {
+ reg := &registry{base: "https://registry.example"}
+ for target, ok := range map[string]bool{
+ "https://registry.example/v2/x": true,
+ "https://registry.example:443/v2/x": true,
+ "https://REGISTRY.example/v2/x": true,
+ "http://registry.example/v2/x": false,
+ "https://registry.example:8443/v2/x": false,
+ "https://other.example/v2/x": false,
+ "https://a.registry.example/v2/x": false,
+ "https://user@registry.example/v2/x": false,
+ "https://u:p@registry.example/v2/x": false,
+ } {
+ u, err := url.Parse(target)
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = reg.checkOrigin(u)
+ if ok && err != nil {
+ t.Errorf("%s refused: %v", target, err)
+ }
+ if !ok && !errors.Is(err, errUnsafeLocation) {
+ t.Errorf("%s = %v, want errUnsafeLocation", target, err)
+ }
+ }
+}
+
func TestPushRefusals(t *testing.T) {
f := newFixture(t)
f.build(t)
diff --git a/cmd/mediaimage/oci.go b/cmd/mediaimage/oci.go
index ed1191a16..7178e3505 100644
--- a/cmd/mediaimage/oci.go
+++ b/cmd/mediaimage/oci.go
@@ -40,6 +40,8 @@ var (
errBadHash = errors.New("sha256 mismatch")
// errBadBase is a base image this tool cannot use.
errBadBase = errors.New("bad base image")
+ // errUnsafeLocation is a registry sending credentials somewhere else.
+ errUnsafeLocation = errors.New("the registry pointed outside itself")
)
type ociPlatform struct {
@@ -165,8 +167,10 @@ func withRetry(ctx context.Context, f func() error) error {
}
func retryable(err error) bool {
- if errors.Is(err, errBadHash) || errors.Is(err, context.Canceled) {
- return false
+ for _, final := range []error{errBadHash, errBadRelease, errNoGPGV, errUnsafeLocation, context.Canceled} {
+ if errors.Is(err, final) {
+ return false
+ }
}
var status *statusError
if errors.As(err, &status) {
@@ -287,15 +291,53 @@ type registry struct {
func (r *registry) url(path string) string { return r.base + "/v2/" + r.repo + "/" + path }
-// do sends a request. An anonymous GET answered 401 fetches the token the
-// challenge names and is sent once more.
+// authority is a URL's host and port in one form, the scheme's default
+// port spelled out.
+func authority(u *url.URL) string {
+ port := u.Port()
+ if port == "" {
+ port = map[string]string{"https": "443", "http": "80"}[strings.ToLower(u.Scheme)]
+ }
+ return strings.ToLower(u.Hostname()) + ":" + port
+}
+
+// checkOrigin refuses a URL that would carry the registry's credentials
+// off the configured registry: another scheme, another host or port, or
+// credentials of its own. The registry's own base decides, so http is
+// possible only for a loopback registry (registryBase).
+func (r *registry) checkOrigin(u *url.URL) error {
+ base, err := url.Parse(r.base)
+ if err != nil {
+ return err
+ }
+ if u.User != nil || !strings.EqualFold(u.Scheme, base.Scheme) || authority(u) != authority(base) {
+ return fmt.Errorf("%w: %s://%s", errUnsafeLocation, u.Scheme, u.Hostname())
+ }
+ return nil
+}
+
+// do sends a request. With credentials, every request and every redirect
+// stays on the configured registry. An anonymous GET answered 401 fetches
+// the token the challenge names and is sent once more.
func (r *registry) do(req *http.Request) (*http.Response, error) {
+ client := httpClient
if r.basic != "" {
+ if err := r.checkOrigin(req.URL); err != nil {
+ return nil, err
+ }
+ guarded := *httpClient
+ guarded.CheckRedirect = func(next *http.Request, via []*http.Request) error {
+ if len(via) >= 10 {
+ return errors.New("too many redirects")
+ }
+ return r.checkOrigin(next.URL)
+ }
+ client = &guarded
req.Header.Set("Authorization", r.basic)
} else if r.bearer != "" {
req.Header.Set("Authorization", "Bearer "+r.bearer)
}
- resp, err := httpClient.Do(req)
+ resp, err := client.Do(req)
if err != nil || resp.StatusCode != http.StatusUnauthorized || r.basic != "" || r.bearer != "" || req.Method != http.MethodGet {
return resp, err
}
diff --git a/cmd/mediaimage/push.go b/cmd/mediaimage/push.go
index 10faad7a0..bfce0cc49 100644
--- a/cmd/mediaimage/push.go
+++ b/cmd/mediaimage/push.go
@@ -62,27 +62,36 @@ func pushImage(ctx context.Context, o pushOptions) (string, error) {
if got := digestBytes(held); got != digest {
return "", fmt.Errorf("%w: %s is %s, this image is %s", errTagReused, o.Tag, got, digest)
}
- return digest, nil
- }
- for _, blob := range blobs {
- err := withRetry(ctx, func() error { return uploadBlob(ctx, reg, o.Layout, blob) })
- if err != nil {
- return "", fmt.Errorf("blob %s: %w", blob.Digest, err)
+ } else {
+ for _, blob := range blobs {
+ err := withRetry(ctx, func() error { return uploadBlob(ctx, reg, o.Layout, blob) })
+ if err != nil {
+ return "", fmt.Errorf("blob %s: %w", blob.Digest, err)
+ }
+ }
+ if err := putManifest(ctx, reg, o.Tag, manifest); err != nil {
+ return "", err
}
}
- if err := putManifest(ctx, reg, o.Tag, manifest); err != nil {
+ if err := verifyPushed(ctx, reg, o.Tag, digest); err != nil {
return "", err
}
- for _, ref := range []string{digest, o.Tag} {
+ return digest, nil
+}
+
+// verifyPushed reads the image back by digest and by tag. A first push and
+// a repeat of a finished one both end here.
+func verifyPushed(ctx context.Context, reg *registry, tag, digest string) error {
+ for _, ref := range []string{digest, tag} {
held, err := fetchManifest(ctx, reg, ref)
if err != nil {
- return "", err
+ return err
}
if held == nil || digestBytes(held) != digest {
- return "", fmt.Errorf("%w: %s after the push, want %s", errDigestMismatch, ref, digest)
+ return fmt.Errorf("%w: %s after the push, want %s", errDigestMismatch, ref, digest)
}
}
- return digest, nil
+ return nil
}
// pushRegistry validates the options before anything reaches the network.
@@ -215,9 +224,13 @@ func uploadBlob(ctx context.Context, reg *registry, layout string, blob ociDescr
if err != nil {
return "", err
}
- loc, err := base.Parse(resp.Header.Get("Location"))
+ header := resp.Header.Get("Location")
+ if header == "" {
+ return "", fmt.Errorf("%w: an upload answer has no Location", errUnsafeLocation)
+ }
+ loc, err := base.Parse(header)
if err != nil {
- return "", fmt.Errorf("upload location: %w", err)
+ return "", fmt.Errorf("%w: an upload Location does not parse", errUnsafeLocation)
}
return loc.String(), nil
}
diff --git a/cmd/mediaimage/release.go b/cmd/mediaimage/release.go
new file mode 100644
index 000000000..2cabc2f95
--- /dev/null
+++ b/cmd/mediaimage/release.go
@@ -0,0 +1,254 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var (
+ // errNoGPGV is a lock run on a machine that cannot check signatures.
+ errNoGPGV = errors.New("gpgv is required to verify Debian's signatures")
+ // errBadRelease is a suite's release file that Debian's keys do not
+ // vouch for, or that does not describe the requested snapshot.
+ errBadRelease = errors.New("unauthenticated release")
+)
+
+const (
+ clearsignHeader = "-----BEGIN PGP SIGNED MESSAGE-----"
+ signatureHeader = "-----BEGIN PGP SIGNATURE-----"
+ signatureFooter = "-----END PGP SIGNATURE-----"
+
+ packagesIndex = "main/binary-arm64/Packages.xz"
+ // maxIndexBytes bounds a Packages.xz before its size is compared with
+ // the release's.
+ maxIndexBytes = 256 << 20
+)
+
+// verifyInRelease checks a clearsigned InRelease with gpgv against the
+// keyring and returns only the bytes the signature covers.
+func verifyInRelease(ctx context.Context, keyring string, data []byte) ([]byte, error) {
+ if err := checkClearsignShape(data); err != nil {
+ return nil, err
+ }
+ keyring, err := filepath.Abs(keyring)
+ if err != nil {
+ return nil, err
+ }
+ dir, err := os.MkdirTemp("", "mediaimage-gpgv-")
+ if err != nil {
+ return nil, err
+ }
+ defer os.RemoveAll(dir)
+ home := filepath.Join(dir, "home")
+ if err := os.Mkdir(home, 0o700); err != nil {
+ return nil, err
+ }
+ input, output := filepath.Join(dir, "InRelease"), filepath.Join(dir, "signed")
+ if err := os.WriteFile(input, data, 0o600); err != nil {
+ return nil, err
+ }
+ cmd := exec.CommandContext(ctx, "gpgv", "--homedir", home, "--keyring", keyring, "--status-fd", "1", "--output", output, input)
+ // The exit status is not the verdict: gpgv also fails when one of
+ // several signatures comes from a key outside the keyring, which is how
+ // a new archive key first appears. The status lines decide.
+ status, runErr := cmd.Output()
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ var execErr *exec.Error
+ if errors.As(runErr, &execErr) {
+ return nil, fmt.Errorf("%w: %w", errNoGPGV, runErr)
+ }
+ if err := checkGPGVStatus(status); err != nil {
+ return nil, err
+ }
+ signed, err := os.ReadFile(output)
+ if err != nil {
+ return nil, fmt.Errorf("%w: gpgv wrote no signed content", errBadRelease)
+ }
+ return signed, nil
+}
+
+// checkClearsignShape refuses a file with anything outside one signed
+// message, so unsigned text can never be read as part of the release.
+func checkClearsignShape(data []byte) error {
+ text := string(data)
+ if !strings.HasPrefix(text, clearsignHeader+"\n") ||
+ strings.Count(text, clearsignHeader) != 1 || strings.Count(text, signatureHeader) != 1 {
+ return fmt.Errorf("%w: not one clearsigned message", errBadRelease)
+ }
+ _, tail, ok := strings.Cut(text, signatureFooter)
+ if !ok || strings.TrimSpace(tail) != "" {
+ return fmt.Errorf("%w: text after the signature", errBadRelease)
+ }
+ return nil
+}
+
+// checkGPGVStatus accepts a release with at least one good signature from
+// a key in the keyring and no bad one.
+func checkGPGVStatus(status []byte) error {
+ good, valid := false, false
+ for _, line := range strings.Split(string(status), "\n") {
+ fields := strings.Fields(line)
+ if len(fields) < 2 || fields[0] != "[GNUPG:]" {
+ continue
+ }
+ switch fields[1] {
+ case "BADSIG":
+ return fmt.Errorf("%w: a signature does not match", errBadRelease)
+ case "GOODSIG":
+ good = true
+ case "VALIDSIG":
+ valid = true
+ }
+ }
+ if !good || !valid {
+ return fmt.Errorf("%w: no good signature from a Debian archive key", errBadRelease)
+ }
+ return nil
+}
+
+// indexHash is one file a release vouches for.
+type indexHash struct {
+ sum string
+ size int64
+}
+
+// release is the authenticated content of an InRelease.
+type release struct {
+ codename string
+ date, validUntil time.Time
+ files map[string]indexHash
+}
+
+// parseRelease reads signed release content.
+func parseRelease(content []byte) (release, error) {
+ var r release
+ count := 0
+ err := stanzas(bytes.NewReader(content), func(fields map[string]string) error {
+ count++
+ r.codename = fields["Codename"]
+ var err error
+ if r.date, err = parseReleaseTime(fields["Date"]); err != nil {
+ return fmt.Errorf("%w: Date: %w", errBadRelease, err)
+ }
+ if until := fields["Valid-Until"]; until != "" {
+ if r.validUntil, err = parseReleaseTime(until); err != nil {
+ return fmt.Errorf("%w: Valid-Until: %w", errBadRelease, err)
+ }
+ }
+ r.files = map[string]indexHash{}
+ list := strings.Fields(fields["SHA256"])
+ if len(list)%3 != 0 {
+ return fmt.Errorf("%w: the SHA256 list is damaged", errBadRelease)
+ }
+ for i := 0; i < len(list); i += 3 {
+ size, err := strconv.ParseInt(list[i+1], 10, 64)
+ if err != nil || !sha256Pattern.MatchString(list[i]) {
+ return fmt.Errorf("%w: the SHA256 list is damaged", errBadRelease)
+ }
+ r.files[list[i+2]] = indexHash{sum: list[i], size: size}
+ }
+ return nil
+ })
+ if err != nil {
+ return release{}, err
+ }
+ if count != 1 {
+ return release{}, fmt.Errorf("%w: not one release stanza", errBadRelease)
+ }
+ return r, nil
+}
+
+func parseReleaseTime(value string) (time.Time, error) {
+ t, err := time.Parse(time.RFC1123, value)
+ if err != nil {
+ return time.Parse(time.RFC1123Z, value)
+ }
+ return t, nil
+}
+
+// checkFor refuses a release that is not this suite's at this snapshot.
+//
+// Validity is judged at the snapshot's time, never the wall clock: a
+// snapshot is history, so its release has usually passed Valid-Until by the
+// time anyone reads it. That is the only allowance. The release must still
+// have been valid at the snapshot, and gpgv still judges the signing key
+// as it stands today.
+func (r release) checkFor(suite string, snapshot time.Time) error {
+ if r.codename != suite {
+ return fmt.Errorf("%w: the release is %q, want %q", errBadRelease, r.codename, suite)
+ }
+ if r.date.After(snapshot) {
+ return fmt.Errorf("%w: %s is dated after the snapshot", errBadRelease, suite)
+ }
+ if !r.validUntil.IsZero() && r.validUntil.Before(snapshot) {
+ return fmt.Errorf("%w: %s had expired at the snapshot", errBadRelease, suite)
+ }
+ return nil
+}
+
+// readBounded reads a URL into memory, at most limit bytes and one more.
+func readBounded(ctx context.Context, target string, limit int64) ([]byte, error) {
+ body, err := httpGet(ctx, target)
+ if err != nil {
+ return nil, err
+ }
+ defer body.Close()
+ return io.ReadAll(io.LimitReader(body, limit+1))
+}
+
+// fetchPackages downloads one suite's index and parses it only after
+// Debian's signature has vouched for the release and the release for the
+// index's exact bytes.
+func fetchPackages(ctx context.Context, origin, suite, keyring string, snapshot time.Time) ([]debPackage, error) {
+ var packages []debPackage
+ err := withRetry(ctx, func() error {
+ data, err := readBounded(ctx, origin+"dists/"+suite+"/InRelease", maxManifestBytes)
+ if err != nil {
+ return err
+ }
+ signed, err := verifyInRelease(ctx, keyring, data)
+ if err != nil {
+ return err
+ }
+ rel, err := parseRelease(signed)
+ if err != nil {
+ return err
+ }
+ if err := rel.checkFor(suite, snapshot); err != nil {
+ return err
+ }
+ want, ok := rel.files[packagesIndex]
+ if !ok || want.size > maxIndexBytes {
+ return fmt.Errorf("%w: %s does not list %s", errBadRelease, suite, packagesIndex)
+ }
+ index, err := readBounded(ctx, origin+"dists/"+suite+"/"+packagesIndex, want.size)
+ if err != nil {
+ return err
+ }
+ sum := sha256.Sum256(index)
+ if got := hex.EncodeToString(sum[:]); int64(len(index)) != want.size || got != want.sum {
+ return fmt.Errorf("%w: %s %s is not the file its release names", errBadHash, suite, packagesIndex)
+ }
+ xz, err := xzReader(ctx, bytes.NewReader(index))
+ if err != nil {
+ return err
+ }
+ defer xz.Close()
+ packages, err = parsePackages(xz, origin)
+ return err
+ })
+ return packages, err
+}
diff --git a/deploy/media-image/README.md b/deploy/media-image/README.md
index 5381f97bd..10ba68f2d 100644
--- a/deploy/media-image/README.md
+++ b/deploy/media-image/README.md
@@ -1,8 +1,8 @@
# The media engine image
-This is the arm64 container image that converts video and audio. It holds Debian 13’s slim base image, Debian’s ffmpeg with the libraries it needs, and the `carlos-media` binary. `debs.lock` pins every package by version and sha256, and it pins the base image by digest.
+This is the arm64 container image that converts video and audio. It holds Debian 13’s slim base image, Debian’s ffmpeg with the libraries it needs, and the `carlos-media` binary. `debs.lock` pins every package by version and sha256, and it pins the base image by digest. Nothing in the image is setuid or setgid.
-`cmd/mediaimage` assembles the image directly, with no container runtime. The same commit and lock give the same image digest when built with the same Go version.
+`cmd/mediaimage` assembles the image directly, with no container runtime. The same commit and lock give the same image digest.
## Build the image
@@ -10,9 +10,9 @@ This is the arm64 container image that converts video and audio. It holds Debian
make media-image
```
-You need Go and `xz`. The first build downloads the packages into `dist/media-image-cache`; later builds reuse them. The image lands in `dist/media-image`, and `dist/media-image/image.json` records its digest, build time and ffmpeg version.
+You need `xz` and the Go version releases use, which `.amadan/go-toolchain.sh` pins. The first build downloads the packages into `dist/media-image-cache`; later builds reuse them. The image lands in `dist/media-image`, and `dist/media-image/image.json` records its digest, build time and ffmpeg version.
-The build stops if a download doesn’t match the lock, or if any program in the image needs a library the image doesn’t hold.
+The build stops if a download doesn’t match the lock, if any program in the image needs a library the image doesn’t hold, or if it runs on a different Go version.
## Push it to a deployment
@@ -54,7 +54,7 @@ Debian’s security fixes reach the image through a new lock. Once a week, on a
make media-image-lock
```
-Commit only `debs.lock`. The next platform release builds an image from it. `carlos system media status` warns when the running image is more than 30 days old.
+You need `gpgv` and `xz`. The command checks Debian’s signature on each suite against `debian-archive-keyring.gpg` and stops if a signature or an index doesn’t match. Commit only `debs.lock`. The next platform release builds an image from it. `carlos system media status` warns when the running image is more than 30 days old.
The weekly run belongs to an amadan scheduled job if amadan CI has schedules. If it doesn’t, it belongs to a Paseo schedule on docs-t1. The media conversion spike report settles which one, and the first release sets it up.
@@ -64,6 +64,8 @@ To move to a newer Debian base image as well, name its digest:
make media-image-lock MEDIA_IMAGE_BASE=docker.io/library/debian@sha256:<digest>
```
+`debian-archive-keyring.gpg` is an unchanged copy of the keyring in Debian’s `debian-archive-keyring` 2025.1 package. It is committed so that the keys you trust show up in review. When Debian starts signing with a new key, replace the file with the one from a newer package.
+
## When a build stops on a library
Debian’s install scripts don’t run here, so links they would have made are missing. If a new package reaches a library through `update-alternatives`, add the link to `alternativeLinks` in `cmd/mediaimage/build.go`. If a package ships an optional plugin that can never load, add it to `unloadableFiles` in the same file.
diff --git a/deploy/media-image/debian-archive-keyring.gpg b/deploy/media-image/debian-archive-keyring.gpg
new file mode 100644
index 000000000..3370a11cc
Binary files /dev/null and b/deploy/media-image/debian-archive-keyring.gpg differ
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 71ef861db..c362cbba8 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -603,17 +603,23 @@ Operator-facing text from `cmd/mediaimage`, which builds and pushes the engine i
|---|---|
| `image.usage` | `usage: mediaimage <lock\|build\|push> [flags]` (pending Luna pass; plan 3 Task 8) |
| `image.error` | `mediaimage: %s`, the prefix of every failure on stderr (pending Luna pass; plan 3 Task 8) |
-| `image.flags` | `snapshot.debian.org timestamp, YYYYMMDDTHHMMSSZ`; `base image, docker.io/library/debian@sha256:<digest>`; `lock file to write`; `directory that keeps downloads between runs`; `lock file`; `carlos-media built for linux/arm64`; `image creation time, RFC 3339`; `directory to write the OCI layout to`; `OCI layout written by build`; `image repository, <registry>/<repo>`; `release tag; each release has its own, never reused` (pending Luna pass; plan 3 Task 8) |
-| `image.lock.refused` | `bad lock file: line %d: %s`, the reason one of `the snapshot is not YYYYMMDDTHHMMSSZ`, `the base is not pinned by digest`, `the lock starts with # snapshot and # base`, `packages are not sorted`, `a package line has five columns`, `the size is not a positive number`, `the sha256 is not 64 hex digits`, `the url is not https`, `the package or version is empty`; `bad lock file: no packages`; `bad lock file: no ffmpeg package`; `bad lock file: --snapshot is not YYYYMMDDTHHMMSSZ`; `bad lock file: --out is required` (pending Luna pass; plan 3 Task 8) |
+| `image.flags` | `snapshot.debian.org timestamp, YYYYMMDDTHHMMSSZ`; `base image, docker.io/library/debian@sha256:<digest>`; `lock file to write`; `Debian archive keyring that authenticates the snapshot`; `directory that keeps downloads between runs`; `lock file`; `carlos-media built for linux/arm64`; `image creation time, RFC 3339`; `directory to write the OCI layout to`; `OCI layout written by build`; `image repository, <registry>/<repo>`; `release tag; each release has its own, never reused` (pending Luna pass; plan 3 Task 8) |
+| `image.lock.refused` | `bad lock file: line %d: %s`, the reason one of `the snapshot is not YYYYMMDDTHHMMSSZ`, `the base is not pinned by digest`, `the lock starts with # snapshot and # base`, `packages are not sorted`, `a package line has five columns`, `the size is not a positive number`, `the sha256 is not 64 hex digits`, `the url is not https`, `the package or version is empty`; `bad lock file: no packages`; `bad lock file: no ffmpeg package`; `bad lock file: --snapshot is not YYYYMMDDTHHMMSSZ`; `bad lock file: --out is required`; `bad lock file: --keyring must name a keyring file: %s` (pending Luna pass; plan 3 Task 8) |
| `image.lock.unresolved` | `unresolved dependency: no package %s in the snapshot`; `unresolved dependency: %s depends on %s` (pending Luna pass; plan 3 Task 8) |
| `image.base.refused` | `bad base image: %q is not <registry>/<repo>@sha256:<digest>`; `bad base image: no linux/arm64 image`; `bad base image: the image is %s/%s`; `bad base image: %d layers and %d diff ids`; `bad base image: layer type %s`; `bad base image: the base image has no var/lib/dpkg/status`; `bad base image: the registry asked for %q sign-in`; `bad base image: the registry's token address is not https` (pending Luna pass; plan 3 Task 8) |
| `image.hash` | `sha256 mismatch: %s holds %s, want %s`; `sha256 mismatch: downloaded %s, want %s` (pending Luna pass; plan 3 Task 8) |
-| `image.deb.refused` | `bad deb: not an ar archive`; `bad deb: no data member`; `bad deb: a member header is damaged`; `bad deb: a member size is damaged`; `bad deb: a member is cut short`; `bad deb: %s is not a compression this tool reads` (pending Luna pass; plan 3 Task 8) |
+| `image.deb.refused` | `bad deb: not an ar archive`; `bad deb: no %s member`; `bad deb: no control file`; `bad deb: the control file of %s says %s %s for %s`; `bad deb: a member header is damaged`; `bad deb: a member size is damaged`; `bad deb: a member is cut short`; `bad deb: %s is not a compression this tool reads` (pending Luna pass; plan 3 Task 8) |
| `image.entry.refused` | `refused package entry: %s leaves the root`; `refused package entry: %s would delete files from a lower layer`; `refused package entry: hard link %s has no target in its package`; `refused package entry: %s is not a file, directory or link` (pending Luna pass; plan 3 Task 8) |
| `image.conflict` | `conflicting paths: two packages ship different %s`; `conflicting paths: a package directory %s covers a base file`; `conflicting paths: a package entry %s covers a base directory` (pending Luna pass; plan 3 Task 8) |
| `image.library` | `unresolved library: /%s needs %s`, joined by `; ` when there are several; `unresolved library: %s no longer ships %s` (pending Luna pass; plan 3 Task 8) |
| `image.executable` | `missing executable: /%s is not an arm64 program` (pending Luna pass; plan 3 Task 8) |
| `image.build.refused` | `--out, --binary and --cache are required`; `--created: %s`; `%s exists and is not an image layout` (pending Luna pass; plan 3 Task 8) |
+| `image.release.gpgv` | `gpgv is required to verify Debian's signatures: %s` (pending Luna pass; plan 3 Task 8) |
+| `image.release.refused` | `unauthenticated release: ` then one of `not one clearsigned message`, `text after the signature`, `a signature does not match`, `no good signature from a Debian archive key`, `gpgv wrote no signed content`, `not one release stanza`, `the SHA256 list is damaged`, `Date: %s`, `Valid-Until: %s`, `the release is %q, want %q`, `%s is dated after the snapshot`, `%s had expired at the snapshot`, `%s does not list %s` (pending Luna pass; plan 3 Task 8) |
+| `image.release.index` | `sha256 mismatch: %s %s is not the file its release names` (pending Luna pass; plan 3 Task 8) |
+| `image.privileged` | `setuid or setgid path in the image: %s`, the paths joined by `, ` (pending Luna pass; plan 3 Task 8) |
+| `image.toolchain` | `wrong Go toolchain: mediaimage runs on %s, releases use %s`; `wrong Go toolchain: %s was built with %s, releases use %s`; `wrong Go toolchain: %s names no Go version: %s` (pending Luna pass; plan 3 Task 8) |
+| `image.location` | `the registry pointed outside itself: %s://%s`; `the registry pointed outside itself: an upload answer has no Location`; `the registry pointed outside itself: an upload Location does not parse` (pending Luna pass; plan 3 Task 8) |
| `image.push.refused` | `push refused: CARLOS_REGISTRY_PASSWORD is not set`; `push refused: --tag must be a release tag`; `push refused: --repo must be <registry>/<repo>`; `push refused: the layout holds %d manifests` (pending Luna pass; plan 3 Task 8) |
| `image.push.tag` | `tag already holds another image: %s is %s, this image is %s` (pending Luna pass; plan 3 Task 8) |
| `image.push.digest` | `the registry holds a different image: %s after the push, want %s` (pending Luna pass; plan 3 Task 8) |