ez-agent-ruby/internal/launcher/launcher.go

package launcher

import (
	"archive/zip"
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"syscall"
	"unsafe"

	"git.cafe/ezterry/ez-agent/ez-agent-ruby/internal/runtimepayload"
)

const (
	manifestName    = runtimepayload.ManifestName
	supportedTarget = runtimepayload.Target
	maxArchive      = 128 << 20
	maxFiles        = runtimepayload.MaxFiles
	maxFile         = runtimepayload.MaxFile
	maxTotal        = runtimepayload.MaxTotal
)

const launcherHelp = `Usage:
  ez-agent-ruby [Ruby options] [script.rb] [arguments...]
  ez-agent-ruby --ez-runtime-home PATH [--save] --ez-runtime-install

ez-agent-ruby options:
  --ez-help                 Show this launcher help
  --ez-runtime-home PATH    Use PATH for this invocation (or "auto")
  --save                    Save runtime-home with a management command
  --ez-runtime-install      Install, or reuse a valid existing runtime
  --ez-runtime-info         Show runtime identity and location
  --ez-runtime-path         Show the selected runtime path
  --ez-runtime-verify       Verify the installed runtime without repairing it
  --ez-runtime-notices      Print bundled license notices without network access
  --ez-runtime-prune        Remove valid old immutable runtimes

All other options are passed unchanged to the private CRuby interpreter.
Launcher install/extraction/verify/notices are offline; executed Ruby is not a network sandbox.
`

const rubyHelpPreamble = `==================== ez-agent-ruby ====================
This command runs a private, curated CRuby runtime.
For ez-agent-specific options, run: ez-agent-ruby --ez-help
======================= Ruby help ======================

`

type Entry = runtimepayload.Entry
type Manifest = runtimepayload.Manifest

func parseCLI(args []string) (home string, save bool, cmd string, ruby []string, err error) {
	home = ""
	i := 0
	if len(args) > 0 && args[0] == "--ez-runtime-home" {
		if len(args) < 2 {
			return "", false, "", nil, errors.New("--ez-runtime-home requires a value")
		}
		home = args[1]
		i = 2
		if i < len(args) && args[i] == "--save" {
			save = true
			i++
		}
	}
	if i < len(args) && (args[i] == "--ez-help" || strings.HasPrefix(args[i], "--ez-runtime-")) {
		cmd = args[i]
		i++
		if i != len(args) {
			return "", false, "", nil, errors.New("launcher management commands accept no arguments")
		}
		switch cmd {
		case "--ez-help", "--ez-runtime-path", "--ez-runtime-info", "--ez-runtime-install", "--ez-runtime-verify", "--ez-runtime-notices", "--ez-runtime-prune":
		default:
			return "", false, "", nil, errors.New("unknown launcher command")
		}
		return home, save, cmd, nil, nil
	}
	if save {
		return "", false, "", nil, errors.New("--save requires a runtime-home management operation")
	}
	return home, false, "", args[i:], nil
}

