feat: add Linux system-wide setup

Install shared shims, managed configuration, and login-shell PATH integration so golden images and multi-user hosts can protect package installs for every user.

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 d3e656edcd
commit 8f6d0fcce0
19 changed files with 915 additions and 66 deletions
+40 -8
View File
@@ -91,11 +91,17 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
Name: checkEventLogDir,
Category: "Configuration",
Run: func() doctor.CheckResult {
if cfg.Config.SkipEventLogging {
return doctor.CheckResult{
Status: doctor.StatusWarn,
Message: "Event logging is disabled",
}
}
info, err := os.Stat(cfg.EventLogDir())
if err != nil {
return doctor.CheckResult{
Status: doctor.StatusFail,
Message: "Event log directory not found",
Status: doctor.StatusWarn,
Message: "Event log directory not found (PMG still runs without event logs)",
}
}
if !info.IsDir() {
@@ -114,6 +120,12 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
Name: checkShellAliases,
Category: "Shell Integration",
Run: func() doctor.CheckResult {
if shim.SystemShimsInstalled() {
return doctor.CheckResult{
Status: doctor.StatusPass,
Message: "System shims installed (aliases optional)",
}
}
aliasCfg := alias.DefaultConfig()
rcFileManager, err := alias.NewDefaultRcFileManager(aliasCfg.RcFileName)
if err != nil {
@@ -146,6 +158,12 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
Name: checkShimDirectory,
Category: "Shell Integration",
Run: func() doctor.CheckResult {
if shim.SystemShimsInstalled() {
return doctor.CheckResult{
Status: doctor.StatusPass,
Message: fmt.Sprintf("System shim directory found (%s)", shim.SystemBinDir()),
}
}
sm, err := shim.NewDefaultShimManager()
if err != nil {
return doctor.CheckResult{
@@ -171,6 +189,20 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
Name: checkShimInPath,
Category: "Shell Integration",
Run: func() doctor.CheckResult {
pathEntries := filepath.SplitList(os.Getenv("PATH"))
if shim.SystemShimsInstalled() {
systemDir := shim.SystemBinDir()
if slices.Contains(pathEntries, systemDir) {
return doctor.CheckResult{
Status: doctor.StatusPass,
Message: "System shim directory is in PATH",
}
}
return doctor.CheckResult{
Status: doctor.StatusFail,
Message: fmt.Sprintf("System shim directory not in PATH (add ENV PATH=\"%s:$PATH\" for Docker RUN)", systemDir),
}
}
sm, err := shim.NewDefaultShimManager()
if err != nil {
return doctor.CheckResult{
@@ -179,7 +211,7 @@ func runCoreChecks(cfg *config.RuntimeConfig) []doctor.CheckResult {
}
}
shimDir := sm.GetBinDir()
if slices.Contains(filepath.SplitList(os.Getenv("PATH")), shimDir) {
if slices.Contains(pathEntries, shimDir) {
return doctor.CheckResult{
Status: doctor.StatusPass,
Message: "Shim directory is in PATH",
@@ -334,15 +366,15 @@ var checkDisplayNames = map[string]string{
var checkFixes = map[string]string{
checkConfigFile: "pmg setup install",
checkEventLogDir: "pmg setup install",
checkShellAliases: "pmg setup install",
checkShimDirectory: "pmg setup install",
checkShimInPath: "Restart shell or source config",
checkShellAliases: "pmg setup install [--system]",
checkShimDirectory: "pmg setup install [--system]",
checkShimInPath: "Restart shell, source profile, or set ENV PATH for Docker",
checkProxyMode: "Set proxy.enabled: true in config",
checkSandbox: "Set sandbox.enabled: true in config",
checkDependencyCooldown: "Set dependency_cooldown.enabled: true in config",
checkEventLogging: "Set skip_event_logging: false in config",
checkProtectionNpm: "pmg setup install",
checkProtectionPip: "pmg setup install",
checkProtectionNpm: "pmg setup install [--system]",
checkProtectionPip: "pmg setup install [--system]",
checkCA: "pmg setup cert install",
}
+7
View File
@@ -13,6 +13,7 @@ import (
"github.com/safedep/pmg/internal/alias"
"github.com/safedep/pmg/internal/analytics"
"github.com/safedep/pmg/internal/audit"
"github.com/safedep/pmg/internal/shim"
"github.com/safedep/pmg/internal/ui"
"github.com/safedep/pmg/internal/version"
"github.com/safedep/pmg/proxy/certmanager"
@@ -78,6 +79,12 @@ func executeSetupInfo() error {
shellEntries["Detected Shell"] = shell
shellEntries["Alias Installed"] = strconv.FormatBool(isInstalled)
shellEntries["User Shims"] = strconv.FormatBool(shim.UserShimsInstalled())
shellEntries["System Shims"] = strconv.FormatBool(shim.SystemShimsInstalled())
shellEntries["System Profile"] = strconv.FormatBool(shim.SystemProfileInstalled())
if shim.SystemShimsInstalled() {
shellEntries["System Shim Dir"] = shim.SystemBinDir()
}
ui.PrintInfoSection("Shell Integration", shellEntries)
// Security section
+131 -38
View File
@@ -1,10 +1,14 @@
package setup
import (
"errors"
"fmt"
"os"
"runtime"
"github.com/safedep/dry/usefulerror"
"github.com/safedep/pmg/config"
"github.com/safedep/pmg/errcodes"
"github.com/safedep/pmg/internal/alias"
"github.com/safedep/pmg/internal/shim"
"github.com/safedep/pmg/internal/ui"
@@ -12,7 +16,13 @@ import (
"github.com/spf13/cobra"
)
var setupRemoveConfigFile = false
var (
setupRemoveConfigFile bool
setupInstallSystem bool
setupRemoveSystem bool
)
var setupGeteuid = os.Geteuid
func NewSetupCommand() *cobra.Command {
setupCmd := &cobra.Command{
@@ -35,7 +45,7 @@ func NewSetupCommand() *cobra.Command {
}
func NewInstallCommand() *cobra.Command {
return &cobra.Command{
cmd := &cobra.Command{
Use: "install",
Short: "Setup PMG config, aliases, and shims for package managers (npm, pnpm, pip, and more)",
SilenceUsage: true,
@@ -44,9 +54,20 @@ func NewInstallCommand() *cobra.Command {
return install()
},
}
cmd.Flags().BoolVar(&setupInstallSystem, "system", false, "Install system-wide for all users (Linux, requires root)")
return cmd
}
func install() error {
if setupInstallSystem {
return installSystem()
}
if setupGeteuid() == 0 {
fmt.Printf("%s %s\n", ui.Colors.Yellow("⚠"),
"Running as root without --system configures only root's home. Use `pmg setup install --system` so all users are covered.")
}
if err := config.WriteTemplateConfig(); err != nil {
return fmt.Errorf("failed to write template config: %w", err)
}
@@ -88,6 +109,28 @@ func install() error {
return nil
}
func installSystem() error {
if err := errIfSystemInstallAllowed(); err != nil {
return err
}
if err := config.WriteSystemTemplateConfig(); err != nil {
return fmt.Errorf("failed to write system config: %w", err)
}
shimMgr, err := shim.NewSystemShimManager()
if err != nil {
return fmt.Errorf("failed to create system shim manager: %w", err)
}
if err := shimMgr.Install(); err != nil {
return fmt.Errorf("failed to install system shims: %w", err)
}
ui.PrintSetupSystemInstallCmdInfo(shimMgr.GetBinDir(), config.SystemConfigDir(), shim.SystemProfilePath())
return nil
}
func NewRemoveCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "remove",
@@ -95,45 +138,95 @@ func NewRemoveCommand() *cobra.Command {
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Print(ui.GeneratePMGBanner(version.Version, version.Commit))
if setupRemoveConfigFile {
// Only ever remove the per-user file; the globally managed
// config is not ours to delete from a per-user uninstall.
if err := config.RemoveUserConfigFile(); err != nil {
return err
}
}
if runtime.GOOS == "windows" {
fmt.Printf("%s %s\n", ui.Colors.Green("✓"), "PMG config removed. No aliases or shims to clean up on Windows.")
return nil
}
cfg := alias.DefaultConfig()
rcFileManager, err := alias.NewDefaultRcFileManager(cfg.RcFileName)
if err != nil {
return err
}
aliasManager := alias.New(cfg, rcFileManager)
if err := aliasManager.Remove(); err != nil {
return fmt.Errorf("failed to remove aliases: %w", err)
}
shimMgr, err := shim.NewDefaultShimManager()
if err != nil {
return fmt.Errorf("failed to create shim manager: %w", err)
}
if err := shimMgr.Remove(); err != nil {
return fmt.Errorf("failed to remove shims: %w", err)
}
fmt.Printf("%s %s\n", ui.Colors.Green("✓"), "PMG aliases and shims removed. Restart your terminal for changes to take effect")
return nil
return remove()
},
}
cmd.Flags().BoolVar(&setupRemoveConfigFile, "config-file", false, "Remove the config file")
cmd.Flags().BoolVar(&setupRemoveSystem, "system", false, "Remove system-wide install (Linux, requires root)")
return cmd
}
func remove() error {
if setupRemoveSystem {
return removeSystem()
}
if setupRemoveConfigFile {
// Only ever remove the per-user file; the globally managed
// config is not ours to delete from a per-user uninstall.
if err := config.RemoveUserConfigFile(); err != nil {
return err
}
}
if runtime.GOOS == "windows" {
fmt.Printf("%s %s\n", ui.Colors.Green("✓"), "PMG config removed. No aliases or shims to clean up on Windows.")
return nil
}
cfg := alias.DefaultConfig()
rcFileManager, err := alias.NewDefaultRcFileManager(cfg.RcFileName)
if err != nil {
return err
}
aliasManager := alias.New(cfg, rcFileManager)
if err := aliasManager.Remove(); err != nil {
return fmt.Errorf("failed to remove aliases: %w", err)
}
shimMgr, err := shim.NewDefaultShimManager()
if err != nil {
return fmt.Errorf("failed to create shim manager: %w", err)
}
if err := shimMgr.Remove(); err != nil {
return fmt.Errorf("failed to remove shims: %w", err)
}
fmt.Printf("%s %s\n", ui.Colors.Green("✓"), "PMG aliases and shims removed. Restart your terminal for changes to take effect")
return nil
}
func removeSystem() error {
if err := errIfSystemInstallAllowed(); err != nil {
return err
}
if setupRemoveConfigFile {
if err := config.RemoveSystemConfigFile(); err != nil {
return err
}
}
shimMgr, err := shim.NewSystemShimManager()
if err != nil {
return fmt.Errorf("failed to create system shim manager: %w", err)
}
if err := shimMgr.Remove(); err != nil {
return fmt.Errorf("failed to remove system shims: %w", err)
}
fmt.Printf("%s %s\n", ui.Colors.Green("✓"), "PMG system install removed")
return nil
}
func errIfSystemInstallAllowed() error {
if runtime.GOOS != "linux" {
return usefulerror.NewUsefulError().
WithCode(errcodes.UnsupportedPlatform).
WithHumanError("system install is only supported on Linux").
WithHelp("Use `pmg setup install` without --system for per-user setup, or run on Linux").
Wrap(errors.New("unsupported platform for --system"))
}
if setupGeteuid() != 0 {
return usefulerror.NewUsefulError().
WithCode(errcodes.PermissionDenied).
WithHumanError("system install requires root").
WithHelp("Re-run as root, e.g. `sudo pmg setup install --system`").
Wrap(errors.New("not root"))
}
return nil
}
+66
View File
@@ -0,0 +1,66 @@
package setup
import (
"runtime"
"testing"
"github.com/safedep/dry/usefulerror"
"github.com/safedep/pmg/errcodes"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestErrIfSystemInstallAllowed(t *testing.T) {
orig := setupGeteuid
t.Cleanup(func() { setupGeteuid = orig })
setupGeteuid = func() int { return 0 }
err := errIfSystemInstallAllowed()
if runtime.GOOS == "linux" {
assert.NoError(t, err)
} else {
require.Error(t, err)
usefulErr, ok := usefulerror.AsUsefulError(err)
require.True(t, ok)
assert.Equal(t, errcodes.UnsupportedPlatform, usefulErr.Code())
}
setupGeteuid = func() int { return 1000 }
err = errIfSystemInstallAllowed()
require.Error(t, err)
usefulErr, ok := usefulerror.AsUsefulError(err)
require.True(t, ok)
if runtime.GOOS == "linux" {
assert.Equal(t, errcodes.PermissionDenied, usefulErr.Code())
} else {
assert.Equal(t, errcodes.UnsupportedPlatform, usefulErr.Code())
}
}
func TestInstallSystemRequiresLinuxAndRoot(t *testing.T) {
orig := setupGeteuid
t.Cleanup(func() {
setupGeteuid = orig
setupInstallSystem = false
})
setupInstallSystem = true
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
}
require.Error(t, err)
usefulErr, ok := usefulerror.AsUsefulError(err)
require.True(t, ok)
assert.Equal(t, errcodes.UnsupportedPlatform, usefulErr.Code())
}