mirror of
https://github.com/safedep/pmg.git
synced 2026-08-03 07:24:09 +02:00
* 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>
320 lines
10 KiB
Go
320 lines
10 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
|
|
"github.com/safedep/dry/usefulerror"
|
|
"github.com/safedep/pmg/config"
|
|
"github.com/safedep/pmg/errcodes"
|
|
"github.com/safedep/pmg/internal/ui"
|
|
pmgsandbox "github.com/safedep/pmg/sandbox"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// allowFactory bundles the dependencies needed by `pmg sandbox allow`. Tests
|
|
// inject stubs. Production wiring uses defaultAllowFactory.
|
|
type allowFactory struct {
|
|
overlayDir func() string
|
|
repoRoot func() (string, error)
|
|
cache func() *pmgsandbox.ViolationCache
|
|
locked func() bool
|
|
presets func() (pmgsandbox.PresetRegistry, error)
|
|
}
|
|
|
|
func defaultAllowFactory() allowFactory {
|
|
return allowFactory{
|
|
overlayDir: func() string { return config.Get().SandboxOverlayDir() },
|
|
repoRoot: resolveCurrentRepoRoot,
|
|
cache: func() *pmgsandbox.ViolationCache {
|
|
return pmgsandbox.NewViolationCache(config.Get().SandboxViolationCacheDir())
|
|
},
|
|
locked: func() bool { return config.Get().IsLocked() },
|
|
presets: defaultPresetRegistryFactory,
|
|
}
|
|
}
|
|
|
|
// NewAllowCommand returns the `pmg sandbox allow` command.
|
|
func NewAllowCommand() *cobra.Command {
|
|
return newAllowCommand(defaultAllowFactory())
|
|
}
|
|
|
|
type allowOptions struct {
|
|
last bool
|
|
all bool
|
|
force bool
|
|
}
|
|
|
|
func newAllowCommand(factory allowFactory) *cobra.Command {
|
|
opts := &allowOptions{}
|
|
|
|
cmd := &cobra.Command{
|
|
Use: "allow [type=value …]",
|
|
Short: "Persist sandbox allowances for the current repository",
|
|
Long: "Save allowances into the current repo's sandbox project overlay so future PMG runs in this repo apply them automatically.\n\n" +
|
|
"Use --last to promote the primary violation from the most recent cached report,\n" +
|
|
"or --last --all to promote every safe FS/exec violation from that report.\n" +
|
|
"Manual entries (type=value …) accept any allow type and persist as-is.",
|
|
Example: " pmg sandbox allow write=./.astro net-bind=localhost:4321\n" +
|
|
" pmg sandbox allow env=AWS_PROFILE\n" +
|
|
" pmg sandbox allow preset=git preset=astro\n" +
|
|
" pmg sandbox allow --last --all",
|
|
Args: cobra.ArbitraryArgs,
|
|
SilenceErrors: false,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
if err := runAllow(cmd.OutOrStdout(), args, opts, factory); err != nil {
|
|
return sandboxErrorExit(cmd, err)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
cmd.Flags().BoolVar(&opts.last, "last", false, "Promote allowances from the most recent cached violation report")
|
|
cmd.Flags().BoolVar(&opts.all, "all", false, "With --last: promote every safe FS/exec violation (default: primary only)")
|
|
cmd.Flags().BoolVar(&opts.force, "force", false, "Allow saving entries that touch sensitive paths (.env, .npmrc, .ssh, ...)")
|
|
return cmd
|
|
}
|
|
|
|
func runAllow(out io.Writer, args []string, opts *allowOptions, factory allowFactory) error {
|
|
// ApplySandbox ignores overlays under global_lockdown, so refuse up-front
|
|
// instead of letting the user think their allowances took effect.
|
|
if factory.locked != nil && factory.locked() {
|
|
return usefulerror.NewUsefulError().
|
|
WithCode(errcodes.PermissionDenied).
|
|
WithHumanError("sandbox overlays are disabled while global_lockdown is in force").
|
|
WithHelp("This machine's PMG configuration is locked. Contact your administrator to change sandbox policy.").
|
|
Wrap(errors.New("sandbox overlay refused under global_lockdown"))
|
|
}
|
|
|
|
if !opts.last && len(args) == 0 {
|
|
return invalidArgumentError(
|
|
"nothing to save: pass type=value arguments or --last",
|
|
"Example: `pmg sandbox allow write=./.astro` or `pmg sandbox allow --last --all`.",
|
|
)
|
|
}
|
|
if opts.all && !opts.last {
|
|
return invalidArgumentError(
|
|
"--all requires --last",
|
|
"Use `pmg sandbox allow --last --all` to promote every FS/exec violation from the most recent cached report.",
|
|
)
|
|
}
|
|
|
|
repoRoot, err := factory.repoRoot()
|
|
if err != nil {
|
|
return wrapUseful(fmt.Errorf("resolve repo root: %w", err),
|
|
errcodes.Unknown,
|
|
"Could not determine the current repository root. Ensure the working directory is accessible.")
|
|
}
|
|
if repoRoot == "" {
|
|
return invalidArgumentError(
|
|
"could not determine current repository root",
|
|
"Change to a directory inside the repository, then retry.",
|
|
)
|
|
}
|
|
|
|
overlayDir := factory.overlayDir()
|
|
if overlayDir == "" {
|
|
return invalidArgumentError(
|
|
"sandbox overlay directory is not configured",
|
|
"Ensure the PMG config directory is writable, then retry.",
|
|
)
|
|
}
|
|
|
|
overlay, _, err := pmgsandbox.LoadOverlayForRepo(overlayDir, repoRoot)
|
|
if err != nil {
|
|
return wrapUseful(err, errcodes.Unknown,
|
|
"Could not read the existing project overlay. Check the file under SandboxOverlayDir().")
|
|
}
|
|
if overlay == nil {
|
|
overlay = &pmgsandbox.Overlay{}
|
|
}
|
|
|
|
pending, err := collectAllowEntries(args, opts, factory)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(pending) == 0 {
|
|
return invalidArgumentError(
|
|
"no eligible allowances to save",
|
|
"Run a sandboxed command first to populate the violation cache, or pass explicit type=value arguments.",
|
|
)
|
|
}
|
|
|
|
if err := validatePresetEntries(pending, factory); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := guardSensitiveEntries(pending, opts.force); err != nil {
|
|
return err
|
|
}
|
|
|
|
addedEntries := make([]pmgsandbox.OverlayAllow, 0, len(pending))
|
|
for _, entry := range pending {
|
|
if overlay.Add(entry) {
|
|
addedEntries = append(addedEntries, entry)
|
|
}
|
|
}
|
|
|
|
if len(addedEntries) == 0 {
|
|
_, err := fmt.Fprintf(out, "%s\n", ui.Colors.Dim(fmt.Sprintf("No new allowances (%d already present).", len(pending))))
|
|
return err
|
|
}
|
|
|
|
path, err := pmgsandbox.SaveOverlay(overlayDir, repoRoot, overlay)
|
|
if err != nil {
|
|
return wrapUseful(err, errcodes.Unknown,
|
|
"Could not write the project overlay file. Check filesystem permissions for the overlay directory.")
|
|
}
|
|
|
|
if _, err := fmt.Fprintf(out, "%s Saved %d allowance(s) for %s\n", ui.Colors.Green("✓"), len(addedEntries), repoRoot); err != nil {
|
|
return err
|
|
}
|
|
for _, e := range addedEntries {
|
|
if _, err := fmt.Fprintf(out, " %s %s=%s\n", ui.Colors.Dim("•"), e.Type, e.Value); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
_, err = fmt.Fprintf(out, " %s %s\n", ui.Colors.Dim("overlay:"), ui.Colors.Dim(path))
|
|
return err
|
|
}
|
|
|
|
func collectAllowEntries(args []string, opts *allowOptions, factory allowFactory) ([]pmgsandbox.OverlayAllow, error) {
|
|
out := make([]pmgsandbox.OverlayAllow, 0, len(args)+1)
|
|
|
|
for _, raw := range args {
|
|
override, err := config.ParseSingleOverride(raw)
|
|
if err != nil {
|
|
return nil, invalidArgumentError(
|
|
err.Error(),
|
|
"Each positional argument must be `type=value` (read, write, exec, net-connect, net-bind, env, preset).",
|
|
)
|
|
}
|
|
out = append(out, pmgsandbox.OverlayAllow{Type: override.Type, Value: override.Value})
|
|
}
|
|
|
|
if !opts.last {
|
|
return out, nil
|
|
}
|
|
|
|
suggestions, err := suggestionsFromCache(factory.cache(), opts.all)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, sugg := range suggestions {
|
|
typ := overrideTypeForKind(sugg.Kind)
|
|
if typ == "" {
|
|
continue
|
|
}
|
|
// Normalize through the manual-entry validator so stored values match
|
|
// how applyRuntimeOverrides resolves them against the policy. Skip on
|
|
// rejection so one bad target does not block the rest of the report.
|
|
normalized, err := config.ParseSingleOverride(fmt.Sprintf("%s=%s", typ, sugg.Target))
|
|
if err != nil {
|
|
continue
|
|
}
|
|
out = append(out, pmgsandbox.OverlayAllow{Type: normalized.Type, Value: normalized.Value})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// suggestionsFromCache loads the latest cached violation report and returns
|
|
// the override suggestions to promote. When all is true, every safe FS/exec
|
|
// suggestion is returned, otherwise just the primary one (if any).
|
|
func suggestionsFromCache(cache *pmgsandbox.ViolationCache, all bool) ([]pmgsandbox.OverrideSuggestion, error) {
|
|
entry, err := cache.Latest()
|
|
if err != nil {
|
|
return nil, wrapUseful(err, errcodes.Unknown,
|
|
"Could not read the sandbox violation cache. Check the cache directory and retry.")
|
|
}
|
|
if entry == nil || entry.Record.Report == nil {
|
|
return nil, notFoundError(
|
|
"no cached violation report",
|
|
"Run a sandboxed command that hits a denial first, then retry `pmg sandbox allow --last`.",
|
|
)
|
|
}
|
|
|
|
if all {
|
|
return pmgsandbox.BuildAllOverrides(entry.Record.Report), nil
|
|
}
|
|
if override := pmgsandbox.BuildExplanation(entry.Record.Report).Override; override != nil {
|
|
return []pmgsandbox.OverrideSuggestion{*override}, nil
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
// overrideTypeForKind maps a ViolationKind to the matching SandboxAllowType.
|
|
// Only FS + exec are handled; network kinds are not classified by drivers and
|
|
// will never reach this function via BuildAllOverrides.
|
|
func overrideTypeForKind(kind pmgsandbox.ViolationKind) config.SandboxAllowType {
|
|
switch kind {
|
|
case pmgsandbox.ViolationKindFSRead:
|
|
return config.SandboxAllowRead
|
|
case pmgsandbox.ViolationKindFSWrite, pmgsandbox.ViolationKindFSDeleteOrRename:
|
|
return config.SandboxAllowWrite
|
|
case pmgsandbox.ViolationKindExec:
|
|
return config.SandboxAllowExec
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
func guardSensitiveEntries(entries []pmgsandbox.OverlayAllow, force bool) error {
|
|
if force {
|
|
return nil
|
|
}
|
|
for _, e := range entries {
|
|
// Preset values are names, not paths. Preset content is validated
|
|
// against sensitive targets when the preset itself is loaded.
|
|
if e.Type == config.SandboxAllowPreset {
|
|
continue
|
|
}
|
|
|
|
if pmgsandbox.IsSensitiveProjectTarget(e.Value) {
|
|
return usefulerror.NewUsefulError().
|
|
WithCode(errcodes.PermissionDenied).
|
|
WithHumanError(fmt.Sprintf("refusing to allow sensitive target: %s", e.Value)).
|
|
WithHelp("Re-run with --force to allow saving this entry, after verifying the path is intentional.").
|
|
Wrap(errors.New("sensitive target"))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Preset references resolve at save time so a typo fails immediately
|
|
// instead of surfacing as a runtime warning on the next sandboxed command.
|
|
func validatePresetEntries(entries []pmgsandbox.OverlayAllow, factory allowFactory) error {
|
|
var registry pmgsandbox.PresetRegistry
|
|
for _, e := range entries {
|
|
if e.Type != config.SandboxAllowPreset {
|
|
continue
|
|
}
|
|
|
|
if registry == nil {
|
|
if factory.presets == nil {
|
|
return invalidArgumentError(
|
|
"preset entries are not supported here",
|
|
"Pass concrete type=value allowances instead.",
|
|
)
|
|
}
|
|
|
|
r, err := factory.presets()
|
|
if err != nil {
|
|
return registryInitError(err)
|
|
}
|
|
registry = r
|
|
}
|
|
|
|
if _, err := registry.Get(e.Value); err != nil {
|
|
if errors.Is(err, pmgsandbox.ErrPresetNotFound) {
|
|
return notFoundError(
|
|
fmt.Sprintf("unknown preset %q", e.Value),
|
|
"Use `pmg sandbox preset list` to see available presets.",
|
|
)
|
|
}
|
|
return wrapUseful(err, errcodes.Unknown,
|
|
"Failed to resolve the preset. Run with --verbose for details.")
|
|
}
|
|
}
|
|
return nil
|
|
}
|