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>
334 lines
8.6 KiB
Go
334 lines
8.6 KiB
Go
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.
|
|
// Users opt out via allow_read / allow_write (see GetMandatoryDenyPatterns).
|
|
var DANGEROUS_FILES = []string{
|
|
".env",
|
|
".env.*",
|
|
".aws",
|
|
".azure",
|
|
".gcloud",
|
|
".config/gcloud",
|
|
".kube",
|
|
".ssh",
|
|
".gnupg",
|
|
".docker/config.json",
|
|
".netrc",
|
|
".git-credentials",
|
|
".pgpass",
|
|
".config/gh",
|
|
}
|
|
|
|
// DANGEROUS_ENV_VARS are credential-bearing environment variables scrubbed from
|
|
// the child process by default when the sandbox is enabled (see ScrubEnv). This
|
|
// is an explicit, curated list of known secret names. There are deliberately
|
|
// no generic "*_TOKEN" / "*_SECRET" catch-alls here, because broad wildcards in
|
|
// the default would risk clipping legitimate build variables for every user.
|
|
// The matcher (ScrubEnv) does support glob patterns, so users who want broader
|
|
// coverage opt into it per profile via environment.deny.
|
|
//
|
|
// Matching is case-insensitive (see ScrubEnv). A package manager's own
|
|
// publishing token is intentionally left scrubbable here and re-allowed per
|
|
// ecosystem in the profile's environment.allow (e.g. npm re-allows NPM_TOKEN).
|
|
var DANGEROUS_ENV_VARS = []string{
|
|
// Cloud providers
|
|
"AWS_ACCESS_KEY_ID",
|
|
"AWS_SECRET_ACCESS_KEY",
|
|
"AWS_SESSION_TOKEN",
|
|
"AWS_SECURITY_TOKEN",
|
|
"AZURE_CLIENT_SECRET",
|
|
"AZURE_CLIENT_ID",
|
|
"AZURE_TENANT_ID",
|
|
"ARM_CLIENT_SECRET",
|
|
"GOOGLE_APPLICATION_CREDENTIALS",
|
|
"GOOGLE_CREDENTIALS",
|
|
"GOOGLE_OAUTH_ACCESS_TOKEN",
|
|
"GCP_SERVICE_ACCOUNT_KEY",
|
|
"CLOUDSDK_AUTH_ACCESS_TOKEN",
|
|
"DIGITALOCEAN_ACCESS_TOKEN",
|
|
"DIGITALOCEAN_TOKEN",
|
|
"CLOUDFLARE_API_TOKEN",
|
|
"CLOUDFLARE_API_KEY",
|
|
"HEROKU_API_KEY",
|
|
"FLY_API_TOKEN",
|
|
"RAILWAY_TOKEN",
|
|
"VERCEL_TOKEN",
|
|
"NETLIFY_AUTH_TOKEN",
|
|
|
|
// Package registry / publishing tokens
|
|
"NPM_TOKEN",
|
|
"NPM_AUTH_TOKEN",
|
|
"NODE_AUTH_TOKEN",
|
|
"NPM_CONFIG__AUTH",
|
|
"YARN_NPM_AUTH_TOKEN",
|
|
"YARN_NPM_AUTH_IDENT",
|
|
"BUN_AUTH_TOKEN",
|
|
"TWINE_USERNAME",
|
|
"TWINE_PASSWORD",
|
|
"PYPI_TOKEN",
|
|
"UV_PUBLISH_TOKEN",
|
|
"FLIT_PASSWORD",
|
|
"POETRY_PYPI_TOKEN_PYPI",
|
|
"POETRY_HTTP_BASIC_PYPI_PASSWORD",
|
|
"ANACONDA_API_TOKEN",
|
|
"GEM_HOST_API_KEY",
|
|
"RUBYGEMS_API_KEY",
|
|
"CARGO_REGISTRY_TOKEN",
|
|
"COMPOSER_AUTH",
|
|
"HEX_API_KEY",
|
|
"NUGET_API_KEY",
|
|
"CONAN_LOGIN_PASSWORD",
|
|
"CONAN_PASSWORD",
|
|
"DENO_AUTH_TOKENS",
|
|
"EXPO_TOKEN",
|
|
"JFROG_ACCESS_TOKEN",
|
|
"ARTIFACTORY_ACCESS_TOKEN",
|
|
"ARTIFACTORY_API_KEY",
|
|
"ARTIFACTORY_PASSWORD",
|
|
|
|
// VCS / CI
|
|
"GITHUB_TOKEN",
|
|
"GH_TOKEN",
|
|
"GH_ENTERPRISE_TOKEN",
|
|
"GITLAB_TOKEN",
|
|
"CI_JOB_TOKEN",
|
|
"CIRCLE_TOKEN",
|
|
"BUILDKITE_AGENT_TOKEN",
|
|
"BUILDKITE_API_TOKEN",
|
|
"AZURE_DEVOPS_EXT_PAT",
|
|
"SYSTEM_ACCESSTOKEN",
|
|
|
|
// Secrets managers
|
|
"VAULT_TOKEN",
|
|
"CONSUL_HTTP_TOKEN",
|
|
"NOMAD_TOKEN",
|
|
"OP_SERVICE_ACCOUNT_TOKEN",
|
|
"OP_CONNECT_TOKEN",
|
|
"BW_SESSION",
|
|
"BWS_ACCESS_TOKEN",
|
|
"DOPPLER_TOKEN",
|
|
"INFISICAL_TOKEN",
|
|
|
|
// Infrastructure as code
|
|
"TFE_TOKEN",
|
|
"TF_API_TOKEN",
|
|
"PULUMI_ACCESS_TOKEN",
|
|
|
|
// Misc high-value
|
|
"DOCKER_PASSWORD",
|
|
"DOCKER_AUTH_CONFIG",
|
|
"SNYK_TOKEN",
|
|
"CODECOV_TOKEN",
|
|
"SONAR_TOKEN",
|
|
"SENTRY_AUTH_TOKEN",
|
|
"DATADOG_API_KEY",
|
|
"DD_API_KEY",
|
|
"DD_APP_KEY",
|
|
"NEW_RELIC_API_KEY",
|
|
"SLACK_BOT_TOKEN",
|
|
"STRIPE_SECRET_KEY",
|
|
"STRIPE_API_KEY",
|
|
"TWILIO_AUTH_TOKEN",
|
|
"SENDGRID_API_KEY",
|
|
"FIREBASE_TOKEN",
|
|
"SUPABASE_SERVICE_ROLE_KEY",
|
|
"SUPABASE_ACCESS_TOKEN",
|
|
|
|
// AI providers
|
|
"OPENAI_API_KEY",
|
|
"ANTHROPIC_API_KEY",
|
|
"AZURE_OPENAI_API_KEY",
|
|
"HUGGING_FACE_HUB_TOKEN",
|
|
"HF_TOKEN",
|
|
"GEMINI_API_KEY",
|
|
"GOOGLE_API_KEY",
|
|
"COHERE_API_KEY",
|
|
"MISTRAL_API_KEY",
|
|
"GROQ_API_KEY",
|
|
"OPENROUTER_API_KEY",
|
|
"DEEPSEEK_API_KEY",
|
|
"XAI_API_KEY",
|
|
}
|
|
|
|
// ProtectedEnvVars are core process variables never scrubbed, regardless of
|
|
// deny patterns. They are matched case-insensitively as globs (see ScrubEnv),
|
|
// so "LC_*" covers the whole locale family. This is a safety net so that a
|
|
// profile opting into a broad deny glob (e.g. "*_TOKEN") cannot break process
|
|
// startup. The built-in DANGEROUS_ENV_VARS list never touches these names.
|
|
var ProtectedEnvVars = []string{
|
|
"PATH",
|
|
"HOME",
|
|
"USER",
|
|
"LOGNAME",
|
|
"SHELL",
|
|
"PWD",
|
|
"OLDPWD",
|
|
"TERM",
|
|
"TMPDIR",
|
|
"TEMP",
|
|
"TMP",
|
|
"LANG",
|
|
"LC_*",
|
|
"TZ",
|
|
"DISPLAY",
|
|
"HOSTNAME",
|
|
"NODE_ENV",
|
|
}
|
|
|
|
// MandatoryDenyOptions configures GetMandatoryDenyPatterns. AllowRead and
|
|
// AllowWrite must be already expanded (post-ExpandVariables); the function
|
|
// does not call ExpandVariables itself.
|
|
type MandatoryDenyOptions struct {
|
|
AllowGitConfig bool
|
|
AllowRead []string
|
|
AllowWrite []string
|
|
}
|
|
|
|
// MandatoryDenyResult splits mandatory denies by direction and reports the
|
|
// patterns the user opted out of (for audit logging by translators).
|
|
type MandatoryDenyResult struct {
|
|
DenyRead []string
|
|
DenyWrite []string
|
|
SuppressedRead []string
|
|
SuppressedWrite []string
|
|
}
|
|
|
|
// GetMandatoryDenyPatterns returns mandatory deny patterns for both directions,
|
|
// suppressing any pattern the user has explicitly named in the corresponding
|
|
// allow list. Suppression is exact post-expansion byte-equal match — broad
|
|
// globs in user allow lists do not suppress.
|
|
//
|
|
// .git/hooks is never suppressed (arbitrary code execution risk).
|
|
// .git/config is emitted only when !AllowGitConfig and may be suppressed.
|
|
func GetMandatoryDenyPatterns(opts MandatoryDenyOptions) MandatoryDenyResult {
|
|
allowReadSet := toSet(opts.AllowRead)
|
|
allowWriteSet := toSet(opts.AllowWrite)
|
|
|
|
cwd, err := os.Getwd()
|
|
if err != nil {
|
|
cwd = "."
|
|
}
|
|
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
home = ""
|
|
}
|
|
|
|
// Naming an absolute form (CWD or HOME) of a dangerous file also suppresses
|
|
// the corresponding "**/<file>" glob on the same direction — otherwise the
|
|
// glob deny would still block the user's explicit opt-out. The unnamed
|
|
// absolute form remains mandatory.
|
|
absToDangerous := make(map[string]string)
|
|
for _, fileName := range DANGEROUS_FILES {
|
|
absToDangerous[filepath.Clean(filepath.Join(cwd, fileName))] = fileName
|
|
if home != "" {
|
|
absToDangerous[filepath.Clean(filepath.Join(home, fileName))] = fileName
|
|
}
|
|
}
|
|
|
|
readGlobAlsoSuppressed := make(map[string]bool)
|
|
for entry := range allowReadSet {
|
|
if fileName, ok := absToDangerous[entry]; ok {
|
|
readGlobAlsoSuppressed[filepath.Clean(filepath.Join("**", fileName))] = true
|
|
}
|
|
}
|
|
writeGlobAlsoSuppressed := make(map[string]bool)
|
|
for entry := range allowWriteSet {
|
|
if fileName, ok := absToDangerous[entry]; ok {
|
|
writeGlobAlsoSuppressed[filepath.Clean(filepath.Join("**", fileName))] = true
|
|
}
|
|
}
|
|
|
|
suppressible := []string{}
|
|
|
|
for _, fileName := range DANGEROUS_FILES {
|
|
suppressible = append(suppressible, filepath.Join(cwd, fileName))
|
|
suppressible = append(suppressible, filepath.Join("**", fileName))
|
|
if home != "" {
|
|
suppressible = append(suppressible, filepath.Join(home, fileName))
|
|
}
|
|
}
|
|
|
|
if !opts.AllowGitConfig {
|
|
suppressible = append(suppressible, filepath.Join(cwd, GitConfigPath))
|
|
if home != "" {
|
|
suppressible = append(suppressible, filepath.Join(home, GitConfigPath))
|
|
}
|
|
}
|
|
|
|
result := MandatoryDenyResult{}
|
|
|
|
for _, pattern := range suppressible {
|
|
cleaned := filepath.Clean(pattern)
|
|
|
|
if allowReadSet[cleaned] || readGlobAlsoSuppressed[cleaned] {
|
|
result.SuppressedRead = append(result.SuppressedRead, cleaned)
|
|
} else {
|
|
result.DenyRead = append(result.DenyRead, cleaned)
|
|
}
|
|
|
|
if allowWriteSet[cleaned] || writeGlobAlsoSuppressed[cleaned] {
|
|
result.SuppressedWrite = append(result.SuppressedWrite, cleaned)
|
|
} else {
|
|
result.DenyWrite = append(result.DenyWrite, cleaned)
|
|
}
|
|
}
|
|
|
|
// Git hooks can execute arbitrary code; never suppressible.
|
|
gitHooks := []string{
|
|
filepath.Join(cwd, GitHooksPath),
|
|
filepath.Join(cwd, GitHooksPath, "**"),
|
|
}
|
|
if home != "" {
|
|
gitHooks = append(gitHooks,
|
|
filepath.Join(home, GitHooksPath),
|
|
filepath.Join(home, GitHooksPath, "**"),
|
|
)
|
|
}
|
|
for _, p := range gitHooks {
|
|
cleaned := filepath.Clean(p)
|
|
result.DenyRead = append(result.DenyRead, cleaned)
|
|
result.DenyWrite = append(result.DenyWrite, cleaned)
|
|
}
|
|
|
|
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 {
|
|
m[filepath.Clean(v)] = true
|
|
}
|
|
return m
|
|
}
|