func Run(payload []byte, args []string) error {
	override, save, cmd, rubyArgs, err := parseCLI(args)
	if err != nil {
		return err
	}
	if cmd == "--ez-help" {
		fmt.Print(launcherHelp)
		return nil
	}
	mergedRubyHelp := len(rubyArgs) == 1 && (rubyArgs[0] == "--help" || rubyArgs[0] == "-h")
	m, err := parsePayload(payload)
	if err != nil {
		return fmt.Errorf("invalid embedded payload: %w", err)
	}
	sum := sha256.Sum256(payload)
	id := hex.EncodeToString(sum[:12])
	sp, err := statePath()
	if err != nil {
		return err
	}
	st, err := loadState(sp)
	if err != nil {
		return fmt.Errorf("invalid launcher state %s: %w", sp, err)
	}
	home := st.RuntimeHome
	if override != "" {
		home = override
		if home != "auto" && !filepath.IsAbs(home) {
			return errors.New("runtime home must be auto or absolute")
		}
	}
	args = rubyArgs
	stateBase, err := canonicalBase(filepath.Dir(sp))
	if err != nil {
		return fmt.Errorf("unsafe data home: %w", err)
	}
	sp = filepath.Join(stateBase, filepath.Base(sp))
	root := filepath.Join(stateBase, "ruby")
	if home != "auto" {
		root, err = canonicalBase(home)
		if err != nil {
			return fmt.Errorf("unsafe runtime home: %w", err)
		}
	}
	base := filepath.Join(root, runtime.GOOS+"-"+runtime.GOARCH, id)
	if save {
		if st.RuntimeHome != home {
			// A new saved home invalidates the cached selection, even for a
			// management command that does not install the new runtime yet.
			st = State{Schema: 1, RuntimeHome: home}
		}
		if err = writeState(sp, st); err != nil {
			return err
		}
	}
	if (cmd == "--ez-runtime-path" || cmd == "--ez-runtime-verify") && override == "" && st.RuntimeID == id && st.PrivateExecutable != "" {
		base = filepath.Dir(filepath.Dir(st.PrivateExecutable))
	}
	if cmd == "--ez-runtime-path" {
		fmt.Println(base)
		return nil
	}
	if cmd == "--ez-runtime-verify" {
		if err = validateInstalled(base, m); err != nil {
			return fmt.Errorf("verification failed: %w", err)
		}
		fmt.Println("ok")
		return nil
	}
	if err = Install(payload, base); err != nil {
		return err
	}
	env := sanitizedEnv()
	// The private CRuby installation is content-addressed and may be shared by
	// public launchers. Pass this launcher's own runnable sibling to Ruby before
	// exec, replacing any inherited value from another installation.
	if webfetch := ownWebfetchSibling(); webfetch != "" {
		env = append(env, "EZ_AGENT_WEBFETCH="+webfetch)
	}
	exe := filepath.Join(base, "bin", "ruby")
	if home == "auto" {
		if e := probeExecutable(exe, env); e != nil {
			if !isNoExec(e) {
				return fmt.Errorf("runtime execution probe: %w", e)
			}
			fb, fe := runtimeFallbackHome()
			if fe != nil {
				return fmt.Errorf("preferred runtime is not executable and fallback unavailable: %w", fe)
			}
			base = filepath.Join(fb, runtime.GOOS+"-"+runtime.GOARCH, id)
			if err = Install(payload, base); err != nil {
				return err
			}
			exe = filepath.Join(base, "bin", "ruby")
			if e = probeExecutable(exe, env); e != nil {
				return fmt.Errorf("fallback runtime execution probe: %w", e)
			}
		}
	}
	selected := State{Schema: 1, RuntimeHome: st.RuntimeHome, RuntimeID: id, InstallationRoot: filepath.Dir(filepath.Dir(base)), PrivateExecutable: exe, PayloadSHA256: hex.EncodeToString(sum[:])}
	if selected != st {
		if err = writeState(sp, selected); err != nil {
			return err
		}
	}
	if cmd == "--ez-runtime-info" {
		fmt.Printf("ruby=%s\nruntime=%s\npath=%s\n", m.RubyVersion, id, base)
		return nil
	}
	if cmd == "--ez-runtime-install" {
		return nil
	}
	if cmd == "--ez-runtime-notices" {
		const rel = "share/ez-agent-ruby/NOTICES.txt"
		if err = noSymlinkComponents(base, rel); err != nil {
			return err
		}
		b, e := readNoFollowRegular(filepath.Join(base, filepath.FromSlash(rel)), 4<<20)
		if e != nil {
			return fmt.Errorf("read bundled notices: %w", e)
		}
		_, e = os.Stdout.Write(b)
		return e
	}
	if cmd == "--ez-runtime-prune" {
		n, e := prune(filepath.Dir(base), filepath.Base(base))
		if e != nil {
			return e
		}
		fmt.Printf("pruned=%d\n", n)
		return nil
	}
	if mergedRubyHelp {
		fmt.Print(rubyHelpPreamble)
	}
	return syscall.Exec(exe, append([]string{exe}, args...), env)
}

