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

391 lines
13 KiB
Go

package flows
import (
"context"
"fmt"
"os"
"time"
"github.com/safedep/dry/log"
"github.com/safedep/pmg/analyzer"
"github.com/safedep/pmg/config"
"github.com/safedep/pmg/internal/audit"
"github.com/safedep/pmg/internal/localstore"
"github.com/safedep/pmg/internal/runner"
"github.com/safedep/pmg/internal/ui"
"github.com/safedep/pmg/packagemanager"
"github.com/safedep/pmg/proxy"
"github.com/safedep/pmg/proxy/certmanager"
"github.com/safedep/pmg/proxy/interceptors"
)
type proxyFlow struct {
pm packagemanager.PackageManager
}
// ProxyFlow creates a new proxy-based flow for package manager protection
func ProxyFlow(pm packagemanager.PackageManager) *proxyFlow {
return &proxyFlow{
pm: pm,
}
}
// RunProxy parses args with pm and runs the proxy flow on the parsed command.
// It is the shared entry point for package manager commands.
func RunProxy(ctx context.Context, pm packagemanager.PackageManager, args []string) error {
parsedCommand, err := pm.ParseCommand(args)
if err != nil {
return fmt.Errorf("failed to parse command: %w", err)
}
return ProxyFlow(pm).Run(ctx, args, parsedCommand)
}
// Run executes the proxy-based flow
func (f *proxyFlow) Run(ctx context.Context, args []string, parsedCmd *packagemanager.ParsedCommand) (runErr error) {
// Guard mode is removed: a config or environment that still disables proxy
// interception must fail loudly instead of being silently switched to proxy
// mode. Checked here rather than at CLI startup so non-install commands
// (pmg config, setup remove, doctor, ...) stay usable to fix the config.
if err := config.RejectRemovedProxyOptOut(); err != nil {
return err
}
// Check if we have a supported ecosystem else fail fast
ecosystem := f.pm.Ecosystem()
if !interceptors.IsSupported(ecosystem) {
return fmt.Errorf("proxy mode is not supported for %s", ecosystem.String())
}
// Configure sandbox based on command type and enforcement policy
config.ConfigureSandbox(parsedCmd.IsInstallationCommand() || parsedCmd.MayDownloadPackages())
cfg := config.Get()
// When install_only is enabled, skip proxy for known non-download commands
// and user-defined skip commands
if cfg.Config.Proxy.InstallOnly {
if !parsedCmd.MayDownloadPackages() {
log.Debugf("Skipping proxy for non-download command (install_only=true)")
return runner.Execute(ctx, parsedCmd, f.pm.Name(), cfg.DryRun)
}
if cmds, ok := cfg.Config.Proxy.SkipCommands[f.pm.Name()]; ok && len(cmds) > 0 {
if packagemanager.IsFirstNonFlagArgInList(parsedCmd.Command.Args, cmds) {
log.Debugf("Skipping proxy for user-defined skip command (install_only=true)")
return runner.Execute(ctx, parsedCmd, f.pm.Name(), cfg.DryRun)
}
}
}
// Initialize report data at the start
reportData := ui.NewReportData()
reportData.PackageManagerName = f.pm.Name()
reportData.FlowType = ui.FlowTypeProxy
reportData.DryRun = cfg.DryRun
reportData.InsecureMode = cfg.InsecureInstallation
reportData.ParanoidMode = cfg.Config.Paranoid
reportData.SandboxEnabled = cfg.Config.Sandbox.Enabled
if cfg.Config.Sandbox.Enabled {
if policyRef, exists := cfg.Config.Sandbox.PolicyFor(f.pm.Name()); exists {
reportData.SandboxProfile = policyRef.Profile
}
}
if cfg.SandboxProfileOverride != "" {
reportData.SandboxProfile = cfg.SandboxProfileOverride
}
startTime := time.Now()
audit.LogInstallStarted(f.pm.Name(), args)
sessionCompleted := false
defer func() {
if sessionCompleted {
return
}
// On early error returns (e.g. CA cert, analyzer init), reportData.Outcome
// is still the default (Success). Override to Error for these cases.
if runErr != nil && reportData.Outcome == ui.OutcomeSuccess {
reportData.Outcome = ui.OutcomeError
}
audit.LogSessionComplete(audit.Outcome(reportData.Outcome.String()), audit.FlowTypeProxy)
}()
// Check if dry-run mode is enabled
if cfg.DryRun {
log.Infof("Dry-run mode: Would execute %s with proxy protection", f.pm.Name())
log.Infof("Dry-run mode: Command would be: %s %v", parsedCmd.Command.Exe, parsedCmd.Command.Args)
reportData.Outcome = ui.OutcomeDryRun
ui.Report(reportData)
return nil
}
// Setup CA certificate for MITM
caCert, caCertPath, err := f.setupCACertificate()
if err != nil {
return fmt.Errorf("failed to setup CA certificate for proxy mode: %w", err)
}
defer func() {
// Clean up temporary CA certificate file
if caCertPath != "" {
if err := os.Remove(caCertPath); err != nil {
log.Errorf("Failed to remove CA certificate file: %v", err)
}
}
}()
// Create certificate manager
certMgr, err := f.createCertificateManager(caCert)
if err != nil {
return fmt.Errorf("failed to create certificate manager: %w", err)
}
localDB := localstore.NewManager(cfg)
defer func() {
if cerr := localDB.Close(); cerr != nil {
log.Warnf("failed to close localdb: %v", cerr)
}
}()
// Analyzer with an optional persistent cache. Cache failures degrade to
// running uncached and never block the install.
malysisAnalyzer, err := BuildMalysisAnalyzer(ctx, cfg, localDB)
if err != nil {
return fmt.Errorf("failed to create analyzer: %w", err)
}
// Create analysis cache and stats collector
cache := interceptors.NewInMemoryAnalysisCache()
statsCollector := interceptors.NewAnalysisStatsCollector()
// Create confirmation channel and start confirmation handler
confirmationChan := make(chan *interceptors.ConfirmationRequest, 10)
defer close(confirmationChan)
// Create interaction callbacks for user prompts
// Note: We use a pointer so we can later inject the input reader via SetInput
interaction := &packagemanager.PackageManagerInteraction{}
// Extract pinned versions from install targets so cooldown handlers can
// report when a user's explicitly requested version was blocked.
pinnedVersions := make(map[string]string)
for _, target := range parsedCmd.InstallTargets {
if target.IsExplicitVersion {
pinnedVersions[target.PackageVersion.GetPackage().GetName()] = target.PackageVersion.GetVersion()
}
}
// Package managers with run-specific proxy routing (Go's user-configurable
// GOPROXY) contribute extra child env vars and dynamic MITM hosts.
routing := &packagemanager.ProxyRouting{}
if provider, ok := f.pm.(packagemanager.ProxyRoutingProvider); ok {
routing, err = provider.ProxyRouting(ctx)
if err != nil {
return fmt.Errorf("failed to resolve proxy routing for %s: %w", f.pm.Name(), err)
}
}
// Create ecosystem-specific interceptor using factory
factory := interceptors.NewInterceptorFactory(malysisAnalyzer, cache, statsCollector, confirmationChan, interceptors.InterceptorContext{
PinnedVersions: pinnedVersions,
GoProxyBaseURLs: routing.MITMHosts,
})
interceptor, err := factory.CreateInterceptor(ecosystem)
if err != nil {
return fmt.Errorf("failed to create interceptor for %s: %w", ecosystem.String(), err)
}
log.Debugf("Created %s interceptor for ecosystem %s", interceptor.Name(), ecosystem.String())
// Create and start proxy server
proxyServer, proxyAddr, err := f.createAndStartProxyServer(certMgr, []proxy.Interceptor{
interceptor,
interceptors.NewAuditLoggerInterceptor(),
})
if err != nil {
return fmt.Errorf("failed to start proxy server: %w", err)
}
// Ensure proxy is stopped on exit
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := proxyServer.Stop(shutdownCtx); err != nil {
log.Errorf("Failed to stop proxy server: %v", err)
}
}()
ui.ClearStatus()
log.Infof("Proxy server started on %s", proxyAddr)
log.Infof("Running %s with proxy protection enabled", f.pm.Name())
executionError := runner.ExecuteWithOptions(ctx, parsedCmd, runner.ExecuteOptions{
PackageManagerName: f.pm.Name(),
DryRun: cfg.DryRun,
SandboxProxyAddr: proxyAddr,
Mode: runner.ExecutionModeAuto,
EnvOverrides: append(packagemanager.EnvVarForProxy(proxyAddr, caCertPath), routing.ExtraEnv...),
DirectEnvOverrides: ciEnvOverride(),
BeforeDirectRun: func() error {
log.Debugf("Executing proxy for non interactive TTY")
interaction.GetConfirmationOnMalware = func(_ []*analyzer.PackageVersionAnalysisResult) (bool, error) {
return false, nil
}
go interceptors.HandleConfirmationRequests(confirmationChan, interaction, nil)
return nil
},
PreparePTYSession: func(runtime *runner.PTYRuntime) error {
log.Debugf("Executing proxy for interactive TTY")
interaction.GetConfirmationOnMalware = func(malwarePackages []*analyzer.PackageVersionAnalysisResult) (bool, error) {
return ui.GetConfirmationOnMalwareWithReader(malwarePackages, interaction.Reader())
}
go interceptors.HandleConfirmationRequests(
confirmationChan,
interaction,
&interceptors.ConfirmationHook{
BeforeInteraction: func(_ []*analyzer.PackageVersionAnalysisResult) error {
runtime.OutputRouter.Pause()
if err := runtime.Session.SetCookedMode(); err != nil {
return fmt.Errorf("failed to set cooked mode: %w", err)
}
if _, err := fmt.Fprint(os.Stdout, "\033[?25h"); err != nil {
log.Warnf("failed to force cursor visible: %v", err)
}
runtime.InputRouter.RouteToPrompt(runtime.PromptWriter)
interaction.SetInput(runtime.PromptReader)
return nil
},
AfterInteraction: func(_ []*analyzer.PackageVersionAnalysisResult, _ bool) error {
runtime.InputRouter.RouteToPTY()
if err := runtime.Session.SetRawMode(); err != nil {
return fmt.Errorf("failed to set raw mode: %w", err)
}
interaction.SetInput(nil)
runtime.OutputRouter.Resume()
return nil
},
},
)
return nil
},
})
// Populate report data from stats collector
stats := statsCollector.GetStats()
reportData.StartTime = startTime
reportData.TotalAnalyzed = stats.TotalAnalyzed
reportData.AllowedCount = stats.AllowedCount
reportData.ConfirmedCount = stats.ConfirmedCount
reportData.BlockedCount = stats.BlockedCount
reportData.BlockedPackages = statsCollector.GetBlockedPackages()
reportData.ConfirmedPackages = statsCollector.GetConfirmedPackages()
reportData.CooldownBlockedPackages = statsCollector.GetCooldownBlocks()
reportData.AdvisoryMessage = cfg.Config.AdvisoryMessage
// Set outcome based on execution result using shared inference logic
reportData.Outcome = inferOutcome(cfg.InsecureInstallation, cfg.DryRun, reportData.BlockedCount, stats.UserCancelledCount, executionError)
// Emit session complete before report/exit — handleExecutionResultError may call
// os.Exit which skips defers, so we must emit the session summary here.
audit.LogSessionComplete(audit.Outcome(reportData.Outcome.String()), audit.FlowTypeProxy)
sessionCompleted = true
// Show the report
ui.Report(reportData)
// Run should always end with handleExecutionResultError to ensure the process exits with the correct exit code
// from the execution result.
return handleExecutionResultError(executionError)
}
// handleExecutionResultError returns the execution error so RunE can route it
// through ui.ExitFromCommandError, the single exit point. A transparent
// *runner.ChildExitError survives the %w wrap (errors.As unwraps it) and is
// passed through with the child's exit code; everything else keeps the visible
// PMG error framing.
func handleExecutionResultError(err error) error {
if err == nil {
return nil
}
return fmt.Errorf("failed to execute command: %w", err)
}
func (f *proxyFlow) setupCACertificate() (*certmanager.Certificate, string, error) {
dir := config.Get().ConfigDir()
outputPath := certmanager.EphemeralProxyCABundlePath()
cert, _, err := SetupCACertificate(dir, outputPath)
return cert, outputPath, err
}
// createCertificateManager creates a certificate manager with the given CA certificate
func (f *proxyFlow) createCertificateManager(caCert *certmanager.Certificate) (certmanager.CertificateManager, error) {
caConfig := certmanager.DefaultCertManagerConfig()
certMgr, err := certmanager.NewCertificateManagerWithCA(caCert, caConfig)
if err != nil {
return nil, fmt.Errorf("failed to create certificate manager: %w", err)
}
return certMgr, nil
}
// createAndStartProxyServer creates and starts the proxy server with the given interceptor
func (f *proxyFlow) createAndStartProxyServer(
certMgr certmanager.CertificateManager,
interceptorsList []proxy.Interceptor,
) (proxy.ProxyServer, string, error) {
proxyConfig := proxy.DefaultProxyConfig()
proxyConfig.CertManager = certMgr
proxyConfig.Interceptors = interceptorsList
presenter := ui.ProxyPresenter{Advisory: config.AdvisoryMessage}
proxyConfig.BlockMessageRenderer = presenter.BlockMessage
proxyServer, err := proxy.NewProxyServer(proxyConfig)
if err != nil {
return nil, "", fmt.Errorf("failed to create proxy server: %w", err)
}
if err := proxyServer.Start(); err != nil {
return nil, "", fmt.Errorf("failed to start proxy server: %w", err)
}
proxyAddr := proxyServer.Address()
if proxyAddr == "" {
return nil, "", fmt.Errorf("proxy server started but address is empty")
}
return proxyServer, proxyAddr, nil
}
// ciEnvOverride forces CI=true for non-interactive runs so package managers
// behave non-interactively. It respects an explicitly set CI value (including
// CI=false) so we don't clobber the user's intent. See issue #335.
func ciEnvOverride() []string {
if _, ok := os.LookupEnv("CI"); ok {
return nil
}
return []string{"CI=true"}
}