pkg

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Native package management

Package pkg provides one interface for apt, DNF/DNF5, pacman, and zypper. It detects an installed backend or accepts an explicit backend, executes every mutation non-interactively, and returns typed errors and captured command results.

r, err := exec.NewRunner(exec.Direct)
if err != nil {
    return err
}

m, err := pkg.New(pkg.Auto, r)
if err != nil {
    return err
}

_, err = m.Install(ctx, pkg.InstallOptions{}, "curl")

The core mutation surface is package install/remove and full-system update. Read operations remain available for status and diagnostics. Package names, versions, search terms, local package paths, and GPG key references are validated before execution.

Use exec.Direct when the caller already runs as root. exec.Sudo and exec.Doas use non-interactive escalation and fail closed if authorization would require a password.

Documentation

Overview

Package pkg provides a uniform package-manager abstraction for Linux.

A Manager is built for an explicit Backend over an injected exec.Runner — the SDK keeps no global escalation state and every Manager is unit-testable with exectest.FakeRunner (no host, no sudo, no container):

r, _ := exec.NewRunner(exec.Sudo)
m, err := pkg.New(pkg.Apt, r)
if err != nil { ... }
if _, err := m.Install(ctx, pkg.InstallOptions{}, pkg.InstallSpec{Name: "vim"}, pkg.InstallSpec{Name: "git"}); err != nil { ... }

Reads (Search/List/Show/IsInstalled/…) run unprivileged; mutations (Install/InstallLocal/Remove/Update/Upgrade/Pin/Unpin/Autoremove) run through the Runner's privilege backend. Every package-name, version, and local-file-path argument is validated before it can reach argv — there is no opt-out.

Use Detect to discover which native backends are installed; it lists and never picks, so the caller decides.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound reports that the requested package is absent.
	ErrNotFound = errors.New("package not found")
	// ErrUnsupported reports that the backend cannot perform an operation.
	ErrUnsupported = errors.New("package operation unsupported")
	// ErrInvalidArgument reports an invalid package-manager argument.
	ErrInvalidArgument = errors.New("invalid package argument")
)
View Source
var ErrUnknownBackend = errors.New("pkg: unknown package-manager backend")

ErrUnknownBackend is returned by New for a Backend the SDK does not implement (including the zero value). Fail-closed: no silent default.

Functions

func ValidateGpgKeyRef

func ValidateGpgKeyRef(ref string) error

ValidateGpgKeyRef validates a dnf/zypper Gpgkey reference before it reaches `rpm --import`. Accepted iff it is (a) an https URL with a host, (b) a file:// absolute path (file:///… — empty host, no `..`), or (c) a bare absolute filesystem path (no `..`). Everything else is refused: a leading '-' (option injection into `rpm --import`), plaintext http (MITM of the trust anchor itself), rpm's `ext::` external transport (which executes a command), and relative or traversing paths.

func ValidateLocalPackagePath

func ValidateLocalPackagePath(path string) error

ValidateLocalPackagePath validates a filesystem path before it reaches a package manager as the operand of a local-file install (apt-get install <file>, dnf install <file>, pacman -U <file>, or zypper install <file>). It is NOT a package name, so the package-name grammar does not apply; what matters is that the path cannot masquerade as an option and cannot smuggle a config/log-injecting control character:

  • absolute (a leading '/'): a relative path is ambiguous w.r.t. the privileged process's working directory, and an absolute path can never be flag-shaped. Callers pass a concrete file location (typically a temp file they downloaded and checksum-verified), so this costs them nothing.
  • no ".." segment: defence-in-depth against a traversing path, mirroring ValidateGpgKeyRef.
  • no control characters (incl. NUL, newline, tab) or DEL: a space is left alone (it is argv-safe and legal in a path), but control characters are refused so a crafted path can neither break a log line nor confuse a tool.

Existence is NOT checked: the Manager has no host access (it drives an injected Runner), and a missing file surfaces cleanly as the tool's own non-zero exit. The absolute-path requirement — not a "--" end-of-options separator — is what keeps the path from being read as an option, because some tools (dnf5) reject "--" for their install/search subcommands entirely.

func ValidatePackageName

func ValidatePackageName(name string) error

ValidatePackageName returns a non-nil error when name would be unsafe to pass as a positional argument to any of the supported package managers. Callers MUST invoke this (or ValidatePackageNames) at the top of every public method that accepts a package name, before any exec.CommandContext call.

func ValidatePackageNames

func ValidatePackageNames(names []string) error

ValidatePackageNames runs ValidatePackageName against every entry. Returns the first rejection; does not try to be exhaustive — actions are signed and a rejection here is a caller bug, not an adversarial probe to enumerate.

func ValidatePackageVersion

func ValidatePackageVersion(version string) error

ValidatePackageVersion checks a version string before it lands in `<name>=<version>` (apt) or similar argv constructs. Empty version is treated as "no version pinned" and accepted; any non-empty version must match the cross-distro grammar in validPackageVersion.

func ValidateRpmPackageName

