pinstall

package module
v3.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

README

pinstall

Go Reference Go version Mutation

pinstall installs a pinned version of another program from your Go code, refuses it unless its SHA-256 matches your pin, and tells your program when it is ready to run.

It replaces the download, checksum and install steps you would otherwise write in a shell script or a container entrypoint. It runs on Linux only, needs Go 1.27.1 or later and is licensed under Apache-2.0. Its one dependency outside the standard library is pathinside, which uses only the standard library itself.

Why use it

pinstall is built for a long-running Linux program, often a container, that downloads another vendor's binary at run time. A typical case is a tool whose license lets you download it but not include it in your image.

  • Nothing reaches a version directory until the archive's SHA-256 matches your pin.
  • Each version installs into its own directory and is marked complete last, so an interrupted install is never used.
  • On every start it checks the binary's version and reruns your required setup commands, such as turning auto-update off.
  • It keeps one earlier version by default as a fallback, retries with bounded backoff and never exits your process.
  • By default it refuses an install tree that an account other than yours, root's or one you list can write to, and names the path and the account. InstallWithoutCustody turns that refusal into a warning.

Consider aqua if you want to pin CLI tool versions per project in a config file, for development and CI on Windows, macOS and Linux.

Install

go get github.com/cplieger/pinstall/v3@latest

Usage

A Release describes the package and is written once. A Config is one deployment of it, with the pin, the digests, the install root and your local policy.

package main

import (
	"context"
	"log"
	"os/exec"

	"github.com/cplieger/pinstall/v3"
)

// The pinned digests. Whatever bumps your version literal bumps these with it.
const (
	widgetVersion = "1.4.2"
	amd64SHA      = "9f2b...64 lowercase hex characters..."
	arm64SHA      = "3ce1...64 lowercase hex characters..."
)

// The profile: written once, reused by every deployment.
func widgetRelease() pinstall.Release {
	return pinstall.Release{
		Name:        "widget",
		URLTemplate: "https://widgets.example/dl/{arch}/widget_{version}.zip",
		ArchTokens:  map[string]string{"amd64": "linux-64", "arm64": "linux-arm"},
		ArtifactDir: "dist/bin", // the archive already holds the artifacts
		ProbeArgs:   []string{"--version"},
		Mandatory: []pinstall.Assertion{
			// Must hold after every install; a deployment cannot drop it.
			{Name: "autoupdate", Args: []string{"config", "set", "autoupdate", "off"}},
		},
	}
}

func main() {
	mgr, err := pinstall.New(&pinstall.Config{
		Release: widgetRelease(),
		Version: widgetVersion,
		Digests: map[string]string{"amd64": amd64SHA, "arm64": arm64SHA},
		Root:    "/var/lib/example/tools",
		LinkDir: "bin",                     // optional convenience symlinks
		Require: []string{"widget-helper"}, // artifacts you cannot run without
	})
	if err != nil {
		log.Fatal(err)
	}

	// Bounded, retrying, and non-fatal: a failure leaves your program running.
	if err := mgr.EnsureWithRetry(context.Background()); err != nil {
		log.Printf("widget install failed, serving degraded: %v", err)
	}

	if ready, why := mgr.Ready(); !ready {
		log.Printf("widget is not usable yet: %s", why)
		return
	}

	// Always the absolute version-directory path, never the convenience link.
	out, err := exec.Command(mgr.Path(), "run").Output()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("%s", out)
}

Run the binary at mgr.Path(). Put mgr.PathEntry() first in the PATH of anything you start. You can instead append mgr.PathEnv() to os.Environ(). Either way, a program that looks up this release's artifacts by name finds the active version.

Each digest is the SHA-256 of that architecture's archive, which you record when you choose the version. pinstall downloads with its own HTTP client, which reads no proxy settings from the environment. Config.URLTemplate can point at a mirror instead.

The pinstall/kirocli package is a ready-made Release for kiro-cli, Kiro's terminal coding agent. Configuration lists every field and its default.

API

  • New checks a Release and a Config and returns a *Manager. It refuses a release that declares no mandatory assertion.
  • Ensure runs one idempotent install pass, EnsureWithRetry retries it with backoff, and Rescan rereads the disk without downloading.
  • Ready, Active, Path, PathEntry and PathEnv report readiness and where the active binary is.
  • Reason is one of ReasonReady, ReasonInstalling, ReasonRetrying, ReasonUnavailable and ReasonAssertion. Your program chooses the words it shows for each.
  • ErrDigestMismatch, ErrUnsupportedArch, ErrNoVersion, ErrVersionMismatch, ErrNoCustody, ErrACLUnreadable and ErrACLDialectUnsupported match with errors.Is.
  • UnpackZip and LastFieldOfFirstLine are the default unpacker and version parser. ParseIdentities parses a list of trusted user or group IDs. It reports how many entries it refused, never their text, so a secret set on the wrong variable stays out of your logs.

