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

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

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

Closes #384

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

* fix(sandbox): address review findings on presets

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

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

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

Addresses external security review findings on the preset mechanism:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-21 15:14:07 +05:30

454 lines
12 KiB
Go

package sandbox
import (
"embed"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/safedep/dry/log"
"gopkg.in/yaml.v3"
)
//go:embed profiles/*.yml
var profilesFS embed.FS
type defaultProfileRegistry struct {
mu sync.RWMutex
profiles map[string]*SandboxPolicy
builtins map[string]struct{}
builtinYAML map[string][]byte
userProfileDir string
presets PresetRegistry
}
func newDefaultProfileRegistry(opts ...RegistryOption) (*defaultProfileRegistry, error) {
options := &registryOptions{}
for _, opt := range opts {
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 {
return nil, fmt.Errorf("failed to load built-in sandbox profiles: %w", err)
}
return registry, nil
}
// loadBuiltinProfiles loads all built-in YAML profiles from the embedded filesystem.
// Inheritance is resolved in a second pass after all profiles are loaded.
func (r *defaultProfileRegistry) loadBuiltinProfiles() error {
entries, err := profilesFS.ReadDir("profiles")
if err != nil {
return fmt.Errorf("failed to read profiles directory: %w", err)
}
// First pass: load all profiles without resolving inheritance
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".yml") {
continue
}
profilePath := filepath.Join("profiles", entry.Name())
data, err := profilesFS.ReadFile(profilePath)
if err != nil {
return fmt.Errorf("failed to read profile %s: %w", entry.Name(), err)
}
policy, err := parsePolicy(data)
if err != nil {
return fmt.Errorf("failed to parse profile %s: %w: %w", entry.Name(), ErrProfileInvalid, err)
}
// Basic validation (without inheritance resolution)
if err := policy.Validate(); err != nil {
return fmt.Errorf("invalid profile %s: %w: %w", entry.Name(), ErrProfileInvalid, err)
}
r.mu.Lock()
r.profiles[policy.Name] = policy
r.builtins[policy.Name] = struct{}{}
r.builtinYAML[policy.Name] = data
r.mu.Unlock()
}
// Second pass: resolve inheritance and validate
r.mu.Lock()
defer r.mu.Unlock()
for name, policy := range r.profiles {
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)
}
}
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)
}
}
}
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.
func (r *defaultProfileRegistry) resolveInheritance(child *SandboxPolicy) error {
if child.Inherits == "" {
return nil
}
// Look up parent profile (must be a built-in profile)
parent, exists := r.profiles[child.Inherits]
if !exists {
return fmt.Errorf("%w: parent profile '%s' (only built-in profiles can be inherited)", ErrProfileNotFound, child.Inherits)
}
// Prevent inheritance chains (parent must not itself inherit)
if parent.Inherits != "" {
return fmt.Errorf("%w: inheritance chains not allowed: parent profile '%s' inherits from '%s'", ErrProfileInvalid, parent.Name, parent.Inherits)
}
// Merge parent into child
child.MergeWithParent(parent)
// Clear the inherits field after resolution to indicate it's been processed
child.Inherits = ""
return nil
}
// GetProfile retrieves a policy by name.
// Resolution order: built-in profiles first, then user profile directory
// (by bare name, looking up <name>.yml or <name>.yaml), then a literal file path.
func (r *defaultProfileRegistry) GetProfile(name string) (*SandboxPolicy, error) {
r.mu.RLock()
if _, isBuiltin := r.builtins[name]; isBuiltin {
policy := r.profiles[name]
r.mu.RUnlock()
return policy, nil
}
r.mu.RUnlock()
path, found, err := r.findUserProfileByName(name)
if err != nil {
return nil, err
}
if found {
return r.LoadCustomProfile(path)
}
if fileExists(name) {
return r.LoadCustomProfile(name)
}
return nil, fmt.Errorf("%w: %s (not a built-in profile, no matching user profile, and file does not exist)", ErrProfileNotFound, name)
}
// findUserProfileByName looks for `<name>.yml` then `<name>.yaml` under
// the user profile directory. Returns the absolute path if found.
func (r *defaultProfileRegistry) findUserProfileByName(name string) (string, bool, error) {
if r.userProfileDir == "" || !isBareProfileName(name) {
return "", false, nil
}
files, err := r.userProfileFiles()
if err != nil {
return "", false, fmt.Errorf("failed to read user profile directory %s: %w", r.userProfileDir, err)
}
for _, file := range files {
if file.name == name {
return file.path, true, nil
}
}
return "", false, nil
}
func isBareProfileName(name string) bool {
return name != "" && name == filepath.Base(name) && name != "." && name != ".."
}
// UserProfileDir returns the directory scanned for user profiles.
func (r *defaultProfileRegistry) UserProfileDir() string {
return r.userProfileDir
}
// ListUserProfiles enumerates *.yml / *.yaml files under UserProfileDir().
// A missing directory returns an empty slice with no error. Profiles whose
// name collides with a built-in are marked as Shadowed.
func (r *defaultProfileRegistry) ListUserProfiles() ([]ProfileInfo, error) {
files, err := r.userProfileFiles()
if err != nil {
return nil, fmt.Errorf("failed to read user profile directory %s: %w", r.userProfileDir, err)
}
r.mu.RLock()
defer r.mu.RUnlock()
profiles := make([]ProfileInfo, 0, len(files))
for _, file := range files {
_, shadowed := r.builtins[file.name]
profiles = append(profiles, ProfileInfo{
Name: file.name,
Path: file.path,
Shadowed: shadowed,
})
}
return profiles, nil
}
// LoadCustomProfile loads a policy from a custom YAML file path.
// Inheritance is resolved if the profile inherits from a built-in profile.
func (r *defaultProfileRegistry) LoadCustomProfile(path string) (*SandboxPolicy, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read custom profile %s: %w", path, err)
}
policy, err := parsePolicy(data)
if err != nil {
return nil, fmt.Errorf("failed to parse custom profile %s: %w: %w", path, ErrProfileInvalid, err)
}
// Basic validation
if err := policy.Validate(); err != nil {
return nil, fmt.Errorf("invalid custom profile %s: %w: %w", path, ErrProfileInvalid, err)
}
// Resolve inheritance if present
if policy.Inherits != "" {
r.mu.RLock()
parent, exists := r.profiles[policy.Inherits]
r.mu.RUnlock()
if !exists {
return nil, fmt.Errorf("%w: custom profile %s inherits from unknown profile '%s' (only built-in profiles can be inherited)", ErrProfileNotFound, path, policy.Inherits)
}
// Prevent inheritance chains
if parent.Inherits != "" {
return nil, fmt.Errorf("%w: custom profile %s parent '%s' inherits from '%s' (chains not allowed)", ErrProfileInvalid, path, parent.Name, parent.Inherits)
}
// Merge parent into child
policy.MergeWithParent(parent)
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)
}
r.mu.Lock()
r.profiles[path] = policy
r.mu.Unlock()
return policy, nil
}
// ListProfiles returns all discoverable profiles: built-ins first, then user
// profiles (including shadowed entries so the cmd layer can warn the user).
func (r *defaultProfileRegistry) ListProfiles() ([]ProfileSummary, error) {
r.mu.RLock()
builtinNames := make([]string, 0, len(r.builtins))
for name := range r.builtins {
builtinNames = append(builtinNames, name)
}
sort.Strings(builtinNames)
summaries := make([]ProfileSummary, 0, len(builtinNames))
for _, name := range builtinNames {
p := r.profiles[name]
summaries = append(summaries, ProfileSummary{
Name: name,
Source: ProfileSourceBuiltin,
Inherits: p.Inherits,
PackageManagers: append([]string(nil), p.PackageManagers...),
Description: p.Description,
})
}
r.mu.RUnlock()
files, err := r.userProfileFiles()
if err != nil {
return nil, fmt.Errorf("failed to read user profile directory %s: %w", r.userProfileDir, err)
}
userEntries := make([]ProfileSummary, 0, len(files))
for _, file := range files {
r.mu.RLock()
_, shadowed := r.builtins[file.name]
r.mu.RUnlock()
summary := ProfileSummary{
Name: file.name,
Source: ProfileSourceUser,
Path: file.path,
Shadowed: shadowed,
}
data, err := os.ReadFile(file.path)
if err != nil {
log.Warnf("failed to read user profile %s: %v", file.path, err)
userEntries = append(userEntries, summary)
continue
}
var parsed SandboxPolicy
if err := yaml.Unmarshal(data, &parsed); err != nil {
log.Warnf("failed to parse user profile %s: %v", file.path, err)
userEntries = append(userEntries, summary)
continue
}
summary.Inherits = parsed.Inherits
summary.PackageManagers = parsed.PackageManagers
summary.Description = parsed.Description
userEntries = append(userEntries, summary)
}
sort.Slice(userEntries, func(i, j int) bool {
return userEntries[i].Name < userEntries[j].Name
})
return append(summaries, userEntries...), nil
}
type userProfileFile struct {
name string
path string
}
func (r *defaultProfileRegistry) userProfileFiles() ([]userProfileFile, error) {
if r.userProfileDir == "" {
return nil, nil
}
entries, err := os.ReadDir(r.userProfileDir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
byName := make(map[string]userProfileFile, len(entries))
for _, entry := range entries {
if entry.IsDir() {
continue
}
ext := filepath.Ext(entry.Name())
if ext != ".yml" && ext != ".yaml" {
continue
}
name := strings.TrimSuffix(entry.Name(), ext)
if !isBareProfileName(name) {
continue
}
file := userProfileFile{
name: name,
path: filepath.Join(r.userProfileDir, entry.Name()),
}
if existing, ok := byName[name]; ok && filepath.Ext(existing.path) == ".yml" {
continue
}
byName[name] = file
}
files := make([]userProfileFile, 0, len(byName))
for _, file := range byName {
files = append(files, file)
}
sort.Slice(files, func(i, j int) bool { return files[i].name < files[j].name })
return files, nil
}
// BuiltinProfileYAML returns the embedded YAML for a built-in profile.
func (r *defaultProfileRegistry) BuiltinProfileYAML(name string) ([]byte, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
data, ok := r.builtinYAML[name]
if !ok {
return nil, false
}
out := make([]byte, len(data))
copy(out, data)
return out, true
}
func parsePolicy(data []byte) (*SandboxPolicy, error) {
var policy SandboxPolicy
if err := yaml.Unmarshal(data, &policy); err != nil {
return nil, fmt.Errorf("failed to parse policy from YAML: %w", err)
}
return &policy, nil
}
func fileExists(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return !info.IsDir()
}