Files
nfpm/msi/validation.go
Dj GilcreaseandClaude Fable 5.1 c953fe3995 feat: add msi support (#1097)
* chore(deps): add go-msi and go-pkcs12

go.digitalxero.dev/go-msi is the pure-Go Windows Installer database
writer, validator, reader and Authenticode signer behind the new msi
packager; go-pkcs12 becomes a direct dependency for the signing tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Hnro326ZTAu2EqUTGGkCB

* feat: add msi support

Adds an `msi` packager that writes a real Windows Installer database with
the pure-Go go-msi library: contents are mapped onto the standard Windows
folders (everything else under the product's Program Files folder), root
metadata (description, homepage, license, vendor/maintainer, scripts) is
reused where MSI has a place for it, and advertised shortcuts, Windows
services, registry values, per-user installs and Authenticode signing are
exposed under `msi:`.

Every release replaces older installs of the same upgrade code in place:
the upgrade code and component GUIDs are derived from identities that
survive releases, while the product code follows the full version. A
version Windows Installer cannot represent is an error rather than a
silently clamped (and colliding) one.

Maintainer scripts run as elevated deferred custom actions embedded in the
package so they work before any file is installed and after every file is
removed; they are extracted to a randomly named, freshly created file
since the SYSTEM temp directory is world-writable.

Unit tests build real packages, run go-msi's ICE validator and assert on
the decoded tables; golden GUIDs pin the derivation contract. The
acceptance suite installs, exercises, upgrades and removes the package
with msiexec on a Windows runner and proves a failing script rolls back.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Hnro326ZTAu2EqUTGGkCB

* ci: validate nfpm-signed MSI on real Windows

Build and Authenticode-sign the MSI on Linux with nfpm's pure-Go signer
and a throwaway openssl certificate, then validate the signature with the
real Windows trust stack (Get-AuthenticodeSignature, signtool verify) and
install, exercise and remove it with msiexec on a Windows runner. The
unsigned msi-windows-install job remains as the control.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Hnro326ZTAu2EqUTGGkCB

* chore(deps): update go-msi to latest main

* Revert "chore(deps): update go-msi to latest main"

This reverts commit 05aaa91684.

* ci: integrate MSI validation with merge queue checks

* fix(msi): decode quoted maintainer names

* fix: preserve address-only maintainer fallback

* fix(msi): update go-msi and support explicit file versions

Pin the latest upstream fixes for string references, column limits, and PE version detection. Expose per-destination file version overrides so intentionally unversioned Go binaries can still be packaged, and update fixtures, docs, and schema.

* chore(deps): pin go-msi v0.5.1 release

* fix(msi): Correct downgrade removal and shortcut resources

Match Windows destinations without case sensitivity, reuse PE icon streams by source and target extension, and cover newer products in downgrade removal ranges.

Add table regressions, native icon extraction and ICE50 checks, and Windows downgrade acceptance with distinct payloads. Run MSI installation checks on pull requests.

See #1097

* test(msi): Correct native icon extraction assertions

Distinguish one RT_GROUP_ICON resource from the two extracted icon handles requested from the Windows shell. Preserve checks for both handles and cover malformed resource directories and extensionless icon targets.

See #1097

* fix(msi): Adopt go-msi v0.5.2 and reject install-path aliases

Use the released dependency fixes for downgrade sequencing, non-elevating per-user packages, and lossless non-ASCII summary metadata. Preserve the explicit removal rule for allowed downgrades.

Reject duplicate resolved installation targets while preserving GUID identities. Add downstream table regressions and native silent-downgrade and standard-user Unicode/script verification.

See #1097

* fix(msi): Adopt go-msi v0.5.3 and close authoring gaps

* test(msi): Normalize redirected native install paths

* fix(msi): Preserve upgrade targets and release artifacts

* fix(msi): Adopt go-msi v0.5.5 signing and AppSearch fixes

* fix(msi): expand remaining strings and prove hook rollback

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-11 02:25:17 +00:00

169 lines
5.4 KiB
Go

package msi
import (
"fmt"
"log"
"path"
"strconv"
"strings"
"github.com/goreleaser/nfpm/v2"
"github.com/goreleaser/nfpm/v2/files"
)
// identitySeed preserves the original GUID contract for ordinary fields, while
// putting ambiguous tuples in a separate, length-framed namespace. Escaping
// only a separator would itself collide with literal escape characters.
func identitySeed(fields ...string) string {
for _, field := range fields {
if strings.Contains(field, "|") {
var b strings.Builder
b.WriteString("framed:")
for _, value := range fields {
fmt.Fprintf(&b, "%d:%s", len(value), value)
}
return b.String()
}
}
return strings.Join(fields, "|")
}
func validateVersionFields(version string) error {
core := strings.TrimPrefix(version, "v")
if i := strings.IndexAny(core, "-+"); i >= 0 {
core = core[:i]
}
parts := strings.Split(core, ".")
if len(parts) > 4 {
return fmt.Errorf("version must have at most four numeric fields")
}
for _, field := range parts {
if field == "" || strings.IndexFunc(field, func(r rune) bool { return r < '0' || r > '9' }) >= 0 {
return fmt.Errorf("version field %q must be numeric", field)
}
if _, err := strconv.ParseUint(field, 10, 63); err != nil {
return fmt.Errorf("version field %q overflows the Windows Installer version limits", field)
}
}
return nil
}
func firstLicense(contents files.Contents) string {
var first string
for _, c := range contents {
if c.Packager != "" && c.Packager != packagerName {
continue
}
if c.Type != files.TypeRPMLicense && c.Type != files.TypeRPMLicence {
continue
}
if first == "" {
first = c.Source
} else {
log.Printf("warning: multiple license contents, %s is not used for the install UI", c.Source)
}
}
return first
}
func validatePathTree(info *nfpm.Info, filePaths map[string]string) error {
directories := map[string]bool{}
for target, source := range filePaths {
for parent := path.Dir(target); parent != "." && parent != "/"; parent = path.Dir(parent) {
if previous, ok := filePaths[parent]; ok {
return fmt.Errorf("package contents %q is a file but also a directory for %q", previous, source)
}
directories[parent] = true
}
}
for _, c := range info.Contents {
if c.Type != files.TypeDir {
continue
}
// Model a directory by resolving an imaginary child. This also handles
// an exact standard-folder prefix without treating its name as a file.
target := path.Dir(resolvedDestinationKey(info, path.Join(normalizeDest(c.Destination), "_directory_child")))
for parent := target; parent != "." && parent != "/"; parent = path.Dir(parent) {
if previous, ok := filePaths[parent]; ok {
return fmt.Errorf("package contents %q is a file but also a directory for %q", previous, c.Destination)
}
}
if !directories[target] {
return fmt.Errorf("package contents %q: msi does not support empty directories; remove the directory entry or include a file", c.Destination)
}
}
return nil
}
// mapPackageDestination routes the product's explicit Program Files subtree
// through INSTALLFOLDER too. This gives its files, shortcuts, service and
// registry references the same target when an installer redirects the folder.
func mapPackageDestination(info *nfpm.Info, dest string) (root, defaultDir, rel string) {
root, defaultDir, rel = mapDestination(dest, is64bit(info.Arch))
productRoot := "ProgramFilesFolder"
if is64bit(info.Arch) {
productRoot = "ProgramFiles64Folder"
}
if !info.MSI.PerUser && root == productRoot {
parts := strings.SplitN(rel, "/", 2)
if len(parts) == 2 && strings.EqualFold(parts[0], info.MSI.InstallDir) {
return installFolder, "", parts[1]
}
}
return root, defaultDir, rel
}
func registryResourceKey(info *nfpm.Info, r nfpm.MSIRegistry) string {
root, key := strings.ToUpper(r.Root), strings.ToLower(r.Key)
if root == "HKMU" || root == "HKCR" {
if root == "HKCR" {
key = `software\classes\` + key
}
root = "HKLM"
if info.MSI.PerUser {
root = "HKCU"
}
}
return identitySeed(root, key, strings.ToLower(r.Name))
}
func validateResourceOwners(info *nfpm.Info) error {
registry := map[string]int{}
for n, r := range info.MSI.Registry {
key := registryResourceKey(info, r)
if previous, exists := registry[key]; exists {
return fmt.Errorf("package msi.registry[%d] and msi.registry[%d] resolve to the same registry value", previous, n)
}
registry[key] = n
}
services := map[string]int{}
for n, s := range info.MSI.Services {
key := strings.ToLower(s.Name)
if previous, exists := services[key]; exists {
return fmt.Errorf("package msi.services[%d] and msi.services[%d] name the same Windows service %q", previous, n, s.Name)
}
services[key] = n
}
shortcuts := map[string]int{}
for n, s := range info.MSI.Shortcuts {
if info.MSI.PerUser && protectedShortcutDirectory(s.Directory) {
return fmt.Errorf("package msi.shortcuts[%d].directory %q is protected and cannot be used by a non-elevated per-user install", n, s.Directory)
}
key := identitySeed(s.Directory, strings.ToLower(s.Name))
if previous, exists := shortcuts[key]; exists {
return fmt.Errorf("package msi.shortcuts[%d] and msi.shortcuts[%d] create the same Windows shortcut %q", previous, n, s.Name)
}
shortcuts[key] = n
}
return nil
}
func protectedShortcutDirectory(dir string) bool {
switch dir {
case "WindowsFolder", "WindowsVolume", "SystemFolder", "System64Folder", "FontsFolder", "CommonAppDataFolder":
return true
default:
return false
}
}