A Manager logs installs, retries and warnings through the default log/slog logger. pinstall reads no environment variable for its own settings and does no work at import time. The full reference is on pkg.go.dev.

What it guarantees

  • A version directory is complete or absent. Each file is synced, a .complete marker is written and synced last, and only then is the directory renamed into place.
  • The install root stays private. Before anything is fetched, the root and every directory above it must be owned by you or root and writable by nobody else, access-control lists included.
  • It refuses an unsafe tree and leaves the fix to you. When another account that can write the tree already holds root, such as an administrator, list it in TrustedUIDs or TrustedGIDs.
  • The verified archive cannot be swapped. Its file name is deleted before the first byte arrives, and extraction reads the same open file the digest check read.
  • Names it acts on stay under Root. Archive entries, moved artifacts, the state record, the links and every sweep target go through an os.Root, so the kernel refuses a symlink that would redirect one.
  • Required settings hold on every start. Each Mandatory assertion runs against the staged binary before publication and against the active one on every pass, and a failure withholds readiness.
  • A failed install keeps the old version serving. Pruning runs only after a successful publish.

The ownership check has two exemptions. A directory above the root may be writable by others when its sticky bit is set, as on /tmp. Group 0 counts as trusted, so the check does not guard against an account that belongs to group 0. How pinstall works has the full contract.

Unsupported by design

  • Signature or attestation checks. Your pinned digest is the trust anchor, so check a signature where you produce the pin.
  • Resolving "latest". It installs exactly the version it is given.
  • Repairing permissions it finds wrong. It refuses and names the path.
  • Rollback journals and backups. Nothing is overwritten in place, and the kept predecessor is the recovery.
  • Archive formats other than zip. For a tar.gz release, write an Unpacker, one function that receives the verified bytes and an os.Root on the destination. Staying inside that root is your code's job.
  • Windows and macOS.
  • Changing the version inside a running process. A new pin arrives by restarting your program.

Non-goals gives the reasoning for each, and for leaving out per-file digest checks at activation.

Documentation

  • Configuration lists every Release and Config field, its default, and how retention and trusted identities work.
  • How pinstall works covers the install protocol, the ownership check, assertions, downloads and the sweep of an older install layout.
  • Non-goals explains what is left out and why.

Credits

The ownership check verifies once and refuses, as OpenSSH's StrictModes, sudo's ownership check on sudoers and git's safe.directory do.

Contributing

See CONTRIBUTING.md.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI-assisted tooling using Claude, GPT, and Kiro. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package pinstall installs, activates and maintains a digest-pinned upstream release under <Root>/<Name>-versions/<version>/, populated only from a digest-verified archive, published by one same-filesystem rename and marked by a ".complete" sentinel written last, so an interrupted install is never a selection candidate.

Custody is verified before any byte is fetched and never repaired: Root and every directory above it must be writable only by this process's identity or root (see ErrNoCustody, Config.TrustedUIDs and Config.InstallWithoutCustody). Names taken from a profile, an archive or an on-disk tree are acted on through an os.Root; paths the package generates itself are acted on directly. Build a Release once and a Config per deployment, then call New. Nothing exits the process, reads the environment or works at import time. Linux only.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrDigestMismatch reports that the downloaded archive is not the artifact the
	// pinned digest names. No version directory and no staging tree are created when
	// it is returned, so nothing becomes a selection candidate. The installation root
	// itself may exist — custody has to be judged on the real directory — and the
	// archive's own blocks are freed with its descriptor, having never had a name.
	ErrDigestMismatch = errors.New("archive SHA-256 mismatch")
	// ErrUnsupportedArch reports an architecture the release publishes no
	// archive for, or one with no pinned digest.
	ErrUnsupportedArch = errors.New("unsupported architecture")
	// ErrNoVersion reports that no complete version is installed and none could
	// be installed, so there is nothing to activate.
	ErrNoVersion = errors.New("no complete version is installed")
	// ErrVersionMismatch reports that a candidate artifact answered the version
	// probe with something other than the version its directory and sentinel
	// claim.
	ErrVersionMismatch = errors.New("binary reported a version its install directory does not claim")
	// ErrNoCustody reports that the installation root, or a directory on the way to
	// it, can be modified by a principal other than this process's identity or root —
	// so nothing installed there can be trusted to stay what was installed. The
	// wrapped text names the offending path and what is wrong with it: an owner, a
	// mode, or an access-control list whose entries the mode does not show. Fix the
	// volume, or set [Config.InstallWithoutCustody] to proceed anyway.
	//
	// Its absence is not a proof of safety. Two limits are worth knowing before relying
	// on a clean verdict. Group 0 is trusted, so a host where the root GROUP has members
	// is not covered — those accounts can write a root:root group-writable tree and this
	// check will not say so (see the reasoning on trustedWriters.allows). And the check
	// reads Unix ownership, the mode and the ACL-dialect attributes; a filesystem that does not make the mode its
	// access decision at all — a cifs mount with noperm, a FUSE filesystem without
	// default_permissions — returns a clean verdict from inside the process no matter
	// who can write. If that is your volume, you know something this library cannot
	// measure, and [Config.InstallWithoutCustody] is where you say so.
	ErrNoCustody = errors.New("the installation root is not under this process's exclusive control")
)