var ownWebfetchSibling = func() string {
	self, err := os.Executable()
	if err != nil {
		return ""
	}
	webfetch, err := filepath.Abs(filepath.Join(filepath.Dir(self), "ez-agent-webfetch"))
	if err != nil {
		return ""
	}
	if _, err := exec.LookPath(webfetch); err != nil {
		return ""
	}
	return webfetch
}

var probeExecutable = func(exe string, env []string) error {
	c := exec.Command(exe, "--version")
	c.Env = env
	c.Stdout = io.Discard
	c.Stderr = io.Discard
	return c.Run()
}

func renameAt(dirfd int, old, new string) error {
	op, _ := syscall.BytePtrFromString(old)
	np, _ := syscall.BytePtrFromString(new)
	_, _, errno := syscall.Syscall6(syscall.SYS_RENAMEAT, uintptr(dirfd), uintptr(unsafe.Pointer(op)), uintptr(dirfd), uintptr(unsafe.Pointer(np)), 0, 0)
	if errno != 0 {
		return errno
	}
	return nil
}
func openAt(dirfd int, name string, flags int) (int, error) {
	p, _ := syscall.BytePtrFromString(name)
	r, _, e := syscall.Syscall6(syscall.SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(flags), 0, 0, 0)
	if e != 0 {
		return -1, e
	}
	return int(r), nil
}
func unlinkAt(dirfd int, name string, dir bool) error {
	p, _ := syscall.BytePtrFromString(name)
	flags := 0
	if dir {
		flags = 0x200
	}
	_, _, e := syscall.Syscall(syscall.SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(flags))
	if e != 0 {
		return e
	}
	return nil
}
func removeTreeFD(fd int) error {
	f := os.NewFile(uintptr(fd), "prune-dir")
	if f == nil {
		return errors.New("invalid directory fd")
	}
	defer f.Close()
	names, e := f.Readdirnames(-1)
	if e != nil && e != io.EOF {
		return e
	}
	for _, name := range names {
		c, e := openAt(int(f.Fd()), name, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW)
		if e == nil {
			if e = removeTreeFD(c); e != nil {
				return e
			}
			if e = unlinkAt(int(f.Fd()), name, true); e != nil {
				return e
			}
			continue
		}
		if !errors.Is(e, syscall.ENOTDIR) && !errors.Is(e, syscall.ELOOP) {
			return e
		}
		if e = unlinkAt(int(f.Fd()), name, false); e != nil {
			return e
		}
	}
	return nil
}

var beforeQuarantineCleanup func(parentFD int, qname string)

var errConcurrentPruneChange = errors.New("prune candidate changed concurrently")

func quarantineAndDelete(parent *os.File, target, name string, want os.FileInfo) error {
	q, err := os.MkdirTemp(target, ".prune-")
	if err != nil {
		return err
	}
	qname := filepath.Base(q)
	qi, err := os.Lstat(q)
	if err != nil {
		return err
	}
	// Move the validated inode into a private, unpredictable quarantine directory.
	if err = renameAt(int(parent.Fd()), name, filepath.Join(qname, "runtime")); err != nil {
		return err
	}
	moved := filepath.Join(q, "runtime")
	got, err := os.Lstat(moved)
	if err != nil || !os.SameFile(want, got) {
		if err == nil {
			_ = renameAt(int(parent.Fd()), filepath.Join(qname, "runtime"), name)
		}
		return errors.New("prune candidate changed during quarantine")
	}
	qnow, err := os.Lstat(q)
	if err != nil || !os.SameFile(qi, qnow) {
		return errors.New("prune quarantine changed")
	}
	if beforeQuarantineCleanup != nil {
		beforeQuarantineCleanup(int(parent.Fd()), qname)
	}
	qfd, err := openAt(int(parent.Fd()), qname, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW)
	if err != nil {
		return errConcurrentPruneChange
	}
	qf := os.NewFile(uintptr(qfd), "quarantine")
	defer qf.Close()
	openedQI, err := qf.Stat()
	if err != nil {
		return err
	}
	if !os.SameFile(qi, openedQI) {
		return errConcurrentPruneChange
	}
	rfd, err := openAt(int(qf.Fd()), "runtime", syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW)
	if err != nil {
		return err
	}
	if err = removeTreeFD(rfd); err != nil {
		return err
	}
	if err = unlinkAt(int(qf.Fd()), "runtime", true); err != nil {
		return err
	}
	// Remove the quarantine name only if it still resolves to the opened inode. A replacement is preserved.
	current, err := openAt(int(parent.Fd()), qname, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW)
	if err != nil {
		return nil
	}
	cf := os.NewFile(uintptr(current), "current-quarantine")
	ci, _ := cf.Stat()
	cf.Close()
	if ci == nil || !os.SameFile(qi, ci) {
		return nil
	}
	return unlinkAt(int(parent.Fd()), qname, true)
}

