fix: harden and simplify Linux system install

Tighten shim detection, profile repair, and install ordering while
trimming over-specific doctor/info hints from the system-install path.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Sahilb315
2026-07-11 02:19:59 +05:30
co-authored by Cursor
parent 7922606644
commit ffd0e7e759
13 changed files with 227 additions and 105 deletions
+43 -35
View File
@@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"slices"
"github.com/safedep/pmg/config" "github.com/safedep/pmg/config"
"github.com/safedep/pmg/internal/alias" "github.com/safedep/pmg/internal/alias"
@@ -120,12 +119,6 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
Name: checkShellAliases, Name: checkShellAliases,
Category: "Shell Integration", Category: "Shell Integration",
Run: func() doctor.CheckResult { Run: func() doctor.CheckResult {
if shim.SystemShimsInstalled() {
return doctor.CheckResult{
Status: doctor.StatusPass,
Message: "System shims installed (aliases optional)",
}
}
aliasCfg := alias.DefaultConfig() aliasCfg := alias.DefaultConfig()
rcFileManager, err := alias.NewDefaultRcFileManager(aliasCfg.RcFileName) rcFileManager, err := alias.NewDefaultRcFileManager(aliasCfg.RcFileName)
if err != nil { if err != nil {
@@ -142,15 +135,21 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
Message: fmt.Sprintf("Could not determine alias status: %v", err), Message: fmt.Sprintf("Could not determine alias status: %v", err),
} }
} }
if !installed { if installed {
return doctor.CheckResult{ return doctor.CheckResult{
Status: doctor.StatusFail, Status: doctor.StatusPass,
Message: "Aliases not installed", Message: "Shell aliases installed",
}
}
if shim.SystemShimsInstalled() {
return doctor.CheckResult{
Status: doctor.StatusWarn,
Message: "Aliases not installed (optional with system shims)",
} }
} }
return doctor.CheckResult{ return doctor.CheckResult{
Status: doctor.StatusPass, Status: doctor.StatusFail,
Message: "Shell aliases installed", Message: "Aliases not installed",
} }
}, },
}, },
@@ -190,33 +189,29 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
Category: "Shell Integration", Category: "Shell Integration",
Run: func() doctor.CheckResult { Run: func() doctor.CheckResult {
pathEntries := filepath.SplitList(os.Getenv("PATH")) pathEntries := filepath.SplitList(os.Getenv("PATH"))
if shim.SystemShimsInstalled() { systemDir := shim.SystemBinDir()
systemDir := shim.SystemBinDir() if shim.SystemShimsInstalled() && pathContainsDir(pathEntries, systemDir) {
if slices.Contains(pathEntries, systemDir) {
return doctor.CheckResult{
Status: doctor.StatusPass,
Message: "System shim directory is in PATH",
}
}
return doctor.CheckResult{ return doctor.CheckResult{
Status: doctor.StatusFail, Status: doctor.StatusPass,
Message: fmt.Sprintf("System shim directory not in PATH (add ENV PATH=\"%s:$PATH\" for Docker RUN)", systemDir), Message: "System shim directory is in PATH",
} }
} }
sm, err := shim.NewDefaultShimManager() userDir := ""
if err != nil { if home, err := os.UserHomeDir(); err == nil {
return doctor.CheckResult{ userDir = filepath.Join(home, ".pmg", "bin")
Status: doctor.StatusWarn,
Message: fmt.Sprintf("Could not check shims: %v", err),
}
} }
shimDir := sm.GetBinDir() if pathContainsDir(pathEntries, userDir) {
if slices.Contains(pathEntries, shimDir) {
return doctor.CheckResult{ return doctor.CheckResult{
Status: doctor.StatusPass, Status: doctor.StatusPass,
Message: "Shim directory is in PATH", Message: "Shim directory is in PATH",
} }
} }
if shim.SystemShimsInstalled() {
return doctor.CheckResult{
Status: doctor.StatusFail,
Message: "System shim directory not in PATH",
}
}
return doctor.CheckResult{ return doctor.CheckResult{
Status: doctor.StatusFail, Status: doctor.StatusFail,
Message: "Shim directory not in PATH", Message: "Shim directory not in PATH",
@@ -307,6 +302,19 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
return doctor.RunChecks(checks) return doctor.RunChecks(checks)
} }
func pathContainsDir(pathEntries []string, dir string) bool {
if dir == "" {
return false
}
cleanDir := filepath.Clean(dir)
for _, entry := range pathEntries {
if filepath.Clean(entry) == cleanDir {
return true
}
}
return false
}
func runProtectionChecks(coreResults []doctor.CheckResult) []doctor.CheckResult { func runProtectionChecks(coreResults []doctor.CheckResult) []doctor.CheckResult {
if !isInterceptionActive(coreResults) { if !isInterceptionActive(coreResults) {
var results []doctor.CheckResult var results []doctor.CheckResult
@@ -366,15 +374,15 @@ var checkDisplayNames = map[string]string{
var checkFixes = map[string]string{ var checkFixes = map[string]string{
checkConfigFile: "pmg setup install", checkConfigFile: "pmg setup install",
checkEventLogDir: "pmg setup install", checkEventLogDir: "pmg setup install",
checkShellAliases: "pmg setup install [--system]", checkShellAliases: "pmg setup install",
checkShimDirectory: "pmg setup install [--system]", checkShimDirectory: "pmg setup install",
checkShimInPath: "Restart shell, source profile, or set ENV PATH for Docker", checkShimInPath: "Restart shell or source profile",
checkProxyMode: "Set proxy.enabled: true in config", checkProxyMode: "Set proxy.enabled: true in config",
checkSandbox: "Set sandbox.enabled: true in config", checkSandbox: "Set sandbox.enabled: true in config",
checkDependencyCooldown: "Set dependency_cooldown.enabled: true in config", checkDependencyCooldown: "Set dependency_cooldown.enabled: true in config",
checkEventLogging: "Set skip_event_logging: false in config", checkEventLogging: "Set skip_event_logging: false in config",
checkProtectionNpm: "pmg setup install [--system]", checkProtectionNpm: "pmg setup install",
checkProtectionPip: "pmg setup install [--system]", checkProtectionPip: "pmg setup install",
checkCA: "pmg setup cert install", checkCA: "pmg setup cert install",
} }
+23
View File
@@ -0,0 +1,23 @@
package setup
import (
"testing"
"github.com/safedep/pmg/internal/doctor"
"github.com/stretchr/testify/assert"
)
func TestPathContainsDir(t *testing.T) {
assert.True(t, pathContainsDir([]string{"/usr/local/lib/pmg/bin/"}, "/usr/local/lib/pmg/bin"))
assert.False(t, pathContainsDir([]string{"/usr/local/bin"}, "/usr/local/lib/pmg/bin"))
assert.False(t, pathContainsDir([]string{"/usr/bin"}, ""))
}
func TestSystemShimsWithoutPathDoNotActivateInterception(t *testing.T) {
results := []doctor.CheckResult{
{Name: checkShellAliases, Status: doctor.StatusWarn},
{Name: checkShimInPath, Status: doctor.StatusFail},
}
assert.False(t, isInterceptionActive(results))
}
+3 -3
View File
@@ -80,10 +80,10 @@ func executeSetupInfo() error {
shellEntries["Detected Shell"] = shell shellEntries["Detected Shell"] = shell
shellEntries["Alias Installed"] = strconv.FormatBool(isInstalled) shellEntries["Alias Installed"] = strconv.FormatBool(isInstalled)
shellEntries["User Shims"] = strconv.FormatBool(shim.UserShimsInstalled()) shellEntries["User Shims"] = strconv.FormatBool(shim.UserShimsInstalled())
shellEntries["System Shims"] = strconv.FormatBool(shim.SystemShimsInstalled())
shellEntries["System Profile"] = strconv.FormatBool(shim.SystemProfileInstalled())
if shim.SystemShimsInstalled() { if shim.SystemShimsInstalled() {
shellEntries["System Shim Dir"] = shim.SystemBinDir() shellEntries["System Shims"] = shim.SystemBinDir()
} else {
shellEntries["System Shims"] = "not installed"
} }
ui.PrintInfoSection("Shell Integration", shellEntries) ui.PrintInfoSection("Shell Integration", shellEntries)
+27 -28
View File
@@ -16,12 +16,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var (
setupRemoveConfigFile bool
setupInstallSystem bool
setupRemoveSystem bool
)
var setupGeteuid = os.Geteuid var setupGeteuid = os.Geteuid
func NewSetupCommand() *cobra.Command { func NewSetupCommand() *cobra.Command {
@@ -45,21 +39,22 @@ func NewSetupCommand() *cobra.Command {
} }
func NewInstallCommand() *cobra.Command { func NewInstallCommand() *cobra.Command {
var system bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "install", Use: "install",
Short: "Setup PMG config, aliases, and shims for package managers (npm, pnpm, pip, and more)", Short: "Setup PMG config, aliases, and shims for package managers (npm, pnpm, pip, and more)",
SilenceUsage: true, SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
fmt.Print(ui.GeneratePMGBanner(version.Version, version.Commit)) fmt.Print(ui.GeneratePMGBanner(version.Version, version.Commit))
return install() return install(system)
}, },
} }
cmd.Flags().BoolVar(&setupInstallSystem, "system", false, "Install system-wide for all users (Linux, requires root)") cmd.Flags().BoolVar(&system, "system", false, "Install system-wide for all users (Linux, requires root)")
return cmd return cmd
} }
func install() error { func install(system bool) error {
if setupInstallSystem { if system {
return installSystem() return installSystem()
} }
@@ -114,45 +109,50 @@ func installSystem() error {
return err return err
} }
if err := config.WriteSystemTemplateConfig(); err != nil {
return fmt.Errorf("failed to write system config: %w", err)
}
shimMgr, err := shim.NewSystemShimManager() shimMgr, err := shim.NewSystemShimManager()
if err != nil { if err != nil {
return fmt.Errorf("failed to create system shim manager: %w", err) return fmt.Errorf("failed to create system shim manager: %w", err)
} }
// Shims/profile first so a failed config write does not leave a managed
// config active without interception.
if err := shimMgr.Install(); err != nil { if err := shimMgr.Install(); err != nil {
return fmt.Errorf("failed to install system shims: %w", err) return fmt.Errorf("failed to install system shims: %w", err)
} }
if err := config.WriteSystemTemplateConfig(); err != nil {
return fmt.Errorf("failed to write system config: %w", err)
}
ui.PrintSetupSystemInstallCmdInfo(shimMgr.GetBinDir(), config.SystemConfigDir(), shim.SystemProfilePath()) ui.PrintSetupSystemInstallCmdInfo(shimMgr.GetBinDir(), config.SystemConfigDir(), shim.SystemProfilePath())
return nil return nil
} }
func NewRemoveCommand() *cobra.Command { func NewRemoveCommand() *cobra.Command {
var (
removeConfig bool
system bool
)
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "remove", Use: "remove",
Short: "Removes pmg aliases and shims from the user's shell config.", Short: "Removes pmg aliases and shims from the user's shell config.",
SilenceUsage: true, SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
fmt.Print(ui.GeneratePMGBanner(version.Version, version.Commit)) fmt.Print(ui.GeneratePMGBanner(version.Version, version.Commit))
return remove() return remove(system, removeConfig)
}, },
} }
cmd.Flags().BoolVar(&setupRemoveConfigFile, "config-file", false, "Remove the config file") cmd.Flags().BoolVar(&removeConfig, "config-file", false, "Remove the config file")
cmd.Flags().BoolVar(&setupRemoveSystem, "system", false, "Remove system-wide install (Linux, requires root)") cmd.Flags().BoolVar(&system, "system", false, "Remove system-wide install (Linux, requires root)")
return cmd return cmd
} }
func remove() error { func remove(system, removeConfig bool) error {
if setupRemoveSystem { if system {
return removeSystem() return removeSystem(removeConfig)
} }
if setupRemoveConfigFile { if removeConfig {
// Only ever remove the per-user file; the globally managed // Only ever remove the per-user file; the globally managed
// config is not ours to delete from a per-user uninstall. // config is not ours to delete from a per-user uninstall.
if err := config.RemoveUserConfigFile(); err != nil { if err := config.RemoveUserConfigFile(); err != nil {
@@ -189,17 +189,11 @@ func remove() error {
return nil return nil
} }
func removeSystem() error { func removeSystem(removeConfig bool) error {
if err := errIfSystemInstallAllowed(); err != nil { if err := errIfSystemInstallAllowed(); err != nil {
return err return err
} }
if setupRemoveConfigFile {
if err := config.RemoveSystemConfigFile(); err != nil {
return err
}
}
shimMgr, err := shim.NewSystemShimManager() shimMgr, err := shim.NewSystemShimManager()
if err != nil { if err != nil {
return fmt.Errorf("failed to create system shim manager: %w", err) return fmt.Errorf("failed to create system shim manager: %w", err)
@@ -208,6 +202,11 @@ func removeSystem() error {
if err := shimMgr.Remove(); err != nil { if err := shimMgr.Remove(); err != nil {
return fmt.Errorf("failed to remove system shims: %w", err) return fmt.Errorf("failed to remove system shims: %w", err)
} }
if removeConfig {
if err := config.RemoveSystemConfigFile(); err != nil {
return err
}
}
fmt.Printf("%s %s\n", ui.Colors.Green("✓"), "PMG system install removed") fmt.Printf("%s %s\n", ui.Colors.Green("✓"), "PMG system install removed")
return nil return nil
+9 -20
View File
@@ -37,30 +37,19 @@ func TestErrIfSystemInstallAllowed(t *testing.T) {
} }
} }
func TestInstallSystemRequiresLinuxAndRoot(t *testing.T) { func TestInstallSystemRequiresRoot(t *testing.T) {
orig := setupGeteuid orig := setupGeteuid
t.Cleanup(func() { t.Cleanup(func() { setupGeteuid = orig })
setupGeteuid = orig
setupInstallSystem = false
})
setupInstallSystem = true setupGeteuid = func() int { return 1000 }
setupGeteuid = func() int { return 0 }
err := install()
if runtime.GOOS == "linux" {
if err != nil {
usefulErr, ok := usefulerror.AsUsefulError(err)
if ok {
assert.NotEqual(t, errcodes.UnsupportedPlatform, usefulErr.Code())
assert.NotEqual(t, errcodes.PermissionDenied, usefulErr.Code())
}
}
return
}
err := install(true)
require.Error(t, err) require.Error(t, err)
usefulErr, ok := usefulerror.AsUsefulError(err) usefulErr, ok := usefulerror.AsUsefulError(err)
require.True(t, ok) require.True(t, ok)
assert.Equal(t, errcodes.UnsupportedPlatform, usefulErr.Code()) if runtime.GOOS == "linux" {
assert.Equal(t, errcodes.PermissionDenied, usefulErr.Code())
} else {
assert.Equal(t, errcodes.UnsupportedPlatform, usefulErr.Code())
}
} }
+10 -4
View File
@@ -14,6 +14,7 @@ sudo pmg setup remove --system --config-file # also remove the system config f
``` ```
Per-user `pmg setup install` remains available and does not conflict with a system install. Per-user `pmg setup install` remains available and does not conflict with a system install.
The PMG executable used during setup must be executable by every user. Install PMG under a system path such as `/usr/local/bin`.
## Files created ## Files created
@@ -56,7 +57,7 @@ pmg setup doctor
Docker `RUN` does not load `/etc/profile.d`. After system install you **must** set `ENV PATH` so build steps and the runtime container see the shims: Docker `RUN` does not load `/etc/profile.d`. After system install you **must** set `ENV PATH` so build steps and the runtime container see the shims:
```dockerfile ```dockerfile
FROM ubuntu:24.04 FROM node:22-bookworm
RUN curl -fsSL https://raw.githubusercontent.com/safedep/pmg/main/install.sh | sh \ RUN curl -fsSL https://raw.githubusercontent.com/safedep/pmg/main/install.sh | sh \
&& pmg setup install --system && pmg setup install --system
@@ -65,7 +66,10 @@ RUN curl -fsSL https://raw.githubusercontent.com/safedep/pmg/main/install.sh | s
ENV PATH="/usr/local/lib/pmg/bin:$PATH" ENV PATH="/usr/local/lib/pmg/bin:$PATH"
# Optional: switch user; PATH from ENV still applies # Optional: switch user; PATH from ENV still applies
USER appuser RUN mkdir -p /app && chown node:node /app
WORKDIR /app
USER node
COPY --chown=node:node package*.json ./
RUN npm ci RUN npm ci
``` ```
@@ -73,6 +77,8 @@ Derived images inherit that `ENV`. Later `RUN npm install` / `RUN pip install` g
If a child Dockerfile sets `ENV PATH=...` again, keep `/usr/local/lib/pmg/bin` ahead of the real `npm`/`pip` directories. Leaving it out (or behind those toolchains) drops interception. If a child Dockerfile sets `ENV PATH=...` again, keep `/usr/local/lib/pmg/bin` ahead of the real `npm`/`pip` directories. Leaving it out (or behind those toolchains) drops interception.
PMG running on the Docker host cannot inspect package installations inside `docker build`. PMG must be installed in the image as shown above.
## Configuration ## Configuration
The system config file is authoritative for every user. A per-user `config.yml` is ignored while `/etc/safedep/pmg/config.yml` exists. The system config file is authoritative for every user. A per-user `config.yml` is ignored while `/etc/safedep/pmg/config.yml` exists.
@@ -86,8 +92,8 @@ Optional lockdown (`global_lockdown: true`) is documented in [config.md](./confi
- **Virtualenv.** After `source .venv/bin/activate`, bare `pip` uses the venv binary and skips PMG shims. Call `pmg pip …` explicitly. - **Virtualenv.** After `source .venv/bin/activate`, bare `pip` uses the venv binary and skips PMG shims. Call `pmg pip …` explicitly.
- **No shell aliases.** System install only installs PATH shims. There is no `~/.pmg.rc` alias layer. - **No shell aliases.** System install only installs PATH shims. There is no `~/.pmg.rc` alias layer.
- **Config changes.** `pmg config set` and `pmg config edit` are unavailable while the system config is active. Edit `/etc/safedep/pmg/config.yml` as root, or redeploy the file. - **Config changes.** `pmg config set` and `pmg config edit` are unavailable while the system config is active. Edit `/etc/safedep/pmg/config.yml` as root, or redeploy the file.
- **Custom sandbox** `policy_templates`**.** Relative paths in the system config resolve under each user's config directory, not `/etc/safedep/pmg`. Prefer absolute paths. - **Custom sandbox `policy_templates`.** Relative paths in the system config resolve under each user's config directory, not `/etc/safedep/pmg`. Prefer absolute paths.
- `pmg sandbox allow`**.** Blocked when the system config sets `global_lockdown: true`. - **`pmg sandbox allow`.** Blocked when the system config sets `global_lockdown: true`.
## User data directories ## User data directories
+3
View File
@@ -50,6 +50,9 @@ func FilterPMGFromPath(pathEnv string) string {
if strings.HasSuffix(entry, pmgBinSuffix) { if strings.HasSuffix(entry, pmgBinSuffix) {
continue continue
} }
if filepath.Clean(entry) == filepath.Clean(SystemBinDir()) {
continue
}
if shimDir != "" && filepath.Clean(entry) == shimDir { if shimDir != "" && filepath.Clean(entry) == shimDir {
continue continue
} }
+5
View File
@@ -58,6 +58,11 @@ func TestFilterPMGFromPath(t *testing.T) {
shimEnv: "/usr/local/lib/pmg/bin/npm", shimEnv: "/usr/local/lib/pmg/bin/npm",
expected: "/usr/local/bin:/usr/bin", expected: "/usr/local/bin:/usr/bin",
}, },
{
name: "system shim dir is stripped without env var",
path: "/usr/local/lib/pmg/bin:/usr/local/bin:/usr/bin",
expected: "/usr/local/bin:/usr/bin",
},
{ {
name: "env var strips arbitrary shim dir", name: "env var strips arbitrary shim dir",
path: "/shims:/usr/local/bin:/usr/bin", path: "/shims:/usr/local/bin:/usr/bin",
+8 -5
View File
@@ -10,7 +10,10 @@ import (
"github.com/safedep/pmg/internal/alias" "github.com/safedep/pmg/internal/alias"
) )
const shimMarker = "PMG shims" const (
shimMarker = "PMG shims"
shimScriptMarker = "# PMG shim - do not edit, managed by pmg setup"
)
type ShimConfig struct { type ShimConfig struct {
BinDir string BinDir string
@@ -91,8 +94,8 @@ func (m *ShimManager) Install() error {
} }
func (m *ShimManager) Remove() error { func (m *ShimManager) Remove() error {
if err := os.RemoveAll(m.config.BinDir); err != nil && !os.IsNotExist(err) { if err := os.RemoveAll(m.config.BinDir); err != nil {
log.Warnf("Warning: failed to remove shim directory: %v", err) return fmt.Errorf("failed to remove shim directory %s: %w", m.config.BinDir, err)
} }
if m.config.ManageProfile { if m.config.ManageProfile {
@@ -142,7 +145,7 @@ func (m *ShimManager) writeShimScript(pm string) error {
pmgBin := shellQuote(m.config.PMGBin) pmgBin := shellQuote(m.config.PMGBin)
content := fmt.Sprintf(`#!/bin/sh content := fmt.Sprintf(`#!/bin/sh
# PMG shim - do not edit, managed by pmg setup %s
PMG_BIN=%s PMG_BIN=%s
if [ ! -x "$PMG_BIN" ]; then if [ ! -x "$PMG_BIN" ]; then
echo "[pmg] error: PMG binary not found or not executable: $PMG_BIN" >&2 echo "[pmg] error: PMG binary not found or not executable: $PMG_BIN" >&2
@@ -152,7 +155,7 @@ fi
PMG_SHIM_PATH=$(cd -- "$(dirname -- "$0")" && pwd)/$(basename -- "$0") PMG_SHIM_PATH=$(cd -- "$(dirname -- "$0")" && pwd)/$(basename -- "$0")
export PMG_SHIM_PATH export PMG_SHIM_PATH
exec "$PMG_BIN" %s "$@" exec "$PMG_BIN" %s "$@"
`, pmgBin, pm) `, shimScriptMarker, pmgBin, pm)
return os.WriteFile(shimPath, []byte(content), 0o755) return os.WriteFile(shimPath, []byte(content), 0o755)
} }
+12
View File
@@ -68,6 +68,18 @@ func TestShimManagerInstall(t *testing.T) {
assert.Contains(t, string(fishContent), ".pmg/bin") assert.Contains(t, string(fishContent), ".pmg/bin")
} }
func TestShimManagerRemoveReturnsDirectoryError(t *testing.T) {
root := t.TempDir()
blocker := filepath.Join(root, "blocker")
require.NoError(t, os.WriteFile(blocker, []byte("not a directory"), 0o644))
mgr := NewShimManager(ShimConfig{
BinDir: filepath.Join(blocker, "bin"),
})
assert.Error(t, mgr.Remove())
}
func TestShimManagerInstallIdempotent(t *testing.T) { func TestShimManagerInstallIdempotent(t *testing.T) {
homeDir := t.TempDir() homeDir := t.TempDir()
binDir := filepath.Join(homeDir, ".pmg", "bin") binDir := filepath.Join(homeDir, ".pmg", "bin")
+34 -8
View File
@@ -15,9 +15,8 @@ const (
systemProfileMarker = "PMG system shims" systemProfileMarker = "PMG system shims"
) )
// systemBinDirOverride and systemProfilePathOverride replace the OS-level // These overrides replace OS-level system install paths in tests. There is
// system install paths. They exist only for tests within this package. There // intentionally no env var or flag for them.
// is intentionally no env var or flag for them.
var ( var (
systemBinDirOverride string systemBinDirOverride string
systemProfilePathOverride string systemProfilePathOverride string
@@ -48,6 +47,10 @@ func NewSystemShimManager() (*ShimManager, error) {
return nil, err return nil, err
} }
if err := validateSystemExecutable(pmgBin); err != nil {
return nil, err
}
return &ShimManager{ return &ShimManager{
config: ShimConfig{ config: ShimConfig{
BinDir: SystemBinDir(), BinDir: SystemBinDir(),
@@ -59,6 +62,19 @@ func NewSystemShimManager() (*ShimManager, error) {
}, nil }, nil
} }
// validateSystemExecutable rejects binaries other users cannot execute. System shims hard-code this path.
func validateSystemExecutable(path string) error {
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("failed to inspect pmg executable %s: %w", path, err)
}
if info.Mode().Perm()&0o001 == 0 {
return fmt.Errorf("pmg executable %s is not executable by all users", path)
}
return nil
}
// SystemShimsInstalled reports whether the system shim directory contains at // SystemShimsInstalled reports whether the system shim directory contains at
// least one shim script. // least one shim script.
func SystemShimsInstalled() bool { func SystemShimsInstalled() bool {
@@ -71,7 +87,11 @@ func shimsPresent(dir string) bool {
return false return false
} }
for _, e := range entries { for _, e := range entries {
if !e.IsDir() { if e.IsDir() {
continue
}
content, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err == nil && strings.Contains(string(content), shimScriptMarker) {
return true return true
} }
} }
@@ -91,19 +111,25 @@ func SystemProfileInstalled() bool {
func writeSystemProfile() error { func writeSystemProfile() error {
binDir := SystemBinDir() binDir := SystemBinDir()
path := SystemProfilePath() path := SystemProfilePath()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return fmt.Errorf("failed to create profile.d directory: %w", err) return fmt.Errorf("failed to create profile.d directory: %w", err)
} }
if data, err := os.ReadFile(path); err == nil && strings.Contains(string(data), systemProfileMarker) {
return nil
}
content := fmt.Sprintf(`# %s - managed by pmg setup install --system content := fmt.Sprintf(`# %s - managed by pmg setup install --system
# remove by running: pmg setup remove --system # remove by running: pmg setup remove --system
export PATH="%s:$PATH" export PATH="%s:$PATH"
`, systemProfileMarker, binDir) `, systemProfileMarker, binDir)
data, err := os.ReadFile(path)
if err == nil && string(data) == content {
return nil
}
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to read system profile %s: %w", path, err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil { if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
return fmt.Errorf("failed to write system profile %s: %w", path, err) return fmt.Errorf("failed to write system profile %s: %w", path, err)
} }
+47
View File
@@ -37,6 +37,8 @@ func TestSystemShimManagerInstallAndRemove(t *testing.T) {
content, err := os.ReadFile(npmShim) content, err := os.ReadFile(npmShim)
require.NoError(t, err) require.NoError(t, err)
assert.Contains(t, string(content), "export PMG_SHIM_PATH") assert.Contains(t, string(content), "export PMG_SHIM_PATH")
assert.Contains(t, string(content), "pmg setup install")
assert.Contains(t, string(content), "pmg setup remove")
profile, err := os.ReadFile(SystemProfilePath()) profile, err := os.ReadFile(SystemProfilePath())
require.NoError(t, err) require.NoError(t, err)
@@ -71,3 +73,48 @@ func TestSystemShimManagerDoesNotTouchUserRc(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "# user bashrc\n", string(content)) assert.Equal(t, "# user bashrc\n", string(content))
} }
func TestSystemShimsInstalledIgnoresUnmanagedFiles(t *testing.T) {
root := t.TempDir()
useSystemPaths(t, root)
require.NoError(t, os.MkdirAll(SystemBinDir(), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(SystemBinDir(), "README"), []byte("not a shim"), 0o644))
assert.False(t, SystemShimsInstalled())
require.NoError(t, os.WriteFile(
filepath.Join(SystemBinDir(), "npm"),
[]byte("#!/bin/sh\n# PMG shim - do not edit, managed by pmg setup\n"),
0o755,
))
assert.True(t, SystemShimsInstalled())
}
func TestWriteSystemProfileRepairsStalePath(t *testing.T) {
root := t.TempDir()
useSystemPaths(t, root)
require.NoError(t, os.MkdirAll(filepath.Dir(SystemProfilePath()), 0o755))
require.NoError(t, os.WriteFile(
SystemProfilePath(),
[]byte("# PMG system shims\nexport PATH=\"/stale/path:$PATH\"\n"),
0o644,
))
require.NoError(t, writeSystemProfile())
content, err := os.ReadFile(SystemProfilePath())
require.NoError(t, err)
assert.Contains(t, string(content), SystemBinDir())
assert.NotContains(t, string(content), "/stale/path")
}
func TestValidateSystemExecutableRejectsPrivateBinary(t *testing.T) {
privateDir := t.TempDir()
privateExecutable := filepath.Join(privateDir, "pmg")
require.NoError(t, os.WriteFile(privateExecutable, []byte("binary"), 0o700))
err := validateSystemExecutable(privateExecutable)
require.Error(t, err)
assert.Contains(t, err.Error(), "not executable by all users")
}
+3 -2
View File
@@ -103,9 +103,10 @@ func main() {
} }
if eventlogErr != nil { if eventlogErr != nil {
// Soft-fail: unusable HOME (e.g. system accounts, some containers)
// must not prevent package-manager commands from running.
log.Warnf("failed to initialize event logging: %v", eventlogErr) log.Warnf("failed to initialize event logging: %v", eventlogErr)
// Soft-fail: unusable HOME must not block package-manager commands.
ui.Infof("%s Event logging unavailable (%v); continuing without recording this run",
ui.Colors.Yellow("⚠"), eventlogErr)
} }
if err := audit.Initialize(config.Get()); err != nil { if err := audit.Initialize(config.Get()); err != nil {