Errors callers can classify. Everything else is wrapped with context.

View Source
var ErrACLDialectUnsupported = fmt.Errorf("%w: the dialect is not one this parser can decode", ErrACLUnreadable)

ErrACLDialectUnsupported reports that an object carries an access-control list in a dialect this package cannot decode, as distinct from one it decoded and refused. It wraps ErrACLUnreadable, because the consequence is the same one: the check does not know who can write, so it fails closed.

system.nfs4_acl is the only dialect in this state, and it is worth stating why rather than dropping it from the list of attributes consulted. It is the attribute nfs4-acl-tools reads and writes, and it carries VARIABLE-LENGTH STRING principals ("root@example.com") rather than the numeric ids of the XDR encoding OpenZFS serves through system.nfs4_acl_xdr, which is where every list this parser has been checked against came from. Decoding the one with the other's fixed-size layout misreads ids wherever the lengths happen to line up and skips entries wherever they do not — a writer set quietly missing a writer. Ignoring the attribute instead would make a grant served over NFS invisible, which is the same failure by omission. So it is named: an operator who knows the identities on that export can declare them in Config.TrustedUIDs and Config.TrustedGIDs, and one who knows the volume needs no checking can say so with Config.InstallWithoutCustody.

View Source
var ErrACLUnreadable = errors.New("the access-control list could not be evaluated")

ErrACLUnreadable reports that an access-control list is present but could not be evaluated. It is deliberately distinct from a refusal on the CONTENT of an ACL: this one says the check does not know, which is why it fails closed.

Functions

func LastFieldOfFirstLine

func LastFieldOfFirstLine(out string) string

LastFieldOfFirstLine is the default Release.ParseVersion: the last whitespace-separated field of the first line, and "" when there is none. It covers the common `<name> <version>` and bare `<version>` shapes and never panics on arbitrary input.

A release whose probe prints something else — JSON, a multi-column banner — sets its own parser, because probe output has no universal shape.

Example

ExampleLastFieldOfFirstLine shows the default version parser, which covers the two common probe shapes and returns "" when there is nothing to take.

package main

import (
	"fmt"

	"github.com/cplieger/pinstall/v3"
)

func main() {
	fmt.Printf("%q\n", pinstall.LastFieldOfFirstLine("widget 1.4.2\n"))
	fmt.Printf("%q\n", pinstall.LastFieldOfFirstLine("1.4.2\n"))
	fmt.Printf("%q\n", pinstall.LastFieldOfFirstLine("widget 1.4.2\nbuilt 2026-01-01\n"))
	fmt.Printf("%q\n", pinstall.LastFieldOfFirstLine("\n"))

}
Output:
"1.4.2"
"1.4.2"
"1.4.2"
""

func ParseIdentities

func ParseIdentities(raw string) (ids []int, rejected int)

ParseIdentities parses a comma-separated list of numeric identities into the shape Config.TrustedUIDs and Config.TrustedGIDs take, and reports how many entries it refused.

It exists because every consumer that installs through this library faces the same question about the same volume, and each was answering it with its own copy of the same twenty lines. The rule those copies encode is this package's, not the application's: what a uid means here, why zero grants nothing, and which values are not identities at all are all consequences of Config.TrustedUIDs's contract, so they belong beside it rather than in each caller.

It does NOT read the environment and it does NOT log, and both halves of that are deliberate. The caller owns the variable name, because a knob is spelled by the application that documents it; and the caller owns every word an operator reads, because the diagnosis is written against that name and its own README. This package logs plenty elsewhere, so the silence here is a division of labour rather than a house style.

What is returned is a COUNT of refusals, never the refused text, and that is the part a caller must not work around. A malformed entry is the operator's own input, and a compose interpolation mistake can put a credential on any variable — `TRUSTED_UIDS: ${SOME_TOKEN}` is one typo away from an environment that looks fine. Echoing the rejected value would then leave a durable, queryable copy of a secret in the log store (CWE-532), which is also why strconv.Atoi's own error is dropped rather than wrapped: a strconv.NumError carries the text that must not travel. A count is the most a caller can report and still be safe, and it is enough to say "some of what you wrote did not land".