func prune(target, keep string) (int, error) {
	if err := validateManagedDir(target); err != nil {
		return 0, fmt.Errorf("unsafe prune target: %w", err)
	}
	parent, e := os.OpenFile(target, os.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW, 0)
	if e != nil {
		return 0, e
	}
	defer parent.Close()
	ents, e := parent.ReadDir(-1)
	if e != nil {
		return 0, e
	}
	n := 0
	for _, x := range ents {
		name := x.Name()
		if name == keep || len(name) != 24 {
			continue
		}
		if _, e = hex.DecodeString(name); e != nil {
			continue
		}
		p := filepath.Join(target, name)
		i, e := os.Lstat(p)
		if e != nil || !i.IsDir() || i.Mode()&os.ModeSymlink != 0 {
			continue
		}
		mb, e := readNoFollowRegular(filepath.Join(p, manifestName), 1<<20)
		if e != nil {
			continue
		}
		m, e := runtimepayload.DecodeInstalledManifestStrict(mb)
		if e != nil {
			continue
		}
		if validateInstalled(p, m) != nil {
			continue
		}
		if e = quarantineAndDelete(parent, target, name, i); e != nil {
			// A concurrent replacement is preserved; other failures are actionable.
			if errors.Is(e, syscall.ENOENT) || errors.Is(e, errConcurrentPruneChange) || strings.Contains(e.Error(), "changed during quarantine") {
				continue
			}
			return n, e
		}
		n++
	}
	return n, nil
}

func sanitizedEnv() []string {
	blocked := map[string]bool{
		"RUBYOPT": true, "RUBYLIB": true, "RUBYPATH": true,
		"RUBYGEMS_GEMDEPS": true, "GEM_HOME": true, "GEM_PATH": true,
		"GEM_SPEC_CACHE": true, "EZ_AGENT_WEBFETCH": true,
	}
	env := []string{}
	for _, v := range os.Environ() {
		key := strings.SplitN(v, "=", 2)[0]
		if !blocked[key] && !strings.HasPrefix(key, "BUNDLE_") {
			env = append(env, v)
		}
	}
	return env
}

