mirror of
https://github.com/safedep/pmg.git
synced 2026-08-03 07:24:09 +02:00
* refactor: remove guard mode execution paths and guard-only packages Guard (non-proxy) mode is removed; all package-manager commands now always run the proxy flow. Removes the guard engine, the common flow, the extractor package, the npm/pypi dependency resolvers and the PackageResolver plumbing that only guard mode consumed. The guard package retains only PackageManagerGuardInteraction, which the proxy flow and confirmation interceptors reuse for user prompts. Proxy behavior is unchanged. * refactor: remove proxy opt-out surfaces, guard references in config, action and docs Removes Config.ProxyMode, ProxyConfig.Enabled, IsProxyModeEnabled, the proxy_mode legacy fallback, PMG_PROXY_ENABLED handling and the --proxy-mode / --include-dev-dependencies flags. Proxy interception can no longer be disabled. Also removes the proxy-mode input from the GitHub Action, the proxy-mode doctor check and setup info row, updates the E2E workflow to stop passing --proxy-mode=false, and sweeps guard-mode wording from docs and the config template. The legacy proxy_install_only flat key and PMG_PROXY_INSTALL_ONLY env var remain supported. audit.FlowTypeGuard is kept so previously recorded audit events still translate for cloud sync. * feat: fail loudly when a removed proxy opt-out is still configured A leftover proxy.enabled: false / proxy_mode: false config key or PMG_PROXY_ENABLED=false / PMG_PROXY_MODE=false env var previously meant guard mode; silently ignoring it would switch those users to proxy interception without notice. PMG now exits with an actionable error naming the exact source. Precedence mirrors the old resolution order: env (ignored under lockdown) > proxy.enabled > legacy proxy_mode. The pmg config subtree is exempt so the config file can still be fixed with pmg config edit/set. The GitHub Action's proxy-mode input is kept as a tombstone that fails the action when set to false and warns otherwise. * refactor: extract flows.RunProxy and address review findings Collapses the identical parse-then-run body duplicated across the 12 package manager commands into flows.RunProxy. Documents the cache-hit / offline analysis trade-off versus the removed guard manifest path, fixes a stale non-proxy label in the E2E workflow and a stale guard reference in the uvx parser comment. * fix(config): mirror old proxy opt-out precedence exactly PMG_PROXY_MODE only ever took effect through the legacy fallback, which was gated on the presence of a proxy: key in the config file (even a null one). Promoting it to the top env tier caused two inversions: a stale PMG_PROXY_MODE=false hard-failed configs that resolved to proxy mode, and PMG_PROXY_MODE=true silently overrode an explicit proxy.enabled: false file opt-out. The check now resolves in the old order: PMG_PROXY_ENABLED > proxy: section (presence gates the legacy tier) > PMG_PROXY_MODE > flat proxy_mode. parseOptOutBool also accepts numeric values (0 = false) to match viper's WeaklyTypedInput/cast.ToBool coercion, so proxy.enabled: 0 and proxy_mode: 0 are detected as opt-outs. * refactor: move package manager interaction out of guard * refactor: trim package manager interaction * fix(config): normalize config keys viper-style in proxy opt-out check Viper resolved config file keys case-insensitively and expanded dotted keys, so spellings like Proxy:, Enabled:, a literal proxy.enabled key or Proxy_Mode selected guard mode before the removal. The opt-out check now lowercases keys recursively and nests dotted keys before matching, so those existing opt-outs fail loudly instead of being silently ignored. * refactor: remove inert transitive controls, dead parser state and guard audit variant transitive / transitive_depth lost their only consumers with the dependency resolvers; remove the config fields, flags, template and doc entries, and the report/audit plumbing that misreported transitive analysis as enabled. Remove write-only parser state (PackageInstallTarget.Extras, ParsedCommand.ManifestFiles, ShouldExtractFromManifest); IsManifestInstall stays as it feeds sandbox gating via IsInstallationCommand. Remove audit.FlowTypeGuard and its cloud mapping; guard events recorded by pre-removal versions in an unsynced WAL translate to UNSPECIFIED. * fix: address review findings on the opt-out wiring and cleanups Move the removed-opt-out rejection from the CLI PersistentPreRun into proxyFlow.Run: the check now fires exactly for package-manager runs, so non-install commands (pmg setup remove, doctor, config, version) stay usable to fix or remove an opted-out installation, and future commands inherit or avoid the check by construction instead of by exemption list. Also: make the e2e malicious-package assertion actually fail the job when an install is not blocked, route pmg go through flows.RunProxy, and drop the dead extras return from pypiParsePackageInfo (extras are still stripped from package names). * fix(config): make the removed opt-out check faithful to the old resolution The gate that silenced the legacy proxy_mode surfaces matched the raw proxy key case-sensitively in the old code, while values resolved viper-style (case-insensitive, dotted keys); applying each semantic where the old code did fixes both divergences: a case-variant Proxy: section no longer hides a flat proxy_mode: false opt-out, and a dotted proxy.enabled: false overridden by proxy_mode: true no longer errors. Replace the generic key-tree normalization with two targeted lookups (the check only ever resolves proxy.enabled and proxy_mode), which also makes colliding spellings resolve deterministically. Coerce legacy-tier values cast.ToBool-style so PMG_PROXY_MODE=off style opt-outs are detected, log the config read error instead of swallowing it, and shorten the error to a one-line statement with the specific remedy in the help text. Add lockdown coverage (env inert both directions) and a repeated-run determinism test. * fix(config): fall back to defaults for unrecognized proxy opt-out values The old loader swallowed viper errors and ran on defaults, so values like proxy.enabled: yes or PMG_PROXY_ENABLED=banana silently discarded the whole config and defaulted to proxy. Treat them the same way now: unrecognized values mean the default (proxy on) instead of a hard error, and the doc comment no longer claims the old loader failed loudly. Only values that actually meant guard mode fail. Also check the removed opt-out before the CA trust check in pmg go, restoring the old error precedence: a config problem must not steer the user into an unnecessary OS trust store change. * fix(e2e): PMG_PROXY_MODE assertion must match the legacy gate semantics The runner's setup step writes the template config, which has a proxy: section — and with one present the legacy PMG_PROXY_MODE was always inert, so expecting a loud failure there asserts pre-fidelity-fix behavior. Assert both sides instead: inert (command succeeds) with the standard config, loud failure against an empty config dir where the legacy fallback actually applied. * refactor(config): collapse parseOptOutBool to ParseBool over the string form YAML hands us typed values (bool, int), so route them through fmt.Sprintf %v and strconv.ParseBool instead of a per-type switch. Identical behavior for every recognized value; numbers other than 0/1 now read as no opinion instead of cast.ToBool's nonzero-true, which no real config relies on.
435 lines
12 KiB
Go
435 lines
12 KiB
Go
package config
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/goccy/go-yaml/ast"
|
|
"github.com/goccy/go-yaml/parser"
|
|
"github.com/goccy/go-yaml/token"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func Test_setValueInYAML(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
key string
|
|
value string
|
|
expected string
|
|
wantErr string
|
|
}{
|
|
{
|
|
name: "set top-level bool to true",
|
|
input: "transitive: true\nparanoid: false\n",
|
|
key: "paranoid",
|
|
value: "true",
|
|
expected: "transitive: true\nparanoid: true\n",
|
|
},
|
|
{
|
|
name: "set top-level bool to false",
|
|
input: "transitive: true\nparanoid: true\n",
|
|
key: "paranoid",
|
|
value: "false",
|
|
expected: "transitive: true\nparanoid: false\n",
|
|
},
|
|
{
|
|
name: "set top-level integer",
|
|
input: "transitive_depth: 5\n",
|
|
key: "transitive_depth",
|
|
value: "10",
|
|
expected: "transitive_depth: 10\n",
|
|
},
|
|
{
|
|
name: "set top-level string",
|
|
input: "verbosity: normal\n",
|
|
key: "verbosity",
|
|
value: "verbose",
|
|
expected: "verbosity: verbose\n",
|
|
},
|
|
{
|
|
name: "set nested key",
|
|
input: "cloud:\n enabled: false\n endpoint_id: \"\"\n",
|
|
key: "cloud.enabled",
|
|
value: "true",
|
|
expected: "cloud:\n enabled: true\n endpoint_id: \"\"\n",
|
|
},
|
|
{
|
|
name: "set deeply nested key",
|
|
input: "dependency_cooldown:\n enabled: true\n days: 5\n",
|
|
key: "dependency_cooldown.days",
|
|
value: "10",
|
|
expected: "dependency_cooldown:\n enabled: true\n days: 10\n",
|
|
},
|
|
{
|
|
name: "preserve comments",
|
|
input: "# Important setting\ntransitive: true\n# Paranoid mode\nparanoid: false\n",
|
|
key: "paranoid",
|
|
value: "true",
|
|
expected: "# Important setting\ntransitive: true\n# Paranoid mode\nparanoid: true\n",
|
|
},
|
|
{
|
|
name: "set string with spaces",
|
|
input: "verbosity: normal\n",
|
|
key: "verbosity",
|
|
value: "my custom value",
|
|
expected: "verbosity: my custom value\n",
|
|
},
|
|
{
|
|
name: "set same value is idempotent",
|
|
input: "paranoid: false\n",
|
|
key: "paranoid",
|
|
value: "false",
|
|
expected: "paranoid: false\n",
|
|
},
|
|
{
|
|
name: "error on empty key",
|
|
input: "transitive: true\n",
|
|
key: "",
|
|
value: "false",
|
|
wantErr: "key cannot be empty",
|
|
},
|
|
{
|
|
name: "error on nonexistent key",
|
|
input: "transitive: true\n",
|
|
key: "nonexistent",
|
|
value: "false",
|
|
wantErr: "key not found",
|
|
},
|
|
{
|
|
name: "error on nonexistent nested key",
|
|
input: "cloud:\n enabled: false\n",
|
|
key: "cloud.nonexistent",
|
|
value: "true",
|
|
wantErr: "key not found",
|
|
},
|
|
{
|
|
name: "error when setting non-leaf node",
|
|
input: "cloud:\n enabled: false\n",
|
|
key: "cloud",
|
|
value: "true",
|
|
wantErr: "cannot set value on non-scalar node",
|
|
},
|
|
{
|
|
name: "error when intermediate key is not a mapping",
|
|
input: "transitive: true\n",
|
|
key: "transitive.nested",
|
|
value: "true",
|
|
wantErr: "intermediate key",
|
|
},
|
|
{
|
|
name: "error on sequence node target",
|
|
input: "trusted_packages:\n - purl: pkg:npm/foo\n reason: test\n",
|
|
key: "trusted_packages",
|
|
value: "true",
|
|
wantErr: "cannot set value on non-scalar node",
|
|
},
|
|
{
|
|
name: "error on invalid bool value",
|
|
input: "paranoid: false\n",
|
|
key: "paranoid",
|
|
value: "falce",
|
|
wantErr: "invalid value",
|
|
},
|
|
{
|
|
name: "error on non-integer for integer field",
|
|
input: "transitive_depth: 5\n",
|
|
key: "transitive_depth",
|
|
value: "abc",
|
|
wantErr: "invalid value",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := setValueInYAML([]byte(tt.input), tt.key, tt.value)
|
|
if tt.wantErr != "" {
|
|
require.Error(t, err)
|
|
assert.Contains(t, err.Error(), tt.wantErr)
|
|
return
|
|
}
|
|
require.NoError(t, err)
|
|
assert.Equal(t, tt.expected, string(result))
|
|
})
|
|
}
|
|
}
|
|
|
|
func Test_createScalarNode(t *testing.T) {
|
|
pos := &token.Position{Line: 1, Column: 1, Offset: 0}
|
|
|
|
tests := []struct {
|
|
name string
|
|
value string
|
|
expectedType ast.NodeType
|
|
}{
|
|
{name: "true is bool", value: "true", expectedType: ast.BoolType},
|
|
{name: "false is bool", value: "false", expectedType: ast.BoolType},
|
|
{name: "positive int", value: "42", expectedType: ast.IntegerType},
|
|
{name: "zero is int", value: "0", expectedType: ast.IntegerType},
|
|
{name: "negative int", value: "-5", expectedType: ast.IntegerType},
|
|
{name: "plain string", value: "hello", expectedType: ast.StringType},
|
|
{name: "float-like is string", value: "3.14", expectedType: ast.StringType},
|
|
{name: "True (capitalized) is string", value: "True", expectedType: ast.StringType},
|
|
{name: "empty string", value: "", expectedType: ast.StringType},
|
|
{name: "numeric-prefix string", value: "123abc", expectedType: ast.StringType},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
node, err := createScalarNode(tt.value, pos)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, tt.expectedType, node.Type())
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestSetConfigValue(t *testing.T) {
|
|
t.Run("creates config from template and sets value", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Setenv("PMG_CONFIG_DIR", tmpDir)
|
|
initConfig()
|
|
|
|
err := SetConfigValue("paranoid", "true")
|
|
require.NoError(t, err)
|
|
|
|
data, err := os.ReadFile(filepath.Join(tmpDir, "config.yml"))
|
|
require.NoError(t, err)
|
|
assert.Contains(t, string(data), "paranoid: true")
|
|
})
|
|
|
|
t.Run("updates existing config preserving other values", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Setenv("PMG_CONFIG_DIR", tmpDir)
|
|
initConfig()
|
|
|
|
configPath := filepath.Join(tmpDir, "config.yml")
|
|
err := os.WriteFile(configPath, []byte("transitive: true\nparanoid: false\n"), 0o644)
|
|
require.NoError(t, err)
|
|
|
|
err = SetConfigValue("paranoid", "true")
|
|
require.NoError(t, err)
|
|
|
|
data, err := os.ReadFile(configPath)
|
|
require.NoError(t, err)
|
|
assert.Contains(t, string(data), "transitive: true")
|
|
assert.Contains(t, string(data), "paranoid: true")
|
|
})
|
|
|
|
t.Run("returns error for nonexistent key", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Setenv("PMG_CONFIG_DIR", tmpDir)
|
|
initConfig()
|
|
|
|
err := os.WriteFile(filepath.Join(tmpDir, "config.yml"), []byte("paranoid: false\n"), 0o644)
|
|
require.NoError(t, err)
|
|
|
|
err = SetConfigValue("nonexistent", "true")
|
|
require.Error(t, err)
|
|
assert.Contains(t, err.Error(), "key not found")
|
|
})
|
|
}
|
|
|
|
func TestGetConfigValue(t *testing.T) {
|
|
configYAML := "paranoid: true\nskip_event_logging: false\nevent_log_retention_days: 10\nverbosity: verbose\n" +
|
|
"cloud:\n enabled: true\n endpoint_id: ep-123\n" +
|
|
"dependency_cooldown:\n enabled: true\n days: 7\n" +
|
|
"proxy:\n install_only: true\n" +
|
|
"sandbox:\n enabled: true\n enforce_always: false\n"
|
|
|
|
setupConfig := func(t *testing.T) {
|
|
t.Helper()
|
|
tmpDir := t.TempDir()
|
|
t.Setenv("PMG_CONFIG_DIR", tmpDir)
|
|
err := os.WriteFile(filepath.Join(tmpDir, "config.yml"), []byte(configYAML), 0o644)
|
|
require.NoError(t, err)
|
|
initConfig()
|
|
}
|
|
|
|
tests := []struct {
|
|
name string
|
|
key string
|
|
expected any
|
|
wantErr string
|
|
}{
|
|
{name: "top-level bool true", key: "paranoid", expected: true},
|
|
{name: "top-level bool false", key: "skip_event_logging", expected: false},
|
|
{name: "top-level integer", key: "event_log_retention_days", expected: 10},
|
|
{name: "top-level string", key: "verbosity", expected: "verbose"},
|
|
{name: "nested bool", key: "cloud.enabled", expected: true},
|
|
{name: "nested string", key: "cloud.endpoint_id", expected: "ep-123"},
|
|
{name: "nested integer", key: "dependency_cooldown.days", expected: 7},
|
|
{name: "nested bool under proxy install_only", key: "proxy.install_only", expected: true},
|
|
{name: "nested bool under sandbox", key: "sandbox.enabled", expected: true},
|
|
{name: "nested bool under sandbox enforce_always", key: "sandbox.enforce_always", expected: false},
|
|
{name: "error on empty key", key: "", wantErr: "key cannot be empty"},
|
|
{name: "error on unknown top-level key", key: "totally_bogus", wantErr: "unknown config key"},
|
|
{name: "error on unknown nested key", key: "cloud.nonexistent", wantErr: "unknown config key"},
|
|
{name: "error on too-deep key", key: "cloud.enabled.deep", wantErr: "unknown config key"},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
setupConfig(t)
|
|
|
|
val, err := GetConfigValue(tt.key)
|
|
if tt.wantErr != "" {
|
|
require.Error(t, err)
|
|
assert.Contains(t, err.Error(), tt.wantErr)
|
|
return
|
|
}
|
|
require.NoError(t, err)
|
|
assert.Equal(t, tt.expected, val)
|
|
})
|
|
}
|
|
|
|
t.Run("returns nested object as map", func(t *testing.T) {
|
|
setupConfig(t)
|
|
|
|
val, err := GetConfigValue("cloud")
|
|
require.NoError(t, err)
|
|
|
|
m, ok := val.(map[string]any)
|
|
require.True(t, ok, "expected map[string]any, got %T", val)
|
|
assert.Equal(t, true, m["enabled"])
|
|
assert.Equal(t, "ep-123", m["endpoint_id"])
|
|
})
|
|
|
|
t.Run("returns defaults when no config file exists", func(t *testing.T) {
|
|
t.Setenv("PMG_CONFIG_DIR", "/tmp/pmg-test/random-does-not-exist")
|
|
initConfig()
|
|
|
|
val, err := GetConfigValue("dependency_cooldown.enabled")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, true, val)
|
|
|
|
val, err = GetConfigValue("paranoid")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, false, val)
|
|
})
|
|
|
|
t.Run("env var overrides config file", func(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Setenv("PMG_CONFIG_DIR", tmpDir)
|
|
t.Setenv("PMG_PARANOID", "true")
|
|
|
|
err := os.WriteFile(filepath.Join(tmpDir, "config.yml"), []byte("paranoid: false\n"), 0o644)
|
|
require.NoError(t, err)
|
|
|
|
initConfig()
|
|
|
|
val, err := GetConfigValue("paranoid")
|
|
require.NoError(t, err)
|
|
// Viper returns env var values as strings
|
|
assert.Equal(t, "true", val)
|
|
})
|
|
}
|
|
|
|
func TestSetStringFieldPreservesType(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
key string
|
|
value string
|
|
}{
|
|
{
|
|
name: "string field set to bool-like value stays string",
|
|
input: "verbosity: normal\n",
|
|
key: "verbosity",
|
|
value: "true",
|
|
},
|
|
{
|
|
name: "string field set to integer-like value stays string",
|
|
input: "verbosity: normal\n",
|
|
key: "verbosity",
|
|
value: "42",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := setValueInYAML([]byte(tt.input), tt.key, tt.value)
|
|
require.NoError(t, err)
|
|
|
|
file, err := parser.ParseBytes(result, parser.ParseComments)
|
|
require.NoError(t, err)
|
|
|
|
root := file.Docs[0].Body.(*ast.MappingNode)
|
|
for _, mv := range root.Values {
|
|
if mv.Key.String() == tt.key {
|
|
assert.Equal(t, ast.StringType, mv.Value.Type(),
|
|
"expected StringType but got %s", mv.Value.Type())
|
|
return
|
|
}
|
|
}
|
|
t.Fatalf("key %q not found in result", tt.key)
|
|
})
|
|
}
|
|
}
|
|
|
|
func Test_needsQuoting(t *testing.T) {
|
|
tests := []struct {
|
|
value string
|
|
expected bool
|
|
}{
|
|
{"true", true},
|
|
{"false", true},
|
|
{"True", true},
|
|
{"False", true},
|
|
{"yes", true},
|
|
{"no", true},
|
|
{"null", true},
|
|
{"42", true},
|
|
{"-5", true},
|
|
{"0", true},
|
|
{"3.14", true},
|
|
{"hello", false},
|
|
{"normal", false},
|
|
{"verbose", false},
|
|
{"", true},
|
|
{"123abc", false},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.value, func(t *testing.T) {
|
|
assert.Equal(t, tt.expected, needsQuoting(tt.value))
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestSetThenGetRoundTrip(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Setenv("PMG_CONFIG_DIR", tmpDir)
|
|
|
|
configPath := filepath.Join(tmpDir, "config.yml")
|
|
err := os.WriteFile(configPath, []byte("paranoid: false\nevent_log_retention_days: 5\nverbosity: normal\n"), 0o644)
|
|
require.NoError(t, err)
|
|
|
|
initConfig()
|
|
|
|
err = SetConfigValue("paranoid", "true")
|
|
require.NoError(t, err)
|
|
|
|
err = SetConfigValue("event_log_retention_days", "20")
|
|
require.NoError(t, err)
|
|
|
|
err = SetConfigValue("verbosity", "silent")
|
|
require.NoError(t, err)
|
|
|
|
// Reload global config from file to pick up changes
|
|
initConfig()
|
|
|
|
val, err := GetConfigValue("paranoid")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, true, val)
|
|
|
|
val, err = GetConfigValue("event_log_retention_days")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, 20, val)
|
|
|
|
val, err = GetConfigValue("verbosity")
|
|
require.NoError(t, err)
|
|
assert.Equal(t, "silent", val)
|
|
}
|