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{}, "vim", "git"); err != nil { ... }
Reads (Search/List/Show/IsInstalled/…) run unprivileged; mutations (Install/InstallLocal/Remove/Update/Upgrade/Pin/Unpin/Repair/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 backends are installed; it lists and never picks, so the caller decides (a host can have both a native manager and flatpak).
Index ¶
- Variables
- func ValidateGpgKeyRef(ref string) error
- func ValidateLocalPackagePath(path string) error
- func ValidatePackageName(name string) error
- func ValidatePackageNames(names []string) error
- func ValidatePackageVersion(version string) error
- func ValidateRemoteName(name string) error
- func ValidateRepoBaseURL(rawURL string) error
- func ValidateRpmPackageName(name string) error
- func ValidateSearchQuery(query string) error
- type AvailableVersion
- type Backend
- type FlatpakManager
- type InstallLocalOptions
- type InstallOptions
- type LocalPackage
- type Manager
- type Option
- type Package
- type PackageUpdate
- type RemoveOptions
- type SearchResult
- type UpgradeOptions
- type VersionInfo
Constants ¶
This section is empty.
Variables ¶
var ErrSecurityOnlyUnsupported = errors.New("pkg: security-only upgrade not supported by this backend")
ErrSecurityOnlyUnsupported is returned by UpgradeAll when UpgradeOptions. SecurityOnly is set on a backend that has no security-only upgrade path: pacman (a rolling release with no security/non-security distinction) and flatpak (no security channel). Fail-closed: the SDK never silently performs a full upgrade when only security updates were requested.
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 ¶
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 ¶
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>, zypper install <file>, flatpak install <bundle>). 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 ¶
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 ¶
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 ¶
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 ValidateRemoteName ¶
ValidateRemoteName returns a non-nil error when name is not a safe flatpak remote alias to pass as an operand to `flatpak install`. A flag-shaped remote (`--from=…`) would otherwise be parsed as an option.
func ValidateRepoBaseURL ¶
ValidateRepoBaseURL validates a dnf baseurl / zypper url / pacman server. A repository base URL is where the package manager fetches ROOT-installed packages, so it must be https (no http/ftp/file — the transport is the only thing standing between a MITM and arbitrary root code), a real URL with a host, and free of control characters. Package-manager template variables ($releasever, $arch, $basearch) survive url.Parse and are intentionally allowed.
NOTE: apt is deliberately NOT validated through here — apt's security model is the gpg-signed Release file, so an http transport with a trusted key is a legitimate, long-standing configuration.
func ValidateRpmPackageName ¶
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 ¶
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 ¶
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 // Pacman is the Arch Linux package manager. Pacman // Zypper is the openSUSE/SLES package manager (zypper / rpm). Zypper // Flatpak is the cross-distro application bundle manager. Flatpak )
func Detect ¶
Detect returns the package-manager backends whose primary binary resolves on PATH, in priority order (native managers before flatpak). The result may be empty (no supported manager) or hold several entries (e.g. a native manager plus flatpak). It lists; it never picks — the caller chooses.
type FlatpakManager ¶
type FlatpakManager interface {
Manager
// AddRemote registers a flatpak remote. name must be a valid remote alias
// and url an https repository URL.
AddRemote(ctx context.Context, name, url string) error
// RemoveRemote deletes a flatpak remote.
RemoveRemote(ctx context.Context, name string) error
// ListRemotes returns the configured flatpak remote names.
ListRemotes(ctx context.Context) ([]string, error)
}
FlatpakManager is the Manager returned by New(Flatpak, …); it adds remote (repository) management, which has no analogue on the native managers. Callers reach it with a type assertion:
if fm, ok := m.(pkg.FlatpakManager); ok { fm.AddRemote(ctx, "flathub", url) }
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),
// dnf (retried as an explicit downgrade when the install is rejected) and
// zypper (--oldpackage). pacman -U downgrades regardless, and a flatpak
// bundle has no version-ordering concept, so it is a no-op on those two.
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
// - flatpak: no-op — a bundle's signing is not a per-file GPG check
AllowUnsigned bool
}
InstallLocalOptions configures an InstallLocal call.
type InstallOptions ¶
type InstallOptions struct {
// Version pins the install to a specific version. When set, exactly one
// package name must be given (a version applies to a single package).
Version string
// AllowDowngrade permits installing a lower version than the one installed.
AllowDowngrade bool
// Remote names the flatpak remote to install FROM (e.g. "flathub"). It is
// honored only by the flatpak backend — where it disambiguates which remote
// provides the app instead of relying on flatpak's auto-resolution — and is
// ignored by the native package managers. Empty selects flatpak's default
// resolution.
Remote string
}
InstallOptions configures an Install call.
type LocalPackage ¶
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. The flatpak backend has no clean
// local name-introspection command and returns a not-supported error.
LocalPackageInfo(ctx context.Context, path string) (*LocalPackage, error)
// InstalledVersion returns the installed version of name, or "" if absent.
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. When securityOnly is
// true only security updates are considered (where the backend supports it).
HasUpdates(ctx context.Context, securityOnly bool) (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 the named packages. opts.Version pins a single package
// (exactly one name required when set); opts.AllowDowngrade permits a lower
// version than installed.
Install(ctx context.Context, opts InstallOptions, packages ...string) (pmexec.Result, error)
// InstallLocal installs a package from a local file already on disk — a
// downloaded .deb, .rpm, pacman package, or flatpak bundle — 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) (pmexec.Result, error)
// Remove removes the named packages. opts.Purge also deletes configuration
// where the backend distinguishes it (apt/pacman/flatpak); elsewhere Purge
// is equivalent to a plain remove.
Remove(ctx context.Context, opts RemoveOptions, packages ...string) (pmexec.Result, error)
// Update refreshes the package metadata/database.
Update(ctx context.Context) (pmexec.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) (pmexec.Result, error)
// UpgradeAll performs a full system upgrade (apt dist-upgrade / dnf upgrade /
// pacman -Syu / zypper dist-upgrade / flatpak update). With
// opts.SecurityOnly it upgrades only security updates where the backend
// supports it (apt/dnf/zypper); pacman and flatpak return
// ErrSecurityOnlyUnsupported.
UpgradeAll(ctx context.Context, opts UpgradeOptions) (pmexec.Result, error)
// Pin holds the named packages back from upgrades.
Pin(ctx context.Context, packages ...string) (pmexec.Result, error)
// Unpin releases the named packages so they upgrade again.
Unpin(ctx context.Context, packages ...string) (pmexec.Result, error)
// Repair attempts to fix a wedged package-manager state (stale locks,
// interrupted transactions, broken dependencies). It runs several recovery
// commands; the returned Result is that of the final (or first failing) step.
Repair(ctx context.Context) (pmexec.Result, error)
// Autoremove removes packages installed only as now-unneeded dependencies.
// It is a no-op (zero Result, nil error) on backends with no native equivalent.
Autoremove(ctx context.Context) (pmexec.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).
type Option ¶
type Option func(*config)
Option customizes a Manager at construction.
func WithUserScope ¶
func WithUserScope() Option
WithUserScope makes a flatpak Manager operate on the per-user installation (--user, unprivileged) instead of the system installation. It has no effect on the native package managers.
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
Pinned bool // whether the package is pinned (hold)
}
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
// (apt purge / pacman -Rns / flatpak --delete-data). On backends with no
// such distinction it is equivalent to a plain remove.
Purge bool
}
RemoveOptions configures a Remove call.
type SearchResult ¶
SearchResult represents a package search result.
type UpgradeOptions ¶
type UpgradeOptions struct {
// SecurityOnly restricts the upgrade to security updates. Supported on apt
// (simulate dist-upgrade, then upgrade only packages from a security suite),
// dnf (--security) and zypper (patch --category security). pacman and flatpak
// return ErrSecurityOnlyUnsupported.
SecurityOnly bool
}
UpgradeOptions configures UpgradeAll.
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.