func Install(payload []byte, dst string) error {
	m, err := parsePayload(payload)
	if err != nil {
		return err
	}
	if err = secureParent(filepath.Dir(dst)); err != nil {
		return err
	}
	if self, e := os.Executable(); e == nil {
		self, _ = filepath.EvalSymlinks(self)
		dc, _ := filepath.Abs(dst)
		if self == dc {
			return errors.New("runtime destination aliases public launcher")
		}
		if di, de := os.Stat(dst); de == nil {
			if si, se := os.Stat(self); se == nil && os.SameFile(si, di) {
				return errors.New("runtime destination aliases public launcher")
			}
		}
	}
	if i, e := os.Lstat(dst); e == nil && i.Mode()&os.ModeSymlink != 0 {
		return errors.New("runtime destination is a symlink")
	}
	// Published runtimes are never modified in place. Valid reuse needs no
	// writer lock, including when the installation has been made read-only.
	if err = validateInstalled(dst, m); err == nil {
		return nil
	}
	lock, err := lockPath(dst + ".lock")
	if err != nil {
		return err
	}
	defer unlock(lock)
	if err = validateInstalled(dst, m); err == nil {
		return nil
	}
	if _, e := os.Lstat(dst); e == nil {
		return fmt.Errorf("existing runtime is incomplete or corrupt: %s: %w", dst, err)
	}
	parent := filepath.Dir(dst)
	tmp, err := os.MkdirTemp(parent, ".ez-agent-ruby-install-")
	if err != nil {
		return err
	}
	if err = os.Chmod(tmp, 0700); err != nil {
		return err
	}
	defer os.RemoveAll(tmp)
	if err = extract(payload, tmp, m); err != nil {
		return err
	}
	mb, _ := json.MarshalIndent(m, "", "  ")
	mb = append(mb, '\n')
	if err = os.WriteFile(filepath.Join(tmp, manifestName), mb, 0600); err != nil {
		return err
	}
	if err = validateInstalled(tmp, m); err != nil {
		return err
	}
	return os.Rename(tmp, dst)
}

func lockPath(p string) (*os.File, error) {
	if i, e := os.Lstat(p); e == nil && i.Mode()&os.ModeSymlink != 0 {
		return nil, errors.New("runtime lock is a symlink")
	}
	f, e := os.OpenFile(p, os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600)
	if e != nil {
		return nil, e
	}
	if e = syscall.Flock(int(f.Fd()), syscall.LOCK_EX); e != nil {
		f.Close()
		return nil, e
	}
	return f, nil
}
func unlock(f *os.File) { syscall.Flock(int(f.Fd()), syscall.LOCK_UN); f.Close() }
func validateManagedDir(p string) error {
	p = filepath.Clean(p)
	cur := string(os.PathSeparator)
	parts := strings.Split(strings.TrimPrefix(p, cur), string(os.PathSeparator))
	for _, part := range parts {
		if part == "" {
			continue
		}
		cur = filepath.Join(cur, part)
		i, e := os.Lstat(cur)
		if e != nil {
			return e
		}
		if !i.IsDir() || i.Mode()&os.ModeSymlink != 0 {
			return fmt.Errorf("%s is not a real directory", cur)
		}
		// Root-owned ancestors such as /home are a normal, secure part of a
		// user-owned path when they are not writable by group or other.
		if st, ok := i.Sys().(*syscall.Stat_t); ok && int(st.Uid) != os.Geteuid() && st.Uid != 0 && cur != os.TempDir() {
			return fmt.Errorf("%s is not owned by the user or root", cur)
		}
		if unsafeMode(i) {
			return fmt.Errorf("%s is writable by an unsafe group/other", cur)
		}
	}
	return nil
}

func unsafeMode(i os.FileInfo) bool {
	perm := i.Mode().Perm()
	// Sticky directories protect entries from replacement by other writers,
	// whether those writers have access through group or other permissions.
	// The callers separately validate ancestor ownership and managed trees.
	if perm&0022 == 0 || i.Mode()&os.ModeSticky != 0 {
		return false
	}
	if perm&0002 != 0 {
		return true
	}
	st, ok := i.Sys().(*syscall.Stat_t)
	return !ok || int(st.Uid) != os.Geteuid() || int(st.Gid) != os.Getegid()
}

