Files
pmg/sandbox/executor/apply.go
T
ee684a29a9 feat(sandbox): presets — additive workload allowance bundles (#387)
* feat(sandbox): introduce presets - additive workload allowance bundles

Presets are named, additive-only bundles of sandbox allowances for a
specific workload (git hooks tooling, Astro/Vite/Next.js dev servers).
They solve the per-workload tuning friction from #384 without weakening
the default posture: no built-in profile references a preset, presets
cannot carry deny rules or profile booleans (strict YAML decoding), and
mandatory denies still win everywhere except the existing exact-match
suppression.

- Preset schema with metadata (author, labels) and schema_version gating
- Registry over ordered sources (embedded builtin, user dir); builtin
  wins name collisions; source abstraction is the extension point for a
  future hosted registry and SafeDep cloud sync
- Official presets: git, astro, vite, nextjs (with threat notes)
- Overlay/runtime integration: pmg sandbox allow preset=<name> and
  --sandbox-allow preset=<name>, stored by reference, resolved at apply
  time, missing presets warn (fail closed) instead of aborting
- Profile integration: presets: [...] list resolved after inherits
- CLI: pmg sandbox preset list (metadata filters, --json), show (prints
  YAML with threat notes), lint
- Docs: user guide (docs/sandbox-presets.md) and design spec

Closes #384

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* fix(sandbox): address review findings on presets

- Presets never modify deny lists: a profile authored deny now survives a
  preset allowing the same path (deny-beats-allow keeps it enforced).
  Regression test added.
- Profile inspection commands (show, diff, lint) construct the profile
  registry with the user-aware preset registry so they agree with runtime
  resolution of custom profiles referencing user presets.
- Handle stderr write error when warning about unresolvable presets.
- Compute preset show underline from the uncolored header.
- Use path.Join for embed.FS reads (slash-separated on all platforms).
- Clarify in docs that lint-staged/astro are examples of preset workloads.
- Drop the design spec from the PR per review.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* fix(sandbox): harden preset precedence against authored denies

Addresses external security review findings on the preset mechanism:

- Bubblewrap: a mandatory write-denied path listed in allow_read lost its
  protection when a later writable parent bind covered it (bwrap last
  mount wins) - exactly the git preset shape (allow_read .git/config +
  allow_write .git/**). The mandatory deny now re-binds the path
  read-only after all writable mounts instead of being skipped.
  Regression test asserts mount ordering. Landlock and Seatbelt were
  unaffected (tests added for the same policy shape on Landlock).
- Environment: ScrubEnv is allow-wins, so a preset environment allowance
  could override a profile-authored deny. Preset env allowances
  overlapping an authored deny pattern are now dropped at application
  time (conservative bidirectional glob overlap, fail closed). Surviving
  entries still opt out of built-in credential scrubbing as intended.
- Network: removed allow_outbound from the preset schema. Both platform
  translators are all-or-nothing for outbound (one allow rule means
  blanket network access), so a preset outbound entry would silently
  change network posture far beyond what its YAML conveys. Strict
  decoding rejects the key.
- Added a dual-path expansion equivalence test (profile presets: field
  vs overlay/--sandbox-allow) and documented the precedence guarantees
  in docs/sandbox-presets.md.

Explicit --sandbox-allow and pmg sandbox allow overrides keep their
existing semantics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* docs(sandbox): document env and preset allowances in allow command and overlay docs

pmg sandbox allow help, the --sandbox-allow flag usage, and the project
overlay docs enumerated only read/write/exec/net types. Add env and
preset to all of them, with an overlay example for persisting an env
allowance and a note on why env entries are not auto-promoted by --last.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* chore(sandbox): trim preset code comments to corner cases and minimal godocs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* fix(sandbox): exact glob intersection for preset env deny overlap

The bidirectional literal-text heuristic missed overlapping globs with
different literal structure: preset allow AWS_*_KEY and authored deny
AWS_SECRET_* both match AWS_SECRET_ACCESS_KEY but neither pattern
matches the other's text, so the allowance merged and allow-wins
scrubbing exposed the variable. EnvPatternsOverlap now computes exact
intersection non-emptiness for the name glob dialect (case-insensitive,
'*' any sequence, '?' single char) via memoized DP.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* fix(sandbox): preset env allowances are exact names, not globs

Glob-vs-glob intersection is a losing game: every dialect extension
(character classes today) silently reopens the deny-bypass hole.
Restricting preset environment allowances to literal variable names
makes the authored-deny precedence check exact by construction: each
deny pattern is evaluated against the concrete name with the same
matcher ScrubEnv uses at runtime, so the decision cannot diverge from
enforcement regardless of deny dialect. Removes the glob intersection
machinery. Profile and --sandbox-allow env globs are unaffected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* fix(sandbox): reject mandatory-deny targets in preset paths

Preset validation relied on IsSensitiveProjectTarget, which covers fewer
files than util.DANGEROUS_FILES. A preset naming .git-credentials,
.pgpass, .docker/config.json or .config/gh exactly would exact-match
suppress the mandatory deny; .git/config in allow_write would suppress
the write protection. Preset paths are now checked against
DANGEROUS_FILES (single source of truth), .git/hooks is rejected in any
direction, and .git/config is rejected for write/exec while read stays
allowed for git repo discovery. Docs state the two deliberate opt-outs
precisely.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* feat(sandbox): preset init and edit commands for community authoring

pmg sandbox preset init scaffolds a valid user preset (metadata flags,
threat-note template, starter rule) and refuses built-in names since
builtins win resolution. pmg sandbox preset edit opens the file via the
shared editor package and validates the result, warning when a user
preset is shadowed by a built-in. Docs lead with the scaffolded flow and
spell out builtin-vs-community provenance in preset list.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

* refactor(sandbox): move mandatory-target matching into util

Preset path validation re-encoded knowledge util already owns: the
dangerous-files comparison and hardcoded .git/config and .git/hooks
strings. util now exports GitConfigPath, GitHooksPath (also used by
GetMandatoryDenyPatterns), PathCoveredBy and DangerousFileMatch, and
preset validation consumes them so the mandatory deny policy has a
single definition.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-21 15:14:07 +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 both guard and proxy flows 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)
}