The refusals, all four of them:

  • Text that is not a number at all.
  • Zero, because root is trusted unconditionally, so naming it grants nothing and is more likely a placeholder that expanded to an empty value.
  • Any negative value, which is not an identity.
  • Nothing else. A blank between separators is SKIPPED rather than counted: a doubled or trailing comma declares no identity, so it is neither a grant nor a mistake worth a diagnostic.

Duplicates collapse and first-seen order is kept, so what reaches the library is a set rather than a transcript of the operator's typing.

The name is not ParseTrustedUIDs, because whether these identities are TRUSTED is the caller's assertion — made by passing the result to one of those two fields — and the same list shape feeds both. A uid-specific name handed to Config.TrustedGIDs would read as a bug at every call site that does the correct thing.

func UnpackZip

func UnpackZip(ctx context.Context, archive *io.SectionReader, dst *os.Root) error

UnpackZip is the shipped Unpacker: archive/zip written through the destination root, with entry-count and total-size guards. It is used whenever Release.Unpack is nil.

Executable bits survive (an in-archive installer has to run) but nothing wider than owner-write does, because the extracted tree lands on a persistent volume.

Types

type ArchiveInstaller

type ArchiveInstaller struct {
	// Path is the script's path relative to the extraction directory
	// (e.g. "pkg/install.sh").
	Path string
	// HomeEnv is the environment variable pointed at the private staging home.
	// Empty means HOME.
	HomeEnv string
	// Args is the argv passed to the script (e.g. {"--no-confirm"}).
	Args []string
	// Timeout bounds the run. Zero uses two minutes.
	Timeout time.Duration
}

ArchiveInstaller describes an installer script shipped inside the archive. Its exit code is deliberately not fatal: an upstream installer commonly touches shell profiles and other surfaces that legitimately fail in a minimal container, so what decides is whether the artifacts it produced pass the staged gates.

type Assertion

type Assertion struct {
	// Name identifies the assertion in logs and is the key
	// [Release.Mandatory] overrides on. It is not passed to the artifact.
	Name string
	// Args is the full argv after the artifact path
	// (e.g. {"settings", "app.disableAutoupdates", "true"}).
	Args []string
	// Required marks an assertion whose failure is integrity-relevant.
	Required bool
}

Assertion is one bounded command run against the installed artifact on every start, and against the STAGED artifact before publication when Required. Args is the full argv after the artifact path, so the library needs no knowledge of the package's configuration grammar.

A Required failure withholds readiness (and, before publication, refuses to publish). Anything else only warns.

type Config