// canonicalBase validates existing lexical and resolved prefixes and preserves
// a missing suffix. Launcher-managed names are appended only after this step.
func canonicalBase(p string) (string, error) {
	if !filepath.IsAbs(p) {
		return "", errors.New("base must be absolute")
	}
	p = filepath.Clean(p)
	cur := string(os.PathSeparator)
	parts := strings.Split(strings.TrimPrefix(p, cur), string(os.PathSeparator))
	for n, part := range parts {
		if part == "" {
			continue
		}
		next := filepath.Join(cur, part)
		i, err := os.Lstat(next)
		if os.IsNotExist(err) {
			return filepath.Join(append([]string{cur}, parts[n:]...)...), nil
		}
		if err != nil {
			return "", err
		}
		st, ok := i.Sys().(*syscall.Stat_t)
		if !ok || (int(st.Uid) != os.Geteuid() && st.Uid != 0) {
			return "", fmt.Errorf("%s is not owned by the user or root", next)
		}
		if i.Mode()&os.ModeSymlink != 0 {
			resolved, e := filepath.EvalSymlinks(next)
			if e != nil {
				return "", e
			}
			if e = validateManagedDir(resolved); e != nil {
				return "", e
			}
			cur = resolved
		} else {
			if !i.IsDir() {
				return "", fmt.Errorf("%s is not a directory", next)
			}
			if unsafeMode(i) {
				return "", fmt.Errorf("%s is writable by an unsafe group/other", next)
			}
			cur = next
		}
	}
	return filepath.Clean(cur), nil
}
func secureParent(p string) error {
	if err := os.MkdirAll(p, 0700); err != nil {
		return err
	}
	return validateManagedDir(p)
}

func canonical(n string) (string, error) {
	if n == "" || strings.Contains(n, "\\") || strings.HasPrefix(n, "/") {
		return "", errors.New("non-canonical path")
	}
	c := filepath.ToSlash(filepath.Clean(filepath.FromSlash(n)))
	if c != n || c == "." || c == ".." || strings.HasPrefix(c, "../") {
		return "", errors.New("non-canonical path")
	}
	return c, nil
}
func parsePayload(payload []byte) (Manifest, error) {
	var m Manifest
	if len(payload) == 0 || len(payload) > maxArchive {
		return m, errors.New("archive is empty or too large")
	}
	z, err := zip.NewReader(bytes.NewReader(payload), int64(len(payload)))
	if err != nil {
		return m, err
	}
	if len(z.File) < 2 || len(z.File) > maxFiles+1 {
		return m, errors.New("invalid archive entry count")
	}
	manifestCount := 0
	for _, f := range z.File {
		if f.Name != manifestName {
			continue
		}
		manifestCount++
		if f.FileInfo().Mode()&os.ModeType != 0 || f.Mode().Perm() != 0644 || f.UncompressedSize64 > 1<<20 {
			return m, errors.New("invalid manifest metadata")
		}
		r, e := f.Open()
		if e != nil {
			return m, e
		}
		d, readErr := io.ReadAll(io.LimitReader(r, (1<<20)+1))
		closeErr := r.Close()
		if readErr != nil || closeErr != nil || len(d) > 1<<20 {
			return m, errors.New("invalid manifest")
		}
		m, e = runtimepayload.DecodeManifestStrict(d)
		if e != nil {
			return m, e
		}
	}
	if manifestCount != 1 {
		return m, errors.New("exactly one manifest required")
	}
	if m.Target != runtime.GOOS+"-"+runtime.GOARCH {
		return m, fmt.Errorf("launcher host %s-%s cannot run payload target %q", runtime.GOOS, runtime.GOARCH, m.Target)
	}
	want := make(map[string]Entry, len(m.Files))
	for _, x := range m.Files {
		want[x.Path] = x
	}
	if len(z.File) != len(m.Files)+1 {
		return m, errors.New("manifest and archive entry counts differ")
	}
	seen := make(map[string]bool, len(m.Files))
	for _, f := range z.File {
		if f.Name == manifestName {
			continue
		}
		n, e := canonical(f.Name)
		x, ok := want[n]
		if e != nil || !ok || seen[n] {
			return m, fmt.Errorf("unmanifested, duplicate, or unsafe ZIP path %q", f.Name)
		}
		seen[n] = true
		if f.FileInfo().Mode()&os.ModeType != 0 || f.UncompressedSize64 != uint64(x.Size) || f.Mode().Perm() != os.FileMode(x.Mode) {
			return m, errors.New("ZIP metadata differs from manifest")
		}
	}
	if len(seen) != len(want) {
		return m, errors.New("manifest file missing from archive")
	}
	return m, nil
}

