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>
This commit is contained in:
Abhisek Datta
2026-07-21 15:14:07 +05:30
committed by GitHub
co-authored by Claude Fable 5
parent 695a1d739d
commit ee684a29a9
39 changed files with 2895 additions and 49 deletions
+54 -2
View File
@@ -20,6 +20,7 @@ type allowFactory struct {
repoRoot func() (string, error)
cache func() *pmgsandbox.ViolationCache
locked func() bool
presets func() (pmgsandbox.PresetRegistry, error)
}
func defaultAllowFactory() allowFactory {
@@ -29,7 +30,8 @@ func defaultAllowFactory() allowFactory {
cache: func() *pmgsandbox.ViolationCache {
return pmgsandbox.NewViolationCache(config.Get().SandboxViolationCacheDir())
},
locked: func() bool { return config.Get().IsLocked() },
locked: func() bool { return config.Get().IsLocked() },
presets: defaultPresetRegistryFactory,
}
}
@@ -55,6 +57,8 @@ func newAllowCommand(factory allowFactory) *cobra.Command {
"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,
@@ -136,6 +140,10 @@ func runAllow(out io.Writer, args []string, opts *allowOptions, factory allowFac
)
}
if err := validatePresetEntries(pending, factory); err != nil {
return err
}
if err := guardSensitiveEntries(pending, opts.force); err != nil {
return err
}
@@ -178,7 +186,7 @@ func collectAllowEntries(args []string, opts *allowOptions, factory allowFactory
if err != nil {
return nil, invalidArgumentError(
err.Error(),
"Each positional argument must be `type=value` (read, write, exec, net-connect, net-bind).",
"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})
@@ -255,6 +263,12 @@ func guardSensitiveEntries(entries []pmgsandbox.OverlayAllow, force bool) error
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).
@@ -265,3 +279,41 @@ func guardSensitiveEntries(entries []pmgsandbox.OverlayAllow, force bool) error
}
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
}
+58
View File
@@ -0,0 +1,58 @@
package sandbox
import (
"errors"
"github.com/safedep/pmg/config"
"github.com/safedep/pmg/errcodes"
pmgsandbox "github.com/safedep/pmg/sandbox"
"github.com/spf13/cobra"
)
// presetRegistryFactory builds a PresetRegistry. Tests inject a stub.
type presetRegistryFactory func() (pmgsandbox.PresetRegistry, error)
func defaultPresetRegistryFactory() (pmgsandbox.PresetRegistry, error) {
return pmgsandbox.NewPresetRegistry(
pmgsandbox.WithUserPresetDir(config.Get().SandboxPresetDir()),
)
}
// NewPresetCommand returns the `pmg sandbox preset` parent command.
func NewPresetCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "preset",
Short: "Discover and inspect sandbox presets (workload allowance bundles)",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
cmd.AddCommand(newPresetListCommand(defaultPresetRegistryFactory))
cmd.AddCommand(newPresetShowCommand(defaultPresetRegistryFactory))
cmd.AddCommand(newPresetInitCommand(func() string { return config.Get().SandboxPresetDir() }, defaultPresetRegistryFactory))
cmd.AddCommand(newPresetEditCommand(defaultPresetRegistryFactory))
cmd.AddCommand(newPresetLintCommand())
return cmd
}
func presetRegistryError(err error) error {
return wrapUseful(err, errcodes.Unknown,
"Failed to initialise the sandbox preset registry. Run with --verbose for details.")
}
func presetLoadError(err error) error {
if err == nil {
return nil
}
switch {
case errors.Is(err, pmgsandbox.ErrPresetNotFound):
return wrapUseful(err, errcodes.NotFound,
"Use `pmg sandbox preset list` to see available presets.")
case errors.Is(err, pmgsandbox.ErrPresetInvalid):
return wrapUseful(err, errcodes.InvalidArgument,
"Check the preset YAML against docs/sandbox-presets.md and run `pmg sandbox preset lint <file>`.")
}
return wrapUseful(err, errcodes.Unknown,
"Failed to load the sandbox preset. Run with --verbose for the underlying cause.")
}
+89
View File
@@ -0,0 +1,89 @@
package sandbox
import (
"fmt"
"io"
"github.com/safedep/pmg/errcodes"
"github.com/safedep/pmg/internal/editor"
"github.com/safedep/pmg/internal/ui"
pmgsandbox "github.com/safedep/pmg/sandbox"
"github.com/spf13/cobra"
)
func newPresetEditCommand(factory presetRegistryFactory) *cobra.Command {
cmd := &cobra.Command{
Use: "edit <name>",
Short: "Open a user sandbox preset in $VISUAL / $EDITOR and validate the result",
Example: " pmg sandbox preset edit myapp",
Args: cobra.ExactArgs(1),
SilenceErrors: false,
RunE: func(cmd *cobra.Command, args []string) error {
if err := runPresetEdit(cmd.OutOrStdout(), cmd.ErrOrStderr(), args[0], factory); err != nil {
return sandboxErrorExit(cmd, err)
}
return nil
},
}
return cmd
}
func runPresetEdit(out, errOut io.Writer, name string, factory presetRegistryFactory) error {
registry, err := factory()
if err != nil {
return presetRegistryError(err)
}
path, shadowed, err := findEditableUserPreset(registry, name)
if err != nil {
return err
}
if shadowed {
if _, err := fmt.Fprintf(errOut,
"Warning: user preset %q is shadowed by a built-in preset of the same name — pmg resolves the built-in, so edits here have no effect.\n",
name); err != nil {
return err
}
}
if err := editor.Open(path); err != nil {
return wrapUseful(err, errcodes.InvalidArgument,
"Set $VISUAL or $EDITOR to a working editor command and retry.")
}
if err := lintPresetFile(out, path); err != nil {
return wrapUseful(err, errcodes.InvalidArgument,
"The edited preset is invalid and will be skipped at load time. Fix the reported issue in "+path+".")
}
_, err = fmt.Fprintf(out, "%s %s\n", ui.Colors.Green("✓"), path)
return err
}
func findEditableUserPreset(registry pmgsandbox.PresetRegistry, name string) (string, bool, error) {
infos, err := registry.List()
if err != nil {
return "", false, presetRegistryError(err)
}
for _, info := range infos {
if info.Preset.Name == name && info.Source == pmgsandbox.PresetSourceUser {
return info.Path, info.Shadowed, nil
}
}
for _, info := range infos {
if info.Preset.Name == name && info.Source == pmgsandbox.PresetSourceBuiltin {
return "", false, invalidArgumentError(
fmt.Sprintf("cannot edit built-in preset %q: built-in presets are embedded in the pmg binary", name),
fmt.Sprintf("Scaffold your own with `pmg sandbox preset init %s-custom`.", name),
)
}
}
return "", false, notFoundError(
fmt.Sprintf("no user sandbox preset named %q", name),
"Use `pmg sandbox preset list` to see available presets, or scaffold one with `pmg sandbox preset init`.",
)
}
+182
View File
@@ -0,0 +1,182 @@
package sandbox
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/safedep/pmg/errcodes"
"github.com/safedep/pmg/internal/ui"
pmgsandbox "github.com/safedep/pmg/sandbox"
"github.com/spf13/cobra"
)
var presetInitNameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
type presetInitOptions struct {
description string
author string
labels []string
}
func newPresetInitCommand(dir func() string, factory presetRegistryFactory) *cobra.Command {
opts := &presetInitOptions{}
cmd := &cobra.Command{
Use: "init <name>",
Short: "Scaffold a new user sandbox preset",
Long: "Create a starter preset YAML under the user preset directory.\n\n" +
"Presets are additive-only allowance bundles for one workload. Document the\n" +
"residual risk of each allowance in threat-note comments: `preset show`\n" +
"displays the YAML verbatim so users can review before applying.",
Example: " pmg sandbox preset init myapp --author \"Your Name\" --label myapp --label dev-server",
Args: cobra.ExactArgs(1),
SilenceErrors: false,
RunE: func(cmd *cobra.Command, args []string) error {
if err := runPresetInit(cmd.OutOrStdout(), args[0], opts, dir, factory); err != nil {
return sandboxErrorExit(cmd, err)
}
return nil
},
}
cmd.Flags().StringVar(&opts.description, "description", "", "One-line description of the workload")
cmd.Flags().StringVar(&opts.author, "author", "", "Preset author shown in `preset list`")
cmd.Flags().StringArrayVar(&opts.labels, "label", nil, "Metadata label for discovery (repeatable)")
return cmd
}
func runPresetInit(out io.Writer, name string, opts *presetInitOptions, dir func() string, factory presetRegistryFactory) error {
if !presetInitNameRe.MatchString(name) {
return invalidArgumentError(
fmt.Sprintf("invalid preset name %q", name),
"Preset names are lowercase alphanumeric with dashes, e.g. my-app.",
)
}
registry, err := factory()
if err != nil {
return presetRegistryError(err)
}
if info, err := registry.Get(name); err == nil && info.Source == pmgsandbox.PresetSourceBuiltin {
return invalidArgumentError(
fmt.Sprintf("%q is a built-in preset and cannot be shadowed", name),
"Built-ins win name resolution. Choose a different name, or apply the built-in with `pmg sandbox allow preset="+name+"`.",
)
} else if err != nil && !errors.Is(err, pmgsandbox.ErrPresetNotFound) {
return presetRegistryError(err)
}
userDir := dir()
if userDir == "" {
return invalidArgumentError(
"user preset directory is not configured",
"Ensure the PMG config directory is writable, then retry.",
)
}
target := filepath.Join(userDir, name+".yml")
if _, err := os.Stat(target); err == nil {
return invalidArgumentError(
fmt.Sprintf("preset already exists at %s", target),
"Choose a different preset name, or edit the existing file.",
)
} else if !os.IsNotExist(err) {
return wrapUseful(fmt.Errorf("failed to stat %s: %w", target, err),
ioErrorCode(err, errcodes.Unknown),
"Could not stat the target preset path. Check the user preset directory permissions.")
}
scaffold := renderPresetScaffold(name, opts)
if preset, err := pmgsandbox.ParsePreset([]byte(scaffold)); err != nil {
return wrapUseful(err, errcodes.Unknown, "Scaffold generation produced invalid YAML. Please report this bug.")
} else if err := preset.Validate(); err != nil {
return wrapUseful(err, errcodes.Unknown, "Scaffold generation produced an invalid preset. Please report this bug.")
}
if err := os.MkdirAll(userDir, 0o755); err != nil {
return wrapUseful(fmt.Errorf("failed to create user preset directory %s: %w", userDir, err),
ioErrorCode(err, errcodes.PermissionDenied),
"Could not create the user preset directory. Check filesystem permissions for "+userDir+".")
}
if err := os.WriteFile(target, []byte(scaffold), 0o644); err != nil {
return wrapUseful(fmt.Errorf("failed to write %s: %w", target, err),
ioErrorCode(err, errcodes.PermissionDenied),
"Could not write the scaffolded preset. Check filesystem permissions for "+target+".")
}
if _, err := fmt.Fprintln(out, target); err != nil {
return err
}
_, err = fmt.Fprintf(out, "%s\n%s\n%s\n",
ui.Colors.Dim("Edit the file, then validate: pmg sandbox preset lint "+target),
ui.Colors.Dim("Review it: pmg sandbox preset show "+name),
ui.Colors.Dim("Apply to a repo: pmg sandbox allow preset="+name))
return err
}
func renderPresetScaffold(name string, opts *presetInitOptions) string {
var b strings.Builder
b.WriteString("# pmg sandbox preset — scaffolded by `pmg sandbox preset init`.\n")
b.WriteString("# Presets are additive-only: allowances on top of a hardened profile.\n")
b.WriteString("# Deny rules, outbound network and env globs are rejected by design.\n\n")
b.WriteString("schema_version: 1\nkind: preset\nname: ")
b.WriteString(name)
b.WriteString("\n")
description := opts.description
if description == "" {
description = "What this preset enables, one line"
}
b.WriteString("description: ")
b.WriteString(yamlString(description))
b.WriteString("\n")
b.WriteString("\nmetadata:\n")
if opts.author != "" {
b.WriteString(" author: ")
b.WriteString(yamlString(opts.author))
b.WriteString("\n")
} else {
b.WriteString(" # author: Your Name\n")
}
if len(opts.labels) > 0 {
b.WriteString(" labels: [")
b.WriteString(strings.Join(opts.labels, ", "))
b.WriteString("]\n")
} else {
b.WriteString(" labels: [")
b.WriteString(name)
b.WriteString("]\n")
}
b.WriteString("\n# Threat notes: explain what each allowance permits and why the residual\n")
b.WriteString("# risk is acceptable for this workload.\n")
b.WriteString("filesystem:\n")
b.WriteString(" # Starter rule so the preset validates. Replace with what the workload needs.\n")
b.WriteString(" allow_write:\n")
b.WriteString(" - ${CWD}/.")
b.WriteString(name)
b.WriteString("/**\n")
b.WriteString(" # allow_read:\n")
b.WriteString(" # - ${CWD}/.cache/**\n")
b.WriteString("\n# network:\n")
b.WriteString("# allow_bind: # loopback only\n")
b.WriteString("# - localhost:8080\n")
b.WriteString("\n# environment:\n")
b.WriteString("# allow: # exact variable names, no globs\n")
b.WriteString("# - MYAPP_TELEMETRY_DISABLED\n")
return b.String()
}
+69
View File
@@ -0,0 +1,69 @@
package sandbox
import (
"fmt"
"io"
"os"
"github.com/safedep/pmg/internal/ui"
pmgsandbox "github.com/safedep/pmg/sandbox"
"github.com/spf13/cobra"
)
func newPresetLintCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "lint <file>...",
Short: "Validate preset YAML files against the preset schema",
Example: " pmg sandbox preset lint ./my-preset.yml",
SilenceErrors: false,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if err := runPresetLint(cmd.OutOrStdout(), args); err != nil {
return sandboxErrorExit(cmd, err)
}
return nil
},
}
return cmd
}
func runPresetLint(out io.Writer, paths []string) error {
failures := 0
for _, path := range paths {
if err := lintPresetFile(out, path); err != nil {
failures++
if _, werr := fmt.Fprintf(out, "%s %s: %v\n", ui.Colors.Red("✗"), path, err); werr != nil {
return werr
}
continue
}
if _, err := fmt.Fprintf(out, "%s %s\n", ui.Colors.Green("✓"), path); err != nil {
return err
}
}
if failures > 0 {
return invalidArgumentError(
fmt.Sprintf("%d of %d preset file(s) failed validation", failures, len(paths)),
"Fix the reported issues. See docs/sandbox-presets.md for the preset schema.",
)
}
return nil
}
func lintPresetFile(_ io.Writer, path string) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
preset, err := pmgsandbox.ParsePreset(data)
if err != nil {
return err
}
return preset.Validate()
}
+153
View File
@@ -0,0 +1,153 @@
package sandbox
import (
"fmt"
"io"
"strings"
"github.com/safedep/pmg/internal/ui"
pmgsandbox "github.com/safedep/pmg/sandbox"
"github.com/spf13/cobra"
)
type presetListOptions struct {
jsonOut bool
author string
labels []string
}
func newPresetListCommand(factory presetRegistryFactory) *cobra.Command {
opts := &presetListOptions{}
cmd := &cobra.Command{
Use: "list",
Short: "List available sandbox presets (built-in and user)",
Example: " pmg sandbox preset list\n pmg sandbox preset list --label dev-server --author SafeDep",
SilenceErrors: false,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if err := runPresetList(cmd.OutOrStdout(), opts, factory); err != nil {
return sandboxErrorExit(cmd, err)
}
return nil
},
}
cmd.Flags().BoolVar(&opts.jsonOut, "json", false, "Emit presets as JSON")
cmd.Flags().StringVar(&opts.author, "author", "", "Only presets by this author (case-insensitive)")
cmd.Flags().StringArrayVar(&opts.labels, "label", nil, "Only presets carrying this label (repeatable, all must match)")
return cmd
}
func runPresetList(out io.Writer, opts *presetListOptions, factory presetRegistryFactory) error {
registry, err := factory()
if err != nil {
return presetRegistryError(err)
}
infos, err := registry.List()
if err != nil {
return presetRegistryError(err)
}
infos = pmgsandbox.FilterPresets(infos, pmgsandbox.PresetFilter{
Author: opts.author,
Labels: opts.labels,
})
if opts.jsonOut {
return writePresetListJSON(out, infos)
}
return renderPresetListHuman(out, infos)
}
type jsonPresetSummary struct {
Name string `json:"name"`
Source string `json:"source"`
Path string `json:"path,omitempty"`
Author string `json:"author,omitempty"`
Labels []string `json:"labels,omitempty"`
Description string `json:"description,omitempty"`
Shadowed bool `json:"shadowed,omitempty"`
}
type jsonPresetListReport struct {
Presets []jsonPresetSummary `json:"presets"`
}
func writePresetListJSON(out io.Writer, infos []pmgsandbox.PresetInfo) error {
report := jsonPresetListReport{Presets: make([]jsonPresetSummary, 0, len(infos))}
for _, info := range infos {
report.Presets = append(report.Presets, jsonPresetSummary{
Name: info.Preset.Name,
Source: string(info.Source),
Path: info.Path,
Author: info.Preset.Metadata.Author,
Labels: info.Preset.Metadata.Labels,
Description: info.Preset.Description,
Shadowed: info.Shadowed,
})
}
return writeJSONIndent(out, report)
}
func renderPresetListHuman(out io.Writer, infos []pmgsandbox.PresetInfo) error {
if len(infos) == 0 {
_, err := fmt.Fprintln(out, ui.Colors.Dim("No sandbox presets match."))
return err
}
if _, err := fmt.Fprintln(out); err != nil {
return err
}
if _, err := fmt.Fprintln(out, ui.Colors.Cyan("Sandbox Presets")); err != nil {
return err
}
if _, err := fmt.Fprintln(out, ui.Colors.Normal("----------------")); err != nil {
return err
}
rows := make([][]string, 0, len(infos)+1)
rows = append(rows, []string{
ui.Colors.Bold("STATUS"),
ui.Colors.Bold("NAME"),
ui.Colors.Bold("SOURCE"),
ui.Colors.Bold("AUTHOR"),
ui.Colors.Bold("LABELS"),
ui.Colors.Bold("DESCRIPTION"),
})
for _, info := range infos {
rows = append(rows, []string{
presetStatusCell(info),
info.Preset.Name,
presetSourceCell(info),
emptyDash(info.Preset.Metadata.Author),
truncate(strings.Join(info.Preset.Metadata.Labels, ","), 30),
truncate(info.Preset.Description, 60),
})
}
if err := renderTable(out, rows, nil); err != nil {
return err
}
_, err := fmt.Fprintf(out, "\n%s\n",
ui.Colors.Dim("Apply to this repo: pmg sandbox allow preset=<name>"))
return err
}
func presetStatusCell(info pmgsandbox.PresetInfo) string {
if info.Shadowed {
return ui.Colors.Dim("SHADOWED")
}
return " "
}
func presetSourceCell(info pmgsandbox.PresetInfo) string {
if info.Source == pmgsandbox.PresetSourceBuiltin {
return ui.Colors.Dim("builtin")
}
return truncateLeft(info.Path, 50)
}
+105
View File
@@ -0,0 +1,105 @@
package sandbox
import (
"fmt"
"io"
"strings"
"github.com/safedep/pmg/internal/ui"
pmgsandbox "github.com/safedep/pmg/sandbox"
"github.com/spf13/cobra"
)
type presetShowOptions struct {
jsonOut bool
}
func newPresetShowCommand(factory presetRegistryFactory) *cobra.Command {
opts := &presetShowOptions{}
cmd := &cobra.Command{
Use: "show <name>",
Short: "Show a sandbox preset's allowances, metadata and threat notes",
Example: " pmg sandbox preset show git",
SilenceErrors: false,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if err := runPresetShow(cmd.OutOrStdout(), args[0], opts, factory); err != nil {
return sandboxErrorExit(cmd, err)
}
return nil
},
}
cmd.Flags().BoolVar(&opts.jsonOut, "json", false, "Emit the preset as JSON")
return cmd
}
func runPresetShow(out io.Writer, name string, opts *presetShowOptions, factory presetRegistryFactory) error {
registry, err := factory()
if err != nil {
return presetRegistryError(err)
}
info, err := registry.Get(name)
if err != nil {
return presetLoadError(err)
}
if opts.jsonOut {
return writeJSONIndent(out, jsonPresetSummaryWithRules(info))
}
return renderPresetShowHuman(out, info)
}
type jsonPresetDetail struct {
jsonPresetSummary
Filesystem pmgsandbox.PresetFilesystem `json:"filesystem,omitempty"`
Network pmgsandbox.PresetNetwork `json:"network,omitempty"`
Process pmgsandbox.PresetProcess `json:"process,omitempty"`
Environment pmgsandbox.PresetEnvironment `json:"environment,omitempty"`
}
func jsonPresetSummaryWithRules(info *pmgsandbox.PresetInfo) jsonPresetDetail {
return jsonPresetDetail{
jsonPresetSummary: jsonPresetSummary{
Name: info.Preset.Name,
Source: string(info.Source),
Path: info.Path,
Author: info.Preset.Metadata.Author,
Labels: info.Preset.Metadata.Labels,
Description: info.Preset.Description,
},
Filesystem: info.Preset.Filesystem,
Network: info.Preset.Network,
Process: info.Preset.Process,
Environment: info.Preset.Environment,
}
}
// Prints the original YAML so authored threat notes are visible before the
// user trusts the preset.
func renderPresetShowHuman(out io.Writer, info *pmgsandbox.PresetInfo) error {
// Underline length must come from the uncolored header, ANSI escapes
// would inflate it.
plain := fmt.Sprintf("Preset %s (%s)", info.Preset.Name, info.Source)
header := ui.Colors.Cyan(plain)
if info.Path != "" {
header = fmt.Sprintf("%s %s", header, ui.Colors.Dim(info.Path))
plain = fmt.Sprintf("%s %s", plain, info.Path)
}
if _, err := fmt.Fprintf(out, "\n%s\n%s\n\n", header,
ui.Colors.Normal(strings.Repeat("-", len(plain)))); err != nil {
return err
}
if _, err := fmt.Fprintln(out, strings.TrimRight(string(info.Raw), "\n")); err != nil {
return err
}
_, err := fmt.Fprintf(out, "\n%s\n",
ui.Colors.Dim(fmt.Sprintf("Apply to this repo: pmg sandbox allow preset=%s", info.Preset.Name)))
return err
}
+301
View File
@@ -0,0 +1,301 @@
package sandbox
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/safedep/dry/usefulerror"
"github.com/safedep/pmg/errcodes"
pmgsandbox "github.com/safedep/pmg/sandbox"
)
func newTestPresetRegistry(userDir string) presetRegistryFactory {
return func() (pmgsandbox.PresetRegistry, error) {
opts := []pmgsandbox.PresetRegistryOption{}
if userDir != "" {
opts = append(opts, pmgsandbox.WithUserPresetDir(userDir))
}
return pmgsandbox.NewPresetRegistry(opts...)
}
}
func writeTestUserPreset(t *testing.T, dir, name string) {
t.Helper()
body := `kind: preset
name: ` + name + `
description: user preset ` + name + `
metadata:
author: Community
labels: [custom]
filesystem:
allow_write:
- ${CWD}/.` + name + `/**
`
require.NoError(t, os.WriteFile(filepath.Join(dir, name+".yml"), []byte(body), 0o644))
}
func TestPresetListHuman(t *testing.T) {
var out bytes.Buffer
err := runPresetList(&out, &presetListOptions{}, newTestPresetRegistry(""))
require.NoError(t, err)
assert.Contains(t, out.String(), "git")
assert.Contains(t, out.String(), "astro")
assert.Contains(t, out.String(), "SafeDep")
assert.Contains(t, out.String(), "pmg sandbox allow preset=")
}
func TestPresetListFilters(t *testing.T) {
dir := t.TempDir()
writeTestUserPreset(t, dir, "myapp")
t.Run("label filter", func(t *testing.T) {
var out bytes.Buffer
err := runPresetList(&out, &presetListOptions{labels: []string{"custom"}}, newTestPresetRegistry(dir))
require.NoError(t, err)
assert.Contains(t, out.String(), "myapp")
assert.NotContains(t, out.String(), "astro")
})
t.Run("author filter case-insensitive", func(t *testing.T) {
var out bytes.Buffer
err := runPresetList(&out, &presetListOptions{author: "community", jsonOut: true}, newTestPresetRegistry(dir))
require.NoError(t, err)
var report jsonPresetListReport
require.NoError(t, json.Unmarshal(out.Bytes(), &report))
require.Len(t, report.Presets, 1)
assert.Equal(t, "myapp", report.Presets[0].Name)
assert.Equal(t, "user", report.Presets[0].Source)
})
t.Run("no matches", func(t *testing.T) {
var out bytes.Buffer
err := runPresetList(&out, &presetListOptions{labels: []string{"nope"}}, newTestPresetRegistry(""))
require.NoError(t, err)
assert.Contains(t, out.String(), "No sandbox presets match")
})
}
func TestPresetShow(t *testing.T) {
t.Run("human output includes YAML with threat notes", func(t *testing.T) {
var out bytes.Buffer
err := runPresetShow(&out, "git", &presetShowOptions{}, newTestPresetRegistry(""))
require.NoError(t, err)
assert.Contains(t, out.String(), "Preset git (builtin)")
assert.Contains(t, out.String(), "Threat notes")
assert.Contains(t, out.String(), "${CWD}/.git/config")
assert.Contains(t, out.String(), "pmg sandbox allow preset=git")
})
t.Run("json output includes rules", func(t *testing.T) {
var out bytes.Buffer
err := runPresetShow(&out, "astro", &presetShowOptions{jsonOut: true}, newTestPresetRegistry(""))
require.NoError(t, err)
var detail jsonPresetDetail
require.NoError(t, json.Unmarshal(out.Bytes(), &detail))
assert.Equal(t, "astro", detail.Name)
assert.Contains(t, detail.Filesystem.AllowWrite, "${CWD}/.astro/**")
assert.Contains(t, detail.Network.AllowBind, "localhost:4321")
})
t.Run("unknown preset is NotFound", func(t *testing.T) {
var out bytes.Buffer
err := runPresetShow(&out, "missing", &presetShowOptions{}, newTestPresetRegistry(""))
require.Error(t, err)
var useful usefulerror.UsefulError
require.ErrorAs(t, err, &useful)
assert.Equal(t, errcodes.NotFound, useful.Code())
})
}
func TestPresetLint(t *testing.T) {
dir := t.TempDir()
valid := filepath.Join(dir, "valid.yml")
require.NoError(t, os.WriteFile(valid, []byte(`kind: preset
name: valid
filesystem:
allow_write: ["${CWD}/.valid/**"]
`), 0o644))
invalid := filepath.Join(dir, "invalid.yml")
require.NoError(t, os.WriteFile(invalid, []byte(`kind: preset
name: invalid
filesystem:
deny_write: ["${CWD}/x"]
`), 0o644))
t.Run("valid file passes", func(t *testing.T) {
var out bytes.Buffer
require.NoError(t, runPresetLint(&out, []string{valid}))
assert.Contains(t, out.String(), "✓")
})
t.Run("invalid file fails with count", func(t *testing.T) {
var out bytes.Buffer
err := runPresetLint(&out, []string{valid, invalid})
require.Error(t, err)
assert.Contains(t, out.String(), "✗")
assert.Contains(t, err.Error(), "1 of 2")
})
}
func TestAllowPresetEntries(t *testing.T) {
newFactory := func(t *testing.T) allowFactory {
t.Helper()
overlays := t.TempDir()
return allowFactory{
overlayDir: func() string { return overlays },
repoRoot: func() (string, error) { return "/repo/example", nil },
locked: func() bool { return false },
presets: newTestPresetRegistry(""),
}
}
t.Run("known preset saves to overlay by reference", func(t *testing.T) {
factory := newFactory(t)
var out bytes.Buffer
err := runAllow(&out, []string{"preset=git"}, &allowOptions{}, factory)
require.NoError(t, err)
assert.Contains(t, out.String(), "preset=git")
overlay, _, err := pmgsandbox.LoadOverlayForRepo(factory.overlayDir(), "/repo/example")
require.NoError(t, err)
require.NotNil(t, overlay)
require.Len(t, overlay.Allow, 1)
assert.Equal(t, "git", overlay.Allow[0].Value)
})
t.Run("unknown preset fails at save time", func(t *testing.T) {
factory := newFactory(t)
var out bytes.Buffer
err := runAllow(&out, []string{"preset=does-not-exist"}, &allowOptions{}, factory)
require.Error(t, err)
var useful usefulerror.UsefulError
require.ErrorAs(t, err, &useful)
assert.Equal(t, errcodes.NotFound, useful.Code())
})
}
func TestPresetInit(t *testing.T) {
newDeps := func(t *testing.T) (func() string, presetRegistryFactory) {
t.Helper()
dir := t.TempDir()
return func() string { return dir }, newTestPresetRegistry(dir)
}
t.Run("scaffolds a valid preset that loads from the user dir", func(t *testing.T) {
dir, factory := newDeps(t)
var out bytes.Buffer
err := runPresetInit(&out, "myapp", &presetInitOptions{author: "Community", labels: []string{"myapp", "dev-server"}}, dir, factory)
require.NoError(t, err)
target := filepath.Join(dir(), "myapp.yml")
assert.Contains(t, out.String(), target)
assert.Contains(t, out.String(), "preset lint")
require.NoError(t, runPresetLint(&bytes.Buffer{}, []string{target}))
registry, err := factory()
require.NoError(t, err)
info, err := registry.Get("myapp")
require.NoError(t, err)
assert.Equal(t, pmgsandbox.PresetSourceUser, info.Source)
assert.Equal(t, "Community", info.Preset.Metadata.Author)
assert.Equal(t, []string{"myapp", "dev-server"}, info.Preset.Metadata.Labels)
assert.Contains(t, info.Preset.Filesystem.AllowWrite, "${CWD}/.myapp/**")
})
t.Run("refuses builtin names", func(t *testing.T) {
dir, factory := newDeps(t)
err := runPresetInit(&bytes.Buffer{}, "git", &presetInitOptions{}, dir, factory)
require.Error(t, err)
assert.Contains(t, err.Error(), "built-in")
})
t.Run("refuses existing files", func(t *testing.T) {
dir, factory := newDeps(t)
require.NoError(t, runPresetInit(&bytes.Buffer{}, "myapp", &presetInitOptions{}, dir, factory))
err := runPresetInit(&bytes.Buffer{}, "myapp", &presetInitOptions{}, dir, factory)
require.Error(t, err)
assert.Contains(t, err.Error(), "already exists")
})
t.Run("refuses invalid names", func(t *testing.T) {
dir, factory := newDeps(t)
err := runPresetInit(&bytes.Buffer{}, "My_App", &presetInitOptions{}, dir, factory)
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid preset name")
})
}
func TestPresetEdit(t *testing.T) {
setup := func(t *testing.T) (string, presetRegistryFactory) {
t.Helper()
dir := t.TempDir()
factory := newTestPresetRegistry(dir)
require.NoError(t, runPresetInit(&bytes.Buffer{}, "myapp", &presetInitOptions{}, func() string { return dir }, factory))
return dir, factory
}
t.Run("valid edit passes", func(t *testing.T) {
_, factory := setup(t)
t.Setenv("VISUAL", "")
t.Setenv("EDITOR", writeEditorScript(t, `exit 0`))
var out bytes.Buffer
require.NoError(t, runPresetEdit(&out, &bytes.Buffer{}, "myapp", factory))
assert.Contains(t, out.String(), "✓")
})
t.Run("edit that breaks the preset fails validation", func(t *testing.T) {
_, factory := setup(t)
t.Setenv("VISUAL", "")
t.Setenv("EDITOR", writeEditorScript(t, `printf 'kind: preset\nname: myapp\nfilesystem:\n deny_read: ["x"]\n' > "$1"`))
err := runPresetEdit(&bytes.Buffer{}, &bytes.Buffer{}, "myapp", factory)
require.Error(t, err)
assert.Contains(t, err.Error(), "deny_read")
})
t.Run("builtin preset is not editable", func(t *testing.T) {
_, factory := setup(t)
err := runPresetEdit(&bytes.Buffer{}, &bytes.Buffer{}, "git", factory)
require.Error(t, err)
assert.Contains(t, err.Error(), "built-in")
})
t.Run("unknown preset is not found", func(t *testing.T) {
_, factory := setup(t)
err := runPresetEdit(&bytes.Buffer{}, &bytes.Buffer{}, "nope", factory)
require.Error(t, err)
var useful usefulerror.UsefulError
require.ErrorAs(t, err, &useful)
assert.Equal(t, errcodes.NotFound, useful.Code())
})
t.Run("shadowed user preset warns", func(t *testing.T) {
dir := t.TempDir()
factory := newTestPresetRegistry(dir)
writeTestUserPreset(t, dir, "git")
t.Setenv("VISUAL", "")
t.Setenv("EDITOR", writeEditorScript(t, `exit 0`))
var errOut bytes.Buffer
require.NoError(t, runPresetEdit(&bytes.Buffer{}, &errOut, "git", factory))
assert.Contains(t, errOut.String(), "shadowed")
})
}
+8
View File
@@ -10,8 +10,16 @@ import (
type registryFactory func() (pmgsandbox.ProfileRegistry, error)
func defaultRegistryFactory() (pmgsandbox.ProfileRegistry, error) {
// Include user presets so profile inspection agrees with runtime
// resolution of custom profiles referencing presets.
presets, err := defaultPresetRegistryFactory()
if err != nil {
return nil, err
}
return pmgsandbox.NewProfileRegistry(
pmgsandbox.WithUserProfileDir(config.Get().SandboxProfileDir()),
pmgsandbox.WithPresetRegistry(presets),
)
}
+1
View File
@@ -24,5 +24,6 @@ func NewCommand() *cobra.Command {
cmd.AddCommand(NewViolationsCommand())
cmd.AddCommand(NewAllowCommand())
cmd.AddCommand(NewProjectCommand())
cmd.AddCommand(NewPresetCommand())
return cmd
}
+1 -1
View File
@@ -91,7 +91,7 @@ var configFlagSpecs = []flagSpec{
},
},
{
name: "sandbox-allow", usage: "Add runtime sandbox allow rule (type=value). Types: read, write, exec, net-connect, net-bind", managed: true,
name: "sandbox-allow", usage: "Add runtime sandbox allow rule (type=value). Types: read, write, exec, net-connect, net-bind, env, preset", managed: true,
bind: func(fs *pflag.FlagSet, name, usage string) {
fs.StringArrayVar(&sandboxAllowRaw, name, nil, usage)
},
+29 -1
View File
@@ -49,6 +49,10 @@ const (
// Per-repo overlays persisted by `pmg sandbox allow` live here.
pmgDefaultSandboxOverlayDir = "sandbox/overlays"
// Default sandbox preset directory is relative to the config directory.
// User/community preset YAML files live here.
pmgDefaultSandboxPresetDir = "sandbox/presets"
// Default sandbox violation cache directory is relative to the cache root.
pmgDefaultSandboxViolationCacheDir = "sandbox/violations"
@@ -327,6 +331,7 @@ type RuntimeConfig struct {
eventLogDir string
sandboxProfileDir string
sandboxOverlayDir string
sandboxPresetDir string
sandboxViolationCacheDir string
localDBDir string
cacheDir string
@@ -399,6 +404,11 @@ func (r *RuntimeConfig) SandboxOverlayDir() string {
return r.sandboxOverlayDir
}
// SandboxPresetDir returns the path to the user sandbox preset directory.
func (r *RuntimeConfig) SandboxPresetDir() string {
return r.sandboxPresetDir
}
// SandboxViolationCacheDir returns the path to the sandbox violation cache directory.
func (r *RuntimeConfig) SandboxViolationCacheDir() string {
return r.sandboxViolationCacheDir
@@ -439,11 +449,13 @@ const (
SandboxAllowNetConnect SandboxAllowType = "net-connect"
SandboxAllowNetBind SandboxAllowType = "net-bind"
SandboxAllowEnv SandboxAllowType = "env"
SandboxAllowPreset SandboxAllowType = "preset"
)
// SandboxAllowOverride represents a single --sandbox-allow flag value.
type SandboxAllowOverride struct {
// Type is the resource type (read, write, exec, net-connect, net-bind).
// Type is the resource type (read, write, exec, net-connect, net-bind,
// env, preset).
Type SandboxAllowType
// Value is the resolved value (absolute path, host:port, etc.).
@@ -565,6 +577,11 @@ func initConfig() {
panic(fmt.Errorf("failed to get sandbox overlay directory: %w", err))
}
sandboxPresetDir, err := sandboxPresetDir()
if err != nil {
panic(fmt.Errorf("failed to get sandbox preset directory: %w", err))
}
cacheRootDir, err := cacheDir()
if err != nil {
panic(fmt.Errorf("failed to get cache directory: %w", err))
@@ -581,6 +598,7 @@ func initConfig() {
globalConfig.eventLogDir = eventLogDir
globalConfig.sandboxProfileDir = sandboxProfileDir
globalConfig.sandboxOverlayDir = sandboxOverlayDir
globalConfig.sandboxPresetDir = sandboxPresetDir
globalConfig.sandboxViolationCacheDir = sandboxViolationCacheDir
globalConfig.localDBDir = localDBDir
globalConfig.cacheDir = cacheRootDir
@@ -922,6 +940,16 @@ func sandboxOverlayDir() (string, error) {
return filepath.Join(configDir, pmgDefaultSandboxOverlayDir), nil
}
// sandboxPresetDir computes the path to the user sandbox preset directory.
func sandboxPresetDir() (string, error) {
configDir, err := configDir()
if err != nil {
return "", fmt.Errorf("failed to get config directory: %w", err)
}
return filepath.Join(configDir, pmgDefaultSandboxPresetDir), nil
}
// sandboxViolationCacheDir computes the path to the sandbox violation cache directory.
func sandboxViolationCacheDir() (string, error) {
cacheDir, err := cacheDir()
+20 -1
View File
@@ -19,6 +19,7 @@ var validSandboxAllowTypes = map[SandboxAllowType]bool{
SandboxAllowNetConnect: true,
SandboxAllowNetBind: true,
SandboxAllowEnv: true,
SandboxAllowPreset: true,
}
// parseSandboxAllowOverrides parses raw --sandbox-allow flag values into validated overrides.
@@ -72,7 +73,7 @@ func parseSingleOverride(raw string) (SandboxAllowOverride, error) {
}
if !validSandboxAllowTypes[allowType] {
return SandboxAllowOverride{}, fmt.Errorf("unknown type %q, valid types: read, write, exec, net-connect, net-bind, env", typStr)
return SandboxAllowOverride{}, fmt.Errorf("unknown type %q, valid types: read, write, exec, net-connect, net-bind, env, preset", typStr)
}
resolved, err := validateAndResolveValue(allowType, value)
@@ -100,11 +101,29 @@ func validateAndResolveValue(typ SandboxAllowType, value string) (string, error)
return validateNetBind(value)
case SandboxAllowEnv:
return validateEnvName(value)
case SandboxAllowPreset:
return validatePresetRef(value)
default:
return "", fmt.Errorf("unhandled type: %s", typ)
}
}
// The value is a bare preset name kept verbatim so overlays track preset
// updates by reference. Registry resolution happens at the use site.
func validatePresetRef(value string) (string, error) {
for _, r := range value {
valid := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-'
if !valid {
return "", fmt.Errorf("invalid preset name %q (expected lowercase alphanumeric with dashes, e.g. preset=git)", value)
}
}
if value == "" || value[0] == '-' {
return "", fmt.Errorf("invalid preset name %q", value)
}
return value, nil
}
// validateEnvName validates an env allow value. The value is an environment
// variable name or name glob (e.g. NPM_TOKEN, npm_config_*) and is kept
// verbatim. Unlike filesystem/exec values it is NOT path-resolved, since it
+29
View File
@@ -376,3 +376,32 @@ func TestParseSingleOverride_ExportedRejectsInvalid(t *testing.T) {
_, err := ParseSingleOverride("garbage")
assert.Error(t, err)
}
func TestParseSandboxAllowOverrides_Preset(t *testing.T) {
tests := []struct {
name string
raw string
value string
wantErr string
}{
{name: "valid preset name", raw: "preset=git", value: "git"},
{name: "dashed preset name", raw: "preset=my-app", value: "my-app"},
{name: "uppercase rejected", raw: "preset=Git", wantErr: "invalid preset name"},
{name: "path rejected", raw: "preset=./git.yml", wantErr: "invalid preset name"},
{name: "leading dash rejected", raw: "preset=-git", wantErr: "invalid preset name"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
override, err := ParseSingleOverride(tc.raw)
if tc.wantErr != "" {
require.Error(t, err)
assert.Contains(t, err.Error(), tc.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, SandboxAllowPreset, override.Type)
assert.Equal(t, tc.value, override.Value)
})
}
}
+126
View File
@@ -0,0 +1,126 @@
# Sandbox Presets
A preset is a named bundle of sandbox allowances for one workload. For
example: what `lint-staged` needs from git, or what `astro dev` needs to
write and bind. Any tool with a known sandbox footprint can have a preset.
Presets are **additive-only**: they grant allowances on top of your sandbox
profile and can never remove a deny rule. A profile-authored deny always
beats a preset allowance, and preset validation rejects paths that would
opt out of PMG's mandatory protections (`.git/hooks`, `.git/config` writes,
credential files). The two opt-outs a preset can perform, both visible in
its YAML: read access to `.git/config` (required for git to operate) and
un-scrubbing specific built-in credential variables by exact name.
## Using presets
Discover what's available:
```bash
pmg sandbox preset list
pmg sandbox preset list --label dev-server --author SafeDep
```
Inspect a preset before trusting it. The output is the preset's own YAML,
including its threat notes describing the residual risk of each allowance:
```bash
pmg sandbox preset show git
```
Apply presets to the current repository (run from the project root; this
saves into the per-repo overlay used by every future PMG run there):
```bash
pmg sandbox allow preset=git preset=astro
```
Or attach presets permanently to a custom sandbox profile:
```yaml
# ~/.config/safedep/pmg/sandbox/profiles/pnpm-custom.yml
name: pnpm-custom
inherits: pnpm
package_managers: [pnpm]
presets: [git, astro]
```
Presets are applied by reference: upgrading PMG (or editing a user preset)
updates the allowances everywhere the preset is used.
## Available official presets
| Preset | For |
| -------- | -------------------------------------- |
| `git` | lint-staged, husky, turbo, changesets |
| `astro` | Astro dev server and build |
| `vite` | Vite dev server and build |
| `nextjs` | Next.js dev server and build |
## Creating your own preset
Scaffold, edit and validate:
```bash
pmg sandbox preset init myapp --author "Your Name" --label myapp
pmg sandbox preset edit myapp # opens $VISUAL / $EDITOR, validates on save
pmg sandbox allow preset=myapp # apply to the current repo
```
User presets live in `<config-dir>/sandbox/presets/` (e.g.
`~/.config/safedep/pmg/sandbox/presets/` on Linux) — community presets are
installed by dropping a file there. `pmg sandbox preset list` always shows
where a preset came from: `builtin` (embedded in the pmg binary,
maintainer-reviewed) vs the user file path, and a user preset that reuses a
built-in name is marked `SHADOWED` — the built-in always wins, so an
official preset cannot be silently replaced. A preset file looks like:
```yaml
kind: preset
name: myapp
description: What this preset enables, one line
metadata:
author: Your Name
labels: [myapp, dev-server]
# Threat notes: explain what each allowance permits and why it is acceptable.
filesystem:
allow_write:
- ${CWD}/.myapp/**
network:
allow_bind:
- localhost:8080
```
Validate it:
```bash
pmg sandbox preset lint ./myapp.yml
```
Rules the schema enforces:
- Allow-only sections: `filesystem.allow_read/allow_write`,
`process.allow_exec`, `network.allow_bind`, `environment.allow`. Deny
rules and profile booleans are rejected.
- Paths must be anchored at `${CWD}/`, `${HOME}/` or `${TMPDIR}/`, no `..`,
and must not name sensitive files (`.env`, `.ssh`, ...).
- Binds must be loopback (`localhost`, `127.0.0.1`, `::1`).
- `environment.allow` entries are exact variable names, no globs.
- No `network.allow_outbound`: current sandbox drivers cannot enforce
host-granular outbound rules (a single allow means blanket network
access), so presets are not allowed to change outbound posture at all.
Precedence guarantees, in addition to PMG's mandatory denies:
- A preset environment allowance covered by a profile-authored
`environment.deny` pattern is dropped with a warning. Surviving preset
allowances still opt out of PMG's built-in credential variable scrubbing,
which is their intended use.
- A preset filesystem allowance never removes a deny rule authored in a
profile: deny wins over allow on every platform.
- The `git` preset allows reading `.git/config` and writing under `.git/`,
but writes to `.git/config` and everything under `.git/hooks` stay
blocked by mandatory denies on all platforms.
A preset name that collides with an official preset is shadowed — the
official one always wins. To propose an official preset, open a pull request
adding it under `sandbox/presets/` with threat notes and tests.
+23 -2
View File
@@ -269,6 +269,10 @@ weakens mandatory denies, and is ignored when `global_lockdown` is set.
# Save manual allowances for the current repo
pmg sandbox allow write=./.astro net-bind=localhost:4321
# Persist an environment variable allowance so the profile stops scrubbing it
# in this repo (same semantics as --sandbox-allow env=..., but saved)
pmg sandbox allow env=AWS_PROFILE
# Promote the primary violation from the most recent cached report
pmg sandbox allow --last
@@ -289,11 +293,28 @@ pmg sandbox project list
pmg sandbox project reset --yes
```
### Presets
A preset is a named, additive-only bundle of allowances for one workload (git hooks tooling,
an Astro/Vite/Next.js dev server, ...). Instead of discovering allowances one denial at a
time, apply a curated bundle:
```bash
pmg sandbox preset list
pmg sandbox preset show git
pmg sandbox allow preset=git preset=astro
```
Presets can also be attached to a profile via a `presets:` list. See
[sandbox-presets.md](sandbox-presets.md) for usage and how to author your own.
Notes:
- `--last`/`--last --all` only auto-promotes filesystem and exec denials. Network allowances
(`net-connect`, `net-bind`) must be passed manually as `type=value` because drivers do not
classify network denials yet.
(`net-connect`, `net-bind`) and environment allowances (`env`) must be passed manually as
`type=value` because drivers do not classify network denials yet and environment scrubbing is
logged rather than recorded as a violation. Run with `--debug` to see scrubbed variable names,
then persist with `pmg sandbox allow env=NAME`.
- `pmg sandbox allow` refuses sensitive targets (`.env*`, `.npmrc`, `.ssh`, `.aws`, `.kube`,
`.gnupg`, ...) unless `--force` is given.
- Applied overlay entries are recorded in the audit event log with a `+overlay` source tag so
+2
View File
@@ -7,4 +7,6 @@ import "errors"
var (
ErrProfileNotFound = errors.New("sandbox profile not found")
ErrProfileInvalid = errors.New("sandbox profile invalid")
ErrPresetNotFound = errors.New("sandbox preset not found")
ErrPresetInvalid = errors.New("sandbox preset invalid")
)
+33 -6
View File
@@ -59,7 +59,15 @@ func ApplySandbox(ctx context.Context, cmd *exec.Cmd, pmName string, opts ...app
opt(applyConfig)
}
registry, err := sandbox.NewProfileRegistry(sandbox.WithUserProfileDir(cfg.SandboxProfileDir()))
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)
}
@@ -136,7 +144,7 @@ func ApplySandbox(ctx context.Context, cmd *exec.Cmd, pmName string, opts ...app
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()); err != nil {
} 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
@@ -146,7 +154,7 @@ func ApplySandbox(ctx context.Context, cmd *exec.Cmd, pmName string, opts ...app
// Apply runtime --sandbox-allow overrides to the policy before execution
if len(cfg.SandboxAllowOverrides) > 0 {
applyRuntimeOverrides(policy, cfg.SandboxAllowOverrides)
applyRuntimeOverrides(policy, cfg.SandboxAllowOverrides, presetRegistry)
logSandboxOverrides(policy.Name, cfg.SandboxAllowOverrides)
}
@@ -199,9 +207,28 @@ func ApplySandbox(ctx context.Context, cmd *exec.Cmd, pmName string, opts ...app
// 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) {
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)
@@ -286,7 +313,7 @@ func removeExactMatch(slice []string, value string) []string {
// 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) (int, error) {
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
@@ -301,7 +328,7 @@ func applyProjectOverlay(policy *sandbox.SandboxPolicy, overlayDir, repoRoot str
}
entries := overlay.ToAllowOverrides()
applyRuntimeOverrides(policy, entries)
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)
+107
View File
@@ -0,0 +1,107 @@
package executor
import (
"os"
"path/filepath"
"testing"
"github.com/safedep/dry/utils"
"github.com/safedep/pmg/config"
"github.com/safedep/pmg/sandbox"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestApplyRuntimeOverridesPreset(t *testing.T) {
registry, err := sandbox.NewPresetRegistry()
require.NoError(t, err)
t.Run("expands preset allowances into the policy", func(t *testing.T) {
policy := &sandbox.SandboxPolicy{Name: "test"}
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowPreset, Value: "git", Raw: "preset=git"},
{Type: config.SandboxAllowPreset, Value: "astro", Raw: "preset=astro"},
}, registry)
assert.Contains(t, policy.Filesystem.AllowRead, "${CWD}/.git/config")
assert.Contains(t, policy.Filesystem.AllowWrite, "${CWD}/.git/**")
assert.Contains(t, policy.Filesystem.AllowWrite, "${CWD}/.astro/**")
assert.Contains(t, policy.Network.AllowBind, "localhost:4321")
assert.True(t, utils.SafelyGetValue(policy.AllowNetworkBind))
})
t.Run("unknown preset is a warning, never fatal", func(t *testing.T) {
policy := &sandbox.SandboxPolicy{Name: "test"}
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowPreset, Value: "does-not-exist", Raw: "preset=does-not-exist"},
}, registry)
assert.Empty(t, policy.Filesystem.AllowRead)
assert.Empty(t, policy.Filesystem.AllowWrite)
})
t.Run("nil registry skips preset entries", func(t *testing.T) {
policy := &sandbox.SandboxPolicy{Name: "test"}
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowPreset, Value: "git", Raw: "preset=git"},
}, nil)
assert.Empty(t, policy.Filesystem.AllowRead)
})
}
func TestApplyProjectOverlayWithPresets(t *testing.T) {
dir := t.TempDir()
repo := "/repo/example"
_, err := sandbox.SaveOverlay(dir, repo, &sandbox.Overlay{
Allow: []sandbox.OverlayAllow{
{Type: config.SandboxAllowPreset, Value: "git"},
{Type: config.SandboxAllowWrite, Value: "/repo/example/.astro"},
},
})
require.NoError(t, err)
registry, err := sandbox.NewPresetRegistry()
require.NoError(t, err)
policy := &sandbox.SandboxPolicy{Name: "test"}
applied, err := applyProjectOverlay(policy, dir, repo, false, registry)
require.NoError(t, err)
assert.Equal(t, 2, applied)
assert.Contains(t, policy.Filesystem.AllowRead, "${CWD}/.git/config")
assert.Contains(t, policy.Filesystem.AllowWrite, "${CWD}/.git/**")
assert.Contains(t, policy.Filesystem.AllowWrite, "/repo/example/.astro")
}
func TestPresetExpansionEquivalentAcrossEntryPaths(t *testing.T) {
presetRegistry, err := sandbox.NewPresetRegistry()
require.NoError(t, err)
viaOverride := &sandbox.SandboxPolicy{Name: "test", PackageManagers: []string{"pnpm"}}
applyRuntimeOverrides(viaOverride, []config.SandboxAllowOverride{
{Type: config.SandboxAllowPreset, Value: "git", Raw: "preset=git"},
{Type: config.SandboxAllowPreset, Value: "astro", Raw: "preset=astro"},
}, presetRegistry)
dir := t.TempDir()
profilePath := filepath.Join(dir, "via-profile.yml")
require.NoError(t, os.WriteFile(profilePath, []byte(`
name: via-profile
package_managers: [pnpm]
presets: [git, astro]
`), 0o600))
profileRegistry, err := sandbox.NewProfileRegistry()
require.NoError(t, err)
viaProfile, err := profileRegistry.LoadCustomProfile(profilePath)
require.NoError(t, err)
assert.Equal(t, viaProfile.Filesystem.AllowRead, viaOverride.Filesystem.AllowRead)
assert.Equal(t, viaProfile.Filesystem.AllowWrite, viaOverride.Filesystem.AllowWrite)
assert.Equal(t, viaProfile.Network.AllowBind, viaOverride.Network.AllowBind)
assert.Equal(t, viaProfile.Environment.Allow, viaOverride.Environment.Allow)
assert.Equal(t,
utils.SafelyGetValue(viaProfile.AllowNetworkBind),
utils.SafelyGetValue(viaOverride.AllowNetworkBind))
}
+18 -18
View File
@@ -23,7 +23,7 @@ func TestApplyRuntimeOverrides_Read(t *testing.T) {
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowRead, Value: "/new/path", Raw: "read=/new/path"},
})
}, nil)
assert.Contains(t, policy.Filesystem.AllowRead, "/existing")
assert.Contains(t, policy.Filesystem.AllowRead, "/new/path")
@@ -38,7 +38,7 @@ func TestApplyRuntimeOverrides_Write(t *testing.T) {
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowWrite, Value: "/new/file", Raw: "write=/new/file"},
})
}, nil)
assert.Contains(t, policy.Filesystem.AllowWrite, "/existing")
assert.Contains(t, policy.Filesystem.AllowWrite, "/new/file")
@@ -53,7 +53,7 @@ func TestApplyRuntimeOverrides_Exec(t *testing.T) {
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowExec, Value: "/usr/bin/curl", Raw: "exec=/usr/bin/curl"},
})
}, nil)
assert.Contains(t, policy.Process.AllowExec, "/usr/bin/node")
assert.Contains(t, policy.Process.AllowExec, "/usr/bin/curl")
@@ -68,7 +68,7 @@ func TestApplyRuntimeOverrides_Env(t *testing.T) {
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowEnv, Value: "AWS_PROFILE", Raw: "env=AWS_PROFILE"},
})
}, nil)
assert.Contains(t, policy.Environment.Allow, "NPM_TOKEN")
assert.Contains(t, policy.Environment.Allow, "AWS_PROFILE")
@@ -104,7 +104,7 @@ func TestScrubEnv_AllowOverrideUnscrubs(t *testing.T) {
// Simulate a --sandbox-allow env=AWS_SESSION_TOKEN override having been merged.
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowEnv, Value: "AWS_SESSION_TOKEN", Raw: "env=AWS_SESSION_TOKEN"},
})
}, nil)
cmd := &exec.Cmd{Env: []string{"AWS_SESSION_TOKEN=kept"}}
scrubbed := scrubEnv(cmd, policy)
@@ -136,7 +136,7 @@ func TestApplyRuntimeOverrides_NetConnect(t *testing.T) {
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowNetConnect, Value: "example.com:443", Raw: "net-connect=example.com:443"},
})
}, nil)
assert.Contains(t, policy.Network.AllowOutbound, "registry.npmjs.org:443")
assert.Contains(t, policy.Network.AllowOutbound, "example.com:443")
@@ -151,7 +151,7 @@ func TestApplyRuntimeOverrides_NetBind(t *testing.T) {
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowNetBind, Value: "127.0.0.1:3000", Raw: "net-bind=127.0.0.1:3000"},
})
}, nil)
assert.Contains(t, policy.Network.AllowBind, "127.0.0.1:3000")
assert.NotNil(t, policy.AllowNetworkBind)
@@ -168,7 +168,7 @@ func TestApplyRuntimeOverrides_NetBindPreservesExistingTrue(t *testing.T) {
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowNetBind, Value: "127.0.0.1:3000", Raw: "net-bind=127.0.0.1:3000"},
})
}, nil)
assert.Contains(t, policy.Network.AllowBind, "localhost:8080")
assert.Contains(t, policy.Network.AllowBind, "127.0.0.1:3000")
@@ -189,7 +189,7 @@ func TestApplyRuntimeOverrides_MultipleOverrides(t *testing.T) {
{Type: config.SandboxAllowNetConnect, Value: "example.com:443", Raw: "net-connect=example.com:443"},
}
applyRuntimeOverrides(policy, overrides)
applyRuntimeOverrides(policy, overrides, nil)
assert.Len(t, policy.Filesystem.AllowWrite, 2)
assert.Len(t, policy.Process.AllowExec, 1)
@@ -203,7 +203,7 @@ func TestApplyRuntimeOverrides_EmptyOverrides(t *testing.T) {
},
}
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{})
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{}, nil)
// Policy should be unchanged
assert.Equal(t, []string{"/existing"}, policy.Filesystem.AllowWrite)
@@ -228,7 +228,7 @@ func TestApplyRuntimeOverrides_DenyListsUnmodifiedWhenNoConflict(t *testing.T) {
{Type: config.SandboxAllowNetConnect, Value: "example.com:443", Raw: "net-connect=example.com:443"},
}
applyRuntimeOverrides(policy, overrides)
applyRuntimeOverrides(policy, overrides, nil)
// Deny lists should be unchanged when overrides don't conflict
assert.Equal(t, []string{"/protected"}, policy.Filesystem.DenyWrite)
@@ -253,7 +253,7 @@ func TestApplyRuntimeOverrides_RemovesExactDenyConflict(t *testing.T) {
{Type: config.SandboxAllowExec, Value: "/bin/bash", Raw: "exec=/bin/bash"},
}
applyRuntimeOverrides(policy, overrides)
applyRuntimeOverrides(policy, overrides, nil)
// Exact matches should be removed from deny lists
assert.Equal(t, []string{"/other"}, policy.Filesystem.DenyRead)
@@ -283,7 +283,7 @@ func TestApplyRuntimeOverrides_PreservesGlobDenyPatterns(t *testing.T) {
{Type: config.SandboxAllowExec, Value: "/usr/bin/git", Raw: "exec=/usr/bin/git"},
}
applyRuntimeOverrides(policy, overrides)
applyRuntimeOverrides(policy, overrides, nil)
// Glob/wildcard deny patterns must NOT be removed — only exact matches are removed
assert.Equal(t, []string{"/etc/**"}, policy.Filesystem.DenyRead)
@@ -310,7 +310,7 @@ func TestApplyRuntimeOverrides_VariableDenyNotRemovedByAbsoluteOverride(t *testi
applyRuntimeOverrides(policy, []config.SandboxAllowOverride{
{Type: config.SandboxAllowWrite, Value: absolutePath, Raw: "write=./blocked.txt"},
})
}, nil)
// The override is added to the allow list
assert.Contains(t, policy.Filesystem.AllowWrite, absolutePath)
@@ -332,7 +332,7 @@ func TestApplyProjectOverlayAppendsEntries(t *testing.T) {
require.NoError(t, err)
policy := &sandbox.SandboxPolicy{Name: "test"}
applied, err := applyProjectOverlay(policy, dir, repo, false)
applied, err := applyProjectOverlay(policy, dir, repo, false, nil)
assert.NoError(t, err)
assert.Equal(t, 2, applied)
assert.Contains(t, policy.Filesystem.AllowWrite, "/repo/example/.astro")
@@ -351,7 +351,7 @@ func TestApplyProjectOverlaySkippedWhenLocked(t *testing.T) {
require.NoError(t, err)
policy := &sandbox.SandboxPolicy{Name: "test"}
applied, err := applyProjectOverlay(policy, dir, repo, true)
applied, err := applyProjectOverlay(policy, dir, repo, true, nil)
assert.NoError(t, err)
assert.Equal(t, 0, applied)
assert.Empty(t, policy.Filesystem.AllowWrite)
@@ -360,7 +360,7 @@ func TestApplyProjectOverlaySkippedWhenLocked(t *testing.T) {
func TestApplyProjectOverlayMissingFileIsNoop(t *testing.T) {
dir := filepath.Join(t.TempDir(), "no-such")
policy := &sandbox.SandboxPolicy{Name: "test"}
applied, err := applyProjectOverlay(policy, dir, "/repo/example", false)
applied, err := applyProjectOverlay(policy, dir, "/repo/example", false, nil)
assert.NoError(t, err)
assert.Equal(t, 0, applied)
_, statErr := os.Stat(dir)
@@ -369,7 +369,7 @@ func TestApplyProjectOverlayMissingFileIsNoop(t *testing.T) {
func TestApplyProjectOverlayEmptyArgsNoop(t *testing.T) {
policy := &sandbox.SandboxPolicy{Name: "test"}
applied, err := applyProjectOverlay(policy, "", "", false)
applied, err := applyProjectOverlay(policy, "", "", false, nil)
assert.NoError(t, err)
assert.Equal(t, 0, applied)
}
+12 -10
View File
@@ -301,27 +301,29 @@ func (t *bubblewrapPolicyTranslator) translateFilesystem(policy *sandbox.Sandbox
args = append(args, denyArgs...)
}
// Skip mandatory write denies for paths the user listed in allow_read: the
// allow_read --ro-bind already denies writes (EROFS), and overlaying
// /dev/null on top would also mask reads, breaking the read-side opt-out.
// User-listed deny_write entries above are unaffected — "deny wins" still
// applies to explicit user rules.
// Mandatory write denies for paths in allow_read must keep reads working,
// so they get a read-only re-bind instead of the read-blocking
// processDenyRule overlay. The earlier allow_read --ro-bind is not
// sufficient: a later writable parent bind (allow_write ${CWD}/.git/**
// over allow_read ${CWD}/.git/config) wins in bwrap's last-mount-wins
// ordering, so the re-bind must come after all allow_write mounts.
allowReadSet := make(map[string]bool, len(expandedAllowRead))
for _, p := range expandedAllowRead {
allowReadSet[filepath.Clean(p)] = true
}
for _, pattern := range mandatoryResult.DenyWrite {
if allowReadSet[filepath.Clean(pattern)] {
continue
}
expanded, err := util.ExpandVariables(pattern)
if err != nil {
log.Warnf("Failed to expand variables in deny pattern '%s': %v", pattern, err)
continue
}
denyArgs, err := t.processDenyRule(expanded)
var denyArgs []string
if allowReadSet[filepath.Clean(pattern)] {
denyArgs, err = t.processDenyWriteRule(expanded)
} else {
denyArgs, err = t.processDenyRule(expanded)
}
if err != nil {
log.Debugf("Deny rule '%s' skipped: %v", expanded, err)
continue
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/safedep/dry/utils"
@@ -1174,3 +1175,41 @@ func assertReadOnlyBindAfterWritableBind(t *testing.T, args []string, readOnlyPa
require.NotEqual(t, -1, readOnlyBindIndex, "expected read-only bind for %q in args: %v", readOnlyPath, args)
assert.Greater(t, readOnlyBindIndex, writableBindIndex, "deny_write read-only bind must override earlier writable parent bind")
}
func TestBubblewrapMandatoryWriteDenySurvivesWritableParent(t *testing.T) {
dir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(dir, ".git"), 0o755))
gitConfig := filepath.Join(dir, ".git", "config")
require.NoError(t, os.WriteFile(gitConfig, []byte("[core]\n"), 0o644))
t.Chdir(dir)
policy := &sandbox.SandboxPolicy{
Name: "test",
PackageManagers: []string{"pnpm"},
Filesystem: sandbox.FilesystemPolicy{
AllowRead: []string{gitConfig},
AllowWrite: []string{filepath.Join(dir, ".git") + "/**"},
},
}
translator := newBubblewrapPolicyTranslator(newDefaultBubblewrapConfig())
args, err := translator.translate(policy)
require.NoError(t, err)
lastWritableGitBind := -1
lastROConfigBind := -1
for i := 0; i+2 < len(args); i++ {
if (args[i] == "--bind" || args[i] == "--bind-try") && strings.HasPrefix(args[i+1], filepath.Join(dir, ".git")) {
lastWritableGitBind = i
}
if (args[i] == "--ro-bind" || args[i] == "--ro-bind-try") && args[i+1] == gitConfig && args[i+2] == gitConfig {
lastROConfigBind = i
}
}
require.GreaterOrEqual(t, lastWritableGitBind, 0, "expected a writable bind for the .git tree")
require.GreaterOrEqual(t, lastROConfigBind, 0,
"mandatory write deny for .git/config must be re-applied even when the path is in allow_read")
assert.Greater(t, lastROConfigBind, lastWritableGitBind,
"read-only .git/config bind must come after the writable .git bind (bwrap last mount wins)")
}
@@ -591,3 +591,37 @@ func TestLandlockPolicyExplicitlyAllowsProc(t *testing.T) {
})
}
}
func TestLandlockTranslatePolicy_GitPresetShapeKeepsConfigWriteDeny(t *testing.T) {
dir := t.TempDir()
t.Chdir(dir)
policy := newTestPolicy()
policy.Filesystem.AllowRead = []string{filepath.Join(dir, ".git/config")}
policy.Filesystem.AllowWrite = []string{filepath.Join(dir, ".git") + "/**"}
abi := newLandlockABI(3)
ep, err := landlockTranslatePolicy(policy, abi)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var hasWriteDeny, hasReadDeny bool
for _, entry := range ep.DenyPaths {
if strings.HasSuffix(entry.Path, ".git/config") {
if entry.Mode == denyWrite {
hasWriteDeny = true
}
if entry.Mode == denyRead {
hasReadDeny = true
}
}
}
if !hasWriteDeny {
t.Error("expected .git/config write deny to survive allow_read + allow_write ${CWD}/.git/** (git preset shape)")
}
if hasReadDeny {
t.Error("expected .git/config read deny to be suppressed by the exact allow_read entry")
}
}
+7
View File
@@ -17,6 +17,10 @@ type SandboxPolicy struct {
Inherits string `yaml:"inherits,omitempty" json:"inherits,omitempty"`
PackageManagers []string `yaml:"package_managers" json:"package_managers"`
// Presets are expanded by the registry after inheritance resolution.
// Names are kept post-expansion for provenance display.
Presets []string `yaml:"presets,omitempty" json:"presets,omitempty"`
// These fields are affected by inheritance and are merged with the parent policy.
// Any new values added here should be handled in the MergeWithParent method.
Filesystem FilesystemPolicy `yaml:"filesystem" json:"filesystem"`
@@ -160,6 +164,9 @@ func (child *SandboxPolicy) MergeWithParent(parent *SandboxPolicy) {
child.Environment.Allow = unionStringSlices(parent.Environment.Allow, child.Environment.Allow)
child.Environment.Deny = unionStringSlices(parent.Environment.Deny, child.Environment.Deny)
// Union preset references
child.Presets = unionStringSlices(parent.Presets, child.Presets)
// Set boolean fields by duplicating the parent value if not present in the child.
if child.AllowPTY == nil {
child.AllowPTY = utils.PtrTo(utils.SafelyGetValue(parent.AllowPTY))
+268
View File
@@ -0,0 +1,268 @@
package sandbox
import (
"bytes"
"fmt"
"net"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/safedep/dry/log"
"github.com/safedep/dry/utils"
"github.com/safedep/pmg/sandbox/util"
"gopkg.in/yaml.v3"
)
// PresetSchemaVersion is the highest preset schema version this binary
// accepts. Newer versions are rejected instead of being silently misread.
const PresetSchemaVersion = 1
const presetKind = "preset"
// PresetMetadata is descriptive and filterable, never enforced.
type PresetMetadata struct {
Author string `yaml:"author,omitempty" json:"author,omitempty"`
Labels []string `yaml:"labels,omitempty" json:"labels,omitempty"`
}
// PresetFilesystem lists filesystem allowances.
type PresetFilesystem struct {
AllowRead []string `yaml:"allow_read,omitempty" json:"allow_read,omitempty"`
AllowWrite []string `yaml:"allow_write,omitempty" json:"allow_write,omitempty"`
}
// PresetNetwork lists network allowances. No allow_outbound: platform
// translators are all-or-nothing for outbound, so one entry would mean
// blanket network access far beyond what the preset YAML conveys.
type PresetNetwork struct {
AllowBind []string `yaml:"allow_bind,omitempty" json:"allow_bind,omitempty"`
}
// PresetProcess lists process execution allowances.
type PresetProcess struct {
AllowExec []string `yaml:"allow_exec,omitempty" json:"allow_exec,omitempty"`
}
// PresetEnvironment lists environment variable allowances (name globs).
type PresetEnvironment struct {
Allow []string `yaml:"allow,omitempty" json:"allow,omitempty"`
}
// Preset is a named, additive-only bundle of sandbox allowances for one
// workload. Mandatory denies still apply except via the exact-match
// suppression in util.GetMandatoryDenyPatterns.
type Preset struct {
SchemaVersion int `yaml:"schema_version,omitempty" json:"schema_version,omitempty"`
Kind string `yaml:"kind" json:"kind"`
Name string `yaml:"name" json:"name"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Metadata PresetMetadata `yaml:"metadata,omitempty" json:"metadata,omitempty"`
Filesystem PresetFilesystem `yaml:"filesystem,omitempty" json:"filesystem,omitempty"`
Network PresetNetwork `yaml:"network,omitempty" json:"network,omitempty"`
Process PresetProcess `yaml:"process,omitempty" json:"process,omitempty"`
Environment PresetEnvironment `yaml:"environment,omitempty" json:"environment,omitempty"`
}
var presetNameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
// ParsePreset decodes strictly: unknown fields (including any deny_* key)
// are errors, keeping the additive-only contract structural.
func ParsePreset(data []byte) (*Preset, error) {
dec := yaml.NewDecoder(bytes.NewReader(data))
dec.KnownFields(true)
var preset Preset
if err := dec.Decode(&preset); err != nil {
return nil, fmt.Errorf("failed to parse preset YAML: %w", err)
}
return &preset, nil
}
// Validate enforces the preset schema contract.
func (p *Preset) Validate() error {
if p.Kind != presetKind {
return fmt.Errorf("kind must be %q, got %q", presetKind, p.Kind)
}
if !presetNameRe.MatchString(p.Name) {
return fmt.Errorf("preset name %q must be lowercase alphanumeric with dashes", p.Name)
}
if p.SchemaVersion > PresetSchemaVersion {
return fmt.Errorf("preset %s declares schema_version %d, this pmg supports up to %d (upgrade pmg)",
p.Name, p.SchemaVersion, PresetSchemaVersion)
}
ruleCount := len(p.Filesystem.AllowRead) + len(p.Filesystem.AllowWrite) +
len(p.Network.AllowBind) +
len(p.Process.AllowExec) + len(p.Environment.Allow)
if ruleCount == 0 {
return fmt.Errorf("preset %s must define at least one allowance", p.Name)
}
for _, entry := range p.Filesystem.AllowRead {
if err := validatePresetPath(entry, true); err != nil {
return fmt.Errorf("preset %s allow_read: %w", p.Name, err)
}
}
for _, entry := range p.Filesystem.AllowWrite {
if err := validatePresetPath(entry, false); err != nil {
return fmt.Errorf("preset %s allow_write: %w", p.Name, err)
}
}
for _, entry := range p.Process.AllowExec {
if err := validatePresetPath(entry, false); err != nil {
return fmt.Errorf("preset %s allow_exec: %w", p.Name, err)
}
}
for _, entry := range p.Network.AllowBind {
if err := validatePresetBind(entry); err != nil {
return fmt.Errorf("preset %s allow_bind: %w", p.Name, err)
}
}
for _, entry := range p.Environment.Allow {
if err := validatePresetEnv(entry); err != nil {
return fmt.Errorf("preset %s environment.allow: %w", p.Name, err)
}
}
return nil
}
// Anchoring keeps a preset from allowing arbitrary host locations, and
// naming a mandatory-deny target is rejected because an exact-match entry
// would suppress that mandatory deny (see util.GetMandatoryDenyPatterns).
// The one deliberate exception is read access to .git/config, which git
// repo discovery requires and the built-in git preset uses.
func validatePresetPath(entry string, read bool) error {
var rel string
for _, anchor := range []string{util.VarCWD, util.VarHome, util.VarTMPDir} {
if strings.HasPrefix(entry, anchor+"/") {
rel = strings.TrimPrefix(entry, anchor+"/")
break
}
}
if rel == "" {
return fmt.Errorf("path %q must be anchored at ${CWD}/, ${HOME}/ or ${TMPDIR}/", entry)
}
for _, segment := range strings.Split(entry, "/") {
if segment == ".." {
return fmt.Errorf("path %q must not traverse with '..'", entry)
}
}
if IsSensitiveProjectTarget(entry) {
return fmt.Errorf("path %q names a sensitive target and cannot be allowed by a preset", entry)
}
if dangerous, ok := util.DangerousFileMatch(rel); ok {
return fmt.Errorf("path %q names the protected credential target %q and cannot be allowed by a preset", entry, dangerous)
}
if util.PathCoveredBy(rel, util.GitHooksPath) {
return fmt.Errorf("path %q: %s cannot be allowed by a preset", entry, util.GitHooksPath)
}
if !read && rel == util.GitConfigPath {
return fmt.Errorf("path %q: %s write access cannot be allowed by a preset", entry, util.GitConfigPath)
}
return nil
}
var loopbackHosts = map[string]bool{
"localhost": true,
"127.0.0.1": true,
"::1": true,
}
func validatePresetBind(entry string) error {
host, port, err := net.SplitHostPort(entry)
if err != nil {
return fmt.Errorf("bind %q must be host:port: %w", entry, err)
}
if !loopbackHosts[host] {
return fmt.Errorf("bind host %q must be loopback (localhost, 127.0.0.1 or ::1)", host)
}
if port != "*" {
if _, err := strconv.ParseUint(port, 10, 16); err != nil {
return fmt.Errorf("bind port %q must be numeric or '*'", port)
}
}
return nil
}
// Preset env allowances are exact variable names, no glob metacharacters.
// This keeps the authored-deny precedence check exact: a deny pattern (any
// dialect ScrubEnv supports, including character classes) is evaluated
// against the literal name with the same matcher used at scrub time, so no
// glob-vs-glob intersection is ever needed.
func validatePresetEnv(entry string) error {
if entry == "" || strings.ContainsAny(entry, "*?[]=/\\ \t") {
return fmt.Errorf("entry %q must be an exact variable name (globs are not allowed in presets)", entry)
}
return nil
}
// HasLabel reports whether the preset carries the label (case-insensitive).
func (p *Preset) HasLabel(label string) bool {
for _, l := range p.Metadata.Labels {
if strings.EqualFold(l, label) {
return true
}
}
return false
}
// ApplyToPolicy unions the preset's allowances into the policy. Unlike
// explicit `pmg sandbox allow` overrides it never touches deny lists, so an
// authored deny always wins over a preset allowance.
func (p *Preset) ApplyToPolicy(policy *SandboxPolicy) {
policy.Filesystem.AllowRead = unionStringSlices(policy.Filesystem.AllowRead, p.Filesystem.AllowRead)
policy.Filesystem.AllowWrite = unionStringSlices(policy.Filesystem.AllowWrite, p.Filesystem.AllowWrite)
policy.Process.AllowExec = unionStringSlices(policy.Process.AllowExec, p.Process.AllowExec)
policy.Network.AllowBind = unionStringSlices(policy.Network.AllowBind, p.Network.AllowBind)
if len(p.Network.AllowBind) > 0 {
policy.AllowNetworkBind = utils.PtrTo(true)
}
policy.Environment.Allow = unionStringSlices(policy.Environment.Allow, p.filteredEnvAllow(policy))
}
// ScrubEnv is allow-wins, so a preset allowance covered by an authored deny
// must be dropped here or it would override the profile author's deny.
// Allowances are literal names (enforced by validatePresetEnv), so coverage
// is decided by the same matcher ScrubEnv uses at runtime. Surviving entries
// still suppress built-in DANGEROUS_ENV_VARS denies.
func (p *Preset) filteredEnvAllow(policy *SandboxPolicy) []string {
if len(p.Environment.Allow) == 0 || len(policy.Environment.Deny) == 0 {
return p.Environment.Allow
}
kept := make([]string, 0, len(p.Environment.Allow))
for _, allow := range p.Environment.Allow {
if util.EnvNameMatchesAny(allow, policy.Environment.Deny) {
log.Warnf("preset %s: environment allowance %q dropped, it is covered by an authored deny in policy %s", p.Name, allow, policy.Name)
continue
}
kept = append(kept, allow)
}
return kept
}
func presetFileName(fileName string) (string, bool) {
ext := filepath.Ext(fileName)
if ext != ".yml" && ext != ".yaml" {
return "", false
}
return strings.TrimSuffix(fileName, ext), true
}
+322
View File
@@ -0,0 +1,322 @@
package sandbox
import (
"embed"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"github.com/safedep/dry/log"
)
//go:embed presets/*.yml
var presetsFS embed.FS
// PresetSourceName identifies where a preset was loaded from.
type PresetSourceName string
const (
PresetSourceBuiltin PresetSourceName = "builtin"
PresetSourceUser PresetSourceName = "user"
)
// PresetSource is a read-only provider of presets. Sources are consulted in
// registry order; the first source that knows a name wins. Remote sources
// (hosted registry, cloud sync) plug in here.
type PresetSource interface {
Name() PresetSourceName
// List returns all valid presets sorted by name. Invalid preset files
// are skipped with a warning, never fatal.
List() ([]PresetInfo, error)
Get(name string) (*PresetInfo, bool, error)
}
// PresetInfo pairs a preset with its provenance.
type PresetInfo struct {
Preset *Preset
Source PresetSourceName
// Path is the on-disk file for user presets, "" for builtins.
Path string
// Shadowed is true when an earlier source also provides this name and
// wins during resolution.
Shadowed bool
// Raw is the original YAML, preserved so `preset show` can display
// authored comments (threat notes).
Raw []byte
}
// PresetRegistry resolves presets across ordered sources.
type PresetRegistry interface {
Get(name string) (*PresetInfo, error)
// List enumerates presets from all sources, builtins first, marking
// user presets shadowed by builtin names.
List() ([]PresetInfo, error)
}
// PresetFilter narrows List results by metadata. Zero value matches all.
type PresetFilter struct {
Author string
Labels []string
}
// Matches applies the filter: author is case-insensitive equality, labels
// must all be present.
func (f PresetFilter) Matches(p *Preset) bool {
if f.Author != "" && !strings.EqualFold(p.Metadata.Author, f.Author) {
return false
}
for _, label := range f.Labels {
if !p.HasLabel(label) {
return false
}
}
return true
}
// FilterPresets returns the subset of infos matching the filter.
func FilterPresets(infos []PresetInfo, filter PresetFilter) []PresetInfo {
out := make([]PresetInfo, 0, len(infos))
for _, info := range infos {
if filter.Matches(info.Preset) {
out = append(out, info)
}
}
return out
}
type presetRegistry struct {
sources []PresetSource
}
// PresetRegistryOption configures a PresetRegistry.
type PresetRegistryOption func(*presetRegistryOptions)
type presetRegistryOptions struct {
userPresetDir string
}
// WithUserPresetDir sets the directory scanned for user (community) presets.
// The directory does not need to exist.
func WithUserPresetDir(dir string) PresetRegistryOption {
return func(o *presetRegistryOptions) {
o.userPresetDir = dir
}
}
// NewPresetRegistry creates a registry over the embedded builtin source and,
// when configured, the user preset directory. Builtins win name resolution
// so an official preset cannot be silently replaced by a local file.
func NewPresetRegistry(opts ...PresetRegistryOption) (PresetRegistry, error) {
options := &presetRegistryOptions{}
for _, opt := range opts {
opt(options)
}
builtin, err := newBuiltinPresetSource()
if err != nil {
return nil, fmt.Errorf("failed to load built-in sandbox presets: %w", err)
}
sources := []PresetSource{builtin}
if options.userPresetDir != "" {
sources = append(sources, &dirPresetSource{dir: options.userPresetDir})
}
return &presetRegistry{sources: sources}, nil
}
func (r *presetRegistry) Get(name string) (*PresetInfo, error) {
for _, source := range r.sources {
info, found, err := source.Get(name)
if err != nil {
return nil, err
}
if found {
return info, nil
}
}
return nil, fmt.Errorf("%w: preset %s", ErrPresetNotFound, name)
}
func (r *presetRegistry) List() ([]PresetInfo, error) {
seen := make(map[string]bool)
out := []PresetInfo{}
for _, source := range r.sources {
infos, err := source.List()
if err != nil {
return nil, err
}
for _, info := range infos {
info.Shadowed = seen[info.Preset.Name]
if !info.Shadowed {
seen[info.Preset.Name] = true
}
out = append(out, info)
}
}
return out, nil
}
type builtinPresetSource struct {
presets map[string]*PresetInfo
}
func newBuiltinPresetSource() (*builtinPresetSource, error) {
entries, err := presetsFS.ReadDir("presets")
if err != nil {
return nil, fmt.Errorf("failed to read presets directory: %w", err)
}
source := &builtinPresetSource{presets: make(map[string]*PresetInfo, len(entries))}
for _, entry := range entries {
if entry.IsDir() {
continue
}
if _, ok := presetFileName(entry.Name()); !ok {
continue
}
// embed.FS paths are always slash-separated, filepath.Join would
// break on Windows.
data, err := presetsFS.ReadFile(path.Join("presets", entry.Name()))
if err != nil {
return nil, fmt.Errorf("failed to read preset %s: %w", entry.Name(), err)
}
preset, err := loadPreset(data)
if err != nil {
return nil, fmt.Errorf("invalid built-in preset %s: %w", entry.Name(), err)
}
source.presets[preset.Name] = &PresetInfo{
Preset: preset,
Source: PresetSourceBuiltin,
Raw: data,
}
}
return source, nil
}
func (s *builtinPresetSource) Name() PresetSourceName { return PresetSourceBuiltin }
func (s *builtinPresetSource) List() ([]PresetInfo, error) {
names := make([]string, 0, len(s.presets))
for name := range s.presets {
names = append(names, name)
}
sort.Strings(names)
out := make([]PresetInfo, 0, len(names))
for _, name := range names {
out = append(out, *s.presets[name])
}
return out, nil
}
func (s *builtinPresetSource) Get(name string) (*PresetInfo, bool, error) {
info, ok := s.presets[name]
if !ok {
return nil, false, nil
}
return info, true, nil
}
type dirPresetSource struct {
dir string
}
func (s *dirPresetSource) Name() PresetSourceName { return PresetSourceUser }
func (s *dirPresetSource) List() ([]PresetInfo, error) {
entries, err := os.ReadDir(s.dir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("failed to read preset directory %s: %w", s.dir, err)
}
out := []PresetInfo{}
for _, entry := range entries {
if entry.IsDir() {
continue
}
fileBase, ok := presetFileName(entry.Name())
if !ok {
continue
}
path := filepath.Join(s.dir, entry.Name())
info, err := s.load(path)
if err != nil {
log.Warnf("skipping invalid preset %s: %v", path, err)
continue
}
if info.Preset.Name != fileBase {
log.Warnf("preset %s: file name %q does not match preset name %q, using preset name", path, fileBase, info.Preset.Name)
}
out = append(out, *info)
}
sort.Slice(out, func(i, j int) bool { return out[i].Preset.Name < out[j].Preset.Name })
return out, nil
}
func (s *dirPresetSource) Get(name string) (*PresetInfo, bool, error) {
infos, err := s.List()
if err != nil {
return nil, false, err
}
for _, info := range infos {
if info.Preset.Name == name {
return &info, true, nil
}
}
return nil, false, nil
}
func (s *dirPresetSource) load(path string) (*PresetInfo, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
preset, err := loadPreset(data)
if err != nil {
return nil, err
}
return &PresetInfo{
Preset: preset,
Source: PresetSourceUser,
Path: path,
Raw: data,
}, nil
}
func loadPreset(data []byte) (*Preset, error) {
preset, err := ParsePreset(data)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrPresetInvalid, err)
}
if err := preset.Validate(); err != nil {
return nil, fmt.Errorf("%w: %w", ErrPresetInvalid, err)
}
return preset, nil
}
+206
View File
@@ -0,0 +1,206 @@
package sandbox
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func writePresetFile(t *testing.T, dir, fileName, content string) string {
t.Helper()
path := filepath.Join(dir, fileName)
require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
return path
}
func TestPresetRegistryBuiltins(t *testing.T) {
registry, err := NewPresetRegistry()
require.NoError(t, err)
t.Run("official presets load and validate", func(t *testing.T) {
infos, err := registry.List()
require.NoError(t, err)
names := make([]string, 0, len(infos))
for _, info := range infos {
names = append(names, info.Preset.Name)
assert.Equal(t, PresetSourceBuiltin, info.Source)
assert.NotEmpty(t, info.Raw, "raw YAML preserved for show")
assert.NoError(t, info.Preset.Validate())
}
assert.Contains(t, names, "git")
assert.Contains(t, names, "astro")
assert.Contains(t, names, "vite")
assert.Contains(t, names, "nextjs")
})
t.Run("get by name", func(t *testing.T) {
info, err := registry.Get("git")
require.NoError(t, err)
assert.Equal(t, "git", info.Preset.Name)
assert.Contains(t, info.Preset.Filesystem.AllowRead, "${CWD}/.git/config")
})
t.Run("unknown preset is ErrPresetNotFound", func(t *testing.T) {
_, err := registry.Get("does-not-exist")
require.ErrorIs(t, err, ErrPresetNotFound)
})
}
func TestPresetRegistryUserDir(t *testing.T) {
dir := t.TempDir()
writePresetFile(t, dir, "myapp.yml", `
kind: preset
name: myapp
description: Custom app preset
metadata:
author: Community
labels: [myapp]
filesystem:
allow_write:
- ${CWD}/.myapp/**
`)
writePresetFile(t, dir, "git.yml", `
kind: preset
name: git
description: Attempted builtin override
filesystem:
allow_write:
- ${CWD}/anything/**
`)
writePresetFile(t, dir, "broken.yml", `
kind: preset
name: broken
filesystem:
deny_read: ["${CWD}/x"]
`)
registry, err := NewPresetRegistry(WithUserPresetDir(dir))
require.NoError(t, err)
t.Run("user preset resolves", func(t *testing.T) {
info, err := registry.Get("myapp")
require.NoError(t, err)
assert.Equal(t, PresetSourceUser, info.Source)
assert.Equal(t, filepath.Join(dir, "myapp.yml"), info.Path)
})
t.Run("builtin wins name collisions", func(t *testing.T) {
info, err := registry.Get("git")
require.NoError(t, err)
assert.Equal(t, PresetSourceBuiltin, info.Source)
assert.Contains(t, info.Preset.Filesystem.AllowRead, "${CWD}/.git/config")
})
t.Run("list marks shadowed user presets and skips invalid files", func(t *testing.T) {
infos, err := registry.List()
require.NoError(t, err)
var shadowedGit, sawBroken bool
for _, info := range infos {
if info.Preset.Name == "git" && info.Source == PresetSourceUser {
shadowedGit = info.Shadowed
}
if info.Preset.Name == "broken" {
sawBroken = true
}
}
assert.True(t, shadowedGit)
assert.False(t, sawBroken, "invalid preset files are skipped")
})
t.Run("missing user dir is a clean no-op", func(t *testing.T) {
registry, err := NewPresetRegistry(WithUserPresetDir(filepath.Join(dir, "missing")))
require.NoError(t, err)
_, err = registry.Get("git")
assert.NoError(t, err)
})
}
func TestProfilePresetsExpansion(t *testing.T) {
t.Run("custom profile with presets gets allowances", func(t *testing.T) {
dir := t.TempDir()
path := writePresetFile(t, dir, "pnpm-custom.yml", `
name: pnpm-custom
description: Custom pnpm profile with presets
inherits: pnpm
package_managers: [pnpm]
presets: [git, astro]
`)
registry, err := NewProfileRegistry()
require.NoError(t, err)
policy, err := registry.LoadCustomProfile(path)
require.NoError(t, err)
assert.Contains(t, policy.Filesystem.AllowRead, "${CWD}/.git/config")
assert.Contains(t, policy.Filesystem.AllowWrite, "${CWD}/.git/**")
assert.Contains(t, policy.Filesystem.AllowWrite, "${CWD}/.astro/**")
assert.Contains(t, policy.Network.AllowBind, "localhost:4321")
assert.Equal(t, []string{"git", "astro"}, policy.Presets, "names kept for provenance")
// Inherited base profile rules are still present
assert.Contains(t, policy.Filesystem.AllowWrite, "${CWD}/node_modules/**")
})
t.Run("unknown preset in profile is a hard error", func(t *testing.T) {
dir := t.TempDir()
path := writePresetFile(t, dir, "bad.yml", `
name: bad
package_managers: [pnpm]
presets: [does-not-exist]
filesystem:
allow_read: ["${CWD}/**"]
`)
registry, err := NewProfileRegistry()
require.NoError(t, err)
_, err = registry.LoadCustomProfile(path)
require.Error(t, err)
assert.ErrorIs(t, err, ErrPresetNotFound)
})
t.Run("profile authored deny survives a preset allowing the same path", func(t *testing.T) {
dir := t.TempDir()
path := writePresetFile(t, dir, "deny-wins.yml", `
name: deny-wins
package_managers: [pnpm]
presets: [git]
filesystem:
deny_read: ["${CWD}/.git/config"]
`)
registry, err := NewProfileRegistry()
require.NoError(t, err)
policy, err := registry.LoadCustomProfile(path)
require.NoError(t, err)
assert.Contains(t, policy.Filesystem.AllowRead, "${CWD}/.git/config")
assert.Contains(t, policy.Filesystem.DenyRead, "${CWD}/.git/config",
"presets are additive-only, they never remove authored deny rules")
})
t.Run("profile with only presets passes resolved validation", func(t *testing.T) {
dir := t.TempDir()
path := writePresetFile(t, dir, "presets-only.yml", `
name: presets-only
package_managers: [pnpm]
presets: [git]
`)
registry, err := NewProfileRegistry()
require.NoError(t, err)
policy, err := registry.LoadCustomProfile(path)
require.NoError(t, err)
assert.Contains(t, policy.Filesystem.AllowWrite, "${CWD}/.git/**")
})
}
+376
View File
@@ -0,0 +1,376 @@
package sandbox
import (
"testing"
"github.com/safedep/dry/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func validPresetYAML() string {
return `
schema_version: 1
kind: preset
name: git
description: Git operations
metadata:
author: SafeDep
labels: [git, hooks]
filesystem:
allow_read:
- ${CWD}/.git/config
allow_write:
- ${CWD}/.git/**
`
}
func TestParsePreset(t *testing.T) {
t.Run("parses a valid preset", func(t *testing.T) {
preset, err := ParsePreset([]byte(validPresetYAML()))
require.NoError(t, err)
assert.Equal(t, "git", preset.Name)
assert.Equal(t, "SafeDep", preset.Metadata.Author)
assert.Equal(t, []string{"git", "hooks"}, preset.Metadata.Labels)
assert.Equal(t, []string{"${CWD}/.git/config"}, preset.Filesystem.AllowRead)
require.NoError(t, preset.Validate())
})
t.Run("rejects unknown fields keeping additive-only structural", func(t *testing.T) {
yaml := `
kind: preset
name: evil
filesystem:
allow_read: ["${CWD}/x"]
deny_read: ["${CWD}/y"]
`
_, err := ParsePreset([]byte(yaml))
require.Error(t, err)
assert.Contains(t, err.Error(), "deny_read")
})
t.Run("rejects allow_outbound, translators are all-or-nothing for outbound", func(t *testing.T) {
yaml := `
kind: preset
name: evil
network:
allow_outbound: ["registry.example.com:443"]
`
_, err := ParsePreset([]byte(yaml))
require.Error(t, err)
assert.Contains(t, err.Error(), "allow_outbound")
})
t.Run("rejects boolean policy fields", func(t *testing.T) {
yaml := `
kind: preset
name: evil
allow_git_config: true
filesystem:
allow_read: ["${CWD}/x"]
`
_, err := ParsePreset([]byte(yaml))
require.Error(t, err)
})
}
func TestPresetValidate(t *testing.T) {
base := func() *Preset {
return &Preset{
Kind: "preset",
Name: "sample",
Filesystem: PresetFilesystem{
AllowRead: []string{"${CWD}/.cache/**"},
},
}
}
cases := []struct {
name string
mutate func(*Preset)
wantErr string
}{
{
name: "valid minimal preset",
mutate: func(p *Preset) {},
},
{
name: "wrong kind",
mutate: func(p *Preset) { p.Kind = "profile" },
wantErr: "kind must be",
},
{
name: "invalid name",
mutate: func(p *Preset) { p.Name = "Bad_Name" },
wantErr: "lowercase alphanumeric",
},
{
name: "newer schema version rejected",
mutate: func(p *Preset) { p.SchemaVersion = PresetSchemaVersion + 1 },
wantErr: "schema_version",
},
{
name: "no rules",
mutate: func(p *Preset) {
p.Filesystem = PresetFilesystem{}
},
wantErr: "at least one allowance",
},
{
name: "unanchored absolute path",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"/etc/passwd"}
},
wantErr: "anchored",
},
{
name: "relative path",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{".cache/**"}
},
wantErr: "anchored",
},
{
name: "path traversal",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"${CWD}/../outside"}
},
wantErr: "traverse",
},
{
name: "sensitive target",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"${CWD}/.env"}
},
wantErr: "sensitive",
},
{
name: "sensitive write target",
mutate: func(p *Preset) {
p.Filesystem.AllowWrite = []string{"${HOME}/.ssh"}
},
wantErr: "sensitive",
},
{
name: "mandatory-deny credential target rejected",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"${CWD}/.git-credentials"}
},
wantErr: "protected credential target",
},
{
name: "mandatory-deny credential subtree rejected",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"${HOME}/.config/gh/hosts.yml"}
},
wantErr: "protected credential target",
},
{
name: "pgpass rejected",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"${CWD}/.pgpass"}
},
wantErr: "protected credential target",
},
{
name: "docker config rejected",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"${HOME}/.docker/config.json"}
},
wantErr: "protected credential target",
},
{
name: "git hooks rejected in any direction",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"${CWD}/.git/hooks/**"}
},
wantErr: ".git/hooks",
},
{
name: "git config write rejected",
mutate: func(p *Preset) {
p.Filesystem.AllowWrite = []string{"${CWD}/.git/config"}
},
wantErr: ".git/config write",
},
{
name: "git config exec rejected",
mutate: func(p *Preset) {
p.Process.AllowExec = []string{"${CWD}/.git/config"}
},
wantErr: ".git/config write",
},
{
name: "git config read allowed for repo discovery",
mutate: func(p *Preset) {
p.Filesystem.AllowRead = []string{"${CWD}/.git/config"}
},
},
{
name: "non-loopback bind",
mutate: func(p *Preset) {
p.Network.AllowBind = []string{"0.0.0.0:8080"}
},
wantErr: "loopback",
},
{
name: "loopback bind with wildcard port ok",
mutate: func(p *Preset) {
p.Network.AllowBind = []string{"localhost:*"}
},
},
{
name: "ipv6 loopback bind ok",
mutate: func(p *Preset) {
p.Network.AllowBind = []string{"[::1]:4321"}
},
},
{
name: "env glob rejected",
mutate: func(p *Preset) {
p.Environment.Allow = []string{"ASTRO_*"}
},
wantErr: "exact variable name",
},
{
name: "env character class rejected",
mutate: func(p *Preset) {
p.Environment.Allow = []string{"AWS_[A-Z]*_KEY"}
},
wantErr: "exact variable name",
},
{
name: "env exact name ok",
mutate: func(p *Preset) {
p.Environment.Allow = []string{"ASTRO_TELEMETRY_DISABLED"}
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
preset := base()
tc.mutate(preset)
err := preset.Validate()
if tc.wantErr == "" {
assert.NoError(t, err)
return
}
require.Error(t, err)
assert.Contains(t, err.Error(), tc.wantErr)
})
}
}
func TestPresetApplyToPolicy(t *testing.T) {
preset := &Preset{
Kind: "preset",
Name: "sample",
Filesystem: PresetFilesystem{
AllowRead: []string{"${CWD}/.git/config"},
AllowWrite: []string{"${CWD}/.git/**", "${CWD}/dist/**"},
},
Network: PresetNetwork{
AllowBind: []string{"localhost:4321"},
},
Process: PresetProcess{AllowExec: []string{"${CWD}/node_modules/.bin/**"}},
Environment: PresetEnvironment{Allow: []string{"ASTRO_TELEMETRY_DISABLED"}},
}
require.NoError(t, preset.Validate())
policy := &SandboxPolicy{
Name: "test",
PackageManagers: []string{"pnpm"},
Filesystem: FilesystemPolicy{
AllowWrite: []string{"${CWD}/dist/**"},
DenyRead: []string{"${CWD}/.git/config", "${CWD}/**/*.secret"},
},
}
preset.ApplyToPolicy(policy)
assert.Equal(t, []string{"${CWD}/.git/config"}, policy.Filesystem.AllowRead)
assert.Equal(t, []string{"${CWD}/dist/**", "${CWD}/.git/**"}, policy.Filesystem.AllowWrite,
"allow entries union with dedupe")
assert.Equal(t, []string{"${CWD}/.git/config", "${CWD}/**/*.secret"}, policy.Filesystem.DenyRead,
"deny lists are never modified by presets, an authored deny wins")
assert.Equal(t, []string{"localhost:4321"}, policy.Network.AllowBind)
assert.True(t, utils.SafelyGetValue(policy.AllowNetworkBind),
"bind entries enable AllowNetworkBind for translators")
assert.Empty(t, policy.Network.AllowOutbound, "presets cannot contribute outbound rules")
assert.Equal(t, []string{"${CWD}/node_modules/.bin/**"}, policy.Process.AllowExec)
assert.Equal(t, []string{"ASTRO_TELEMETRY_DISABLED"}, policy.Environment.Allow)
}
func TestPresetApplyToPolicyWithoutBindKeepsFlag(t *testing.T) {
preset := &Preset{
Kind: "preset",
Name: "sample",
Filesystem: PresetFilesystem{AllowRead: []string{"${CWD}/x"}},
}
policy := &SandboxPolicy{Name: "test"}
preset.ApplyToPolicy(policy)
assert.Nil(t, policy.AllowNetworkBind)
}
func TestPresetFilter(t *testing.T) {
preset := &Preset{
Kind: "preset",
Name: "astro",
Metadata: PresetMetadata{
Author: "SafeDep",
Labels: []string{"astro", "dev-server"},
},
}
cases := []struct {
name string
filter PresetFilter
want bool
}{
{name: "zero filter matches", filter: PresetFilter{}, want: true},
{name: "author case-insensitive", filter: PresetFilter{Author: "safedep"}, want: true},
{name: "author mismatch", filter: PresetFilter{Author: "someone"}, want: false},
{name: "single label", filter: PresetFilter{Labels: []string{"astro"}}, want: true},
{name: "all labels must match", filter: PresetFilter{Labels: []string{"astro", "missing"}}, want: false},
{name: "label case-insensitive", filter: PresetFilter{Labels: []string{"DEV-SERVER"}}, want: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.want, tc.filter.Matches(preset))
})
}
}
func TestPresetEnvAllowCannotOverrideAuthoredDeny(t *testing.T) {
preset := &Preset{
Kind: "preset",
Name: "sample",
Environment: PresetEnvironment{
Allow: []string{"AWS_SECRET_ACCESS_KEY", "NPM_TOKEN", "GCP_SERVICE_ACCOUNT_KEY"},
},
}
require.NoError(t, preset.Validate())
policy := &SandboxPolicy{
Name: "test",
Environment: EnvironmentPolicy{
Deny: []string{"AWS_*", "GCP_[A-Z]*_KEY"},
},
}
preset.ApplyToPolicy(policy)
assert.Contains(t, policy.Environment.Allow, "NPM_TOKEN",
"preset allow with no authored deny coverage is kept and still beats built-in denies")
assert.NotContains(t, policy.Environment.Allow, "AWS_SECRET_ACCESS_KEY",
"preset allow covered by an authored deny glob is dropped")
assert.NotContains(t, policy.Environment.Allow, "GCP_SERVICE_ACCOUNT_KEY",
"preset allow covered by an authored deny with a character class is dropped")
assert.Equal(t, []string{"AWS_*", "GCP_[A-Z]*_KEY"}, policy.Environment.Deny,
"authored denies are untouched")
}
+22
View File
@@ -0,0 +1,22 @@
schema_version: 1
kind: preset
name: astro
description: Astro dev server and build (astro dev, astro build, astro sync)
metadata:
author: SafeDep
labels: [astro, javascript, dev-server, framework]
# Threat notes:
# - .astro/** holds generated types and content-collection state; dist/** is
# build output. Writes there cannot escape the project.
# - The loopback bind covers Astro's default dev port. Seatbelt's
# "localhost" ip filter matches both 127.0.0.1 and ::1.
filesystem:
allow_write:
- ${CWD}/.astro/**
- ${CWD}/dist/**
network:
allow_bind:
- localhost:4321
+22
View File
@@ -0,0 +1,22 @@
schema_version: 1
kind: preset
name: git
description: Git repository operations for hooks-driven tools (lint-staged, husky, turbo, changesets)
metadata:
author: SafeDep
labels: [git, hooks, javascript, python]
# Threat notes:
# - allow_read on .git/config suppresses the mandatory read deny via exact
# match. Config may embed credentials in remote URLs; accept only when the
# workload runs git (repo discovery requires reading config).
# - allow_write on .git/** lets a sandboxed process tamper with refs/objects
# (data, not code execution). The mandatory write denies on .git/config and
# all .git/hooks rules are NOT suppressed by this glob: hook injection and
# config tampering stay blocked.
filesystem:
allow_read:
- ${CWD}/.git/config
allow_write:
- ${CWD}/.git/**
+19
View File
@@ -0,0 +1,19 @@
schema_version: 1
kind: preset
name: nextjs
description: Next.js dev server and build (next dev, next build)
metadata:
author: SafeDep
labels: [nextjs, javascript, dev-server, framework]
# Threat notes:
# - .next/** is Next.js build/dev state and stays inside the project.
# - The loopback bind covers the default dev port.
filesystem:
allow_write:
- ${CWD}/.next/**
network:
allow_bind:
- localhost:3000
+22
View File
@@ -0,0 +1,22 @@
schema_version: 1
kind: preset
name: vite
description: Vite dev server and build (vite, vite build, vite preview)
metadata:
author: SafeDep
labels: [vite, javascript, dev-server, framework]
# Threat notes:
# - node_modules/.vite is Vite's dep-optimizer cache; dist/** is build
# output. Both stay inside the project.
# - Binds cover the default dev (5173) and preview (4173) ports on loopback.
filesystem:
allow_write:
- ${CWD}/node_modules/.vite/**
- ${CWD}/dist/**
network:
allow_bind:
- localhost:5173
- localhost:4173
+38 -2
View File
@@ -22,6 +22,7 @@ type defaultProfileRegistry struct {
builtins map[string]struct{}
builtinYAML map[string][]byte
userProfileDir string
presets PresetRegistry
}
func newDefaultProfileRegistry(opts ...RegistryOption) (*defaultProfileRegistry, error) {
@@ -30,11 +31,21 @@ func newDefaultProfileRegistry(opts ...RegistryOption) (*defaultProfileRegistry,
opt(options)
}
presets := options.presetRegistry
if presets == nil {
builtinOnly, err := NewPresetRegistry()
if err != nil {
return nil, err
}
presets = builtinOnly
}
registry := &defaultProfileRegistry{
profiles: make(map[string]*SandboxPolicy),
builtins: make(map[string]struct{}),
builtinYAML: make(map[string][]byte),
userProfileDir: options.userProfileDir,
presets: presets,
}
if err := registry.loadBuiltinProfiles(); err != nil {
@@ -86,12 +97,18 @@ func (r *defaultProfileRegistry) loadBuiltinProfiles() error {
defer r.mu.Unlock()
for name, policy := range r.profiles {
if policy.Inherits != "" {
inherited := policy.Inherits != ""
if inherited {
if err := r.resolveInheritance(policy); err != nil {
return fmt.Errorf("failed to resolve inheritance for profile %s: %w", name, err)
}
}
// Validate after inheritance resolution
if err := r.applyPresets(policy); err != nil {
return fmt.Errorf("failed to apply presets for profile %s: %w", name, err)
}
if inherited || len(policy.Presets) > 0 {
if err := policy.ValidateResolved(); err != nil {
return fmt.Errorf("invalid profile %s after inheritance: %w: %w", name, ErrProfileInvalid, err)
}
@@ -101,6 +118,21 @@ func (r *defaultProfileRegistry) loadBuiltinProfiles() error {
return nil
}
// An unknown preset is a hard error so profile authors get immediate
// feedback instead of a silently under-provisioned sandbox at run time.
func (r *defaultProfileRegistry) applyPresets(policy *SandboxPolicy) error {
for _, name := range policy.Presets {
info, err := r.presets.Get(name)
if err != nil {
return fmt.Errorf("preset %s referenced by profile %s: %w", name, policy.Name, err)
}
info.Preset.ApplyToPolicy(policy)
}
return nil
}
// resolveInheritance resolves the inheritance chain for a policy.
// This function is called during registry initialization and modifies the policy in place.
// Assumes registry mutex is already held.
@@ -249,6 +281,10 @@ func (r *defaultProfileRegistry) LoadCustomProfile(path string) (*SandboxPolicy,
policy.Inherits = ""
}
if err := r.applyPresets(policy); err != nil {
return nil, fmt.Errorf("custom profile %s: %w", path, err)
}
// Validate after inheritance resolution
if err := policy.ValidateResolved(); err != nil {
return nil, fmt.Errorf("invalid custom profile %s after inheritance: %w: %w", path, ErrProfileInvalid, err)
+1
View File
@@ -95,6 +95,7 @@ func expandPolicyPaths(p *SandboxPolicy, opts ResolveOptions) (*SandboxPolicy, e
}
out.PackageManagers = append([]string(nil), p.PackageManagers...)
out.Presets = append([]string(nil), p.Presets...)
return &out, nil
}
+9
View File
@@ -294,6 +294,7 @@ type RegistryOption func(*registryOptions)
type registryOptions struct {
userProfileDir string
presetRegistry PresetRegistry
}
// WithUserProfileDir sets the directory the registry uses to discover user
@@ -304,6 +305,14 @@ func WithUserProfileDir(dir string) RegistryOption {
}
}
// WithPresetRegistry sets the preset registry used to expand `presets:`
// references in profiles. Defaults to a builtin-only preset registry.
func WithPresetRegistry(presets PresetRegistry) RegistryOption {
return func(o *registryOptions) {
o.presetRegistry = presets
}
}
// NewProfileRegistry creates a new profile registry with built-in policies.
func NewProfileRegistry(opts ...RegistryOption) (ProfileRegistry, error) {
return newDefaultProfileRegistry(opts...)
+31 -6
View File
@@ -3,6 +3,14 @@ package util
import (
"os"
"path/filepath"
"strings"
)
// GitConfigPath and GitHooksPath are the git-specific mandatory deny
// targets, relative to a repository root ($CWD or $HOME).
const (
GitConfigPath = ".git/config"
GitHooksPath = ".git/hooks"
)
// DANGEROUS_FILES are credential and config files blocked by default.
@@ -255,9 +263,9 @@ func GetMandatoryDenyPatterns(opts MandatoryDenyOptions) MandatoryDenyResult {
}
if !opts.AllowGitConfig {
suppressible = append(suppressible, filepath.Join(cwd, ".git/config"))
suppressible = append(suppressible, filepath.Join(cwd, GitConfigPath))
if home != "" {
suppressible = append(suppressible, filepath.Join(home, ".git/config"))
suppressible = append(suppressible, filepath.Join(home, GitConfigPath))
}
}
@@ -281,13 +289,13 @@ func GetMandatoryDenyPatterns(opts MandatoryDenyOptions) MandatoryDenyResult {
// Git hooks can execute arbitrary code; never suppressible.
gitHooks := []string{
filepath.Join(cwd, ".git/hooks"),
filepath.Join(cwd, ".git/hooks/**"),
filepath.Join(cwd, GitHooksPath),
filepath.Join(cwd, GitHooksPath, "**"),
}
if home != "" {
gitHooks = append(gitHooks,
filepath.Join(home, ".git/hooks"),
filepath.Join(home, ".git/hooks/**"),
filepath.Join(home, GitHooksPath),
filepath.Join(home, GitHooksPath, "**"),
)
}
for _, p := range gitHooks {
@@ -299,6 +307,23 @@ func GetMandatoryDenyPatterns(opts MandatoryDenyOptions) MandatoryDenyResult {
return result
}
// PathCoveredBy reports whether the anchor-relative path rel is base itself
// or falls beneath it.
func PathCoveredBy(rel, base string) bool {
return rel == base || strings.HasPrefix(rel, base+"/")
}
// DangerousFileMatch returns the DANGEROUS_FILES entry covering the
// anchor-relative path rel, if any.
func DangerousFileMatch(rel string) (string, bool) {
for _, dangerous := range DANGEROUS_FILES {
if PathCoveredBy(rel, dangerous) {
return dangerous, true
}
}
return "", false
}
func toSet(s []string) map[string]bool {
m := make(map[string]bool, len(s))
for _, v := range s {
+29
View File
@@ -247,3 +247,32 @@ func TestGetMandatoryDenyPatterns_Suppression(t *testing.T) {
assert.ElementsMatch(t, []string{cwdEnv, globEnv}, r.SuppressedWrite)
})
}
func TestDangerousFileMatch(t *testing.T) {
cases := []struct {
rel string
target string
found bool
}{
{rel: ".git-credentials", target: ".git-credentials", found: true},
{rel: ".config/gh/hosts.yml", target: ".config/gh", found: true},
{rel: ".ssh/id_rsa", target: ".ssh", found: true},
{rel: ".git/config", found: false},
{rel: ".myapp/cache", found: false},
}
for _, tc := range cases {
t.Run(tc.rel, func(t *testing.T) {
target, found := DangerousFileMatch(tc.rel)
assert.Equal(t, tc.found, found)
assert.Equal(t, tc.target, target)
})
}
}
func TestPathCoveredBy(t *testing.T) {
assert.True(t, PathCoveredBy(GitHooksPath, GitHooksPath))
assert.True(t, PathCoveredBy(".git/hooks/pre-commit", GitHooksPath))
assert.False(t, PathCoveredBy(".git/hooksy", GitHooksPath))
assert.False(t, PathCoveredBy(".git", GitHooksPath))
}
+8
View File
@@ -70,6 +70,14 @@ func shouldScrubEnvVar(name string, deny, allow []string) bool {
return matchAnyEnvPattern(name, deny)
}
// EnvNameMatchesAny reports whether a literal variable name matches any of
// the given name glob patterns, using the same matcher ScrubEnv applies at
// scrub time so precedence decisions made against it cannot diverge from
// runtime behavior.
func EnvNameMatchesAny(name string, patterns []string) bool {
return matchAnyEnvPattern(name, patterns)
}
func matchAnyEnvPattern(name string, patterns []string) bool {
for _, pattern := range patterns {
if envNameRegex(pattern).MatchString(name) {
+22
View File
@@ -94,3 +94,25 @@ func TestScrubEnv_NoCatchAllsInBuiltinList(t *testing.T) {
assert.Equal(t, []string{"SOME_RANDOM_TOKEN=x"}, got.Env)
assert.Empty(t, got.Removed)
}
func TestEnvNameMatchesAny(t *testing.T) {
cases := []struct {
name string
varName string
patterns []string
want bool
}{
{name: "literal match case-insensitive", varName: "aws_secret_access_key", patterns: []string{"AWS_SECRET_ACCESS_KEY"}, want: true},
{name: "prefix glob", varName: "AWS_SECRET_ACCESS_KEY", patterns: []string{"AWS_*"}, want: true},
{name: "infix glob", varName: "AWS_SECRET_ACCESS_KEY", patterns: []string{"AWS_SECRET_*"}, want: true},
{name: "character class", varName: "AWS_SECRET_ACCESS_KEY", patterns: []string{"AWS_[A-Z]*_KEY"}, want: true},
{name: "no match", varName: "NPM_TOKEN", patterns: []string{"AWS_*", "GCP_*"}, want: false},
{name: "empty patterns", varName: "NPM_TOKEN", patterns: nil, want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.want, EnvNameMatchesAny(tc.varName, tc.patterns))
})
}
}