type Config struct {
	// Digests maps a GOARCH to the lowercase hex SHA-256 of that
	// architecture's archive. The resolved architecture must have an entry.
	Digests map[string]string
	// Purge sweeps a previous installer's layout once. Nil skips it.
	Purge *Purge
	// Assert are the assertions re-asserted against the active artifact on
	// every start. [Release.Mandatory] is merged in, so a required assertion
	// cannot be dropped here.
	Assert []Assertion
	// Require names artifacts a version directory MUST hold to count as
	// complete. The release's primary artifact is always included.
	Require []string
	// Release is the package profile.
	Release Release
	// Version is the pin, validated against a path- and URL-safe character set
	// because it is interpolated into both a URL and a filesystem path.
	Version string
	// Root is the persistent installation root: the only tree this package
	// reads, writes or deletes.
	Root string
	// GOARCH selects the architecture. Empty resolves it from runtime.GOARCH.
	GOARCH string
	// URLTemplate overrides [Release.URLTemplate], for a mirror or a test
	// server. Empty uses the release's own template.
	URLTemplate string
	// LinkDir is a directory under Root holding a NON-AUTHORITATIVE
	// convenience symlink at each artifact the active version holds (the
	// primary, Require, and every Optional present), for an operator shelling
	// into the environment. A link this manager published is retracted once
	// the active version lacks its artifact or the artifact is no longer
	// declared; an entry another owner put in LinkDir is never touched. Empty
	// publishes none. Nothing in this package ever reads the links.
	LinkDir string
	// Optional names artifacts installed when the archive provides them, and
	// only warned about when it does not. It closes the pointer-bearing fields
	// rather than sitting beside Require only because a trailing slice costs the
	// garbage collector less to scan.
	Optional []string
	// Retain is how many predecessors to keep besides the active version. Zero
	// uses 1, which is what makes a bad activation recoverable without a
	// rollback journal.
	//
	// Retention counts only what could actually SERVE, and that is deliberately
	// NOT the same question as what may be deleted. A directory this process may
	// not activate never spends a slot the real fallback needs — keeping a corrupt
	// newer tree while pruning the good older one is the failure that rule exists
	// to prevent, and it would bite exactly when the pin has already failed.
	//
	// What may be deleted is a second question with its own answer. A directory in
	// a state selection refuses is left as found, because the library did not put
	// it there and deleting evidence is not its call, and so is one that may belong
	// to another principal when custody REFUSED the tree. A directory that merely
	// predates this process under [Config.Untrusted] with a clean verdict is
	// neither: nothing will ever activate it, so it is collected. Retain therefore
	// bounds the tree under a clean verdict whether or not Untrusted is set.
	Retain int
	// RetryBackoff is the first [Manager.EnsureWithRetry] backoff; it doubles
	// per attempt up to a ten minute cap. Zero uses 30s.
	RetryBackoff time.Duration
	// MaxAttempts bounds [Manager.EnsureWithRetry]. Zero uses 4. The retries
	// are bounded deliberately: an endless loop re-downloading a large archive
	// is worse than a visible failure an operator can repair.
	MaxAttempts int
	// TrustedUIDs and TrustedGIDs name identities whose write access to the installation
	// tree does NOT invalidate custody, beyond root and this process's own uid, which are
	// always trusted.
	//
	// This is the knob for the situation the library can see but cannot judge. It reads
	// the mode, the ownership and the access-control list of every directory on the way
	// to Root and can tell you that uid 3000 may write there; it can never tell that uid
	// 3000 is the administrator who already holds root through sudo, so writing those
	// files gains that account nothing. You know that, so you say it, and the library
	// goes back to enforcing the rule everywhere else.
	//
	// Each entry is a claim you are making: this identity is already at least as
	// privileged as the process running the install. An identity that is not — the
	// unprivileged account an application runs as, say — genuinely can escalate through a
	// binary this library installs and a consumer executes, and listing it there defeats
	// the point. Listing "everyone" is not possible, because a grant to everyone names no
	// identity to trust; see InstallWithoutCustody.
	TrustedUIDs []int
	// TrustedGIDs is the group half of TrustedUIDs. A group grant is a grant to every
	// current and future member, so it is the weaker claim of the two.
	TrustedGIDs []int
	// InstallWithoutCustody proceeds even though custody of Root could not be established:
	// the refusal becomes a warning and the install runs anyway.
	//
	// It is the blunt instrument, for a volume whose permissions cannot be described by
	// naming identities — one whose filesystem does not make the mode its access decision
	// at all (a cifs mount with noperm, a FUSE filesystem without default_permissions), or
	// one you simply accept as shared. Prefer TrustedUIDs and TrustedGIDs, which keep the
	// check working; reach for this when there is nothing precise to say.
	//
	// It also re-authorises what the library otherwise declines to do in a tree it does
	// not control: the one-shot Purge, the sweep of partial directories and orphan staging
	// trees, the retention prune, the convenience symlinks, and the state record. That
	// follows from what it means — the library is installing there, so refusing to tidy up
	// after itself would leave Purge silently dead and let partial directories accumulate
	// without bound.
	//
	// Setting it implies Untrusted's restriction on activation: in a tree this process does
	// not control, a completion sentinel is forgeable, so only a version THIS process
	// installed from a verified archive is activated. That carries Untrusted's effect on
	// [Config.Retain] with it — see there.
	InstallWithoutCustody bool
	// Untrusted activates only versions THIS process installed from a verified archive,
	// never one already on the volume, regardless of what the custody check concluded.
	//
	// The check has blind spots a caller may know about — a volume mounted into two
	// containers whose processes both map to uid 0 passes every question it asks — and this
	// is how to say so without also declaring the tree unmanageable. It costs a
	// digest-verified reinstall on every start, which is the price of not believing a
	// sentinel.
	//
	// It no longer stops [Config.Retain] bounding the tree. A directory an earlier
	// process installed is one no process will activate — `installed` is per-process and
	// never persisted — so under this flag with a CLEAN custody verdict such a directory
	// is neither a fallback to keep nor evidence to preserve, and pruning collects it.
	// The one shape still left alone is a complete directory in a tree custody REFUSED
	// and the caller waived: there the tree provably has a writer this library cannot
	// account for, so the directory may be another principal's install.
	Untrusted bool
}

Config is one deployment of one Release: the pin, the digests, the root and the local policy. The zero value is not usable — call New.

profile, then the pin, then the root, then policy, then the two custody escapes last because they are the fields a reader should meet only after the rest. Packing it for the 24 bytes fieldalignment can reclaim scatters that order, and a Config is allocated once per manager.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager installs, activates and maintains one pinned release. It is safe for concurrent use: Manager.Ensure and Manager.Rescan serialise against each other, while the readers never block behind an install.

func New

func New(cfg *Config) (*Manager, error)

New validates cfg and returns a manager.

It resolves the architecture from runtime.GOARCH when Config.GOARCH is empty, requires a well-formed digest for the resolved architecture, merges Release.Mandatory into Config.Assert, and refuses a profile that declares no mandatory assertions.

