Files
w3cjandClaude Opus 5.5 1bd598c791 feat(cosign): ReleaseBuild, the co-signer's own build of a tag
ReleaseBuild rebuilds a release with the co-signer's own devvm: a new
clone of its checkout at its pinned commit (checked clean), the tag and
main fetched into it, the tag's SSH signature checked against the pinned
signers (VerifyTag), the tag naming itself and its commit on main, then
the clone's release.sh --tag with those signers as git's
allowedSignersFile, so release.sh checks the tag again. Nothing of the
tag's runs on the host.

- The clone, its git config and allowed signers and release.sh's log go
  in Src, the state folder's src/, which no build's container can reach,
  as release.sh and git run from it on the host; only release.sh's
  TMPDIR, where its containers work, goes in Work, the build folder. A
  container that could write the clone could otherwise edit release.sh
  as bash reads it, or set gpg.ssh.program or a filter in its .git/config
  for git to run on the host. release.sh's download cache, which only it
  reads, on the host, goes in the state folder too, so nothing that
  escaped a container can plant a link for its next download.
- Build returns Built: the checked tag, its tag object's ID, and the tag
  commit's Homebrew
  formula template (packaging/homebrew/devvm.rb) and CHANGELOG.md, read
  with git before release.sh runs, so no build's container can change
  them. The co-signer renders the tap's formulas and the release's notes
  from them and the signed SHA256SUMS.
- The checkout is root's, so git reads it as the co-signer's user only
  with it named safe on its own command line: its worktree for git
  status, and its .git for a clone, whose upload-pack checks that path.
  A full run on Fedora under the units found the clone refused with the
  worktree alone; TestCheckoutNamedSafe holds both.
- git runs with no system or global config, no hooks or fsmonitor, no
  replace objects, files and HTTPS alone, an environment of its own and
  its output capped.
- The structure test's commandsFree is now keyed by the command, then the
  file, so build.go may run git and no other guarded command; its
  execSites and statusFree entries, and the owners table, say why.

Tests: TestReleaseBuild (the template and changelog read, then a stub
release.sh that deletes the clone's .git, as a build could, and says
where it ran: its script in Src and its TMPDIR in Work, which fails with
the clone in Work, reverted once to see it; the tag object), the
existing refusals (an unpinned signer, off main, a dirty or moved
checkout, a lightweight tag, a tag naming another, release.sh failing),
TestCheckoutNamedSafe, and TestRulesFail's "another command in a file
commandsFree lists for git", which fails with commandsFree keyed by file
alone (reverted once to see it).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 21:36:37 -07:00

311 lines
12 KiB
Go