func extract(payload []byte, dst string, m Manifest) error {
	z, _ := zip.NewReader(bytes.NewReader(payload), int64(len(payload)))
	want := map[string]Entry{}
	for _, x := range m.Files {
		want[x.Path] = x
	}
	seen := map[string]bool{}
	for _, f := range z.File {
		if f.Name == manifestName {
			continue
		}
		n, e := canonical(f.Name)
		if e != nil || seen[n] {
			return fmt.Errorf("unsafe payload path %q", f.Name)
		}
		x, ok := want[n]
		if !ok {
			return fmt.Errorf("unmanifested file %q", n)
		}
		seen[n] = true
		if f.FileInfo().Mode()&os.ModeType != 0 || f.UncompressedSize64 != uint64(x.Size) || f.Mode().Perm() != os.FileMode(x.Mode) {
			return errors.New("ZIP metadata differs from manifest")
		}
		p := filepath.Join(dst, filepath.FromSlash(n))
		if e = os.MkdirAll(filepath.Dir(p), 0700); e != nil {
			return e
		}
		out, e := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, os.FileMode(x.Mode))
		if e != nil {
			return e
		}
		r, e := f.Open()
		if e != nil {
			out.Close()
			return e
		}
		h := sha256.New()
		written, e := io.Copy(io.MultiWriter(out, h), io.LimitReader(r, x.Size+1))
		closeErr := out.Close()
		r.Close()
		if e != nil || written != x.Size || hex.EncodeToString(h.Sum(nil)) != x.SHA256 {
			return errors.New("payload content mismatch")
		}
		if closeErr != nil {
			return fmt.Errorf("close extracted file %s: %w", n, closeErr)
		}
	}
	if len(seen) != len(want) {
		return errors.New("manifest file missing from payload")
	}
	return nil
}
func noSymlinkComponents(root, rel string) error {
	cur := root
	parts := strings.Split(filepath.FromSlash(rel), string(os.PathSeparator))
	for _, part := range parts[:len(parts)-1] {
		cur = filepath.Join(cur, part)
		i, e := os.Lstat(cur)
		if e != nil || !i.IsDir() || i.Mode()&os.ModeSymlink != 0 {
			return errors.New("installed runtime has unsafe path component")
		}
	}
	return nil
}

func readNoFollowRegular(path string, max int64) ([]byte, error) {
	i, e := os.Lstat(path)
	if e != nil {
		return nil, e
	}
	if !i.Mode().IsRegular() || i.Mode()&os.ModeSymlink != 0 {
		return nil, errors.New("not a regular no-follow file")
	}
	f, e := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
	if e != nil {
		return nil, e
	}
	defer f.Close()
	fi, e := f.Stat()
	if e != nil {
		return nil, e
	}
	if !os.SameFile(i, fi) {
		return nil, errors.New("file changed while opening")
	}
	b, e := io.ReadAll(io.LimitReader(f, max+1))
	if e != nil {
		return nil, e
	}
	if int64(len(b)) > max {
		return nil, errors.New("file too large")
	}
	return b, nil
}
func decodeManifestStrict(b []byte) (Manifest, error) {
	return runtimepayload.DecodeManifestStrict(b)
}