func ValidateRpmPackageName(name string) error

ValidateRpmPackageName returns a non-nil error when name is not a safe RPM %{NAME} to pass to `rpm -q`/`rpm -e`. The name a crafted .rpm reports is untrusted; callers MUST validate it before it reaches argv. Mirrors ValidatePackageName / the deb-side validDebPkgName.

func ValidateSearchQuery

func ValidateSearchQuery(query string) error

ValidateSearchQuery guards the free-text query passed to a package-manager search. A search term is not a fixed grammar (it may carry '+', '.', glob characters, etc.), so it is deliberately NOT run through validPackageName; the one thing that must be refused is a value that could be reparsed as an OPTION. A leading '-' is rejected — a search term never legitimately starts with a dash, and a "--" end-of-options separator is NOT portable here (dnf5's `search` subcommand rejects "--"), so validation is the honest defense. Control characters are rejected too. An empty query is allowed (a backend may list everything).

Types

type AvailableVersion

type AvailableVersion struct {
	Version    string
	Repository string
	Size       int64
}

AvailableVersion represents a specific version available for installation.

type Backend

type Backend int

Backend identifies a supported package manager. The zero value is invalid (New rejects it); valid values start at 1.

const (
	// Apt is the Debian/Ubuntu package manager (apt / apt-get / dpkg).
	Apt Backend = iota + 1
	// Dnf is the Fedora/RHEL package manager (dnf / rpm).
	Dnf
	// Dnf5 is the Fedora/RHEL package manager backed by dnf5.
	Dnf5
	// Pacman is the Arch Linux package manager.
	Pacman
	// Zypper is the openSUSE/SLES package manager (zypper / rpm).
	Zypper
)

func Detect

func Detect() []Backend

Detect returns the package-manager backends whose primary binary resolves on PATH, in priority order. The result may be empty or hold several entries. It lists; it never picks — the caller chooses.

func (Backend) String

func (b Backend) String() string

String returns the canonical lowercase backend name.

type InstallLocalOptions

type InstallLocalOptions struct {
	// AllowDowngrade permits installing a package file whose version is lower
	// than the one currently installed. Honored on apt (--allow-downgrades),
	// dnf5 (--allow-downgrade) and zypper (--oldpackage). DNF4 exact package
	// specifications and local files already select the requested version.
	AllowDowngrade bool
	// AllowUnsigned skips the backend's GPG signature check for the local file.
	// It is secure-default-OFF: with the default (false) an unsigned local .rpm
	// is rejected by dnf/zypper. Set it ONLY when the file's authenticity is
	// established out of band — e.g. an HTTPS transport plus a verified SHA256
	// checksum — so the package manager's per-file GPG check is redundant. Per
	// backend:
	//   - dnf:    adds --nogpgcheck
	//   - zypper: adds --allow-unsigned-rpm (per-package; never the global
	//             --no-gpg-checks, which would also drop repo-metadata checks)
	//   - apt:    no-op — a local .deb carries no per-file signature to skip
	//   - pacman: NOT honored — `pacman -U` enforces the repo SigLevel and has no
	//             per-invocation bypass; the install stays signature-checked
	AllowUnsigned bool
}

InstallLocalOptions configures an InstallLocal call.

type InstallOptions

type InstallOptions struct {
	// AllowDowngrade permits installing a lower version than the one installed.
	AllowDowngrade bool
}

InstallOptions configures an Install call.

type InstallSpec

type InstallSpec struct {
	Name    string
	Version string
}

InstallSpec names one package and optionally pins its version.

type LocalPackage

type LocalPackage struct {
	Name    string
	Version string
	Arch    string
}

LocalPackage is the identity read out of a LOCAL package file (a .deb, .rpm or pacman package on disk) by Manager.LocalPackageInfo. Name is the canonical package name — validated against the backend's package-name grammar before it is returned, because the value is read out of an attacker-influenced file. Version and Arch are best-effort extra fields (a backend that cannot report one leaves it empty).

type Manager

type Manager interface {
	// Backend reports which package-manager backend this Manager drives.
	Backend() Backend

	// Version returns the package-manager tool version string.
	Version(ctx context.Context) (string, error)
	// Search returns packages whose name/summary matches query.
	Search(ctx context.Context, query string) ([]SearchResult, error)
	// List returns the installed packages.
	List(ctx context.Context) ([]Package, error)
	// ListUpgradable returns packages with an available upgrade.
	ListUpgradable(ctx context.Context) ([]PackageUpdate, error)
	// Show returns detailed information about a single package.
	Show(ctx context.Context, name string) (*Package, error)
	// ListVersions returns the versions available for a package.
	ListVersions(ctx context.Context, name string) (*VersionInfo, error)
	// IsInstalled reports whether name is currently installed.
	IsInstalled(ctx context.Context, name string) (bool, error)
	// LocalPackageInfo reads a package's canonical name (and, where the backend
	// reports them, version and architecture) from a LOCAL package file already on
	// disk — a .deb, .rpm or pacman package — WITHOUT installing it. path must be
	// an absolute filesystem path (ValidateLocalPackagePath). The name a crafted
	// file embeds is untrusted, so it is validated against the backend's
	// package-name grammar before being returned; a flag-shaped or
	// metacharacter-bearing name is rejected.
	LocalPackageInfo(ctx context.Context, path string) (*LocalPackage, error)
	// InstalledVersion returns the installed version of name, or ErrNotFound.
	InstalledVersion(ctx context.Context, name string) (string, error)
	// InstalledCount returns the number of installed packages.
	InstalledCount(ctx context.Context) (int, error)
	// HasUpdates reports whether any update is available.
	HasUpdates(ctx context.Context) (bool, error)
	// HasSecurityUpdates reports whether security updates are available.
	HasSecurityUpdates(ctx context.Context) (bool, error)
	// IsPinned reports whether name is held back from upgrades.
	IsPinned(ctx context.Context, name string) (bool, error)
	// ListPinned returns the packages held back from upgrades.
	ListPinned(ctx context.Context) ([]Package, error)

	// Install installs each package specification in one transaction.
	Install(ctx context.Context, opts InstallOptions, specs ...InstallSpec) (sysexec.Result, error)
	// InstallLocal installs a package from a local file already on disk — a
	// downloaded .deb, .rpm, or pacman package — rather than by
	// name from a configured repository, resolving dependencies from the
	// configured repositories where the backend supports it (apt/dnf/zypper/
	// pacman). path must be an ABSOLUTE filesystem path to the package file;
	// fetching and verifying the artifact (https transport, checksum) is the
	// caller's responsibility. opts.AllowDowngrade permits a lower version than
	// the one currently installed; opts.AllowUnsigned skips the backend's GPG
	// check (dnf --nogpgcheck / zypper --allow-unsigned-rpm) for a file whose
	// authenticity is established out of band — secure-default-off.
	InstallLocal(ctx context.Context, path string, opts InstallLocalOptions) (sysexec.Result, error)
	// Remove removes the named packages. opts.Purge also deletes configuration
	// where the backend distinguishes it.
	Remove(ctx context.Context, opts RemoveOptions, packages ...string) (sysexec.Result, error)
	// Update refreshes the package metadata/database.
	Update(ctx context.Context) (sysexec.Result, error)
	// Upgrade upgrades the named packages. With NO names it is a no-op (not a
	// full upgrade) — an accidentally-empty list must never upgrade the whole
	// system. Use UpgradeAll for that.
	Upgrade(ctx context.Context, packages ...string) (sysexec.Result, error)
	// UpgradeAll performs a full system upgrade.
	UpgradeAll(ctx context.Context) (sysexec.Result, error)
	// UpgradeSecurity applies only security updates.
	UpgradeSecurity(ctx context.Context) (sysexec.Result, error)
	// Pin holds the named packages back from upgrades.
	Pin(ctx context.Context, packages ...string) (sysexec.Result, error)
	// Unpin releases the named packages so they upgrade again.
	Unpin(ctx context.Context, packages ...string) (sysexec.Result, error)
	// Autoremove removes packages installed only as now-unneeded dependencies.
	Autoremove(ctx context.Context) (sysexec.Result, error)
}

Manager is the uniform package-manager surface. Every method takes a context so the caller controls timeout/cancellation. Query methods return typed results; mutating methods return the command's output (an exec.Result carrying exit code, stdout and stderr) so callers can surface what the package manager actually did, plus an error — a non-zero exit becomes an *exec.CommandError carrying the exit code and stderr while the Result still carries the full stdout/stderr. The Result is populated on both the success and non-zero-exit paths; it is the zero Result only when the command could not be run at all (the error is then a plain runner error) or when the call is a validated no-op (e.g. an empty package list).

func New

func New(b Backend, runner sysexec.Runner) (Manager, error)

New builds a Manager for backend b driven by runner. A nil runner or an unknown backend is rejected (fail-closed). New is pure — it does not probe the host; use Detect to learn which backends are installed.

type Package

type Package struct {
	Name         string
	Version      string
	Architecture string
	Description  string
	Status       string // installed, available, upgradable, pinned
	Size         int64  // installed size in bytes
	Repository   string
}

Package represents an installed or available package.

type PackageUpdate

type PackageUpdate struct {
	Name           string
	CurrentVersion string
	NewVersion     string
	Architecture   string
	Repository     string
}

PackageUpdate represents an available update for a package.

type RemoveOptions

type RemoveOptions struct {
	// Purge also removes configuration/data where the backend distinguishes it.
	Purge bool
}

RemoveOptions configures a Remove call.

type SearchResult

type SearchResult struct {
	Name        string
	Version     string
	Description string
	Repository  string
}

SearchResult represents a package search result.

type VersionInfo

type VersionInfo struct {
	Name      string
	Versions  []AvailableVersion
	Installed string // currently installed version, empty if not installed
}

VersionInfo represents available versions of a package.

Jump to

Keyboard shortcuts

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