mirror of
https://github.com/safedep/pmg.git
synced 2026-08-03 07:24:09 +02:00
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:
co-authored by
Claude Fable 5
parent
695a1d739d
commit
ee684a29a9
+54
-2
@@ -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
|
||||
}
|
||||
|
||||
@@ -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.")
|
||||
}
|
||||
@@ -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`.",
|
||||
)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
})
|
||||
}
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -24,5 +24,6 @@ func NewCommand() *cobra.Command {
|
||||
cmd.AddCommand(NewViolationsCommand())
|
||||
cmd.AddCommand(NewAllowCommand())
|
||||
cmd.AddCommand(NewProjectCommand())
|
||||
cmd.AddCommand(NewPresetCommand())
|
||||
return cmd
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user