package cosign
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"syscall"
"time"
)
// A ReleaseBuilder rebuilds a release from its tag: every file but the
// signatures, into out, a folder that doesn't exist yet.
type ReleaseBuilder interface {
Build(ctx context.Context, tag, out string) (Built, error)
}
// Built is what a release's rebuild read from its tag, besides its files:
// the tag, checked, and two files of the tag's commit, read before
// anything of the tag's ran, so no build can change them: the Homebrew
// formulas' template, packaging/homebrew/devvm.rb, and CHANGELOG.md.
type Built struct {
Tag Tag
// Object is the tag object's ID, which the release is published only
// while the tag still names.
Object string
Formula []byte
Changelog []byte
}
// A BaseBuilder rebuilds a base from its index's commit and snapshot,
// every file the index lists, into out. Bases are built from phase 5 of
// the signing design on; until then NoBaseBuild stands in, and only a
// base whose every file a past rebuild matched is signed.
type BaseBuilder interface {
Build(ctx context.Context, i BaseIndex, out string) error
}
// errNoBaseBuild is a base that needs a rebuild, which the co-signer
// can't make yet.
var errNoBaseBuild = errors.New("the co-signer can't rebuild a base yet, so it signs only a base whose files it has checked before")
// NoBaseBuild is the BaseBuilder until bases are built: it builds none.
type NoBaseBuild struct{}
// Build refuses, as no base can be rebuilt yet.
func (NoBaseBuild) Build(context.Context, BaseIndex, string) error { return errNoBaseBuild }
// maxGitOutput bounds what the co-signer reads of a git command.
const maxGitOutput = 1 << 20
// ReleaseBuild rebuilds a release with the co-signer's own devvm: a new
// clone of its checkout at its pinned commit, the tag fetched into it
// and checked against the pinned signers, then that clone's release.sh
// --tag, which runs the tag's code only in its container. Nothing of the
// tag's runs on the host.
type ReleaseBuild struct {
// Checkout is the co-signer's devvm checkout, which must be at
// Commit and clean.
Checkout, Commit string
// GitURL is where the tag and main are fetched from.
GitURL string
// Signers are the pinned tag signers.
Signers []Signer
// Runtime is DEVVM_RELEASE_RUNTIME's value, or "".
Runtime string
// Src is the folder each build's clone of the checkout, its git config
// and its log go in, which the builds' containers can't reach: the
// clone's release.sh and .git are what the co-signer runs. Work is
// the folder each build's TMPDIR goes in, release.sh's own work,
// which the containers write. Cache is release.sh's download cache,
// which only release.sh, on the host, reads and writes, so it's in the
// state folder too, where nothing that escaped a container can plant a
// link for its next download.
Src, Work, Cache string
// Log gets each step and, when the build fails, the end of its log.
Log io.Writer
}
// Build rebuilds tag into out.
func (b ReleaseBuild) Build(ctx context.Context, tag, out string) (Built, error) {
if err := b.checkCheckout(ctx); err != nil {
return Built{}, err
}
private, err := os.MkdirTemp(b.Src, "build-")
if err != nil {
return Built{}, err
}
defer os.RemoveAll(private)
tmp, err := os.MkdirTemp(b.Work, "tmp-")
if err != nil {
return Built{}, err
}
defer os.RemoveAll(tmp)
src := filepath.Join(private, "src")
if _, err := b.git(ctx, "", "clone", "-q", "--no-hardlinks", "--no-checkout", "--", b.Checkout, src); err != nil {
return Built{}, err
}
if _, err := b.git(ctx, src, "checkout", "-q", "--detach", b.Commit); err != nil {
return Built{}, err
}
if _, err := b.git(ctx, src, "fetch", "-q", "--no-tags", "--", b.GitURL,
"+refs/tags/"+tag+":refs/tags/"+tag, "+refs/heads/main:refs/remotes/upstream/main"); err != nil {
return Built{}, fmt.Errorf("fetching %s and main from %s: %w", tag, b.GitURL, err)
}
t, err := b.checkTag(ctx, src, tag)
if err != nil {
return Built{}, err
}
obj, err := b.git(ctx, src, "rev-parse", "--verify", "refs/tags/"+tag)
if err != nil {
return Built{}, err
}
built := Built{Tag: t, Object: strings.TrimSpace(string(obj))}
// Read now, from the checked commit, before release.sh runs any of the
// tag's code.
if built.Formula, err = b.git(ctx, src, "show", t.Commit+":packaging/homebrew/devvm.rb"); err != nil {
return Built{}, fmt.Errorf("reading %s's formula template: %w", tag, err)
}
if built.Changelog, err = b.git(ctx, src, "show", t.Commit+":CHANGELOG.md"); err != nil {
return Built{}, fmt.Errorf("reading %s's CHANGELOG.md: %w", tag, err)
}
fmt.Fprintf(b.Log, "%s: signed by %s %s, at %s on main; building it with devvm %s's release.sh\n", tag, t.Signer.Fingerprint(), t.Signer.Comment, t.Commit, b.Commit[:12])
if err := b.release(ctx, private, tmp, src, tag, out); err != nil {
return Built{}, err
}
return built, nil
}
// checkCheckout is whether the co-signer's devvm checkout is at its
// pinned commit with nothing changed, so the release.sh it builds with
// is the one the maintainer checked.
func (b ReleaseBuild) checkCheckout(ctx context.Context) error {
head, err := b.git(ctx, b.Checkout, "rev-parse", "--verify", "HEAD^{commit}")
if err != nil {
return fmt.Errorf("reading the co-signer's devvm checkout %s: %w", b.Checkout, err)
}
if got := strings.TrimSpace(string(head)); got != b.Commit {
return fmt.Errorf("the co-signer's devvm checkout %s is at %s, not the pinned %s", b.Checkout, got, b.Commit)
}
status, err := b.git(ctx, b.Checkout, "--no-optional-locks", "status", "--porcelain", "--untracked-files=all")
if err != nil {
return err
}
if len(status) != 0 {
return fmt.Errorf("the co-signer's devvm checkout %s has changes: %s", b.Checkout, snippet(status))
}
return nil
}
// checkTag checks the fetched tag: its object signed by a pinned signer
// over its payload, naming tag and the commit the ref resolves to, and
// that commit on main.
func (b ReleaseBuild) checkTag(ctx context.Context, src, tag string) (Tag, error) {
raw, err := b.git(ctx, src, "cat-file", "tag", "refs/tags/"+tag)
if err != nil {
return Tag{}, fmt.Errorf("%s isn't an annotated tag: %w", tag, err)
}
t, err := VerifyTag(raw, b.Signers, tag)
if err != nil {
return Tag{}, err
}
commit, err := b.git(ctx, src, "rev-parse", "--verify", "refs/tags/"+tag+"^{commit}")
if err != nil {
return Tag{}, err
}
if got := strings.TrimSpace(string(commit)); got != t.Commit {
return Tag{}, fmt.Errorf("%s resolves to %s, not the %s its object names", tag, got, t.Commit)
}
if _, err := b.git(ctx, src, "merge-base", "--is-ancestor", t.Commit, "refs/remotes/upstream/main"); err != nil {
return Tag{}, fmt.Errorf("%s's commit %s isn't on main", tag, t.Commit)
}
return t, nil
}
// release runs the clone's release.sh --tag tag, which checks the tag
// with git and the pinned signers again, then builds it into out. Its
// git config, signers and log are in private, with the clone, src, and
// its TMPDIR is tmp, which the builds' containers write.
func (b ReleaseBuild) release(ctx context.Context, private, tmp, src, tag, out string) error {
gitconfig, signers := filepath.Join(private, "gitconfig"), filepath.Join(private, "allowed_signers")
if err := writeWhole(signers, AllowedSigners(b.Signers), 0o600); err != nil {
return err
}
if err := writeWhole(gitconfig, []byte("[gpg \"ssh\"]\n\tallowedSignersFile = "+signers+"\n"), 0o600); err != nil {
return err
}
logPath := filepath.Join(private, "release.log")
logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) //nolint:gosec // a new file in the build's own folder
if err != nil {
return err
}
defer logFile.Close()
cmd := exec.CommandContext(ctx, "bash", filepath.Join(src, "scripts", "release.sh"), "--tag", tag) //nolint:gosec // the pinned checkout's own release.sh, and a tag a release's draft names, which release.sh checks
cmd.Dir = src
cmd.Stdout, cmd.Stderr = logFile, logFile
// A run that's stopped stops release.sh with TERM, whose trap removes
// its container, and kills it only if it's still there a minute on.
cmd.Cancel = func() error {
return cmd.Process.Signal(syscall.SIGTERM) //nolint:forbidigo // release.sh, the co-signer's own child, which it waits for
}
cmd.WaitDelay = time.Minute
cmd.Env = append(cleanEnv(os.Environ()), "GIT_CONFIG_GLOBAL="+gitconfig, "GIT_CONFIG_NOSYSTEM=1",
"DEVVM_RELEASE_DIST="+out, "XDG_CACHE_HOME="+b.Cache, "TMPDIR="+tmp)
if b.Runtime != "" {
cmd.Env = append(cmd.Env, "DEVVM_RELEASE_RUNTIME="+b.Runtime)
}
if err := cmd.Run(); err != nil {
fmt.Fprintf(b.Log, "%s: release.sh --tag failed; the end of its log:\n%s\n", tag, tail(logPath, 4096))
return fmt.Errorf("release.sh --tag %s: %w", tag, err)
}
return nil
}
// git runs git in dir ("" for none) with args, and returns its output.
// It reads none of the machine's or the user's git config and none of
// the co-signer's environment but cleanEnv's, never asks on a terminal,
// reaches files and HTTPS alone, and runs no hook or fsmonitor that a
// repository's own config names.
func (b ReleaseBuild) git(ctx context.Context, dir string, args ...string) ([]byte, error) {
if dir != "" {
args = append([]string{"-C", dir}, args...)
}
cmd := exec.CommandContext(ctx, "git", args...) //nolint:gosec // the co-signer's own arguments: paths and refs it made, after --
// The checkout is root's, so git needs it named safe to read it as
// the co-signer's user: its worktree for git status, and its .git for
// a clone's upload-pack, which checks that path. Only the command
// line's config can, which also beats a repository's own.
kv := [][2]string{
{"safe.directory", b.Checkout},
{"safe.directory", filepath.Join(b.Checkout, ".git")},
{"core.fsmonitor", "false"},
{"core.hooksPath", os.DevNull},
}
cmd.Env = append(cleanEnv(os.Environ()), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL="+os.DevNull,
"GIT_TERMINAL_PROMPT=0", "GIT_ALLOW_PROTOCOL=file:https", "GIT_NO_REPLACE_OBJECTS=1", "GIT_CONFIG_COUNT="+strconv.Itoa(len(kv)))
for i, p := range kv {
n := strconv.Itoa(i)
cmd.Env = append(cmd.Env, "GIT_CONFIG_KEY_"+n+"="+p[0], "GIT_CONFIG_VALUE_"+n+"="+p[1])
}
var stdout, stderr limited
stdout.max, stderr.max = maxGitOutput, 4096
cmd.Stdout, cmd.Stderr = &stdout, &stderr
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, snippet(stderr.Bytes()))
}
if stdout.over {
return nil, fmt.Errorf("git %s wrote over %d bytes", strings.Join(args, " "), maxGitOutput)
}
return stdout.Bytes(), nil
}
// cleanEnv is the variables of env that git and release.sh get: the
// machine's and the container runtime's, never git's own, which would
// point git at another repository or config, nor release.sh's
// DEVVM_RELEASE_* switches, which the co-signer sets itself.
func cleanEnv(env []string) []string {
keep := []string{"PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TZ", "XDG_RUNTIME_DIR", "CONTAINER_HOST", "DOCKER_HOST"}
var out []string
for _, kv := range env {
if k, _, _ := strings.Cut(kv, "="); slices.Contains(keep, k) {
out = append(out, kv)
}
}
return out
}
// A limited is a buffer that keeps max bytes and drops the rest, noting
// that it did.
type limited struct {
bytes.Buffer
max int
over bool
}
func (l *limited) Write(p []byte) (int, error) {
if room := l.max - l.Len(); len(p) > room {
l.over = true
l.Buffer.Write(p[:max(room, 0)])
return len(p), nil
}
return l.Buffer.Write(p)
}
// tail is the last n bytes of the file at path.
func tail(path string, n int64) string {
f, err := os.Open(path) //nolint:gosec // the build's own log
if err != nil {
return err.Error()
}
defer f.Close()
if fi, err := f.Stat(); err == nil && fi.Size() > n {
if _, err := f.Seek(-n, io.SeekEnd); err != nil {
return err.Error()
}
}
data, err := io.ReadAll(io.LimitReader(f, n))
if err != nil {
return err.Error()
}
return string(data)
}