mirror of
https://github.com/safedep/pmg.git
synced 2026-08-03 07:24:09 +02:00
* 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>
408 lines
11 KiB
Go
408 lines
11 KiB
Go
package config
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestParseSandboxAllowOverrides_ValidFormats(t *testing.T) {
|
|
cwd, err := os.Getwd()
|
|
require.NoError(t, err)
|
|
|
|
tests := []struct {
|
|
name string
|
|
raw string
|
|
expectedType SandboxAllowType
|
|
expectedValue string
|
|
}{
|
|
{
|
|
name: "write with relative path",
|
|
raw: "write=./.gitignore",
|
|
expectedType: SandboxAllowWrite,
|
|
expectedValue: filepath.Join(cwd, ".gitignore"),
|
|
},
|
|
{
|
|
name: "write with absolute path",
|
|
raw: "write=/tmp/output",
|
|
expectedType: SandboxAllowWrite,
|
|
expectedValue: "/tmp/output",
|
|
},
|
|
{
|
|
name: "write with glob pattern",
|
|
raw: "write=./dist/**",
|
|
expectedType: SandboxAllowWrite,
|
|
expectedValue: filepath.Join(cwd, "dist/**"),
|
|
},
|
|
{
|
|
name: "read with absolute path",
|
|
raw: "read=/opt/config/registry.json",
|
|
expectedType: SandboxAllowRead,
|
|
expectedValue: "/opt/config/registry.json",
|
|
},
|
|
{
|
|
name: "read with glob pattern",
|
|
raw: "read=./src/**",
|
|
expectedType: SandboxAllowRead,
|
|
expectedValue: filepath.Join(cwd, "src/**"),
|
|
},
|
|
{
|
|
name: "exec with absolute path",
|
|
raw: "exec=/usr/bin/curl",
|
|
expectedType: SandboxAllowExec,
|
|
expectedValue: "/usr/bin/curl",
|
|
},
|
|
{
|
|
name: "net-connect with host:port",
|
|
raw: "net-connect=registry.npmjs.org:443",
|
|
expectedType: SandboxAllowNetConnect,
|
|
expectedValue: "registry.npmjs.org:443",
|
|
},
|
|
{
|
|
name: "net-bind with localhost",
|
|
raw: "net-bind=127.0.0.1:3000",
|
|
expectedType: SandboxAllowNetBind,
|
|
expectedValue: "127.0.0.1:3000",
|
|
},
|
|
{
|
|
name: "net-bind with localhost wildcard port",
|
|
raw: "net-bind=localhost:*",
|
|
expectedType: SandboxAllowNetBind,
|
|
expectedValue: "localhost:*",
|
|
},
|
|
{
|
|
name: "write with relative path no dot prefix",
|
|
raw: "write=dist/output",
|
|
expectedType: SandboxAllowWrite,
|
|
expectedValue: filepath.Join(cwd, "dist/output"),
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
overrides, err := parseSandboxAllowOverrides([]string{tt.raw})
|
|
require.NoError(t, err)
|
|
require.Len(t, overrides, 1)
|
|
|
|
assert.Equal(t, tt.expectedType, overrides[0].Type)
|
|
assert.Equal(t, tt.expectedValue, overrides[0].Value)
|
|
assert.Equal(t, tt.raw, overrides[0].Raw)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestParseSingleOverride_ExpandsSandboxVariables(t *testing.T) {
|
|
cwd, err := os.Getwd()
|
|
require.NoError(t, err)
|
|
|
|
home, err := os.UserHomeDir()
|
|
require.NoError(t, err)
|
|
|
|
tmpDir := os.TempDir()
|
|
|
|
tests := []struct {
|
|
name string
|
|
raw string
|
|
expectedType SandboxAllowType
|
|
expectedValue string
|
|
notContains string
|
|
}{
|
|
{
|
|
name: "write expands CWD glob",
|
|
raw: "write=${CWD}/**",
|
|
expectedType: SandboxAllowWrite,
|
|
expectedValue: filepath.Clean(filepath.Join(cwd, "**")),
|
|
notContains: "${CWD}",
|
|
},
|
|
{
|
|
name: "read expands HOME",
|
|
raw: "read=${HOME}/x",
|
|
expectedType: SandboxAllowRead,
|
|
expectedValue: filepath.Clean(filepath.Join(home, "x")),
|
|
notContains: "${HOME}",
|
|
},
|
|
{
|
|
name: "write expands TMPDIR",
|
|
raw: "write=${TMPDIR}/pmg-cache",
|
|
expectedType: SandboxAllowWrite,
|
|
expectedValue: filepath.Clean(filepath.Join(tmpDir, "pmg-cache")),
|
|
notContains: "${TMPDIR}",
|
|
},
|
|
{
|
|
name: "exec expands CWD",
|
|
raw: "exec=${CWD}/bin/tool",
|
|
expectedType: SandboxAllowExec,
|
|
expectedValue: filepath.Clean(filepath.Join(cwd, "bin", "tool")),
|
|
notContains: "${CWD}",
|
|
},
|
|
{
|
|
name: "absolute path without variables is unchanged",
|
|
raw: "write=/tmp/pmg-output",
|
|
expectedType: SandboxAllowWrite,
|
|
expectedValue: filepath.Clean("/tmp/pmg-output"),
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
got, err := parseSingleOverride(tt.raw)
|
|
require.NoError(t, err)
|
|
|
|
assert.Equal(t, tt.expectedType, got.Type)
|
|
assert.Equal(t, tt.expectedValue, got.Value)
|
|
assert.Equal(t, tt.raw, got.Raw)
|
|
if tt.notContains != "" {
|
|
assert.NotContains(t, got.Value, tt.notContains)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_Env(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
raw string
|
|
expectedValue string
|
|
}{
|
|
{name: "exact name", raw: "env=NPM_TOKEN", expectedValue: "NPM_TOKEN"},
|
|
{name: "glob name kept verbatim", raw: "env=npm_config_*", expectedValue: "npm_config_*"},
|
|
{name: "not path resolved", raw: "env=AWS_PROFILE", expectedValue: "AWS_PROFILE"},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
overrides, err := parseSandboxAllowOverrides([]string{tt.raw})
|
|
require.NoError(t, err)
|
|
require.Len(t, overrides, 1)
|
|
|
|
assert.Equal(t, SandboxAllowEnv, overrides[0].Type)
|
|
// Value is kept verbatim, with no CWD/path resolution.
|
|
assert.Equal(t, tt.expectedValue, overrides[0].Value)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_EnvInvalid(t *testing.T) {
|
|
invalid := []string{
|
|
"env=NPM/TOKEN",
|
|
"env=FOO=BAR",
|
|
"env=HAS SPACE",
|
|
"env=HAS\tTAB",
|
|
"env=HAS\nNEWLINE",
|
|
"env=HAS\rRETURN",
|
|
"env=BACK\\SLASH",
|
|
"env=CTRL\x07CHAR",
|
|
}
|
|
|
|
for _, raw := range invalid {
|
|
_, err := parseSandboxAllowOverrides([]string{raw})
|
|
assert.Error(t, err, "expected error for %q", raw)
|
|
}
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_MultipleValues(t *testing.T) {
|
|
raw := []string{
|
|
"write=./.gitignore",
|
|
"exec=/usr/bin/curl",
|
|
"net-connect=example.com:443",
|
|
}
|
|
|
|
overrides, err := parseSandboxAllowOverrides(raw)
|
|
require.NoError(t, err)
|
|
require.Len(t, overrides, 3)
|
|
|
|
assert.Equal(t, SandboxAllowWrite, overrides[0].Type)
|
|
assert.Equal(t, SandboxAllowExec, overrides[1].Type)
|
|
assert.Equal(t, SandboxAllowNetConnect, overrides[2].Type)
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_EmptySlice(t *testing.T) {
|
|
overrides, err := parseSandboxAllowOverrides([]string{})
|
|
require.NoError(t, err)
|
|
assert.Empty(t, overrides)
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_InvalidFormats(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
raw string
|
|
errContains string
|
|
}{
|
|
{
|
|
name: "missing separator",
|
|
raw: "./foo",
|
|
errContains: "missing '=' separator",
|
|
},
|
|
{
|
|
name: "missing type",
|
|
raw: "=./foo",
|
|
errContains: "missing type before '='",
|
|
},
|
|
{
|
|
name: "empty value",
|
|
raw: "write=",
|
|
errContains: "missing value after '='",
|
|
},
|
|
{
|
|
name: "unknown type",
|
|
raw: "foo=bar",
|
|
errContains: "unknown type",
|
|
},
|
|
{
|
|
name: "net shorthand rejected",
|
|
raw: "net=host:443",
|
|
errContains: "use net-connect or net-bind",
|
|
},
|
|
{
|
|
name: "exec with glob pattern",
|
|
raw: "exec=/usr/bin/*",
|
|
errContains: "glob patterns are not allowed for exec",
|
|
},
|
|
{
|
|
name: "net-connect with wildcard host",
|
|
raw: "net-connect=*:443",
|
|
errContains: "wildcards are not allowed for net-connect",
|
|
},
|
|
{
|
|
name: "net-connect with glob host",
|
|
raw: "net-connect=*.example.com:443",
|
|
errContains: "wildcards are not allowed for net-connect",
|
|
},
|
|
{
|
|
name: "net-connect with wildcard port",
|
|
raw: "net-connect=example.com:*",
|
|
errContains: "port wildcard is not allowed for net-connect",
|
|
},
|
|
{
|
|
name: "net-bind with host wildcard",
|
|
raw: "net-bind=*:3000",
|
|
errContains: "host wildcards are not allowed for net-bind",
|
|
},
|
|
{
|
|
name: "net-bind with full wildcard",
|
|
raw: "net-bind=*:*",
|
|
errContains: "host wildcards are not allowed for net-bind",
|
|
},
|
|
{
|
|
name: "net-connect missing port",
|
|
raw: "net-connect=example.com",
|
|
errContains: "expected host:port format",
|
|
},
|
|
{
|
|
name: "net-bind missing port",
|
|
raw: "net-bind=localhost",
|
|
errContains: "expected host:port format",
|
|
},
|
|
{
|
|
name: "tilde path for write",
|
|
raw: "write=~/file",
|
|
errContains: "starts with '~'",
|
|
},
|
|
{
|
|
name: "tilde path for read",
|
|
raw: "read=~/.config/foo",
|
|
errContains: "starts with '~'",
|
|
},
|
|
{
|
|
name: "tilde path for exec",
|
|
raw: "exec=~/bin/tool",
|
|
errContains: "starts with '~'",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
_, err := parseSandboxAllowOverrides([]string{tt.raw})
|
|
require.Error(t, err)
|
|
assert.Contains(t, err.Error(), tt.errContains)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_ValueWithEquals(t *testing.T) {
|
|
// Values can contain '=' characters — the parser splits on the first '=' only
|
|
overrides, err := parseSandboxAllowOverrides([]string{"write=./path=with=equals.txt"})
|
|
require.NoError(t, err)
|
|
require.Len(t, overrides, 1)
|
|
|
|
cwd, err := os.Getwd()
|
|
require.NoError(t, err)
|
|
|
|
assert.Equal(t, SandboxAllowWrite, overrides[0].Type)
|
|
assert.Equal(t, filepath.Join(cwd, "path=with=equals.txt"), overrides[0].Value)
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_PathCleaning(t *testing.T) {
|
|
cwd, err := os.Getwd()
|
|
require.NoError(t, err)
|
|
|
|
// Paths with ".." are cleaned via filepath.Clean
|
|
overrides, err := parseSandboxAllowOverrides([]string{"write=./foo/../bar"})
|
|
require.NoError(t, err)
|
|
require.Len(t, overrides, 1)
|
|
|
|
assert.Equal(t, filepath.Join(cwd, "bar"), overrides[0].Value)
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_NetBindNonLocalhost(t *testing.T) {
|
|
// Non-localhost should succeed (with a warning logged, which we can't easily assert here)
|
|
overrides, err := parseSandboxAllowOverrides([]string{"net-bind=0.0.0.0:3000"})
|
|
require.NoError(t, err)
|
|
require.Len(t, overrides, 1)
|
|
|
|
assert.Equal(t, SandboxAllowNetBind, overrides[0].Type)
|
|
assert.Equal(t, "0.0.0.0:3000", overrides[0].Value)
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_FirstErrorStops(t *testing.T) {
|
|
// If the first value is invalid, the second is not parsed
|
|
_, err := parseSandboxAllowOverrides([]string{"write=./ok", "bad"})
|
|
require.Error(t, err)
|
|
assert.Contains(t, err.Error(), "missing '=' separator")
|
|
}
|
|
|
|
func TestParseSingleOverride_Exported(t *testing.T) {
|
|
got, err := ParseSingleOverride("net-bind=localhost:4321")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, SandboxAllowNetBind, got.Type)
|
|
assert.Equal(t, "localhost:4321", got.Value)
|
|
assert.Equal(t, "net-bind=localhost:4321", got.Raw)
|
|
}
|
|
|
|
func TestParseSingleOverride_ExportedRejectsInvalid(t *testing.T) {
|
|
_, err := ParseSingleOverride("garbage")
|
|
assert.Error(t, err)
|
|
}
|
|
|
|
func TestParseSandboxAllowOverrides_Preset(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
raw string
|
|
value string
|
|
wantErr string
|
|
}{
|
|
{name: "valid preset name", raw: "preset=git", value: "git"},
|
|
{name: "dashed preset name", raw: "preset=my-app", value: "my-app"},
|
|
{name: "uppercase rejected", raw: "preset=Git", wantErr: "invalid preset name"},
|
|
{name: "path rejected", raw: "preset=./git.yml", wantErr: "invalid preset name"},
|
|
{name: "leading dash rejected", raw: "preset=-git", wantErr: "invalid preset name"},
|
|
}
|
|
|
|
for _, tc := range tests {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
override, err := ParseSingleOverride(tc.raw)
|
|
if tc.wantErr != "" {
|
|
require.Error(t, err)
|
|
assert.Contains(t, err.Error(), tc.wantErr)
|
|
return
|
|
}
|
|
require.NoError(t, err)
|
|
assert.Equal(t, SandboxAllowPreset, override.Type)
|
|
assert.Equal(t, tc.value, override.Value)
|
|
})
|
|
}
|
|
}
|