The caller's Config is not modified, and nothing the manager keeps shares memory with it: the snapshot is taken BEFORE validation, so what was validated is what the manager will use. That covers the two POINTERS as well as the maps and slices — Config.Purge and Release.Installer — and the argv inside every Assertion, which is what a later mutation would otherwise have been able to rewrite. See [Config.snapshot].

Example

ExampleNew builds a manager for one deployment of the widget release. The pin and the digests come from wherever the consumer keeps them; nothing is downloaded until Ensure runs.

package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/cplieger/pinstall/v3"
)

// widgetRelease is the profile a consumer of a fictional "widget" release writes
// once. Everything in it is true of the package regardless of where it is deployed.
func widgetRelease() pinstall.Release {
	return pinstall.Release{
		Name:        "widget",
		Binary:      "widget-cli",
		URLTemplate: "https://widgets.example/dl/{arch}/widget_{version}.zip",
		ArchTokens:  map[string]string{"amd64": "linux-64", "arm64": "linux-arm"},
		Installer: &pinstall.ArchiveInstaller{
			Path:    "widget/install.sh",
			Args:    []string{"--no-confirm"},
			Timeout: 2 * time.Minute,
		},
		ArtifactDir: ".local/bin",
		ProbeArgs:   []string{"--version"},
		Mandatory: []pinstall.Assertion{

			{Name: "autoupdate", Args: []string{"config", "set", "autoupdate", "off"}},
		},
	}
}

func main() {
	mgr, err := pinstall.New(&pinstall.Config{
		Release: widgetRelease(),
		Version: "1.4.2",
		Digests: map[string]string{
			"amd64": strings.Repeat("a", 64),
			"arm64": strings.Repeat("b", 64),
		},
		Root:    "/var/lib/example/tools",
		GOARCH:  "amd64",
		LinkDir: "bin",
		Require: []string{"widget-helper"},
		Assert: []pinstall.Assertion{
			{Name: "telemetry", Args: []string{"config", "set", "telemetry", "off"}},
		},
		Retain: 2,
	})
	if err != nil {
		fmt.Println("config error:", err)
		return
	}

	// Before the first Ensure nothing is active, and the reason says why.
	ready, why := mgr.Ready()
	fmt.Println("ready:", ready, "reason:", why)
	fmt.Printf("path: %q\n", mgr.Path())

}
Output:
ready: false reason: installing
path: ""
Example (MissingMandatory)

ExampleNew_missingMandatory shows the one construction error a profile author is most likely to hit: a release with no mandatory assertion is refused, so a guarantee cannot be lost by omitting it.

package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/cplieger/pinstall/v3"
)

// widgetRelease is the profile a consumer of a fictional "widget" release writes
// once. Everything in it is true of the package regardless of where it is deployed.
func widgetRelease() pinstall.Release {
	return pinstall.Release{
		Name:        "widget",
		Binary:      "widget-cli",
		URLTemplate: "https://widgets.example/dl/{arch}/widget_{version}.zip",
		ArchTokens:  map[string]string{"amd64": "linux-64", "arm64": "linux-arm"},
		Installer: &pinstall.ArchiveInstaller{
			Path:    "widget/install.sh",
			Args:    []string{"--no-confirm"},
			Timeout: 2 * time.Minute,
		},
		ArtifactDir: ".local/bin",
		ProbeArgs:   []string{"--version"},
		Mandatory: []pinstall.Assertion{

			{Name: "autoupdate", Args: []string{"config", "set", "autoupdate", "off"}},
		},
	}
}

func main() {
	release := widgetRelease()
	release.Mandatory = nil

	_, err := pinstall.New(&pinstall.Config{
		Release: release,
		Version: "1.4.2",
		Digests: map[string]string{"amd64": strings.Repeat("a", 64)},
		Root:    "/var/lib/example/tools",
		GOARCH:  "amd64",
	})
	fmt.Println(strings.SplitN(err.Error(), ". ", 2)[0])

}
Output:
pinstall: Release.Mandatory is empty

func (*Manager) Active

func (m *Manager) Active() (State, bool)

Active returns the diagnostic state record and whether a version is active.

func (*Manager) Ensure

func (m *Manager) Ensure(ctx context.Context) error

Ensure brings the pinned version online and is idempotent: on a start that already has the pin complete and activatable it downloads nothing and still re-asserts every assertion.

The order is the design. The one-shot purge runs first (it deletes a previous layout outright, so nothing downstream can be fooled by it), then partial directories go (a partial is never a selection candidate), then selection probes each candidate's own version before accepting it, then — only when the pin is not already activatable — the install runs, then the assertions are re-asserted against whatever was selected, then the convenience links are republished, and only then may pruning run.

func (*Manager) EnsureWithRetry

func (m *Manager) EnsureWithRetry(ctx context.Context) error

EnsureWithRetry drives Manager.Ensure with bounded exponential backoff. A single one-shot attempt would leave a failed first start withholding readiness forever with no further effort. It never exits the process, and it returns the last error after the attempts are exhausted.

