Files
Sahil BansalandGitHub 94781d6bda Remove guard mode: proxy interception is now the only flow (#386)
* refactor: remove guard mode execution paths and guard-only packages

Guard (non-proxy) mode is removed; all package-manager commands now
always run the proxy flow. Removes the guard engine, the common flow,
the extractor package, the npm/pypi dependency resolvers and the
PackageResolver plumbing that only guard mode consumed.

The guard package retains only PackageManagerGuardInteraction, which
the proxy flow and confirmation interceptors reuse for user prompts.
Proxy behavior is unchanged.

* refactor: remove proxy opt-out surfaces, guard references in config, action and docs

Removes Config.ProxyMode, ProxyConfig.Enabled, IsProxyModeEnabled, the
proxy_mode legacy fallback, PMG_PROXY_ENABLED handling and the
--proxy-mode / --include-dev-dependencies flags. Proxy interception can
no longer be disabled.

Also removes the proxy-mode input from the GitHub Action, the
proxy-mode doctor check and setup info row, updates the E2E workflow to
stop passing --proxy-mode=false, and sweeps guard-mode wording from
docs and the config template.

The legacy proxy_install_only flat key and PMG_PROXY_INSTALL_ONLY env
var remain supported. audit.FlowTypeGuard is kept so previously
recorded audit events still translate for cloud sync.

* feat: fail loudly when a removed proxy opt-out is still configured

A leftover proxy.enabled: false / proxy_mode: false config key or
PMG_PROXY_ENABLED=false / PMG_PROXY_MODE=false env var previously meant
guard mode; silently ignoring it would switch those users to proxy
interception without notice. PMG now exits with an actionable error
naming the exact source. Precedence mirrors the old resolution order:
env (ignored under lockdown) > proxy.enabled > legacy proxy_mode.

The pmg config subtree is exempt so the config file can still be fixed
with pmg config edit/set. The GitHub Action's proxy-mode input is kept
as a tombstone that fails the action when set to false and warns
otherwise.

* refactor: extract flows.RunProxy and address review findings

Collapses the identical parse-then-run body duplicated across the 12
package manager commands into flows.RunProxy. Documents the cache-hit /
offline analysis trade-off versus the removed guard manifest path,
fixes a stale non-proxy label in the E2E workflow and a stale guard
reference in the uvx parser comment.

* fix(config): mirror old proxy opt-out precedence exactly

PMG_PROXY_MODE only ever took effect through the legacy fallback, which
was gated on the presence of a proxy: key in the config file (even a
null one). Promoting it to the top env tier caused two inversions: a
stale PMG_PROXY_MODE=false hard-failed configs that resolved to proxy
mode, and PMG_PROXY_MODE=true silently overrode an explicit
proxy.enabled: false file opt-out. The check now resolves in the old
order: PMG_PROXY_ENABLED > proxy: section (presence gates the legacy
tier) > PMG_PROXY_MODE > flat proxy_mode.

parseOptOutBool also accepts numeric values (0 = false) to match
viper's WeaklyTypedInput/cast.ToBool coercion, so proxy.enabled: 0 and
proxy_mode: 0 are detected as opt-outs.

* refactor: move package manager interaction out of guard

* refactor: trim package manager interaction

* fix(config): normalize config keys viper-style in proxy opt-out check

Viper resolved config file keys case-insensitively and expanded dotted
keys, so spellings like Proxy:, Enabled:, a literal proxy.enabled key or
Proxy_Mode selected guard mode before the removal. The opt-out check now
lowercases keys recursively and nests dotted keys before matching, so
those existing opt-outs fail loudly instead of being silently ignored.

* refactor: remove inert transitive controls, dead parser state and guard audit variant

transitive / transitive_depth lost their only consumers with the
dependency resolvers; remove the config fields, flags, template and doc
entries, and the report/audit plumbing that misreported transitive
analysis as enabled.

Remove write-only parser state (PackageInstallTarget.Extras,
ParsedCommand.ManifestFiles, ShouldExtractFromManifest); IsManifestInstall
stays as it feeds sandbox gating via IsInstallationCommand.

Remove audit.FlowTypeGuard and its cloud mapping; guard events recorded
by pre-removal versions in an unsynced WAL translate to UNSPECIFIED.

* fix: address review findings on the opt-out wiring and cleanups

Move the removed-opt-out rejection from the CLI PersistentPreRun into
proxyFlow.Run: the check now fires exactly for package-manager runs, so
non-install commands (pmg setup remove, doctor, config, version) stay
usable to fix or remove an opted-out installation, and future commands
inherit or avoid the check by construction instead of by exemption list.

Also: make the e2e malicious-package assertion actually fail the job
when an install is not blocked, route pmg go through flows.RunProxy,
and drop the dead extras return from pypiParsePackageInfo (extras are
still stripped from package names).

* fix(config): make the removed opt-out check faithful to the old resolution

The gate that silenced the legacy proxy_mode surfaces matched the raw
proxy key case-sensitively in the old code, while values resolved
viper-style (case-insensitive, dotted keys); applying each semantic
where the old code did fixes both divergences: a case-variant Proxy:
section no longer hides a flat proxy_mode: false opt-out, and a dotted
proxy.enabled: false overridden by proxy_mode: true no longer errors.

Replace the generic key-tree normalization with two targeted lookups
(the check only ever resolves proxy.enabled and proxy_mode), which also
makes colliding spellings resolve deterministically. Coerce legacy-tier
values cast.ToBool-style so PMG_PROXY_MODE=off style opt-outs are
detected, log the config read error instead of swallowing it, and
shorten the error to a one-line statement with the specific remedy in
the help text.

Add lockdown coverage (env inert both directions) and a repeated-run
determinism test.

* fix(config): fall back to defaults for unrecognized proxy opt-out values

The old loader swallowed viper errors and ran on defaults, so values
like proxy.enabled: yes or PMG_PROXY_ENABLED=banana silently discarded
the whole config and defaulted to proxy. Treat them the same way now:
unrecognized values mean the default (proxy on) instead of a hard
error, and the doc comment no longer claims the old loader failed
loudly. Only values that actually meant guard mode fail.

Also check the removed opt-out before the CA trust check in pmg go,
restoring the old error precedence: a config problem must not steer
the user into an unnecessary OS trust store change.

* fix(e2e): PMG_PROXY_MODE assertion must match the legacy gate semantics

The runner's setup step writes the template config, which has a proxy:
section — and with one present the legacy PMG_PROXY_MODE was always
inert, so expecting a loud failure there asserts pre-fidelity-fix
behavior. Assert both sides instead: inert (command succeeds) with the
standard config, loud failure against an empty config dir where the
legacy fallback actually applied.

* refactor(config): collapse parseOptOutBool to ParseBool over the string form

YAML hands us typed values (bool, int), so route them through
fmt.Sprintf %v and strconv.ParseBool instead of a per-type switch.
Identical behavior for every recognized value; numbers other than 0/1
now read as no opinion instead of cast.ToBool's nonzero-true, which no
real config relies on.
2026-07-22 15:19:19 +05:30

350 lines
13 KiB
Go

package executor
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/safedep/dry/log"
"github.com/safedep/dry/usefulerror"
"github.com/safedep/dry/utils"
"github.com/safedep/pmg/config"
"github.com/safedep/pmg/errcodes"
"github.com/safedep/pmg/internal/audit"
"github.com/safedep/pmg/sandbox"
"github.com/safedep/pmg/sandbox/platform"
"github.com/safedep/pmg/sandbox/util"
)
type applySandboxConfig struct {
sb sandbox.Sandbox
rt *sandbox.ExecutionContext
}
type applySandboxOpt func(*applySandboxConfig)
// WithSandbox sets the sandbox to use for the command.
// When not set, the sandbox will be determined by the platform.
func WithSandbox(sb sandbox.Sandbox) applySandboxOpt {
return func(c *applySandboxConfig) {
c.sb = sb
}
}
// WithExecutionContext provides runtime data known only at spawn time
// (e.g. the PMG proxy address) to the sandbox driver.
func WithExecutionContext(rt *sandbox.ExecutionContext) applySandboxOpt {
return func(c *applySandboxConfig) {
c.rt = rt
}
}
// ApplySandbox applies sandbox isolation to the command if sandbox mode is enabled.
// This is a helper function used by the command runner to avoid code duplication.
//
// This is a security sensitive operation. If sandbox is enabled via. config but not available on the platform,
// it will return an error to avoid running the command without sandbox protection.
func ApplySandbox(ctx context.Context, cmd *exec.Cmd, pmName string, opts ...applySandboxOpt) (*sandbox.ExecutionResult, error) {
cfg := config.Get()
if !cfg.Config.Sandbox.Enabled {
return sandbox.NewExecutionResult(), nil
}
applyConfig := &applySandboxConfig{}
for _, opt := range opts {
opt(applyConfig)
}
presetRegistry, err := sandbox.NewPresetRegistry(sandbox.WithUserPresetDir(cfg.SandboxPresetDir()))
if err != nil {
return nil, fmt.Errorf("failed to create preset registry: %w", err)
}
registry, err := sandbox.NewProfileRegistry(
sandbox.WithUserProfileDir(cfg.SandboxProfileDir()),
sandbox.WithPresetRegistry(presetRegistry),
)
if err != nil {
return nil, fmt.Errorf("failed to create profile registry: %w", err)
}
var policy *sandbox.SandboxPolicy
if cfg.SandboxProfileOverride != "" {
log.Debugf("Using sandbox profile override: %s", cfg.SandboxProfileOverride)
policy, err = registry.GetProfile(cfg.SandboxProfileOverride)
if err != nil {
return nil, usefulerror.NewUsefulError().
WithCode(errcodes.InvalidArgument).
WithHumanError(fmt.Sprintf("Failed to load sandbox profile override: %s", cfg.SandboxProfileOverride)).
WithHelp("Please verify the sandbox profile path and try again.").
WithAdditionalHelp("See more at: https://github.com/safedep/pmg/blob/main/docs/sandbox.md").
Wrap(err)
}
} else {
log.Debugf("Looking up sandbox policy for %s", pmName)
// When a policy is not configured for a package manager, we error out
// This is to avoid running the command without sandbox protection.
// To bypass sandbox for a specific package manager, users should explicitly
// disable for the package manager in the config.
policyRef, exists := cfg.Config.Sandbox.PolicyFor(pmName)
if !exists {
return nil, usefulerror.NewUsefulError().
WithCode(errcodes.NotFound).
WithHumanError(fmt.Sprintf("No sandbox policy configured for %s", pmName)).
WithHelp("Please configure a sandbox policy for this package manager in the config file.").
WithAdditionalHelp("See https://github.com/safedep/pmg/blob/main/docs/sandbox.md for more information.").
Wrap(fmt.Errorf("no sandbox policy configured for %s", pmName))
}
// The policy is explicitly disabled for this package manager, so we skip sandbox
if !policyRef.Enabled {
log.Warnf("sandbox policy %s is explicitly disabled for %s, skipping sandbox", policyRef.Profile, pmName)
return sandbox.NewExecutionResult(), nil
}
log.Debugf("Loading sandbox policy %s", policyRef.Profile)
// Check if there is a template for the policy and use it if it exists
// This is a way to override a built-in profile or create a custom profile.
if template, exists := cfg.Config.Sandbox.PolicyTemplates[policyRef.Profile]; exists {
if filepath.IsAbs(template.Path) {
policy, err = registry.GetProfile(template.Path)
if err != nil {
return nil, fmt.Errorf("failed to load sandbox policy %s: %w", template.Path, err)
}
} else {
policyPath := filepath.Join(cfg.ConfigDir(), template.Path)
policy, err = registry.GetProfile(policyPath)
if err != nil {
return nil, fmt.Errorf("failed to load sandbox policy %s: %w", policyPath, err)
}
}
} else {
// Load the policy from the registry by name
policy, err = registry.GetProfile(policyRef.Profile)
if err != nil {
return nil, fmt.Errorf("failed to load sandbox policy %s: %w", policyRef.Profile, err)
}
}
}
log.Debugf("Loaded sandbox policy %s", policy.Name)
// Apply the per-repo project overlay (saved via `pmg sandbox allow`). When
// global_lockdown is set, overlays are ignored so the locked baseline is
// authoritative. An empty cwd is tolerated by ResolveRepoRoot's callers
// downstream, so swallow a Getwd error here.
cwd, _ := os.Getwd()
if repoRoot, repoErr := sandbox.ResolveRepoRoot(cwd); repoErr != nil {
log.Warnf("Project overlay: resolve repo root: %v", repoErr)
} else if _, err := applyProjectOverlay(policy, cfg.SandboxOverlayDir(), repoRoot, cfg.IsLocked(), presetRegistry); err != nil {
log.Warnf("Project overlay: apply: %v", err)
// A failed overlay load means the user's saved allowances were silently
// dropped. Echo to stderr so users at normal verbosity see why their
// sandbox is more restrictive than expected.
fmt.Fprintf(os.Stderr, "pmg: warning: project overlay could not be applied: %v\n", err)
}
// Apply runtime --sandbox-allow overrides to the policy before execution
if len(cfg.SandboxAllowOverrides) > 0 {
applyRuntimeOverrides(policy, cfg.SandboxAllowOverrides, presetRegistry)
logSandboxOverrides(policy.Name, cfg.SandboxAllowOverrides)
}
if !policy.AppliesToPackageManager(pmName) {
return nil, fmt.Errorf("sandbox policy %s does not apply to %s", policy.Name, pmName)
}
var sb sandbox.Sandbox
if applyConfig.sb != nil {
sb = applyConfig.sb
} else {
sb, err = platform.NewSandbox()
if err != nil {
return nil, fmt.Errorf("sandbox not available on this platform: %v", err)
}
}
if !sb.IsAvailable() {
return nil, usefulerror.NewUsefulError().
WithCode(errcodes.InvalidArgument).
WithHumanError(fmt.Sprintf("Sandbox %s is required but not available", sb.Name())).
WithHelp("Please install the sandbox provider and try again.").
WithAdditionalHelp("See more at: https://github.com/safedep/pmg/blob/main/docs/sandbox.md").
Wrap(fmt.Errorf("sandbox %s is required but not available", sb.Name()))
}
log.Debugf("Running %s in %s sandbox with policy %s", pmName, sb.Name(), policy.Name)
// Scrub sensitive environment variables before the child is spawned. This
// runs after overlay and runtime overrides are merged into the policy so
// user allowances are honored, and is platform-independent (it filters the
// env slice regardless of the OS sandbox driver).
scrubbed := scrubEnv(cmd, policy)
if _, err := sandbox.ValidateNetworkLockdown(policy, applyConfig.rt); err != nil {
return nil, err
}
result, err := sb.Execute(ctx, cmd, policy, applyConfig.rt)
if err != nil {
return nil, fmt.Errorf("failed to setup sandbox: %w", err)
}
result.SetScrubbedEnvCount(scrubbed)
return result, nil
}
// applyRuntimeOverrides applies --sandbox-allow overrides to the policy.
// Overrides append to allow lists and remove exact matches from corresponding deny lists
// so that deny rules don't shadow the explicit override. Only full-path exact matches are
// removed — glob and wildcard deny patterns are never modified to stay secure by default.
func applyRuntimeOverrides(policy *sandbox.SandboxPolicy, overrides []config.SandboxAllowOverride, presets sandbox.PresetRegistry) {
for _, override := range overrides {
switch override.Type {
case config.SandboxAllowPreset:
// A missing preset means fewer allowances (fail closed), so warn
// instead of aborting the run.
if presets == nil {
log.Warnf("Sandbox override: preset %s ignored, no preset registry available", override.Value)
continue
}
info, err := presets.Get(override.Value)
if err != nil {
log.Warnf("Sandbox override: preset %s could not be resolved: %v", override.Value, err)
if _, werr := fmt.Fprintf(os.Stderr, "pmg: warning: sandbox preset %q could not be applied: %v\n", override.Value, err); werr != nil {
log.Warnf("failed to write preset warning to stderr: %v", werr)
}
continue
}
log.Infof("Sandbox override: applying preset %s (%s)", override.Value, info.Source)
info.Preset.ApplyToPolicy(policy)
case config.SandboxAllowRead:
log.Infof("Sandbox override: allowing read access to %s", override.Value)
policy.Filesystem.AllowRead = append(policy.Filesystem.AllowRead, override.Value)
policy.Filesystem.DenyRead = removeExactMatch(policy.Filesystem.DenyRead, override.Value)
case config.SandboxAllowWrite:
log.Infof("Sandbox override: allowing write access to %s", override.Value)
policy.Filesystem.AllowWrite = append(policy.Filesystem.AllowWrite, override.Value)
policy.Filesystem.DenyWrite = removeExactMatch(policy.Filesystem.DenyWrite, override.Value)
case config.SandboxAllowExec:
log.Infof("Sandbox override: allowing execution of %s", override.Value)
policy.Process.AllowExec = append(policy.Process.AllowExec, override.Value)
policy.Process.DenyExec = removeExactMatch(policy.Process.DenyExec, override.Value)
case config.SandboxAllowNetConnect:
log.Infof("Sandbox override: allowing outbound connection to %s", override.Value)
policy.Network.AllowOutbound = append(policy.Network.AllowOutbound, override.Value)
case config.SandboxAllowNetBind:
log.Infof("Sandbox override: allowing network bind on %s", override.Value)
policy.Network.AllowBind = append(policy.Network.AllowBind, override.Value)
// Enable AllowNetworkBind so the translator emits bind rules.
// Without this, AllowBind entries would be ignored on some platforms.
policy.AllowNetworkBind = utils.PtrTo(true)
case config.SandboxAllowEnv:
// Allow-wins: appending to Allow un-scrubs the variable regardless
// of whether it was denied by the built-in list or a profile deny
// glob, so (unlike the filesystem cases) there is no deny list to
// remove an exact match from.
log.Infof("Sandbox override: allowing environment variable %s", override.Value)
policy.Environment.Allow = append(policy.Environment.Allow, override.Value)
}
}
}
// scrubEnv removes sensitive environment variables from cmd.Env per the
// resolved policy's environment section and returns how many were removed.
// It runs after project overlay and runtime overrides are merged into the
// policy, so user allowances take effect. A nil cmd.Env would mean "inherit
// the parent environment", which would defeat scrubbing, so it is populated
// from os.Environ() first.
func scrubEnv(cmd *exec.Cmd, policy *sandbox.SandboxPolicy) int {
if cmd.Env == nil {
cmd.Env = os.Environ()
}
result := util.ScrubEnv(cmd.Env, util.EnvScrubOptions{
Allow: policy.Environment.Allow,
Deny: policy.Environment.Deny,
})
cmd.Env = result.Env
if len(result.Removed) > 0 {
log.Infof("Sandbox: scrubbed %d sensitive environment variable(s) from %s: %s",
len(result.Removed), policy.Name, strings.Join(result.Removed, ", "))
}
return len(result.Removed)
}
// removeExactMatch removes entries from the slice that exactly match the given value.
// Glob patterns and wildcards in the slice are never matched. Only literal string
// equality is used. This keeps broad deny rules intact while allowing targeted overrides.
func removeExactMatch(slice []string, value string) []string {
result := make([]string, 0, len(slice))
for _, entry := range slice {
if entry == value {
log.Infof("Sandbox override: removing conflicting deny rule for %s", value)
continue
}
result = append(result, entry)
}
return result
}
// applyProjectOverlay loads the per-repo overlay (when one exists) and feeds
// its entries through applyRuntimeOverrides. Returns the number of entries
// applied. A nil/missing overlay is a clean no-op. When locked, the overlay
// is ignored entirely.
func applyProjectOverlay(policy *sandbox.SandboxPolicy, overlayDir, repoRoot string, locked bool, presets sandbox.PresetRegistry) (int, error) {
if locked {
log.Debugf("Project overlay: skipping under global_lockdown")
return 0, nil
}
overlay, _, err := sandbox.LoadOverlayForRepo(overlayDir, repoRoot)
if err != nil {
return 0, fmt.Errorf("project overlay: load: %w", err)
}
if overlay == nil || len(overlay.Allow) == 0 {
return 0, nil
}
entries := overlay.ToAllowOverrides()
applyRuntimeOverrides(policy, entries, presets)
// The "+overlay" suffix tags audit events as overlay-sourced.
logSandboxOverrides(policy.Name+"+overlay", entries)
log.Infof("Project overlay: applied %d saved allowance(s) for %s", len(entries), repoRoot)
return len(entries), nil
}
// logSandboxOverrides records sandbox allow overrides in the audit event log.
func logSandboxOverrides(profileName string, overrides []config.SandboxAllowOverride) {
entries := make([]map[string]string, 0, len(overrides))
for _, o := range overrides {
entries = append(entries, map[string]string{
"type": string(o.Type),
"value": o.Value,
})
}
audit.LogSandboxOverride(profileName, entries)
}