Files
pmg/config/sandbox_allow.go
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

274 lines
8.7 KiB
Go

package config
import (
"fmt"
"os"
"path/filepath"
"strings"
"unicode"
"github.com/safedep/dry/log"
sandboxutil "github.com/safedep/pmg/sandbox/util"
)
// validSandboxAllowTypes is the set of recognized --sandbox-allow type prefixes.
var validSandboxAllowTypes = map[SandboxAllowType]bool{
SandboxAllowRead: true,
SandboxAllowWrite: true,
SandboxAllowExec: true,
SandboxAllowNetConnect: true,
SandboxAllowNetBind: true,
SandboxAllowEnv: true,
SandboxAllowPreset: true,
}
// parseSandboxAllowOverrides parses raw --sandbox-allow flag values into validated overrides.
// Each raw value must be in the format "type=value" (e.g., "write=./.gitignore").
func parseSandboxAllowOverrides(raw []string) ([]SandboxAllowOverride, error) {
overrides := make([]SandboxAllowOverride, 0, len(raw))
for _, r := range raw {
override, err := parseSingleOverride(r)
if err != nil {
return nil, fmt.Errorf("invalid --sandbox-allow %q: %w", r, err)
}
overrides = append(overrides, override)
}
return overrides, nil
}
// ParseSingleOverride is the exported entry point for callers outside this
// package (e.g. cmd handlers persisting overlay entries). It mirrors the
// validation used for --sandbox-allow flag values.
func ParseSingleOverride(raw string) (SandboxAllowOverride, error) {
return parseSingleOverride(raw)
}
// parseSingleOverride parses and validates a single "type=value" string.
func parseSingleOverride(raw string) (SandboxAllowOverride, error) {
// Split on first '=' only to handle values containing '='
idx := strings.IndexByte(raw, '=')
if idx < 0 {
return SandboxAllowOverride{}, fmt.Errorf("missing '=' separator, expected format: type=value (e.g., write=./file)")
}
typStr := raw[:idx]
value := raw[idx+1:]
if typStr == "" {
return SandboxAllowOverride{}, fmt.Errorf("missing type before '=', expected format: type=value")
}
if value == "" {
return SandboxAllowOverride{}, fmt.Errorf("missing value after '=', expected format: type=value")
}
allowType := SandboxAllowType(typStr)
// Provide a helpful error for the common mistake of using "net" instead of "net-connect"/"net-bind"
if typStr == "net" {
return SandboxAllowOverride{}, fmt.Errorf("unknown type %q (use net-connect or net-bind)", typStr)
}
if !validSandboxAllowTypes[allowType] {
return SandboxAllowOverride{}, fmt.Errorf("unknown type %q, valid types: read, write, exec, net-connect, net-bind, env, preset", typStr)
}
resolved, err := validateAndResolveValue(allowType, value)
if err != nil {
return SandboxAllowOverride{}, err
}
return SandboxAllowOverride{
Type: allowType,
Value: resolved,
Raw: raw,
}, nil
}
// validateAndResolveValue validates the value for the given type and resolves paths.
func validateAndResolveValue(typ SandboxAllowType, value string) (string, error) {
switch typ {
case SandboxAllowRead, SandboxAllowWrite:
return resolveFilesystemPath(value)
case SandboxAllowExec:
return resolveExecPath(value)
case SandboxAllowNetConnect:
return validateNetConnect(value)
case SandboxAllowNetBind:
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
// matches a variable name and not a filesystem location. Matching is
// case-insensitive at scrub time, so the value is not normalized here.
// Whitespace and control characters are rejected because the value is echoed
// back in logs and audit events, and backslash and separators because they
// have no place in a variable name or glob.
func validateEnvName(value string) (string, error) {
invalid := strings.ContainsAny(value, "=/\\") ||
strings.ContainsFunc(value, func(r rune) bool {
return unicode.IsSpace(r) || unicode.IsControl(r)
})
if invalid {
return "", fmt.Errorf("invalid env variable name %q (expected a name or name glob, e.g. NPM_TOKEN or npm_config_*)", value)
}
return value, nil
}
// resolveFilesystemPath resolves a filesystem path for read/write overrides.
// Supports glob patterns. Resolves relative paths to absolute via CWD.
func resolveFilesystemPath(value string) (string, error) {
if err := checkTildePath(value); err != nil {
return "", err
}
return resolveToAbsolute(value)
}
// resolveExecPath resolves an exec path. Rejects glob patterns.
func resolveExecPath(value string) (string, error) {
if err := checkTildePath(value); err != nil {
return "", err
}
if containsGlob(value) {
return "", fmt.Errorf("glob patterns are not allowed for exec type (specify exact path)")
}
return resolveToAbsolute(value)
}
// validateNetConnect validates a net-connect value (host:port format, no wildcards).
func validateNetConnect(value string) (string, error) {
host, port, err := parseHostPort(value)
if err != nil {
return "", fmt.Errorf("invalid net-connect value: %w", err)
}
if host == "*" || strings.Contains(host, "*") || strings.Contains(host, "?") {
return "", fmt.Errorf("wildcards are not allowed for net-connect (specify exact host:port)")
}
if port == "*" {
return "", fmt.Errorf("port wildcard is not allowed for net-connect (specify exact host:port)")
}
return value, nil
}
// validateNetBind validates a net-bind value.
// Allows localhost:* and 127.0.0.1:* as special wildcard forms.
// Warns on non-localhost addresses.
func validateNetBind(value string) (string, error) {
host, _, err := parseHostPort(value)
if err != nil {
return "", fmt.Errorf("invalid net-bind value: %w", err)
}
// Reject host-side wildcards
if host == "*" || strings.Contains(host, "*") || strings.Contains(host, "?") {
return "", fmt.Errorf("host wildcards are not allowed for net-bind (specify a host, e.g., localhost:3000)")
}
// Warn on non-localhost addresses
if !isLocalhostAddress(host) {
log.Warnf("--sandbox-allow net-bind=%s uses non-localhost address, this exposes the port to the network", value)
}
return value, nil
}
// parseHostPort parses a host:port string. The port may be "*" for wildcard.
func parseHostPort(value string) (string, string, error) {
// Find the last ':' to split host and port (handles IPv6 in the future)
lastColon := strings.LastIndex(value, ":")
if lastColon < 0 {
return "", "", fmt.Errorf("expected host:port format (e.g., example.com:443), got %q", value)
}
host := value[:lastColon]
port := value[lastColon+1:]
if host == "" {
return "", "", fmt.Errorf("missing host in host:port value %q", value)
}
if port == "" {
return "", "", fmt.Errorf("missing port in host:port value %q", value)
}
return host, port, nil
}
// isLocalhostAddress returns true if the host is a localhost address.
func isLocalhostAddress(host string) bool {
return host == "localhost" || host == "127.0.0.1" || host == "::1"
}
// resolveToAbsolute resolves a path to an absolute path relative to CWD.
// Glob characters are preserved. The path is cleaned via filepath.Clean().
func resolveToAbsolute(value string) (string, error) {
value, err := sandboxutil.ExpandVariables(value)
if err != nil {
return "", err
}
if filepath.IsAbs(value) {
return filepath.Clean(value), nil
}
// For paths with glob characters, we need to preserve them through Clean.
// filepath.Clean handles ".." and "." but leaves glob chars intact.
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get working directory: %w", err)
}
return filepath.Clean(filepath.Join(cwd, value)), nil
}
// checkTildePath returns an error if the path starts with "~" (unexpanded tilde).
func checkTildePath(value string) error {
if strings.HasPrefix(value, "~") {
return fmt.Errorf("path %q starts with '~' which was not expanded by your shell; use an absolute path instead", value)
}
return nil
}
// containsGlob returns true if the pattern contains glob wildcards.
func containsGlob(pattern string) bool {
return strings.Contains(pattern, "*") ||
strings.Contains(pattern, "?") ||
strings.Contains(pattern, "[")
}