Import Anubis v1.28.2

Replace the tree with upstream TecharoHQ/anubis v1.28.2 (a1384fbf42e3).
Masyunis customizations are re-applied in the following commits.
This commit is contained in:
sol_bot Bot committed 2026-11-28 14:52:26 +03:00
1 parent eb3e46d8d0
commit e07de898cd
573 files changed
+35846 -6807

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# mkmsi
Converts a yeet-generated .zip file to an MSI using [msitools](https://gitlab.gnome.org/GNOME/msitools).
It needs `wixl`, `wixl-heat`, `msibuild` and `msiinfo` from msitools 0.106 or
later on PATH. Use Homebrew (`brew install msitools`) on both macOS and Linux.
Distribution packages are usually too old. Debian and Ubuntu also split the
tools across two packages -- `msibuild` and `msiinfo` in `msitools`, `wixl` and
`wixl-heat` in `wixl` -- and Ubuntu 24.04 ships 0.103, which aborts with
`unhandled child Component node Condition` on the `<Condition>` element in
`run/windows/anubis.wxs`.
> [!NOTE]
> This code was generated using Claude Opus 5 as a correctness fuzzer to ensure that this output is valid, works on Windows systems, and generally behaves like a well-behaved Windows installer. Due to facts and circumstances beyond my control with how these tools and the MSI format works, it is not currently possible to make these MSI builds reproducible.
>
> I tried.
This is intended to be run by `yeet` at package build time:
```js
// Build MSI installers from the Windows zips that were just built.
packages
.flat()
.filter((pkg) => pkg.includes("windows"))
.filter((pkg) => pkg.endsWith(".zip"))
.forEach((zip) => {
const msiPath = zip.replace(/\.zip$/, ".msi");
$`go run ./internal/cmd/mkmsi --zip ${zip} --out ${msiPath}`;
});
```
+201
View File
@@ -0,0 +1,201 @@
package main
import (
"archive/zip"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
)
// ErrWixlDroppedAttribute reports that wixl did not understand part of the wxs.
//
// wixl writes a warning to stderr and then exits 0 with an installer that is
// missing whatever it did not understand, so its exit status cannot be trusted
// on its own.
var ErrWixlDroppedAttribute = errors.New("mkmsi: wixl rejected part of the wxs")
// zipNameRe pulls the version and architecture out of a yeet zip name such as
// anubis-1.26.2-1-gec3cce8a-dev-windows-amd64.zip.
var zipNameRe = regexp.MustCompile(`^anubis-(.+)-windows-(amd64|arm64)\.zip$`)
// versionFromZipName extracts the Anubis version from a zip file's name.
func versionFromZipName(name string) (string, error) {
m := zipNameRe.FindStringSubmatch(filepath.Base(name))
if m == nil {
return "", fmt.Errorf("%w: %q is not an Anubis Windows zip", ErrBadVersion, name)
}
return m[1], nil
}
// archFromZipName extracts the Go architecture from a zip file's name.
func archFromZipName(name string) (string, error) {
m := zipNameRe.FindStringSubmatch(filepath.Base(name))
if m == nil {
return "", fmt.Errorf("%w: %q is not an Anubis Windows zip", ErrBadVersion, name)
}
return m[2], nil
}
// checkWixlOutput fails when wixl reported that it could not handle something.
func checkWixlOutput(stderr string) error {
for line := range strings.SplitSeq(stderr, "\n") {
if strings.Contains(line, "CRITICAL") {
return fmt.Errorf("%w: %s", ErrWixlDroppedAttribute, strings.TrimSpace(line))
}
}
return nil
}
// unzip extracts src into dest, stripping the single top level directory that
// yeet puts in its archives. It returns the list of extracted file paths,
// relative to dest and sorted, so downstream steps are reproducible, along
// with the single modification time yeet stamped every entry with.
//
// That shared mtime is handed back rather than rediscovered so files this
// program generates itself after unzipping -- the config templates
// stageConfigTemplates writes -- can be stamped with it too. Without that,
// only files that came straight out of the zip would have a reproducible
// mtime, and the CAB archive wixl builds embeds every file's mtime
// regardless of where it came from.
func unzip(src, dest string) ([]string, time.Time, error) {
r, err := zip.OpenReader(src)
if err != nil {
return nil, time.Time{}, fmt.Errorf("mkmsi: cannot open %s: %w", src, err)
}
defer func() { _ = r.Close() }()
if len(r.File) == 0 {
return nil, time.Time{}, fmt.Errorf("mkmsi: %s has no entries", src)
}
// yeet stamps every entry in the zip with the same mtime; verified
// empirically across a real build's 151 entries. Any entry's mtime is
// therefore as good as any other's.
srcMTime := r.File[0].Modified
var names []string
for _, f := range r.File {
// yeet wraps everything in one directory named after the package.
rel := f.Name
if i := strings.IndexByte(rel, '/'); i >= 0 {
rel = rel[i+1:]
}
if rel == "" {
continue
}
// Reject traversal before touching the filesystem: the zip is built
// locally, but this program also runs over files from CI artifacts.
out := filepath.Join(dest, filepath.FromSlash(rel))
if !strings.HasPrefix(out, filepath.Clean(dest)+string(os.PathSeparator)) {
return nil, time.Time{}, fmt.Errorf("mkmsi: refusing path %q outside %s", f.Name, dest)
}
if f.FileInfo().IsDir() {
if err := os.MkdirAll(out, 0o755); err != nil {
return nil, time.Time{}, fmt.Errorf("mkmsi: cannot create %s: %w", out, err)
}
continue
}
if err := extractOne(f, out); err != nil {
return nil, time.Time{}, err
}
names = append(names, rel)
}
slices.Sort(names)
return names, srcMTime, nil
}
// extractOne writes a single zip entry to disk.
func extractOne(f *zip.File, out string) error {
if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil {
return fmt.Errorf("mkmsi: cannot create %s: %w", filepath.Dir(out), err)
}
rc, err := f.Open()
if err != nil {
return fmt.Errorf("mkmsi: cannot read %s from zip: %w", f.Name, err)
}
defer func() { _ = rc.Close() }()
w, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode().Perm()|0o200)
if err != nil {
return fmt.Errorf("mkmsi: cannot create %s: %w", out, err)
}
if _, err := io.Copy(w, rc); err != nil {
_ = w.Close()
return fmt.Errorf("mkmsi: cannot write %s: %w", out, err)
}
if err := w.Close(); err != nil {
return fmt.Errorf("mkmsi: cannot close %s: %w", out, err)
}
// yeet pins every zip entry's modification time to a fixed epoch so its
// zips are byte-identical across builds. os.OpenFile above stamps the
// file with the current wall clock instead, and the CAB archive wixl
// builds embeds each file's mtime -- so without restoring it here, the
// CAB stream (and therefore the MSI) differs on every build even when
// the input zip is identical. This must run after w.Close(), not
// before: closing a file does not touch its mtime, but running before
// the copy finishes would use the file's creation time instead.
if err := os.Chtimes(out, f.Modified, f.Modified); err != nil {
return fmt.Errorf("mkmsi: cannot set mtime on %s: %w", out, err)
}
return nil
}
// concatFiles writes the contents of srcs, in order, to dest, then stamps it
// with mtime.
//
// The stamp matters for the same reason extractOne restores one on every
// file it extracts from the zip: dest is a File the MSI installs, so its
// mtime is embedded in the CAB archive wixl builds. Left at the wall clock
// os.WriteFile would otherwise use, it would make the CAB -- and therefore
// the MSI -- differ on every build even when every other input is identical.
// mtime is srcMTime, the single mtime yeet stamped every entry in the source
// zip with (see unzip), so these generated files end up sharing it rather
// than inventing a separate fixed point in time of their own.
func concatFiles(dest string, mtime time.Time, srcs ...string) error {
var buf []byte
for _, src := range srcs {
data, err := os.ReadFile(src)
if err != nil {
return fmt.Errorf("mkmsi: cannot read %s: %w", src, err)
}
buf = append(buf, data...)
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return fmt.Errorf("mkmsi: cannot create %s: %w", filepath.Dir(dest), err)
}
if err := os.WriteFile(dest, buf, 0o644); err != nil {
return fmt.Errorf("mkmsi: cannot write %s: %w", dest, err)
}
if err := os.Chtimes(dest, mtime, mtime); err != nil {
return fmt.Errorf("mkmsi: cannot set mtime on %s: %w", dest, err)
}
return nil
}
+92
View File
@@ -0,0 +1,92 @@
package main
import (
"errors"
"testing"
)
func TestVersionFromZipName(t *testing.T) {
for _, tt := range []struct {
name string
in string
want string
wantErr error
}{
{
name: "dev build with path",
in: "var/win/anubis-1.26.2-1-gec3cce8a-dev-windows-amd64.zip",
want: "1.26.2-1-gec3cce8a-dev",
},
{
name: "tagged release",
in: "anubis-1.26.2-windows-amd64.zip",
want: "1.26.2",
},
{
name: "arm64",
in: "anubis-1.26.2-windows-arm64.zip",
want: "1.26.2",
},
{name: "not an anubis zip", in: "something-else.zip", wantErr: ErrBadVersion},
{name: "no platform suffix", in: "anubis-1.26.2.zip", wantErr: ErrBadVersion},
} {
t.Run(tt.name, func(t *testing.T) {
got, err := versionFromZipName(tt.in)
if tt.wantErr != nil {
if !errors.Is(err, tt.wantErr) {
t.Fatalf("versionFromZipName(%q): got error %v, want %v", tt.in, err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("versionFromZipName(%q): unexpected error: %v", tt.in, err)
}
if got != tt.want {
t.Errorf("versionFromZipName(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
func TestCheckWixlOutput(t *testing.T) {
for _, tt := range []struct {
name string
in string
wantErr error
}{
{name: "clean", in: ""},
{name: "harmless chatter", in: "building anubis.msi\n"},
{
name: "dropped attribute",
in: "(wixl:1234): GLib-GObject-CRITICAL **: object class 'WixlWixFile' has no property named 'NeverOverwrite'\n",
wantErr: ErrWixlDroppedAttribute,
},
{
name: "critical among other lines",
in: "fine\n** (wixl:1): CRITICAL **: assertion failed\nalso fine\n",
wantErr: ErrWixlDroppedAttribute,
},
} {
t.Run(tt.name, func(t *testing.T) {
// checkWixlOutput is a pure string-matching function over
// captured sample wixl stderr; it never shells out to wixl
// itself, so unlike msi_test.go's tests this one needs no
// requireTool gate and must always run.
err := checkWixlOutput(tt.in)
if tt.wantErr == nil {
if err != nil {
t.Fatalf("checkWixlOutput(%q): unexpected error: %v", tt.in, err)
}
return
}
if !errors.Is(err, tt.wantErr) {
t.Errorf("checkWixlOutput(%q): got %v, want %v", tt.in, err, tt.wantErr)
}
})
}
}
+146
View File
@@ -0,0 +1,146 @@
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
"fmt"
"io"
"strings"
)
// rewriteDirectoryIDs replaces wixl-heat's randomized dir<HEX> directory IDs
// in a generated fragment with IDs derived deterministically from each
// directory's path, so the fragment -- and therefore the MSI wixl builds
// from it -- is reproducible across builds.
//
// wixl-heat's cmp<HEX> and fil<HEX> IDs are already stable, derived from
// each component's and file's relative path. Only its dir<HEX> IDs are
// random: running wixl-heat twice over an identical tree produces two
// completely disjoint sets of directory IDs (verified empirically). Each
// dir<HEX> ID appears exactly once in the fragment, as a Directory
// element's own Id attribute -- nothing else in the document references it
// -- which is what makes a single rewrite pass safe.
//
// This walks the document with encoding/xml rather than a regex: a Name
// attribute or a doc file's path could otherwise contain something that
// looks like an id, and a regex over the raw text would have no way to tell
// that apart from a real dir<HEX> attribute.
func rewriteDirectoryIDs(doc []byte) ([]byte, error) {
dec := xml.NewDecoder(bytes.NewReader(doc))
var out bytes.Buffer
enc := xml.NewEncoder(&out)
// dirNames accumulates the Name attributes of open Directory elements,
// in nesting order, so each directory's deterministic ID is derived
// from its full relative path rather than just its own Name -- two
// directories with the same leaf name under different parents (e.g. two
// "haproxy" directories in the Anubis docs tree) must not collide.
var dirNames []string
for {
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("mkmsi: cannot parse doc fragment: %w", err)
}
switch t := tok.(type) {
case xml.StartElement:
// encoding/xml's Encoder writes an xmlns declaration for every
// element with a resolved namespace, regardless of whether an
// ancestor already declared it. Left alone, the xmlns attribute
// this document's root already carries in Attr collides with
// that auto-generated one and produces a duplicate attribute --
// invalid XML that libxml2 (and therefore wixl) rejects. Every
// element's namespace is preserved via Name.Space either way,
// so dropping the explicit declarations here is lossless.
t.Attr = dropXMLNSAttrs(t.Attr)
if t.Name.Local == "Directory" {
dirNames = append(dirNames, attrValue(t.Attr, "Name"))
id := directoryID(directoryPath(dirNames))
for i := range t.Attr {
if t.Attr[i].Name.Local == "Id" {
t.Attr[i].Value = id
}
}
}
tok = t
case xml.EndElement:
if t.Name.Local == "Directory" {
dirNames = dirNames[:len(dirNames)-1]
}
}
if err := enc.EncodeToken(tok); err != nil {
return nil, fmt.Errorf("mkmsi: cannot rewrite doc fragment: %w", err)
}
}
if err := enc.Flush(); err != nil {
return nil, fmt.Errorf("mkmsi: cannot rewrite doc fragment: %w", err)
}
return out.Bytes(), nil
}
// dropXMLNSAttrs removes default and prefixed xmlns declarations from an
// attribute list, keeping everything else in order.
func dropXMLNSAttrs(attrs []xml.Attr) []xml.Attr {
kept := attrs[:0]
for _, a := range attrs {
if a.Name.Space == "xmlns" || (a.Name.Space == "" && a.Name.Local == "xmlns") {
continue
}
kept = append(kept, a)
}
return kept
}
// attrValue returns the value of the first attribute named local, or "" if
// there is none.
func attrValue(attrs []xml.Attr, local string) string {
for _, a := range attrs {
if a.Name.Local == local {
return a.Value
}
}
return ""
}
// directoryPath joins accumulated Directory Name attributes into a relative
// path. wixl-heat's own root directory is named ".", which is dropped so
// the path starts clean instead of carrying a leading "./".
func directoryPath(names []string) string {
var parts []string
for _, n := range names {
if n == "." {
continue
}
parts = append(parts, n)
}
return strings.Join(parts, "/")
}
// directoryID derives a deterministic Directory Id from a relative path, in
// the same dir<HEX> shape wixl-heat itself uses for cmp<HEX> and fil<HEX>: a
// fixed three-letter prefix plus a 32-character uppercase hex digest. This
// is an identifier, not a security boundary, so the first 16 bytes of a
// SHA-256 digest are used rather than MD5, purely to keep the digest the
// same length wixl-heat's own IDs use.
//
// It is path-derived rather than sequential on purpose: a sequential
// numbering scheme would renumber every directory whenever a doc file is
// added or removed anywhere in the tree, while a path-derived one only
// changes for a directory that itself moved.
func directoryID(path string) string {
sum := sha256.Sum256([]byte(path))
return "dir" + strings.ToUpper(hex.EncodeToString(sum[:16]))
}
+735
View File
@@ -0,0 +1,735 @@
// Command mkmsi turns the Windows zip that yeet builds into an MSI installer.
//
// It needs wixl, wixl-heat, msibuild and msiinfo from msitools on PATH.
package main
import (
"bytes"
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
)
var (
zipPath = flag.String("zip", "", "path to the Windows zip built by yeet")
outPath = flag.String("out", "", "path to write the MSI to")
packagingDir = flag.String("packaging-dir", filepath.Join("run", "windows"), "directory holding anubis.wxs and the config templates")
stagingDir = flag.String("staging-dir", filepath.Join("var", "mkmsi"), "directory to stage the MSI build in; an <arch> subdirectory is used and its previous contents are removed first")
)
// The installer is 64-bit only. anubis.wxs installs into ProgramFiles64Folder
// and marks its components Win64, so there is no meaningful 32-bit build to
// select. An --arch flag here would only let a caller produce an MSI that
// claims to be 32-bit while installing 64-bit components.
const (
msiArch = "x64"
msiWin64 = "yes"
// msiInstallerVersionAmd64 declares the Windows Installer engine version
// the package requires. 200 is the long-standing baseline and is what
// amd64 has always shipped.
msiInstallerVersionAmd64 = "200"
// msiInstallerVersionArm64 must be 500: the Arm64 package template (see
// setArm64Template) was only introduced in Windows Installer 5.0. An MSI
// declaring a lower InstallerVersion alongside an Arm64 template risks
// being rejected on the target as "not supported by this processor
// type" instead of failing at build time.
msiInstallerVersionArm64 = "500"
)
func main() {
flag.Parse()
if *zipPath == "" || *outPath == "" {
log.Fatal("both --zip and --out are required")
}
if err := build(); err != nil {
log.Fatalf("%v", err)
}
fmt.Println(*outPath)
}
func build() error {
version, err := versionFromZipName(*zipPath)
if err != nil {
return err
}
arch, err := archFromZipName(*zipPath)
if err != nil {
return err
}
msiVer, err := msiVersion(version)
if err != nil {
return err
}
code, err := productCode(version, arch)
if err != nil {
return err
}
// Computed here, from the raw version string, rather than inside
// runWixl/patchSummaryInfo: those only ever see msiVer, the already-
// converted numeric x.y.z.w form, which msiVersion (and therefore
// packageCode) cannot parse back.
pkgCode, err := packageCode(version, arch)
if err != nil {
return err
}
// Staged per architecture so an amd64 and an arm64 build running one
// after the other -- as both branches of buildTestMSI do -- cannot
// contaminate each other's tree.
staging := filepath.Join(*stagingDir, arch)
// Wipe any previous run's contents before staging fresh ones. A leftover
// file from an earlier build would otherwise still be sitting in
// staging and silently end up in this MSI. The tree is intentionally
// left in place after a successful build (no deferred cleanup) so it
// can be inspected -- var/mkmsi already only lives under a gitignored
// directory, and being able to diff two builds' staging trees directly
// is worth more than tidying up after every run.
if err := os.RemoveAll(staging); err != nil {
return fmt.Errorf("mkmsi: cannot clear staging directory %s: %w", staging, err)
}
if err := os.MkdirAll(staging, 0o755); err != nil {
return fmt.Errorf("mkmsi: cannot create staging directory %s: %w", staging, err)
}
_, srcMTime, err := unzip(*zipPath, staging)
if err != nil {
return err
}
if err := stageConfigTemplates(staging, srcMTime); err != nil {
return err
}
docWxs := filepath.Join(staging, "doc-files.wxs")
if err := generateDocFragment(staging, docWxs); err != nil {
return err
}
return runWixl(staging, docWxs, msiVer, code, pkgCode, arch)
}
// stageConfigTemplates builds the etc directory the installer ships: the env
// file as written, and the default policy with the Windows logging block
// appended. mtime is stamped on both, so they carry the same reproducible
// mtime as everything unzip extracted from the source zip; see concatFiles.
func stageConfigTemplates(staging string, mtime time.Time) error {
etc := filepath.Join(staging, "etc")
if err := concatFiles(filepath.Join(etc, "anubis.env"), mtime, filepath.Join(*packagingDir, "anubis.env")); err != nil {
return err
}
policy := filepath.Join(staging, "doc", "botPolicies.yaml")
if err := concatFiles(filepath.Join(etc, "anubis.yaml"), mtime, policy, filepath.Join(*packagingDir, "logging.yaml")); err != nil {
return err
}
return nil
}
// generateDocFragment runs wixl-heat over the documentation tree. The file
// list is sorted so the fragment, and therefore the MSI, is reproducible.
func generateDocFragment(staging, out string) error {
docDir := filepath.Join(staging, "doc")
var files []string
err := filepath.WalkDir(docDir, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
files = append(files, path)
}
return nil
})
if err != nil {
return fmt.Errorf("mkmsi: cannot walk %s: %w", docDir, err)
}
slices.Sort(files)
// Root the fragment at DOCDIR, which anubis.wxs already declares, and give
// it its own source variable. Pointing wixl-heat at INSTALLDIR instead
// would make it emit a second "doc" directory alongside the declared one.
cmd := exec.Command("wixl-heat",
"--prefix", docDir+string(os.PathSeparator),
"--directory-ref", "DOCDIR",
"--component-group", "DocFiles",
"--var", "var.DocSourceDir",
"--win64",
)
cmd.Stdin = strings.NewReader(strings.Join(files, "\n") + "\n")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
runErr := cmd.Run()
// Check stderr before the exit status, exactly as runWixl does. wixl
// reports a dropped attribute this way and then exits 0, so the exit
// status alone cannot be trusted, and a non-zero exit accompanied by a
// dropped attribute must still surface as ErrWixlDroppedAttribute.
if err := checkWixlOutput(stderr.String()); err != nil {
return err
}
if runErr != nil {
return fmt.Errorf("mkmsi: wixl-heat failed: %w: %s", runErr, stderr.String())
}
// wixl-heat randomizes its Directory IDs on every invocation, even over
// an identical tree; see rewriteDirectoryIDs for the details and why
// that alone breaks build reproducibility.
fragment, err := rewriteDirectoryIDs(stdout.Bytes())
if err != nil {
return err
}
if err := os.WriteFile(out, fragment, 0o644); err != nil {
return fmt.Errorf("mkmsi: cannot write %s: %w", out, err)
}
return nil
}
// runWixl compiles the wxs sources into the output MSI. version and code are
// the MSI ProductVersion and ProductCode (msiVersion/productCode's output);
// pkgCode is the PackageCode patched in afterward (packageCode's output,
// still the raw UUID, not yet braced/uppercased).
func runWixl(staging, docWxs, version, code, pkgCode, arch string) error {
if err := os.MkdirAll(filepath.Dir(*outPath), 0o755); err != nil {
return fmt.Errorf("mkmsi: cannot create %s: %w", filepath.Dir(*outPath), err)
}
installerVersion := msiInstallerVersionAmd64
if arch == "arm64" {
installerVersion = msiInstallerVersionArm64
}
cmd := exec.Command("wixl",
"-a", msiArch,
"--ext", "ui",
"-D", "SourceDir="+staging,
"-D", "DocSourceDir="+filepath.Join(staging, "doc"),
"-D", "Win64="+msiWin64,
"-D", "Version="+version,
"-D", "ProductCode="+code,
"-D", "InstallerVersion="+installerVersion,
"-o", *outPath,
filepath.Join(*packagingDir, "anubis.wxs"),
docWxs,
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmd.Stdout = os.Stdout
runErr := cmd.Run()
// Check stderr first: wixl reports a dropped attribute this way and then
// exits 0, which would otherwise look like success.
if err := checkWixlOutput(stderr.String()); err != nil {
return err
}
if runErr != nil {
return fmt.Errorf("mkmsi: wixl failed: %w: %s", runErr, stderr.String())
}
if err := secureInstallDir(*outPath); err != nil {
return err
}
if err := patchInstallerImages(*outPath); err != nil {
return err
}
if err := patchSummaryInfo(*outPath, pkgCode, arch); err != nil {
return err
}
if err := patchEnvironmentID(*outPath); err != nil {
return err
}
if err := patchCustomActionSequence(*outPath); err != nil {
return err
}
return nil
}
// installerImage pairs one wixl UI extension Binary stream with the image in
// *packagingDir that replaces it.
type installerImage struct {
stream string
file string
}
// installerImages lists the streams patchInstallerImages replaces.
// WixUI_Bmp_Banner is the strip shown across the top of every wizard page;
// WixUI_Bmp_Dialog is the full-height image on the welcome and exit pages.
//
// This is a slice, not a map, so the msibuild arguments below are built in a
// fixed order: build outputs should be reproducible, and map iteration order
// is not.
var installerImages = []installerImage{
{"Binary.WixUI_Bmp_Banner", "banner.bmp"},
{"Binary.WixUI_Bmp_Dialog", "dialog.bmp"},
}
// patchInstallerImages replaces wixl's stock WiX banner and dialog artwork
// with Anubis's own, for both architectures.
//
// There is no declarative way to do this: <WixVariable Id="WixUIBannerBmp">,
// how real WiX overrides these, is not supported by wixl. The alternative --
// pointing --extdir at a local copy of wixl's ext/ui tree so the Binary
// SourceFile paths can be edited -- would mean vendoring ~18 MS-RL licensed
// .wxs files into this MIT-licensed repo, so this patches the built MSI's
// Binary streams directly instead, the same way secureInstallDir and
// setArm64Template patch other parts of the file after wixl runs.
func patchInstallerImages(msiPath string) error {
args := []string{msiPath}
for _, img := range installerImages {
args = append(args, "-a", img.stream, filepath.Join(*packagingDir, img.file))
}
cmd := exec.Command("msibuild", args...)
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("mkmsi: msibuild failed to patch installer images: %w: %s", err, stderr.String())
}
// msibuild's exit status is not proof either stream actually changed --
// see secureInstallDir and setArm64Template for why that trust has
// already twice proven misplaced in this file. Extract each stream back
// and compare its length against the source image rather than assume
// the write landed.
for _, img := range installerImages {
source := filepath.Join(*packagingDir, img.file)
wantInfo, err := os.Stat(source)
if err != nil {
return fmt.Errorf("mkmsi: cannot stat %s: %w", source, err)
}
got, err := exec.Command("msiinfo", "extract", msiPath, img.stream).Output()
if err != nil {
return fmt.Errorf("mkmsi: msiinfo extract %s %s failed: %w", msiPath, img.stream, err)
}
if int64(len(got)) != wantInfo.Size() {
return fmt.Errorf("mkmsi: msibuild did not patch %s on %s: stream is %d bytes, %s is %d bytes",
img.stream, msiPath, len(got), source, wantInfo.Size())
}
}
return nil
}
// secureInstallDir marks INSTALLDIR as a secure custom property, so that a
// command-line `msiexec /i anubis.msi INSTALLDIR=...` override survives
// elevation into the deferred, system-context part of the install. Without
// it, the override is silently ignored and Anubis installs to the default
// location anyway.
//
// This can't be done declaratively in anubis.wxs. Both obvious forms fail
// under wixl 0.106:
//
// - Property/@Secure="yes" is silently dropped; no SecureCustomProperties
// row results at all.
// - A hand-authored <Property Id="SecureCustomProperties"> collides with
// the row wixl generates automatically for MajorUpgrade (populated with
// WIX_UPGRADE_DETECTED and WIX_DOWNGRADE_DETECTED) and aborts the wixl
// build outright with a bare "libmsi_query_execute" and no further
// explanation.
//
// So, the same way setArm64Template patches the summary Template after the
// fact, this patches the SecureCustomProperties row after wixl has built it.
func secureInstallDir(msiPath string) error {
existing, err := readProperty(msiPath, "SecureCustomProperties")
if err != nil {
return err
}
if slices.Contains(strings.Split(existing, ";"), "INSTALLDIR") {
return nil
}
want := "INSTALLDIR"
if existing != "" {
want += ";" + existing
}
// This assumes the SecureCustomProperties row already exists, which
// MajorUpgrade above guarantees today. If that ever stops being true,
// this UPDATE silently affects zero rows -- but the read-back below
// still catches it and fails loudly rather than shipping an MSI where
// INSTALLDIR= quietly does nothing.
cmd := exec.Command("msibuild", msiPath, "-q",
fmt.Sprintf("UPDATE Property SET Value='%s' WHERE Property='SecureCustomProperties'", want))
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("mkmsi: msibuild failed to secure INSTALLDIR: %w: %s", err, stderr.String())
}
got, err := readProperty(msiPath, "SecureCustomProperties")
if err != nil {
return err
}
if !slices.Contains(strings.Split(got, ";"), "INSTALLDIR") {
return fmt.Errorf("mkmsi: msibuild did not add INSTALLDIR to SecureCustomProperties on %s: got %q", msiPath, got)
}
return nil
}
// readProperty returns one row's value from an MSI's Property table, as
// reported by `msiinfo export`, or "" if the property has no row.
func readProperty(msiPath, name string) (string, error) {
out, err := exec.Command("msiinfo", "export", msiPath, "Property").Output()
if err != nil {
return "", fmt.Errorf("mkmsi: msiinfo export %s Property failed: %w", msiPath, err)
}
for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") {
if prop, value, ok := strings.Cut(line, "\t"); ok && prop == name {
return value, nil
}
}
return "", nil
}
// patchSummaryInfo rewrites the summary information stream after wixl has
// built the MSI: the Template field, and the PackageCode (the summary's
// "Revision number (UUID)" field).
//
// Both go through one msibuild -s call site on purpose. msibuild -s
// overwrites Subject, Template and PackageCode together every time it is
// called -- there is no way to set one without restating the other two --
// so a second call site (there used to be one here, setting only Template
// for arm64) would silently clobber whatever this one had just written, or
// vice versa depending on call order. One call site that always states all
// three is the only way they cannot fight.
//
// wixl 0.106 has no arm64 target — it accepts only intel, intel64 and ia64 —
// so an arm64 package is built as x64 and its Template corrected here. Only
// the declared architecture is wrong; the component bitness and the
// ProgramFiles64Folder install location are already right for arm64.
//
// PackageCode is set to a deterministic UUIDv5 (see packageCode) instead of
// the random value wixl assigns on every build; see packageCode's doc
// comment for why turning off that randomness is correct once the rest of
// the build is already reproducible. pkgCode is packageCode's raw output,
// formatted here to match the braced, uppercase shape wixl itself writes
// ProductCode and UpgradeCode in.
func patchSummaryInfo(msiPath, pkgCode, arch string) error {
template := "x64;1033"
if arch == "arm64" {
template = "Arm64;1033"
}
wantCode := "{" + strings.ToUpper(pkgCode) + "}"
cmd := exec.Command("msibuild", msiPath,
"-s", "Anubis Web AI Firewall Utility", "Techaro", template, wantCode,
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("mkmsi: msibuild failed to set summary information: %w: %s", err, stderr.String())
}
// msibuild's exit status alone is not proof either field was actually
// changed: this project has already learned wixl exits 0 while silently
// dropping data, and msibuild deserves no more trust. Read both back and
// fail loudly rather than shipping an MSI with the wrong Template, or a
// PackageCode nobody can reproduce.
gotTemplate, err := readSummaryTemplate(msiPath)
if err != nil {
return err
}
if gotTemplate != template {
return fmt.Errorf("mkmsi: msibuild did not set the summary template on %s: got %q, want %q", msiPath, gotTemplate, template)
}
gotCode, err := readSummaryPackageCode(msiPath)
if err != nil {
return err
}
if gotCode != wantCode {
return fmt.Errorf("mkmsi: msibuild did not set the PackageCode on %s: got %q, want %q", msiPath, gotCode, wantCode)
}
return nil
}
// readSummaryTemplate returns the Template field from an MSI's summary
// information stream, as reported by `msiinfo suminfo`.
func readSummaryTemplate(msiPath string) (string, error) {
out, err := exec.Command("msiinfo", "suminfo", msiPath).Output()
if err != nil {
return "", fmt.Errorf("mkmsi: msiinfo suminfo %s failed: %w", msiPath, err)
}
for _, line := range strings.Split(string(out), "\n") {
if rest, ok := strings.CutPrefix(line, "Template:"); ok {
return strings.TrimSpace(rest), nil
}
}
return "", fmt.Errorf("mkmsi: msiinfo suminfo %s has no Template line", msiPath)
}
// readSummaryPackageCode returns the "Revision number (UUID)" field -- the
// PackageCode -- from an MSI's summary information stream, as reported by
// `msiinfo suminfo`.
func readSummaryPackageCode(msiPath string) (string, error) {
out, err := exec.Command("msiinfo", "suminfo", msiPath).Output()
if err != nil {
return "", fmt.Errorf("mkmsi: msiinfo suminfo %s failed: %w", msiPath, err)
}
for _, line := range strings.Split(string(out), "\n") {
if rest, ok := strings.CutPrefix(line, "Revision number (UUID):"); ok {
return strings.TrimSpace(rest), nil
}
}
return "", fmt.Errorf("mkmsi: msiinfo suminfo %s has no Revision number (UUID) line", msiPath)
}
// patchEnvironmentID overwrites the Environment table's primary key for the
// PATH row with a fixed value.
//
// wixl 0.106 ignores the Id="env_path" declared in anubis.wxs for this row
// and assigns a random GUID to the Environment table's primary key column
// instead, so the row's key differs on every otherwise-identical build.
//
// This can't reuse secureInstallDir's UPDATE approach: Environment is the
// primary key of this table, and the Windows Installer SQL dialect
// (verified empirically -- msibuild reports "failed to execute query" and
// libmsi logs a CRITICAL on the attempt) refuses to UPDATE a primary key
// column. Deleting the row and re-inserting it with the same Name and Value
// but a fixed key is the documented way around that.
func patchEnvironmentID(msiPath string) error {
const (
component = "cmp_path"
want = "env_path"
)
name, value, err := readEnvironmentRow(msiPath, component)
if err != nil {
return err
}
cmd := exec.Command("msibuild", msiPath, "-q",
fmt.Sprintf("DELETE FROM Environment WHERE Component_='%s'", sqlEscape(component)),
"-q",
fmt.Sprintf("INSERT INTO Environment (Environment, Name, Value, Component_) VALUES ('%s', '%s', '%s', '%s')",
sqlEscape(want), sqlEscape(name), sqlEscape(value), sqlEscape(component)),
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("mkmsi: msibuild failed to patch the Environment table: %w: %s", err, stderr.String())
}
gotID, gotName, gotValue, err := readEnvironmentRowByID(msiPath, want)
if err != nil {
return err
}
if gotID != want || gotName != name || gotValue != value {
return fmt.Errorf("mkmsi: msibuild did not replace the Environment row for %s on %s correctly: got (%q, %q, %q), want (%q, %q, %q)",
component, msiPath, gotID, gotName, gotValue, want, name, value)
}
return nil
}
// sqlEscape doubles single quotes so a value can be embedded in an MSI SQL
// string literal. None of the values this program passes through it are
// expected to contain one -- Name and Value come from anubis.wxs, which
// this project controls -- but the values still flow through here rather
// than straight into a query string, the same discipline this being
// security-sensitive software calls for anywhere user- or file-sourced text
// reaches a query.
func sqlEscape(s string) string {
return strings.ReplaceAll(s, "'", "''")
}
// readEnvironmentRow returns the Name and Value columns of the Environment
// table's row for component, as reported by `msiinfo export`.
func readEnvironmentRow(msiPath, component string) (name, value string, err error) {
out, err := exec.Command("msiinfo", "export", msiPath, "Environment").Output()
if err != nil {
return "", "", fmt.Errorf("mkmsi: msiinfo export %s Environment failed: %w", msiPath, err)
}
for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") {
// Environment Name Value Component_
fields := strings.Split(line, "\t")
if len(fields) == 4 && fields[3] == component {
return fields[1], fields[2], nil
}
}
return "", "", fmt.Errorf("mkmsi: msiinfo export %s Environment has no row for component %s", msiPath, component)
}
// readEnvironmentRowByID returns the Name and Value columns of the
// Environment table's row keyed by id, as reported by `msiinfo export`.
func readEnvironmentRowByID(msiPath, id string) (gotID, name, value string, err error) {
out, err := exec.Command("msiinfo", "export", msiPath, "Environment").Output()
if err != nil {
return "", "", "", fmt.Errorf("mkmsi: msiinfo export %s Environment failed: %w", msiPath, err)
}
for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") {
// Environment Name Value Component_
fields := strings.Split(line, "\t")
if len(fields) == 4 && fields[0] == id {
return fields[0], fields[1], fields[2], nil
}
}
return "", "", "", fmt.Errorf("mkmsi: msiinfo export %s Environment has no row with key %s", msiPath, id)
}
// patchCustomActionSequence pins the InstallExecuteSequence Sequence values
// of SetAnubisExePath and BootstrapConfig -- the two custom actions
// anubis.wxs schedules only relative to each other and to InstallFiles
// ("Before BootstrapConfig" and "After InstallFiles" respectively), never to
// an absolute Sequence number of their own.
//
// This is not one of the five sources of drift this file was written to
// fix; it was found while verifying them. wixl resolves relative
// Before/After hints into absolute Sequence numbers itself, and that
// resolution is not deterministic: across repeated builds of
// byte-identical staged input, it has been observed (empirically, running
// the same build eight times in a row) to place SetAnubisExePath at either
// 1402 (immediately after RemoveExistingProducts) or 4001 (immediately
// after InstallFiles, immediately before BootstrapConfig), with
// BootstrapConfig following one step behind either way. Both placements
// satisfy the wxs's own constraints, so wixl's exit status gives no signal
// anything is wrong.
//
// The tightly-packed placement is the one this pins to, because it is the
// only one actually implied by the wxs text: nothing in anubis.wxs
// schedules SetAnubisExePath relative to RemoveExistingProducts, so pinning
// to that position would invent an ordering guarantee the wxs never asked
// for. InstallFiles's own Sequence is read back rather than hardcoded, so
// this keeps working if its position ever changes.
//
// This corrects the value only, not the table's on-disk row order, which
// was tried and abandoned: deleting a row and reinserting it under the same
// Action was observed, empirically, to always land the row back in its
// original physical slot regardless of when or in what order the insert
// ran -- slot placement in this MSI table format appears to be a function
// of the Action string alone, immutable from outside once wixl first
// writes the row, and not reachable through msibuild's SQL interface. Since
// Windows Installer executes actions in Sequence order regardless of
// on-disk row order, that residual is cosmetic -- but it does mean two
// otherwise byte-identical MSIs can still differ in exactly where this
// table's rows for SetAnubisExePath and BootstrapConfig physically sit, in
// addition to the summary information timestamps. TestMSIReproducibleBuild
// tolerates both.
func patchCustomActionSequence(msiPath string) error {
installFiles, err := readSequenceNumber(msiPath, "InstallFiles")
if err != nil {
return err
}
// Applied in this fixed order, not map iteration, so the msibuild
// invocations themselves are reproducible.
type pin struct {
action string
want int
}
pins := []pin{
{"SetAnubisExePath", installFiles + 1},
{"BootstrapConfig", installFiles + 2},
}
for _, p := range pins {
cmd := exec.Command("msibuild", msiPath, "-q",
fmt.Sprintf("UPDATE InstallExecuteSequence SET Sequence=%d WHERE Action='%s'", p.want, sqlEscape(p.action)))
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("mkmsi: msibuild failed to pin the sequence for %s: %w: %s", p.action, err, stderr.String())
}
}
for _, p := range pins {
got, err := readSequenceNumber(msiPath, p.action)
if err != nil {
return err
}
if got != p.want {
return fmt.Errorf("mkmsi: msibuild did not pin the sequence for %s on %s: got %d, want %d", p.action, msiPath, got, p.want)
}
}
return nil
}
// readSequenceNumber returns the Sequence column for one Action row of the
// InstallExecuteSequence table, as reported by `msiinfo export`.
func readSequenceNumber(msiPath, action string) (int, error) {
out, err := exec.Command("msiinfo", "export", msiPath, "InstallExecuteSequence").Output()
if err != nil {
return 0, fmt.Errorf("mkmsi: msiinfo export %s InstallExecuteSequence failed: %w", msiPath, err)
}
for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") {
// Action Condition Sequence
fields := strings.Split(line, "\t")
if len(fields) == 3 && fields[0] == action {
seq, err := strconv.Atoi(fields[2])
if err != nil {
return 0, fmt.Errorf("mkmsi: InstallExecuteSequence row for %s in %s has a non-numeric Sequence %q: %w", action, msiPath, fields[2], err)
}
return seq, nil
}
}
return 0, fmt.Errorf("mkmsi: msiinfo export %s InstallExecuteSequence has no row for action %s", msiPath, action)
}
+805
View File
@@ -0,0 +1,805 @@
package main
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"testing"
"time"
)
// mkmsiRequireVerifyEnv is the opt-in environment variable that turns a skip
// into a failure. It must only be set by workflow jobs that actually install
// msitools and build the zips these tests inspect -- currently
// package-builds-stable.yml and package-builds-unstable.yml's "Verify MSI
// contents" step. Gating on CI alone was tried and failed: GitHub Actions
// sets CI=true on every job, including go.yml, which never installs msitools
// or runs `go tool yeet`, so that made the main Go workflow fail on every PR.
const mkmsiRequireVerifyEnv = "MKMSI_REQUIRE_VERIFY"
// skipOrFail skips the test locally but fails it when mkmsiRequireVerifyEnv
// is set.
//
// These tests are the only automated verification that the MSI's tables
// survived wixl, which silently drops attributes it does not understand. A
// skip and a pass are both exit 0, so a skip in a job that claims to verify
// this would show a green check while checking nothing. Everywhere else --
// including a contributor's laptop and the main Go workflow, neither of
// which installs msitools -- skipping is right.
func skipOrFail(t *testing.T, format string, args ...any) {
t.Helper()
if os.Getenv(mkmsiRequireVerifyEnv) == "true" {
t.Fatalf("refusing to skip with "+mkmsiRequireVerifyEnv+"=true: "+format, args...)
}
t.Skipf(format, args...)
}
// requireTool skips the test when a required external program is missing, so
// contributors without msitools installed are not blocked.
func requireTool(t *testing.T, name string) {
t.Helper()
if _, err := exec.LookPath(name); err != nil {
skipOrFail(t, "%s is not installed, skipping: %v", name, err)
}
}
// findZip returns the Windows zip yeet has built for arch, skipping the test
// if there is none.
//
// It checks both var/ directly and one level of subdirectory: yeet's default
// destination is var/, but the human partner routinely builds with something
// like --package-dest-dir ./var/win.
//
// No zip at all is always a skip, including with mkmsiRequireVerifyEnv set.
// There is nothing to verify without a build, and a checkout that never ran
// `go tool yeet` must not be reported as a broken MSI.
//
// Several candidates for the same architecture are normal on a working
// checkout: var/ accumulates the zips of every release the human partner has
// built. The one that matters is always the newest, so this picks the
// candidate with the latest modification time instead of making the
// contributor delete their own build output to get a green run. Ties break on
// path order, which only happens when two copies were written in the same
// filesystem timestamp tick.
func findZip(t *testing.T, arch string) string {
t.Helper()
pattern := "anubis-*-windows-" + arch + ".zip"
var matches []string
for _, glob := range []string{
filepath.Join("..", "..", "..", "var", pattern),
filepath.Join("..", "..", "..", "var", "*", pattern),
} {
found, err := filepath.Glob(glob)
if err != nil {
t.Fatalf("Glob: %v", err)
}
matches = append(matches, found...)
}
sort.Strings(matches)
switch len(matches) {
case 0:
t.Skipf("no Windows %s zip in var or var/*, run `go tool yeet` first", arch)
case 1:
return matches[0]
}
newest := matches[0]
newestMod, err := modTime(newest)
if err != nil {
t.Fatalf("stat %s: %v", newest, err)
}
for _, m := range matches[1:] {
mod, err := modTime(m)
if err != nil {
t.Fatalf("stat %s: %v", m, err)
}
if mod.After(newestMod) {
newest, newestMod = m, mod
}
}
t.Logf("found %d Windows %s zips under var, using the newest: %s (modified %s)", len(matches), arch, newest, newestMod.Format(time.RFC3339))
return newest
}
// modTime returns the modification time of a file.
func modTime(path string) (time.Time, error) {
st, err := os.Stat(path)
if err != nil {
return time.Time{}, err
}
return st.ModTime(), nil
}
// buildTestMSI builds an MSI for arch from the newest zip and returns its
// path.
func buildTestMSI(t *testing.T, arch string) string {
t.Helper()
requireTool(t, "wixl")
requireTool(t, "wixl-heat")
requireTool(t, "msiinfo")
// Every arch shells out to msibuild now, to patch SecureCustomProperties
// after wixl builds the package (see secureInstallDir); arm64 additionally
// uses it to patch the summary Template.
requireTool(t, "msibuild")
out := filepath.Join(t.TempDir(), "anubis-"+arch+".msi")
cmd := exec.Command("go", "run", ".",
"--zip", findZip(t, arch),
"--out", out,
"--packaging-dir", filepath.Join("..", "..", "..", "run", "windows"),
"--staging-dir", filepath.Join("..", "..", "..", "var", "mkmsi"),
)
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
t.Fatalf("mkmsi failed: %v", err)
}
return out
}
// exportTable returns one MSI table as text.
//
// msiinfo export writes CRLF line endings. Left alone, the trailing \r rides
// along on whichever column is last in each row -- silently, since it prints
// invisibly and only breaks exact-match comparisons against that column.
// Normalizing here means every caller that splits on "\n" and "\t" gets clean
// fields.
func exportTable(t *testing.T, msi, table string) string {
t.Helper()
out, err := exec.Command("msiinfo", "export", msi, table).Output()
if err != nil {
t.Fatalf("msiinfo export %s: %v", table, err)
}
return strings.ReplaceAll(string(out), "\r\n", "\n")
}
// suminfo returns the value of one field from `msiinfo suminfo`, such as
// "Template" or "Version", with the "Field:" prefix and surrounding
// whitespace stripped.
func suminfo(t *testing.T, msi, field string) string {
t.Helper()
out, err := exec.Command("msiinfo", "suminfo", msi).Output()
if err != nil {
t.Fatalf("msiinfo suminfo %s: %v", msi, err)
}
prefix := field + ":"
for _, line := range strings.Split(string(out), "\n") {
if rest, ok := strings.CutPrefix(line, prefix); ok {
return strings.TrimSpace(rest)
}
}
t.Fatalf("msiinfo suminfo %s has no %q line:\n%s", msi, field, out)
return ""
}
// suminfoVersion returns the numeric InstallerVersion from `msiinfo
// suminfo`'s Version line, which msitools renders as "200 (c8)".
func suminfoVersion(t *testing.T, msi string) string {
t.Helper()
v := suminfo(t, msi, "Version")
if i := strings.IndexByte(v, ' '); i >= 0 {
v = v[:i]
}
return v
}
// property returns one row's value from the MSI's Property table.
func property(t *testing.T, msi, name string) string {
t.Helper()
for _, line := range strings.Split(exportTable(t, msi, "Property"), "\n") {
fields := strings.SplitN(line, "\t", 2)
if len(fields) == 2 && fields[0] == name {
return fields[1]
}
}
t.Fatalf("property %s not found in %s", name, msi)
return ""
}
// lastTableRow returns the last line of an exported table, which is its
// final data row when the table has exactly one.
func lastTableRow(t *testing.T, msi, table string) string {
t.Helper()
lines := strings.Split(strings.TrimRight(exportTable(t, msi, table), "\n"), "\n")
if len(lines) == 0 || lines[0] == "" {
t.Fatalf("table %s in %s is empty", table, msi)
}
return lines[len(lines)-1]
}
// componentConditions maps every Component in the MSI to its Condition
// column, which is empty for components that always install.
func componentConditions(t *testing.T, msi string) map[string]string {
t.Helper()
conditions := make(map[string]string)
for _, line := range strings.Split(exportTable(t, msi, "Component"), "\n") {
// Component ComponentId Directory_ Attributes Condition KeyPath
fields := strings.Split(line, "\t")
if len(fields) < 5 {
continue
}
// Attributes is a required integer column; the two header rows
// (column names, column types) do not parse as one, so this is a
// clean way to skip them without hardcoding the header text.
if _, err := strconv.Atoi(fields[3]); err != nil {
continue
}
conditions[fields[0]] = fields[4]
}
return conditions
}
func TestMSIContents(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("skipping on development machines")
}
msi := buildTestMSI(t, "amd64")
for _, tt := range []struct {
name string
table string
// want are substrings that must all appear in the exported table.
want []string
}{
{
name: "service is registered as manual start under its virtual account",
table: "ServiceInstall",
// Columns: ServiceInstall, Name, DisplayName, ServiceType(16 =
// own process), StartType(3 = manual), ErrorControl(1 = normal).
//
// StartName is the NT SERVICE virtual account the service control
// manager creates alongside the service. It has to be the fully
// qualified name: a bare "Anubis" or "LocalService" gets looked up
// as a local user account and the install fails.
want: []string{"svc_anubis\tAnubis\tAnubis\t16\t3\t1", `NT SERVICE\Anubis`},
},
{
name: "service is stopped and deleted on uninstall",
table: "ServiceControl",
// Event 162 = stop on install, stop and delete on uninstall.
want: []string{"Anubis\t162"},
},
{
name: "bin directory is added to the system PATH",
table: "Environment",
want: []string{"=*PATH", "[BINDIR]"},
},
{
name: "bootstrap custom action is present and deferred",
table: "CustomAction",
// 3122 = exe named by a property, deferred, no impersonation.
want: []string{"SetAnubisExePath\t51", "BootstrapConfig\t3122", "--windows-bootstrap-config"},
},
{
name: "major upgrades are configured",
table: "Upgrade",
want: []string{"{92F5FC1F-F6F2-4BD1-BBEF-79B8A46C665F}"},
},
{
name: "both binaries and both config templates are installed",
table: "File",
want: []string{
"anubis.exe",
"anubis-robots2policy.exe",
"fil_tmpl_env",
"fil_tmpl_yaml",
},
},
{
name: "the documentation tree is installed",
table: "File",
want: []string{"CHANGELOG.md", "installation.mdx"},
},
{
// Proof the WixUI_Minimal dialog set actually landed in the
// MSI rather than being silently dropped: wixl has crashed
// internally on hand-authored dialogs before now and emitted
// an MSI with no Dialog table at all.
name: "the WixUI_Minimal dialog set is present",
table: "Dialog",
want: []string{"WelcomeEulaDlg", "VerifyReadyDlg", "ProgressDlg", "ExitDialog"},
},
{
// secureInstallDir patches this row in after wixl builds the
// MSI (see its doc comment for why it cannot be done
// declaratively in anubis.wxs). Without it, a command-line
// INSTALLDIR= would not survive elevation into the deferred
// part of the install.
name: "INSTALLDIR is a secure custom property",
table: "Property",
want: []string{"SecureCustomProperties\tINSTALLDIR"},
},
} {
t.Run(tt.name, func(t *testing.T) {
got := exportTable(t, msi, tt.table)
for _, want := range tt.want {
if !strings.Contains(got, want) {
t.Errorf("table %s does not contain %q\ngot:\n%s", tt.table, want, got)
}
}
})
}
}
// TestMSIStartsServiceOnlyOnUpgrade verifies the fix for an upgrade silently
// leaving Anubis stopped: RemoveExistingProducts sequences before
// InstallServices, so the outgoing product's ServiceControl (Event=162)
// stops and deletes the service, and the incoming ServiceInstall recreates it
// with StartType=demand. Without an explicit start request an upgrade always
// reports success while leaving the site unprotected.
//
// Every ServiceControl row that requests a start (Event bit 0 set) must
// belong to a Component conditioned on WIX_UPGRADE_DETECTED -- the property
// MajorUpgrade sets only when an earlier version of Anubis is already
// installed -- so a fresh install, which has a placeholder target and no
// signing key, never starts the service.
func TestMSIStartsServiceOnlyOnUpgrade(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("skipping on development machines")
}
msi := buildTestMSI(t, "amd64")
conditions := componentConditions(t, msi)
var sawStartRow bool
for _, line := range strings.Split(exportTable(t, msi, "ServiceControl"), "\n") {
fields := strings.Split(line, "\t")
if len(fields) < 6 || fields[1] != "Anubis" {
continue
}
event, err := strconv.Atoi(fields[2])
if err != nil {
// Header rows carry column names and types, not numbers.
continue
}
if event&1 == 0 {
continue
}
sawStartRow = true
component := fields[5]
if cond := conditions[component]; cond != "WIX_UPGRADE_DETECTED" {
t.Errorf("ServiceControl row %q requests a start (event %d) via component %q, whose condition is %q, want %q",
fields[0], event, component, cond, "WIX_UPGRADE_DETECTED")
}
}
if !sawStartRow {
t.Error("no ServiceControl row for the anubis service requests a start; the upgrade fix appears to be missing")
}
}
func TestMSIArm64(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("skipping on development machines")
}
amd64 := buildTestMSI(t, "amd64")
arm64 := buildTestMSI(t, "arm64")
t.Run("summary Template names each architecture", func(t *testing.T) {
if got, want := suminfo(t, amd64, "Template"), "x64;1033"; got != want {
t.Errorf("amd64 Template = %q, want %q", got, want)
}
if got, want := suminfo(t, arm64, "Template"), "Arm64;1033"; got != want {
t.Errorf("arm64 Template = %q, want %q", got, want)
}
})
t.Run("InstallerVersion is 500 on arm64, 200 on amd64", func(t *testing.T) {
// Arm64 package templates require Windows Installer 5.0; declaring a
// lower InstallerVersion risks the MSI being rejected on the target
// as "not supported by this processor type".
if got, want := suminfoVersion(t, amd64), "200"; got != want {
t.Errorf("amd64 Version = %q, want %q", got, want)
}
if got, want := suminfoVersion(t, arm64), "500"; got != want {
t.Errorf("arm64 Version = %q, want %q", got, want)
}
})
t.Run("ProductCode differs between architectures", func(t *testing.T) {
amdCode := property(t, amd64, "ProductCode")
armCode := property(t, arm64, "ProductCode")
if amdCode == armCode {
t.Errorf("amd64 and arm64 MSIs share ProductCode %q; Windows would treat installing one as uninstalling the other", amdCode)
}
})
t.Run("ServiceInstall is identical across architectures", func(t *testing.T) {
amdSvc := lastTableRow(t, amd64, "ServiceInstall")
armSvc := lastTableRow(t, arm64, "ServiceInstall")
if amdSvc != armSvc {
t.Errorf("ServiceInstall row differs between architectures:\namd64: %s\narm64: %s", amdSvc, armSvc)
}
})
}
// extractStream returns the raw bytes of one binary stream from an MSI, as
// reported by `msiinfo extract`.
func extractStream(t *testing.T, msi, stream string) []byte {
t.Helper()
out, err := exec.Command("msiinfo", "extract", msi, stream).Output()
if err != nil {
t.Fatalf("msiinfo extract %s %s: %v", msi, stream, err)
}
return out
}
// TestMSIInstallerImages verifies patchInstallerImages actually replaced
// wixl's stock WiX banner and dialog artwork with run/windows/banner.bmp and
// run/windows/dialog.bmp, rather than the msibuild -a calls silently no-oping
// the way Property/@Secure="yes" did earlier in this file's history. Byte
// length is a cheap, robust stand-in for a full comparison: it is exactly
// what changes if someone swaps in a real image and the patch stops running,
// since the stock artwork's size is fixed and different from Anubis's.
func TestMSIInstallerImages(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("skipping on development machines")
}
msi := buildTestMSI(t, "amd64")
for _, img := range installerImages {
t.Run(img.stream, func(t *testing.T) {
source := filepath.Join("..", "..", "..", "run", "windows", img.file)
wantInfo, err := os.Stat(source)
if err != nil {
t.Fatalf("stat %s: %v", source, err)
}
got := extractStream(t, msi, img.stream)
if int64(len(got)) != wantInfo.Size() {
t.Errorf("stream %s is %d bytes, %s is %d bytes -- patchInstallerImages may not have run",
img.stream, len(got), source, wantInfo.Size())
}
})
}
}
// rtfControlWord matches one RTF control word, with its optional numeric
// parameter and the single trailing space that terminates it, such as
// `\ansicpg1252 ` or `\par`.
var rtfControlWord = regexp.MustCompile(`\\[a-zA-Z]+-?[0-9]*[ ]?`)
// stripRTF reduces an RTF document to plain text: control words (\rtf1,
// \par, \f0, ...) and group braces are removed, and the rest -- including
// stray literal text from groups like the font table, which this does not
// try to identify -- is collapsed to single-spaced words.
//
// This is deliberately crude rather than a real RTF parser. It only needs to
// let TestMSILicenseRTFMatchesLicense find the license wording inside
// License.rtf; a byte-exact comparison would make that test brittle for no
// benefit.
func stripRTF(s string) string {
s = rtfControlWord.ReplaceAllString(s, " ")
s = strings.NewReplacer("{", " ", "}", " ").Replace(s)
return strings.Join(strings.Fields(s), " ")
}
// TestMSILicenseRTFMatchesLicense fails if run/windows/License.rtf, which
// WixUI_Minimal's EULA dialog displays, has fallen out of sync with the
// repo's LICENSE. Someone editing LICENSE has no other reason to think about
// the installer, so nothing else catches this.
func TestMSILicenseRTFMatchesLicense(t *testing.T) {
license, err := os.ReadFile(filepath.Join("..", "..", "..", "LICENSE"))
if err != nil {
t.Fatalf("reading LICENSE: %v", err)
}
rtf, err := os.ReadFile(filepath.Join("..", "..", "..", "run", "windows", "License.rtf"))
if err != nil {
t.Fatalf("reading run/windows/License.rtf: %v", err)
}
if !bytes.HasPrefix(rtf, []byte(`{\rtf1`)) {
t.Fatalf("run/windows/License.rtf does not start with %q, is it valid RTF?", `{\rtf1`)
}
rtfText := stripRTF(string(rtf))
for _, para := range strings.Split(string(license), "\n\n") {
// LICENSE hard-wraps its paragraphs; License.rtf does not, so compare
// each paragraph as one line.
para = strings.Join(strings.Fields(para), " ")
if para == "" {
continue
}
if !strings.Contains(rtfText, para) {
t.Errorf("run/windows/License.rtf is missing text from LICENSE, or has fallen out of sync with it\nmissing paragraph: %q", para)
}
}
}
// msiTables returns the sorted list of table names in an MSI, as reported by
// `msiinfo tables`.
func msiTables(t *testing.T, msi string) []string {
t.Helper()
out, err := exec.Command("msiinfo", "tables", msi).Output()
if err != nil {
t.Fatalf("msiinfo tables %s: %v", msi, err)
}
var tables []string
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if line != "" {
tables = append(tables, line)
}
}
sort.Strings(tables)
return tables
}
// msiStreams returns the sorted list of stream names in an MSI, as reported
// by `msiinfo streams`.
func msiStreams(t *testing.T, msi string) []string {
t.Helper()
out, err := exec.Command("msiinfo", "streams", msi).Output()
if err != nil {
t.Fatalf("msiinfo streams %s: %v", msi, err)
}
var streams []string
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if line != "" {
streams = append(streams, line)
}
}
sort.Strings(streams)
return streams
}
// sortedLines splits s on newlines and sorts the result, so two exports of
// the same table can be compared as sets when row order is not guaranteed
// to match.
func sortedLines(s string) []string {
if strings.TrimSpace(s) == "" {
return nil
}
lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
sort.Strings(lines)
return lines
}
// diffByteCount returns how many bytes differ between a and b at the same
// offset, plus any length mismatch, for a more informative log message than
// a bare "not equal" when two builds turn out not to be byte-identical.
func diffByteCount(a, b []byte) int {
n := 0
for i := 0; i < len(a) && i < len(b); i++ {
if a[i] != b[i] {
n++
}
}
if len(a) > len(b) {
n += len(a) - len(b)
} else {
n += len(b) - len(a)
}
return n
}
// requireSuminfoMatchesExceptTimestamps fails the test if two MSIs' summary
// information differs anywhere other than the Created and Last saved
// fields. wixl stamps both from the wall clock when it builds the package,
// and msibuild's -s -- the only tool available to rewrite summary
// information -- has no argument for either one; see
// TestMSIReproducibleBuild's doc comment.
func requireSuminfoMatchesExceptTimestamps(t *testing.T, msi1, msi2 string) {
t.Helper()
out1, err := exec.Command("msiinfo", "suminfo", msi1).Output()
if err != nil {
t.Fatalf("msiinfo suminfo %s: %v", msi1, err)
}
out2, err := exec.Command("msiinfo", "suminfo", msi2).Output()
if err != nil {
t.Fatalf("msiinfo suminfo %s: %v", msi2, err)
}
lines1 := strings.Split(strings.TrimRight(string(out1), "\n"), "\n")
lines2 := strings.Split(strings.TrimRight(string(out2), "\n"), "\n")
if len(lines1) != len(lines2) {
t.Fatalf("suminfo line count differs between %s (%d) and %s (%d):\n%s\nvs\n%s",
msi1, len(lines1), msi2, len(lines2), out1, out2)
}
for i := range lines1 {
if lines1[i] == lines2[i] {
continue
}
if strings.HasPrefix(lines1[i], "Created:") || strings.HasPrefix(lines1[i], "Last saved:") {
continue
}
t.Errorf("summary information differs beyond the known-unfixable Created/Last saved timestamps:\n%q\nvs\n%q", lines1[i], lines2[i])
}
}
// TestMSIReproducibleBuild builds the same zip into two separate MSIs and
// asserts the results match, aside from two residuals that could not be
// removed with the tools available (msitools' wixl, wixl-heat and
// msibuild):
//
// - The summary information's Created and Last saved timestamps: wixl
// stamps both from the wall clock when it builds the package, and
// msibuild's -s -- the only available way to rewrite summary
// information -- has no argument for either one.
// - The InstallExecuteSequence table's on-disk row order for
// SetAnubisExePath and BootstrapConfig. patchCustomActionSequence pins
// their Sequence *values* deterministically, but not their physical
// storage position: deleting a row and reinserting it under the same
// Action was observed, empirically, to always land the row back in its
// original slot, so nothing reachable through msibuild's SQL interface
// can move it. Windows Installer executes actions in Sequence order
// regardless of on-disk row order, so this has no effect on how the
// installer behaves -- see patchCustomActionSequence's doc comment for
// the full account.
//
// Everything else -- every other table, and every stream including the CAB
// archive -- is required to be exactly byte-identical.
func TestMSIReproducibleBuild(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("skipping on development machines")
}
requireTool(t, "wixl")
requireTool(t, "wixl-heat")
requireTool(t, "msiinfo")
requireTool(t, "msibuild")
zip := findZip(t, "amd64")
build := func(out string) {
t.Helper()
cmd := exec.Command("go", "run", ".",
"--zip", zip,
"--out", out,
"--packaging-dir", filepath.Join("..", "..", "..", "run", "windows"),
"--staging-dir", filepath.Join("..", "..", "..", "var", "mkmsi"),
)
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
t.Fatalf("mkmsi failed building %s: %v", out, err)
}
}
out1 := filepath.Join(t.TempDir(), "build1.msi")
out2 := filepath.Join(t.TempDir(), "build2.msi")
build(out1)
build(out2)
data1, err := os.ReadFile(out1)
if err != nil {
t.Fatalf("reading %s: %v", out1, err)
}
data2, err := os.ReadFile(out2)
if err != nil {
t.Fatalf("reading %s: %v", out2, err)
}
if bytes.Equal(data1, data2) {
// Byte-identical: every check below would necessarily pass too.
return
}
t.Logf("%s and %s are not byte-identical (%d of %d bytes differ); checking whether the difference is limited to the known residuals",
out1, out2, diffByteCount(data1, data2), max(len(data1), len(data2)))
requireSuminfoMatchesExceptTimestamps(t, out1, out2)
tables1 := msiTables(t, out1)
tables2 := msiTables(t, out2)
if !slices.Equal(tables1, tables2) {
t.Fatalf("table lists differ:\nbuild1: %v\nbuild2: %v", tables1, tables2)
}
for _, table := range tables1 {
switch table {
case "_SummaryInformation":
// Already checked, field by field, via `msiinfo suminfo`
// above -- more precisely than a raw property-stream export
// could, since it can name exactly which field differs.
continue
case "InstallExecuteSequence":
// Row order in this one table is a known residual; compare it
// as a set of rows instead of as ordered text. If the values
// themselves differ, that is a real bug in
// patchCustomActionSequence, not a tolerated residual.
rows1 := sortedLines(exportTable(t, out1, table))
rows2 := sortedLines(exportTable(t, out2, table))
if !slices.Equal(rows1, rows2) {
t.Errorf("table %s differs even as a set of rows (this would mean the Sequence *values* differ, not just row order):\nbuild1: %v\nbuild2: %v",
table, rows1, rows2)
}
continue
}
if got, want := exportTable(t, out1, table), exportTable(t, out2, table); got != want {
t.Errorf("table %s differs:\n--- %s ---\n%s\n--- %s ---\n%s", table, out1, got, out2, want)
}
}
streams1 := msiStreams(t, out1)
streams2 := msiStreams(t, out2)
if !slices.Equal(streams1, streams2) {
t.Fatalf("stream lists differ:\nbuild1: %v\nbuild2: %v", streams1, streams2)
}
for _, stream := range streams1 {
// OLE marks a property-set stream by prefixing its name with 0x05;
// `msiinfo streams` prints that literally, so this is
// "\x05SummaryInformation", not "SummaryInformation".
if strings.HasSuffix(stream, "SummaryInformation") {
// The raw property-set stream backing both the
// _SummaryInformation table and `msiinfo suminfo` -- already
// checked field by field, with the Created/Last saved
// exception, by requireSuminfoMatchesExceptTimestamps above.
continue
}
a := extractStream(t, out1, stream)
b := extractStream(t, out2, stream)
if !bytes.Equal(a, b) {
t.Errorf("stream %s differs: %d bytes in build1, %d bytes in build2", stream, len(a), len(b))
}
}
}
+151
View File
@@ -0,0 +1,151 @@
package main
import (
"errors"
"fmt"
"regexp"
"strconv"
"github.com/google/uuid"
)
var (
ErrBadVersion = errors.New("mkmsi: cannot parse version")
ErrVersionOutOfRange = errors.New("mkmsi: version component out of range")
)
// upgradeCode is the fixed MSI UpgradeCode for Anubis. Windows uses it to
// relate one installed version to another. It must never change: changing it
// makes every future installer fail to upgrade existing installs.
const upgradeCode = "92f5fc1f-f6f2-4bd1-bbef-79b8a46c665f"
// versionRe matches the versions yeet produces, such as "1.26.2" for a tagged
// release, "1.27.0-pre1" for a tagged prerelease, and
// "1.26.2-1-gec3cce8a-dev" for a build off a later commit.
//
// It is anchored at both ends on purpose. Without the trailing anchor a string
// like "1.26.2.4" matches its prefix and silently becomes 1.26.2.0, turning a
// version this code does not understand into a plausible wrong answer instead
// of a build failure.
var versionRe = regexp.MustCompile(`^v?(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-pre(?P<pre>\d+))?(?:-(?P<commits>\d+)-g[0-9a-fA-F]+)?(?:-dev)?$`)
// versionFields maps the numeric fields of an MSI ProductVersion onto the
// capture groups of versionRe, in the order they appear in the output, along
// with the maximum value MSI allows in each.
//
// The prerelease number has no field of its own: MSI compares only
// major.minor.build when deciding whether one package upgrades another, and
// there is no way to express "1.27.0-pre1 sorts below 1.27.0" in three
// unsigned numbers. It therefore reaches the installer only through the
// ProductCode, which hashes the raw version string, so a prerelease and its
// release are distinct products that share a ProductVersion. The wxs sets
// AllowSameVersionUpgrades for exactly this reason, so installing 1.27.0 over
// 1.27.0-pre1 still removes the prerelease instead of leaving both registered.
var versionFields = []struct {
name string
group string
limit int
}{
{name: "major", group: "major", limit: 255},
{name: "minor", group: "minor", limit: 255},
{name: "build", group: "patch", limit: 65535},
{name: "revision", group: "commits", limit: 65535},
}
// msiVersion converts a yeet version string into an MSI ProductVersion.
//
// MSI requires a numeric major.minor.build.revision, where major and minor are
// at most 255 and build and revision are at most 65535. The commit count from a
// dev build becomes the revision; a tagged release gets revision 0.
//
// Note that Windows ignores the revision field when deciding whether one
// package upgrades another, so a dev build and its base release look identical
// to the installer.
func msiVersion(in string) (string, error) {
m := versionRe.FindStringSubmatch(in)
if m == nil {
return "", fmt.Errorf("%w: %q", ErrBadVersion, in)
}
parts := make([]int, len(versionFields))
for i, f := range versionFields {
raw := m[versionRe.SubexpIndex(f.group)]
if raw == "" {
continue
}
n, err := strconv.Atoi(raw)
if err != nil {
// A digit string too long for an int is semantically out of
// range, not malformed. Callers distinguish the two.
if errors.Is(err, strconv.ErrRange) {
return "", fmt.Errorf("%w: %s %q does not fit in an int", ErrVersionOutOfRange, f.name, raw)
}
return "", fmt.Errorf("%w: %s %q: %w", ErrBadVersion, f.name, raw, err)
}
if n > f.limit {
return "", fmt.Errorf("%w: %s is %d, maximum is %d", ErrVersionOutOfRange, f.name, n, f.limit)
}
parts[i] = n
}
return fmt.Sprintf("%d.%d.%d.%d", parts[0], parts[1], parts[2], parts[3]), nil
}
// productCode derives the MSI ProductCode for a version and architecture.
// Every distinct version needs a distinct ProductCode, and rebuilding the
// same commit must produce the same one, so it is a UUIDv5 of the version and
// architecture in the UpgradeCode's namespace rather than a random UUID.
//
// The architecture is part of the hash input because it, like the version,
// must vary the ProductCode: two packages built for different architectures
// still install to the same UpgradeCode family, so if they shared a
// ProductCode too, Windows would treat them as the same product and
// installing one would silently uninstall the other.
func productCode(version, arch string) (string, error) {
if _, err := msiVersion(version); err != nil {
return "", err
}
ns, err := uuid.Parse(upgradeCode)
if err != nil {
return "", fmt.Errorf("mkmsi: cannot parse upgrade code %q: %w", upgradeCode, err)
}
return uuid.NewSHA1(ns, []byte(version+"/"+arch)).String(), nil
}
// packageCode derives the MSI PackageCode -- the summary information's
// "Revision number (UUID)" field -- for a version and architecture, the
// same way productCode derives the Product Id: a UUIDv5 in the
// UpgradeCode's namespace, so rebuilding the same commit reproduces the same
// value instead of getting whatever wixl randomizes it to.
//
// This is a deliberate departure from MSI convention, which calls for a
// unique PackageCode per built package file -- PackageCode exists to
// distinguish physical .msi files even when they install the same product,
// and normally two builds of identical bits still deserve two different
// PackageCodes because nothing guarantees the bits stayed identical. Making
// it deterministic is correct here specifically because the rest of this
// build has been made reproducible: once identical inputs are guaranteed to
// produce byte-identical output, a PackageCode that still changed on every
// rebuild would be actively misleading, not conservative.
//
// The hash input is distinguished from productCode's ("packagecode/" vs no
// prefix) so the two never collide: Windows must never see ProductCode and
// PackageCode take on the same GUID.
func packageCode(version, arch string) (string, error) {
if _, err := msiVersion(version); err != nil {
return "", err
}
ns, err := uuid.Parse(upgradeCode)
if err != nil {
return "", fmt.Errorf("mkmsi: cannot parse upgrade code %q: %w", upgradeCode, err)
}
return uuid.NewSHA1(ns, []byte("packagecode/"+version+"/"+arch)).String(), nil
}
+138
View File
@@ -0,0 +1,138 @@
package main
import (
"errors"
"testing"
)
func TestMSIVersion(t *testing.T) {
for _, tt := range []struct {
name string
in string
want string
wantErr error
}{
{name: "plain release", in: "1.26.2", want: "1.26.2.0"},
{name: "v prefix", in: "v1.26.2", want: "1.26.2.0"},
{name: "dev build", in: "1.26.2-1-gec3cce8a-dev", want: "1.26.2.1"},
{name: "dev build many commits", in: "1.26.2-137-gdeadbee", want: "1.26.2.137"},
// Prereleases share a ProductVersion with their release; only the
// ProductCode tells them apart. See versionFields.
{name: "prerelease", in: "1.27.0-pre1", want: "1.27.0.0"},
{name: "prerelease with v prefix", in: "v1.27.0-pre2", want: "1.27.0.0"},
{name: "dev build off a prerelease", in: "1.27.0-pre1-4-gec3cce8a-dev", want: "1.27.0.4"},
{name: "prerelease number is not a version component", in: "1.27.0-pre256", want: "1.27.0.0"},
{name: "major too big", in: "256.0.0", wantErr: ErrVersionOutOfRange},
{name: "minor too big", in: "1.256.0", wantErr: ErrVersionOutOfRange},
{name: "patch too big", in: "1.0.65536", wantErr: ErrVersionOutOfRange},
{name: "revision too big", in: "1.0.0-65536-gdeadbee", wantErr: ErrVersionOutOfRange},
{name: "empty", in: "", wantErr: ErrBadVersion},
{name: "not a version", in: "devel", wantErr: ErrBadVersion},
{name: "two components", in: "1.26", wantErr: ErrBadVersion},
{name: "four components", in: "1.26.2.4", wantErr: ErrBadVersion},
{name: "trailing garbage", in: "1.26.2extra", wantErr: ErrBadVersion},
{name: "garbage after commit hash", in: "1.26.2-1-gdead-devXXX", wantErr: ErrBadVersion},
{name: "prerelease without a number", in: "1.27.0-pre", wantErr: ErrBadVersion},
{name: "unknown prerelease flavour", in: "1.27.0-rc1", wantErr: ErrBadVersion},
{name: "prerelease after commit count", in: "1.27.0-4-gdeadbee-pre1", wantErr: ErrBadVersion},
{name: "overflows an int", in: "99999999999999999999.0.0", wantErr: ErrVersionOutOfRange},
} {
t.Run(tt.name, func(t *testing.T) {
got, err := msiVersion(tt.in)
if tt.wantErr != nil {
if !errors.Is(err, tt.wantErr) {
t.Fatalf("msiVersion(%q): got error %v, want %v", tt.in, err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("msiVersion(%q): unexpected error: %v", tt.in, err)
}
if got != tt.want {
t.Errorf("msiVersion(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
func TestProductCodeIsDeterministic(t *testing.T) {
const version = "1.26.2-1-gec3cce8a-dev"
first, err := productCode(version, "amd64")
if err != nil {
t.Fatalf("productCode(%q): %v", version, err)
}
second, err := productCode(version, "amd64")
if err != nil {
t.Fatalf("productCode(%q): %v", version, err)
}
if first != second {
t.Errorf("productCode is not deterministic: %q != %q", first, second)
}
}
func TestProductCodeVariesByVersion(t *testing.T) {
a, err := productCode("1.26.2", "amd64")
if err != nil {
t.Fatalf("productCode: %v", err)
}
b, err := productCode("1.26.3", "amd64")
if err != nil {
t.Fatalf("productCode: %v", err)
}
if a == b {
t.Errorf("different versions produced the same ProductCode %q", a)
}
}
func TestProductCodeVariesByPrerelease(t *testing.T) {
pre, err := productCode("1.27.0-pre1", "amd64")
if err != nil {
t.Fatalf("productCode: %v", err)
}
release, err := productCode("1.27.0", "amd64")
if err != nil {
t.Fatalf("productCode: %v", err)
}
// A prerelease and its release compare equal as MSI ProductVersions, so
// the ProductCode is the only thing that keeps them from looking like the
// same installed package to Windows.
if pre == release {
t.Errorf("1.27.0-pre1 and 1.27.0 produced the same ProductCode %q", pre)
}
}
func TestProductCodeVariesByArch(t *testing.T) {
const version = "1.26.2"
amd64, err := productCode(version, "amd64")
if err != nil {
t.Fatalf("productCode: %v", err)
}
arm64, err := productCode(version, "arm64")
if err != nil {
t.Fatalf("productCode: %v", err)
}
// Sharing a ProductCode across architectures makes Windows treat the two
// packages as one product, so installing either one uninstalls the other.
if amd64 == arm64 {
t.Errorf("amd64 and arm64 produced the same ProductCode %q", amd64)
}
}
func TestProductCodeRejectsBadVersion(t *testing.T) {
if _, err := productCode("devel", "amd64"); !errors.Is(err, ErrBadVersion) {
t.Errorf("productCode(\"devel\"): got %v, want %v", err, ErrBadVersion)
}
}