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
+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))
})
}
}