package opencode import ( "archive/tar" "bytes" "compress/gzip" "context" "crypto/sha512" "encoding/base64" "errors" "io" "os" "path" "path/filepath" "runtime" "strings" "amadan.net/oficina/equipo/internal/runner/provider" ) // Paths are an install root's tree and the binary in it, as the // installer lays them out: /opencode/node_modules, with the binary // at /bin/opencode. func Paths(root, platformPackage string) (tree, binary string) { tree = filepath.Join(root, "opencode", "node_modules") return tree, filepath.Join(tree, filepath.FromSlash(platformPackage), "bin", "opencode") } // InstallPins are what an install is held to: the tree's digest, the // platform's binary package and the lockfile entries of the packages it // fetches. The committed ones come from Pins and the lockfile; a test // passes its own. type InstallPins struct { Tree string Platform Platform Packages map[string]Locked } // CommittedPins are this repository's pins for goarch. func CommittedPins(goarch string) (InstallPins, bool) { tree, platform, ok := Pins(goarch) if !ok { return InstallPins{}, false } pins := InstallPins{Tree: tree, Platform: platform, Packages: map[string]Locked{}} for _, name := range []string{PackageName, platform.Package} { l, ok := Lock(name) if !ok { return InstallPins{}, false } pins.Packages[name] = l } return pins, Pinned() } // Fetch reads a URL's body, at most limit bytes. type Fetch func(ctx context.Context, url string, limit int64) ([]byte, error) // maxTarball bounds one package's download; maxFile one file in it. const ( maxTarball = 256 << 20 maxFile = 320 << 20 ) // InstallPinned installs the pinned OpenCode under root for goarch: the two // packages the lockfile names (@opencode/cli and this platform's binary // package), each checked against its integrity before it is unpacked, // no script run, the tree sealed read-only, then the tree and the binary // held to the committed digests. An install that does not verify is // removed. An install already in place and verified is kept. func InstallPinned(ctx context.Context, root, goarch string, fetch Fetch) error { pins, ok := CommittedPins(goarch) if !ok { return ErrUnpinned } return InstallWith(ctx, root, pins, fetch) } // InstallWith is InstallPinned held to pins. func InstallWith(ctx context.Context, root string, pins InstallPins, fetch Fetch) error { if VerifyWith(root, pins) == nil { return nil } if !filepath.IsAbs(root) || filepath.Clean(root) != root { return ErrUnpinned } if err := os.MkdirAll(root, 0700); err != nil { return err } scratch, err := os.MkdirTemp(root, ".install-") if err != nil { return err } defer removeTree(scratch) tree := filepath.Join(scratch, "node_modules") for _, name := range []string{PackageName, pins.Platform.Package} { l, ok := pins.Packages[name] if !ok || !strings.HasPrefix(l.Resolved, "https://") { return ErrUnpinned } raw, err := fetch(ctx, l.Resolved, maxTarball) if err != nil { return err } if !integrityMatches(raw, l.Integrity) { return ErrUnpinned } if err := unpack(raw, filepath.Join(tree, filepath.FromSlash(name))); err != nil { return err } } if err := provider.SealTree(tree); err != nil { return err } dst, _ := Paths(root, pins.Platform.Package) removeTree(filepath.Dir(dst)) if err := os.MkdirAll(filepath.Dir(dst), 0700); err != nil { return err } // A directory moves to another parent only while it is writable. if err := os.Chmod(tree, 0755); err != nil { return err } if err := os.Rename(tree, dst); err != nil { return err } if err := os.Chmod(dst, 0555); err != nil { return err } if err := VerifyWith(root, pins); err != nil { removeTree(filepath.Dir(dst)) return err } return nil } // integrityMatches compares an npm sha512 integrity with raw's. func integrityMatches(raw []byte, integrity string) bool { sum := sha512.Sum512(raw) return integrity == "sha512-"+base64.StdEncoding.EncodeToString(sum[:]) } // errArchive: a package archive holds something an install never // unpacks (a link, a device, a path out of its package, a file too // large). var errArchive = errors.New("opencode: the package archive is not one this unpacks") // unpack writes an npm package tarball's package/ files into dir: regular // files and directories only, each path inside dir. func unpack(raw []byte, dir string) error { gz, err := gzip.NewReader(bytes.NewReader(raw)) if err != nil { return errArchive } tr := tar.NewReader(gz) if err := os.MkdirAll(dir, 0755); err != nil { return err } for { h, err := tr.Next() if err == io.EOF { return nil } if err != nil { return errArchive } name := path.Clean(h.Name) rest, ok := strings.CutPrefix(name, "package/") if !ok || rest == "" || path.IsAbs(rest) || rest == ".." || strings.HasPrefix(rest, "../") || strings.Contains(rest, "/../") { return errArchive } target := filepath.Join(dir, filepath.FromSlash(rest)) if !strings.HasPrefix(target, dir+string(filepath.Separator)) { return errArchive } switch h.Typeflag { case tar.TypeDir: if err := os.MkdirAll(target, 0755); err != nil { return err } case tar.TypeReg: if h.Size < 0 || h.Size > maxFile { return errArchive } if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil { return err } mode := os.FileMode(0644) if h.Mode&0111 != 0 { mode = 0755 } f, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode) if err != nil { return err } n, err := io.Copy(f, io.LimitReader(tr, maxFile+1)) if cerr := f.Close(); err == nil { err = cerr } if err != nil { return err } if n != h.Size { return errArchive } default: return errArchive } } } // Verify holds an install root to this platform's committed pins. func Verify(root string) error { pins, ok := CommittedPins(runtime.GOARCH) if !ok { return ErrUnpinned } return VerifyWith(root, pins) } // VerifyWith holds an install root to pins: the tree sealed and safe, // its digest (every file, mode and link) and the binary's. func VerifyWith(root string, pins InstallPins) error { tree, binary := Paths(root, pins.Platform.Package) if provider.TreeRootSafe(tree) != nil { return ErrUnpinned } if got, err := provider.TreeSHA256(tree); err != nil || got != pins.Tree { return ErrUnpinned } if got, err := provider.FileSHA256(binary); err != nil || got != pins.Platform.BinarySHA256 { return ErrUnpinned } return nil } // removeTree removes a tree a seal made read-only. func removeTree(dir string) { filepath.Walk(dir, func(p string, info os.FileInfo, err error) error { if err == nil && info.IsDir() { os.Chmod(p, 0700) } return nil }) os.RemoveAll(dir) }