func (*Manager) Path

func (m *Manager) Path() string

Path returns the absolute path of the active primary artifact, or "" when no version is active. This — never the convenience link — is what a consumer runs.

func (*Manager) PathEntry

func (m *Manager) PathEntry() string

PathEntry returns the absolute directory to lead PATH with, or "" when no version is active. It holds only this release's own artifacts, so leading with it shadows nothing else.

func (*Manager) PathEnv

func (m *Manager) PathEnv() []string

PathEnv returns the environment overlay to append to os.Environ before spawning anything that must resolve this release's artifacts, or nil when no version is active — Manager.PathEntry already composed into [pathEnv]'s rule, so a consumer satisfying the lead-PATH contract does not restate it.

It is exported because stating a contract is not the same as shipping it. Both of this library's consumers were told to lead PATH with Manager.PathEntry and each wrote its own composer, which with this package's own [binPathEnv] made three copies of one rule; the library's copy is the one that drifted, appending an empty inherited PATH and so producing the trailing separator [pathEnv] exists to avoid.

func (*Manager) Ready

func (m *Manager) Ready() (ready bool, why Reason)

Ready reports whether the installation may be used, and why not when it may not.

It is true only when a version is active AND this process asserted every required assertion against that exact artifact. The persisted State.AssertionsOK is never consulted: an assertion's effect lives in the package's own mutable configuration, so remembering that it once succeeded is stale evidence.

func (*Manager) Rescan

func (m *Manager) Rescan(ctx context.Context) (bool, error)

Rescan re-derives the active version from what is on disk right now, without downloading anything, and re-asserts the assertions. It makes a repair performed in place — an operator restoring a version directory, or replacing a wedged artifact — observable without a fresh process. It returns whether a version is active afterwards.

type Purge

type Purge struct {
	// Artifacts are paths relative to Root, removed only when they are regular
	// files.
	Artifacts []string
	// StagePrefix matches orphan staging trees directly under Root, removed
	// only when they are directories. Empty matches nothing.
	StagePrefix string
	// Marker is a dot-file under Root recording that the sweep completed, so it
	// runs once per volume rather than on every start. Empty reruns it every
	// start.
	Marker string
	// Names are entries directly under LinkDir, removed only when they are
	// regular files. A symlink at one of these paths belongs to another owner.
	Names []string
}

Purge is the one-shot sweep of a layout a PREVIOUS installer left on this volume. It is injected rather than built in because the residue is a fact about one deployment's history, not about the package: two consumers of the same upstream release can have arrived from different installers.

Each target is removed only when what is on disk has the SHAPE the old installer left there, so another owner's entry at the same path is refused rather than deleted.

type Reason

type Reason uint8

Reason explains a withheld readiness verdict. It is an enum rather than a string because the wording a consumer shows its own users is the consumer's: the library owns only the distinction between the states.

const (
	// ReasonReady means readiness is not withheld. Its String is empty.
	ReasonReady Reason = iota
	// ReasonInstalling means the first attempt of this process is still in
	// flight and no version has ever been activated.
	ReasonInstalling
	// ReasonRetrying means an attempt failed and another one is scheduled.
	ReasonRetrying
	// ReasonUnavailable means no version is active and no further attempt is
	// scheduled. Only a repair plus [Manager.Rescan], or a fresh process, can
	// clear it.
	ReasonUnavailable
	// ReasonAssertion means a version is active but a Required assertion could
	// not be asserted against it, so a guarantee the install depends on does
	// not hold.
	ReasonAssertion
)

The readiness reasons, in the order a start walks them.

func (Reason) String

func (r Reason) String() string

String returns a short, package-agnostic description of the reason, and "" for ReasonReady.

type Release

