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
+126
View File
@@ -0,0 +1,126 @@
# Sandbox Presets
A preset is a named bundle of sandbox allowances for one workload. For
example: what `lint-staged` needs from git, or what `astro dev` needs to
write and bind. Any tool with a known sandbox footprint can have a preset.
Presets are **additive-only**: they grant allowances on top of your sandbox
profile and can never remove a deny rule. A profile-authored deny always
beats a preset allowance, and preset validation rejects paths that would
opt out of PMG's mandatory protections (`.git/hooks`, `.git/config` writes,
credential files). The two opt-outs a preset can perform, both visible in
its YAML: read access to `.git/config` (required for git to operate) and
un-scrubbing specific built-in credential variables by exact name.
## Using presets
Discover what's available:
```bash
pmg sandbox preset list
pmg sandbox preset list --label dev-server --author SafeDep
```
Inspect a preset before trusting it. The output is the preset's own YAML,
including its threat notes describing the residual risk of each allowance:
```bash
pmg sandbox preset show git
```
Apply presets to the current repository (run from the project root; this
saves into the per-repo overlay used by every future PMG run there):
```bash
pmg sandbox allow preset=git preset=astro
```
Or attach presets permanently to a custom sandbox profile:
```yaml
# ~/.config/safedep/pmg/sandbox/profiles/pnpm-custom.yml
name: pnpm-custom
inherits: pnpm
package_managers: [pnpm]
presets: [git, astro]
```
Presets are applied by reference: upgrading PMG (or editing a user preset)
updates the allowances everywhere the preset is used.
## Available official presets
| Preset | For |
| -------- | -------------------------------------- |
| `git` | lint-staged, husky, turbo, changesets |
| `astro` | Astro dev server and build |
| `vite` | Vite dev server and build |
| `nextjs` | Next.js dev server and build |
## Creating your own preset
Scaffold, edit and validate:
```bash
pmg sandbox preset init myapp --author "Your Name" --label myapp
pmg sandbox preset edit myapp # opens $VISUAL / $EDITOR, validates on save
pmg sandbox allow preset=myapp # apply to the current repo
```
User presets live in `<config-dir>/sandbox/presets/` (e.g.
`~/.config/safedep/pmg/sandbox/presets/` on Linux) — community presets are
installed by dropping a file there. `pmg sandbox preset list` always shows
where a preset came from: `builtin` (embedded in the pmg binary,
maintainer-reviewed) vs the user file path, and a user preset that reuses a
built-in name is marked `SHADOWED` — the built-in always wins, so an
official preset cannot be silently replaced. A preset file looks like:
```yaml
kind: preset
name: myapp
description: What this preset enables, one line
metadata:
author: Your Name
labels: [myapp, dev-server]
# Threat notes: explain what each allowance permits and why it is acceptable.
filesystem:
allow_write:
- ${CWD}/.myapp/**
network:
allow_bind:
- localhost:8080
```
Validate it:
```bash
pmg sandbox preset lint ./myapp.yml
```
Rules the schema enforces:
- Allow-only sections: `filesystem.allow_read/allow_write`,
`process.allow_exec`, `network.allow_bind`, `environment.allow`. Deny
rules and profile booleans are rejected.
- Paths must be anchored at `${CWD}/`, `${HOME}/` or `${TMPDIR}/`, no `..`,
and must not name sensitive files (`.env`, `.ssh`, ...).
- Binds must be loopback (`localhost`, `127.0.0.1`, `::1`).
- `environment.allow` entries are exact variable names, no globs.
- No `network.allow_outbound`: current sandbox drivers cannot enforce
host-granular outbound rules (a single allow means blanket network
access), so presets are not allowed to change outbound posture at all.
Precedence guarantees, in addition to PMG's mandatory denies:
- A preset environment allowance covered by a profile-authored
`environment.deny` pattern is dropped with a warning. Surviving preset
allowances still opt out of PMG's built-in credential variable scrubbing,
which is their intended use.
- A preset filesystem allowance never removes a deny rule authored in a
profile: deny wins over allow on every platform.
- The `git` preset allows reading `.git/config` and writing under `.git/`,
but writes to `.git/config` and everything under `.git/hooks` stay
blocked by mandatory denies on all platforms.
A preset name that collides with an official preset is shadowed — the
official one always wins. To propose an official preset, open a pull request
adding it under `sandbox/presets/` with threat notes and tests.
+23 -2
View File
@@ -269,6 +269,10 @@ weakens mandatory denies, and is ignored when `global_lockdown` is set.
# Save manual allowances for the current repo
pmg sandbox allow write=./.astro net-bind=localhost:4321
# Persist an environment variable allowance so the profile stops scrubbing it
# in this repo (same semantics as --sandbox-allow env=..., but saved)
pmg sandbox allow env=AWS_PROFILE
# Promote the primary violation from the most recent cached report
pmg sandbox allow --last
@@ -289,11 +293,28 @@ pmg sandbox project list
pmg sandbox project reset --yes
```
### Presets
A preset is a named, additive-only bundle of allowances for one workload (git hooks tooling,
an Astro/Vite/Next.js dev server, ...). Instead of discovering allowances one denial at a
time, apply a curated bundle:
```bash
pmg sandbox preset list
pmg sandbox preset show git
pmg sandbox allow preset=git preset=astro
```
Presets can also be attached to a profile via a `presets:` list. See
[sandbox-presets.md](sandbox-presets.md) for usage and how to author your own.
Notes:
- `--last`/`--last --all` only auto-promotes filesystem and exec denials. Network allowances
(`net-connect`, `net-bind`) must be passed manually as `type=value` because drivers do not
classify network denials yet.
(`net-connect`, `net-bind`) and environment allowances (`env`) must be passed manually as
`type=value` because drivers do not classify network denials yet and environment scrubbing is
logged rather than recorded as a violation. Run with `--debug` to see scrubbed variable names,
then persist with `pmg sandbox allow env=NAME`.
- `pmg sandbox allow` refuses sensitive targets (`.env*`, `.npmrc`, `.ssh`, `.aws`, `.kube`,
`.gnupg`, ...) unless `--force` is given.
- Applied overlay entries are recorded in the audit event log with a `+overlay` source tag so