func validateInstalled(root string, m Manifest) error {
	rootInfo, err := os.Lstat(root)
	if err != nil || !rootInfo.IsDir() || rootInfo.Mode()&os.ModeSymlink != 0 {
		return errors.New("runtime absent")
	}
	if st, ok := rootInfo.Sys().(*syscall.Stat_t); !ok || int(st.Uid) != os.Geteuid() {
		return errors.New("runtime is not user-owned")
	}
	if rootInfo.Mode().Perm()&0022 != 0 {
		return errors.New("runtime is group/world writable")
	}
	marker := filepath.Join(root, manifestName)
	mb, err := readNoFollowRegular(marker, 1<<20)
	if err != nil {
		return fmt.Errorf("runtime completion manifest missing or unsafe: %w", err)
	}
	installed, err := runtimepayload.DecodeInstalledManifestStrict(mb)
	if err != nil {
		return fmt.Errorf("invalid completion manifest: %w", err)
	}
	expectedJSON, _ := json.Marshal(m)
	actualJSON, _ := json.Marshal(installed)
	if !bytes.Equal(expectedJSON, actualJSON) {
		return errors.New("completion manifest identity mismatch")
	}

	files := make(map[string]Entry, len(m.Files))
	dirs := map[string]bool{".": true}
	for _, x := range m.Files {
		files[x.Path] = x
		for d := filepath.ToSlash(filepath.Dir(filepath.FromSlash(x.Path))); d != "."; d = filepath.ToSlash(filepath.Dir(filepath.FromSlash(d))) {
			dirs[d] = true
		}
	}
	seen := make(map[string]bool, len(files))
	err = filepath.Walk(root, func(path string, info os.FileInfo, walkErr error) error {
		if walkErr != nil {
			return walkErr
		}
		rel, e := filepath.Rel(root, path)
		if e != nil {
			return e
		}
		rel = filepath.ToSlash(rel)
		if info.Mode()&os.ModeSymlink != 0 {
			return fmt.Errorf("installed runtime contains symlink: %s", rel)
		}
		if st, ok := info.Sys().(*syscall.Stat_t); !ok || int(st.Uid) != os.Geteuid() {
			return fmt.Errorf("installed runtime entry is not user-owned: %s", rel)
		}
		if info.IsDir() {
			if !dirs[rel] || info.Mode().Perm()&0022 != 0 {
				return fmt.Errorf("installed runtime has unexpected or writable directory: %s", rel)
			}
			return nil
		}
		if rel == manifestName {
			return validateRuntimeFilePermissions(rel, info.Mode(), 0400)
		}
		x, ok := files[rel]
		if !ok {
			return fmt.Errorf("installed runtime contains unmanifested entry: %s", rel)
		}
		if err := validateRuntimeFilePermissions(rel, info.Mode(), 0400|os.FileMode(x.Mode&0100)); err != nil {
			return err
		}
		if info.Size() != x.Size {
			return fmt.Errorf("installed runtime size mismatch: %s (got %d bytes; want %d)", rel, info.Size(), x.Size)
		}
		f, e := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
		if e != nil {
			return e
		}
		opened, e := f.Stat()
		if e != nil || !os.SameFile(info, opened) {
			f.Close()
			return errors.New("installed runtime file changed while opening")
		}
		h := sha256.New()
		n, copyErr := io.Copy(h, io.LimitReader(f, x.Size+1))
		closeErr := f.Close()
		if copyErr != nil || closeErr != nil || n != x.Size || hex.EncodeToString(h.Sum(nil)) != x.SHA256 {
			return fmt.Errorf("installed runtime checksum mismatch: %s", rel)
		}
		seen[rel] = true
		return nil
	})
	if err != nil {
		return err
	}
	if len(seen) != len(files) {
		return errors.New("installed runtime is missing manifested files")
	}
	return nil
}

// Installed permissions need to allow the owner to read and, where applicable,
// execute files. Owner-write and group/other read/execute bits are not required
// to match the archive. Never widen a user's deliberately tightened modes.
func validateRuntimeFilePermissions(name string, mode, required os.FileMode) error {
	if !mode.IsRegular() {
		return fmt.Errorf("installed runtime entry is not a regular file: %s", name)
	}
	if mode&(os.ModeSetuid|os.ModeSetgid) != 0 || mode.Perm()&0022 != 0 {
		return fmt.Errorf("installed runtime file has unsafe permissions: %s (%s)", name, mode)
	}
	if mode.Perm()&required != required {
		return fmt.Errorf("installed runtime file lacks required owner permissions: %s (got %04o; need %04o)", name, mode.Perm(), required)
	}
	return nil
}