type Release struct {
	// Unpack extracts the verified archive from an open reader, into an
	// [os.Root] on the extraction directory. A nil Unpack uses [UnpackZip].
	// Neither parameter is a path, deliberately — see [Unpacker].
	Unpack Unpacker
	// Installer describes an installer script shipped INSIDE the archive. A nil
	// Installer means the archive already holds the artifacts.
	Installer *ArchiveInstaller
	// ParseVersion extracts a version from the probe's output. A nil
	// ParseVersion uses [LastFieldOfFirstLine].
	ParseVersion func(out string) string
	// ArchTokens maps a GOARCH to the token the publisher uses in its URLs
	// (e.g. "amd64" -> "x86_64-linux"). An architecture absent from the map is
	// [ErrUnsupportedArch].
	ArchTokens map[string]string
	// ProbeArgs is the argv that makes the primary artifact print its version
	// (e.g. {"--version"}). Required: every start probes the artifact it is
	// about to activate, so a release with no probe cannot be verified.
	//
	// It must be safe to run against a version this deployment will NOT activate, and
	// against one it is about to delete. Retention asks the same question of a retained
	// candidate before counting it as a usable fallback, so the argv has to be a pure
	// query: no migration, no cache warm, no write to shared state. A bare version flag
	// is; a subcommand that touches the package's own configuration is not.
	ProbeArgs []string
	// Name is the package identity. It fixes the versions root
	// (<Root>/<Name>-versions), the state file (<Root>/<Name>-state.json) and
	// the sentinel's claim. It is NOT the artifact name — see Binary.
	Name string
	// Binary is the primary artifact: the file the version probe runs, the file
	// its convenience link points at, and an always-present member of the
	// required set. Empty defaults to Name, which covers the common case; a
	// package named "aws-cli" that ships a binary called "aws" sets both.
	Binary string
	// URLTemplate is the archive URL, carrying the {version} and {arch}
	// placeholders (e.g. "https://example.invalid/{version}/pkg-{arch}.zip").
	// {arch} is substituted with the ArchTokens entry for the resolved GOARCH.
	URLTemplate string
	// ArtifactDir is where the artifacts land, relative to the installer's
	// private home when Installer is set and to the extraction directory
	// otherwise. Empty means the root of whichever of the two applies.
	ArtifactDir string
	// Notice is logged once per install attempt when non-empty: the licence
	// acknowledgement a proprietary upstream requires. Profile-owned, because
	// the library must not carry one vendor's licence text.
	Notice string
	// Mandatory are the assertions a deployment cannot configure away. Each one
	// is forced Required and merged over any caller assertion with the same
	// Name, so an integrity gate the package depends on (a self-update switch,
	// a telemetry kill switch) cannot be lost by a deployment's omission.
	//
	// At least one is required: [New] refuses a profile that declares none,
	// because "this package needs no post-install guarantee" and "the profile
	// author forgot" are indistinguishable from the outside.
	//
	// It closes the field list rather than sitting beside ProbeArgs only because
	// a trailing slice costs the garbage collector less to scan.
	Mandatory []Assertion
}

Release is everything true of the PACKAGE, independent of any deployment: the profile a consumer builds once and reuses across every environment. It is data, not policy — durability, version selection, retry, retention and the readiness verdict belong to the library and are not configurable.

type State

type State struct {
	UpdatedAt     time.Time `json:"updated_at"`
	ActiveVersion string    `json:"active_version"`
	Dir           string    `json:"dir"`
	Pinned        string    `json:"pinned"`
	LastError     string    `json:"last_error,omitempty"`
	AssertionsOK  bool      `json:"assertions_ok"`
}

State is the manager's persisted record, written to <Root>/<Name>-state.json. It is DIAGNOSTIC ONLY: every field is there for an operator reading the volume, and none of them is an input to Manager.Ready. AssertionsOK in particular records the last result as history — the assertion THIS process performed is the only thing that gates readiness, because an assertion's effect lives in the package's own mutable configuration rather than in the immutable version directory.

type Unpacker

type Unpacker func(ctx context.Context, archive *io.SectionReader, dst *os.Root) error

Unpacker extracts a verified archive into dst.

archive reads exactly the byte range the pinned digest was proved over, on the very descriptor the download wrote and hashed. Both access shapes work: io.SectionReader is an io.ReaderAt for a format that needs random access (zip reads its directory from the tail) and an io.Reader for one that streams. io.SectionReader.Size is the verified length.

There is no path to the archive in this signature. A name can be pointed at a different inode between the digest check and the read, so an implementation that opened one would extract bytes nothing ever proved — defeating the pin as completely as replacing the installed binary. Sharing the descriptor is what makes the proof and the extraction the same bytes by construction. (An implementation determined to find a path can still reach the file through io.SectionReader.Outer; the signature removes the accident, not the intent.)

dst is an os.Root on the extraction directory. Write THROUGH it and an archive entry cannot escape: os.Root refuses an absolute name, a traversing name, and a symlink leaving the tree, in the kernel, on every operation. That is strictly stronger than the lexical check this library used to perform and used to require of custom unpackers by documentation — a lexical check cannot see an entry that writes through a symlink an earlier entry in the same archive planted, which is the classic tar escape.

It is a better tool, not a cage. An Unpacker is ordinary in-process Go code: it can read dst.Name() and call os.OpenFile itself, so nothing here can stop an implementation that goes around the root. What the parameter does is remove the need to re-derive containment correctly, and make the contained path the shortest one. Do not join dst's name onto an entry name and open the result; use the os.Root methods.

An implementation MUST still bound the entry count and the total bytes written: containment is not a size limit, and a hostile archive that cannot escape can still fill the volume.

Directories

Path Synopsis
Package kirocli is the pinstall profile for the kiro-cli release.
Package kirocli is the pinstall profile for the kiro-cli release.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL