Resolve user config candidates through a shared absolute-native-path gate, preserve precedence, and keep display fallbacks out of filesystem operations. Add focused and native Windows process coverage for unsafe profile environments. Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
This commit is contained in:
parent
53b73e523f
commit
05e3f99ae0
15 changed files with 625 additions and 72 deletions
|
|
@ -168,7 +168,7 @@ var configSetCmd = &cobra.Command{
|
|||
location := "config.yaml"
|
||||
if config.IsUserGlobalKey(key) {
|
||||
setErr = config.SetUserYamlConfig(key, value)
|
||||
location = config.UserConfigYamlPath()
|
||||
location = config.UserConfigYamlDisplayPath()
|
||||
} else {
|
||||
setErr = config.SetYamlConfig(key, value)
|
||||
}
|
||||
|
|
@ -307,7 +307,7 @@ var configGetCmd = &cobra.Command{
|
|||
// opposite of what `bd metrics` actually honors.
|
||||
if config.IsUserGlobalKey(key) {
|
||||
value := config.GetUserYamlConfig(key)
|
||||
location := config.UserConfigYamlPath()
|
||||
location := config.UserConfigYamlDisplayPath()
|
||||
if jsonOutput {
|
||||
return outputJSON(map[string]interface{}{
|
||||
"key": key,
|
||||
|
|
@ -571,7 +571,7 @@ var configUnsetCmd = &cobra.Command{
|
|||
var unsetErr error
|
||||
if config.IsUserGlobalKey(key) {
|
||||
unsetErr = config.UnsetUserYamlConfig(key)
|
||||
location = config.UserConfigYamlPath()
|
||||
location = config.UserConfigYamlDisplayPath()
|
||||
} else {
|
||||
unsetErr = config.UnsetYamlConfig(key)
|
||||
}
|
||||
|
|
@ -927,7 +927,7 @@ Examples:
|
|||
for _, p := range pairs {
|
||||
location := "database"
|
||||
if config.IsUserGlobalKey(p.key) {
|
||||
location = config.UserConfigYamlPath()
|
||||
location = config.UserConfigYamlDisplayPath()
|
||||
} else if config.IsYamlOnlyKey(p.key) {
|
||||
location = "config.yaml"
|
||||
} else if p.key == "beads.role" {
|
||||
|
|
@ -946,7 +946,7 @@ Examples:
|
|||
for _, p := range pairs {
|
||||
location := ""
|
||||
if config.IsUserGlobalKey(p.key) {
|
||||
location = fmt.Sprintf(" (in %s)", config.UserConfigYamlPath())
|
||||
location = fmt.Sprintf(" (in %s)", config.UserConfigYamlDisplayPath())
|
||||
} else if config.IsYamlOnlyKey(p.key) {
|
||||
location = " (in config.yaml)"
|
||||
} else if p.key == "beads.role" {
|
||||
|
|
|
|||
|
|
@ -179,7 +179,7 @@ func collectViperEntries() []configEntry {
|
|||
if value == "" {
|
||||
continue // unset in user-global; runtime uses the built-in default
|
||||
}
|
||||
sourceLabel = config.UserConfigYamlPath()
|
||||
sourceLabel = config.UserConfigYamlDisplayPath()
|
||||
}
|
||||
|
||||
// Skip empty defaults — they add noise without information
|
||||
|
|
|
|||
|
|
@ -409,7 +409,10 @@ func TestCollectViperEntriesMetricsUserGlobalProvenance(t *testing.T) {
|
|||
}
|
||||
// Source is the explicit user-global path, matching `bd config get`, not the
|
||||
// generic project "config.yaml" label.
|
||||
wantSource := config.UserConfigYamlPath()
|
||||
wantSource, err := config.UserConfigYamlPath()
|
||||
if err != nil {
|
||||
t.Fatalf("resolve user config path: %v", err)
|
||||
}
|
||||
if entry.Source != wantSource {
|
||||
t.Errorf("metrics.disabled source = %q, want %q (user-global path)", entry.Source, wantSource)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -741,7 +741,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
return fmt.Errorf("%s set via %s but server mode is not enabled.\n"+
|
||||
" Embedded mode has no host/port — these settings require server mode.\n"+
|
||||
" Set dolt.mode: server in %s or pass --server to bd init.",
|
||||
detail, conflict.source, config.UserConfigYamlPath())
|
||||
detail, conflict.source, config.UserConfigYamlDisplayPath())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -44,9 +44,13 @@ func TestMetricsOnOffWritesUserConfig(t *testing.T) {
|
|||
|
||||
func readUserConfigYAML(t *testing.T) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(config.UserConfigYamlPath())
|
||||
path, err := config.UserConfigYamlPath()
|
||||
if err != nil {
|
||||
t.Fatalf("read user config %s: %v", config.UserConfigYamlPath(), err)
|
||||
t.Fatalf("resolve user config path: %v", err)
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read user config %s: %v", path, err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -109,6 +109,7 @@ func testMainInner(m *testing.M) int {
|
|||
|
||||
_ = os.Setenv("HOME", tmp)
|
||||
_ = os.Setenv("USERPROFILE", tmp) // Windows compatibility
|
||||
_ = os.Setenv("APPDATA", filepath.Join(tmp, "AppData", "Roaming"))
|
||||
_ = os.Setenv("XDG_CONFIG_HOME", filepath.Join(tmp, "xdg-config"))
|
||||
_ = os.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "1")
|
||||
|
||||
|
|
|
|||
145
cmd/bd/user_config_path_windows_test.go
Normal file
145
cmd/bd/user_config_path_windows_test.go
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestMetricsOffRejectsUnsafeUserRootsInNativeProcess exercises the real bd
|
||||
// executable from a sentinel checkout. It models the profile environment a
|
||||
// Git-for-Windows hook can inherit and proves an explicit user-global write
|
||||
// fails before creating a cwd-relative "~" or APPDATA tree.
|
||||
func TestMetricsOffRejectsUnsafeUserRootsInNativeProcess(t *testing.T) {
|
||||
sentinel := t.TempDir()
|
||||
bdBinary := buildBDForInitTests(t)
|
||||
validHome := filepath.Join(sentinel, "bootstrap-home")
|
||||
validAppData := filepath.Join(validHome, "AppData", "Roaming")
|
||||
if err := os.MkdirAll(validAppData, 0o755); err != nil {
|
||||
t.Fatalf("create isolated bootstrap profile: %v", err)
|
||||
}
|
||||
|
||||
baseEnv := filteredWindowsUserConfigEnv(os.Environ())
|
||||
initEnv := append(baseEnv,
|
||||
"HOME="+validHome,
|
||||
"USERPROFILE="+validHome,
|
||||
"APPDATA="+validAppData,
|
||||
"XDG_CONFIG_HOME="+filepath.Join(validHome, ".config"),
|
||||
"BD_DISABLE_METRICS=1",
|
||||
"BD_DISABLE_EVENT_FLUSH=1",
|
||||
"BEADS_TEST_MODE=1",
|
||||
)
|
||||
|
||||
gitInit := exec.Command("git", "init", "--quiet")
|
||||
gitInit.Dir = sentinel
|
||||
gitInit.Env = initEnv
|
||||
if out, err := gitInit.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git init: %v\n%s", err, out)
|
||||
}
|
||||
gitHooks := exec.Command("git", "config", "core.hooksPath", ".git/hooks")
|
||||
gitHooks.Dir = sentinel
|
||||
gitHooks.Env = initEnv
|
||||
if out, err := gitHooks.CombinedOutput(); err != nil {
|
||||
t.Fatalf("isolate git hooks: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
profileEnv []string
|
||||
}{
|
||||
{
|
||||
name: "literal tilde profile",
|
||||
profileEnv: []string{"HOME=~", "USERPROFILE=~", "APPDATA=relative-appdata"},
|
||||
},
|
||||
{
|
||||
name: "missing native profile",
|
||||
profileEnv: []string{"HOME=/c/Users/hook-user", "APPDATA=relative-appdata"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
env := append([]string{}, baseEnv...)
|
||||
env = append(env, tt.profileEnv...)
|
||||
env = append(env,
|
||||
"BD_DISABLE_METRICS=1",
|
||||
"BD_DISABLE_EVENT_FLUSH=1",
|
||||
"BEADS_TEST_MODE=1",
|
||||
)
|
||||
|
||||
cmd := exec.Command(bdBinary, "metrics", "off")
|
||||
cmd.Dir = sentinel
|
||||
cmd.Env = env
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err == nil {
|
||||
t.Fatalf("metrics off unexpectedly succeeded:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(string(out), "not an absolute native path") &&
|
||||
!strings.Contains(string(out), "cannot find home directory") {
|
||||
t.Fatalf("metrics off did not report path resolution failure: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
for _, relativeRoot := range []string{"~", "relative-appdata"} {
|
||||
if _, statErr := os.Stat(filepath.Join(sentinel, relativeRoot)); !os.IsNotExist(statErr) {
|
||||
t.Errorf("unsafe relative root %q was materialized: %v", relativeRoot, statErr)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("hook skips implicit bootstrap when profile is missing", func(t *testing.T) {
|
||||
env := append([]string{}, baseEnv...)
|
||||
env = append(env,
|
||||
"HOME=/c/Users/hook-user",
|
||||
"APPDATA=relative-appdata",
|
||||
"BD_DISABLE_EVENT_FLUSH=1",
|
||||
"BEADS_TEST_MODE=1",
|
||||
)
|
||||
|
||||
cmd := exec.Command(bdBinary, "hooks", "run", "pre-commit")
|
||||
cmd.Dir = sentinel
|
||||
cmd.Env = env
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("hooks run pre-commit failed after user config resolution was skipped: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
for _, relativeRoot := range []string{"~", "relative-appdata"} {
|
||||
if _, statErr := os.Stat(filepath.Join(sentinel, relativeRoot)); !os.IsNotExist(statErr) {
|
||||
t.Errorf("unsafe relative root %q was materialized by hook process: %v", relativeRoot, statErr)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func filteredWindowsUserConfigEnv(env []string) []string {
|
||||
blocked := map[string]bool{
|
||||
"HOME": true,
|
||||
"USERPROFILE": true,
|
||||
"HOMEDRIVE": true,
|
||||
"HOMEPATH": true,
|
||||
"APPDATA": true,
|
||||
"LOCALAPPDATA": true,
|
||||
"XDG_CONFIG_HOME": true,
|
||||
"BEADS_DIR": true,
|
||||
"BEADS_DB": true,
|
||||
"BD_DB": true,
|
||||
"BD_DISABLE_METRICS": true,
|
||||
"BD_DISABLE_EVENT_FLUSH": true,
|
||||
"DO_NOT_TRACK": true,
|
||||
"BEADS_TEST_MODE": true,
|
||||
"BEADS_TEST_IGNORE_REPO_CONFIG": true,
|
||||
}
|
||||
out := make([]string, 0, len(env))
|
||||
for _, entry := range env {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
if blocked[strings.ToUpper(key)] {
|
||||
continue
|
||||
}
|
||||
out = append(out, entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
@ -64,7 +64,9 @@ func Initialize() error {
|
|||
// subsequent file so higher-priority values overwrite lower-priority ones.
|
||||
//
|
||||
// Precedence (highest to lowest):
|
||||
// BEADS_DIR/config.yaml > project .beads/config.yaml > ~/.config/bd/config.yaml > ~/.beads/config.yaml
|
||||
// BEADS_DIR/config.yaml > project .beads/config.yaml > documented
|
||||
// <home>/.config/bd/config.yaml > native os.UserConfigDir()/bd/config.yaml
|
||||
// > legacy <home>/.beads/config.yaml
|
||||
//
|
||||
// Previously, only ONE config file was loaded (the highest-priority match),
|
||||
// which meant user-level config was silently ignored when project-level
|
||||
|
|
@ -72,41 +74,28 @@ func Initialize() error {
|
|||
var configPaths []string // ordered lowest priority first
|
||||
var primaryConfigPath string // project-level config (for config.local.yaml and SaveConfigValue)
|
||||
|
||||
// 3. Legacy: ~/.beads/config.yaml (lowest priority)
|
||||
if homeDir, err := os.UserHomeDir(); err == nil {
|
||||
p := filepath.Join(homeDir, ".beads", "config.yaml")
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
configPaths = append(configPaths, p)
|
||||
// User-level paths are built once through the same absolute-native-path
|
||||
// gate used by direct reads and writes. Invalid roots are silently skipped
|
||||
// here because Initialize is an implicit read path: absent user config is a
|
||||
// supported state, while a relative root must never reach os.Stat.
|
||||
userConfigPaths := currentUserConfigYamlCandidates()
|
||||
appendExistingUserConfig := func(path string) {
|
||||
if !userConfigPathExists(path) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 2. User: ~/.config/bd/config.yaml
|
||||
if configDir, err := os.UserConfigDir(); err == nil {
|
||||
p := filepath.Join(configDir, "bd", "config.yaml")
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
configPaths = append(configPaths, p)
|
||||
}
|
||||
}
|
||||
|
||||
// Also check ~/.config/bd/config.yaml explicitly. On macOS,
|
||||
// os.UserConfigDir() returns ~/Library/Application Support, not ~/.config.
|
||||
// This ensures the documented path works on all platforms.
|
||||
if homeDir, err := os.UserHomeDir(); err == nil {
|
||||
xdgPath := filepath.Join(homeDir, ".config", "bd", "config.yaml")
|
||||
alreadyAdded := false
|
||||
for _, existing := range configPaths {
|
||||
if filepath.Clean(existing) == filepath.Clean(xdgPath) {
|
||||
alreadyAdded = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !alreadyAdded {
|
||||
if _, err := os.Stat(xdgPath); err == nil {
|
||||
configPaths = append(configPaths, xdgPath)
|
||||
if filepath.Clean(existing) == path {
|
||||
return
|
||||
}
|
||||
}
|
||||
configPaths = append(configPaths, path)
|
||||
}
|
||||
|
||||
// Lowest to highest user-level precedence: legacy, native, documented.
|
||||
appendExistingUserConfig(userConfigPaths.legacy)
|
||||
appendExistingUserConfig(userConfigPaths.native)
|
||||
appendExistingUserConfig(userConfigPaths.documented)
|
||||
|
||||
// 1. Project: walk up from CWD to find .beads/config.yaml
|
||||
beadsDirEnv := strings.TrimSpace(os.Getenv("BEADS_DIR"))
|
||||
beadsEnvConfigPath := ""
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ func TestMain(m *testing.M) {
|
|||
_ = os.Chdir(tmp)
|
||||
_ = os.Setenv("HOME", tmp)
|
||||
_ = os.Setenv("USERPROFILE", tmp) // Windows compatibility
|
||||
_ = os.Setenv("APPDATA", filepath.Join(tmp, "AppData", "Roaming"))
|
||||
_ = os.Setenv("XDG_CONFIG_HOME", filepath.Join(tmp, "xdg-config"))
|
||||
|
||||
code := m.Run()
|
||||
|
|
|
|||
111
internal/config/user_config_path.go
Normal file
111
internal/config/user_config_path.go
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const userConfigYamlDisplayFallback = "~/.config/bd/config.yaml"
|
||||
|
||||
// userConfigYamlCandidates contains only cleaned, absolute paths suitable for
|
||||
// the current operating system's filesystem APIs. A missing candidate means
|
||||
// its source could not be resolved safely.
|
||||
type userConfigYamlCandidates struct {
|
||||
legacy string // <home>/.beads/config.yaml
|
||||
native string // <os.UserConfigDir()>/bd/config.yaml
|
||||
documented string // <home>/.config/bd/config.yaml
|
||||
|
||||
homeErr error
|
||||
nativeErr error
|
||||
}
|
||||
|
||||
func currentUserConfigYamlCandidates() userConfigYamlCandidates {
|
||||
homeDir, homeErr := os.UserHomeDir()
|
||||
nativeConfigDir, nativeErr := os.UserConfigDir()
|
||||
return buildUserConfigYamlCandidates(homeDir, homeErr, nativeConfigDir, nativeErr)
|
||||
}
|
||||
|
||||
func buildUserConfigYamlCandidates(homeDir string, homeErr error, nativeConfigDir string, nativeErr error) userConfigYamlCandidates {
|
||||
var candidates userConfigYamlCandidates
|
||||
|
||||
if home, err := cleanAbsoluteUserDirectory("user home directory", homeDir, homeErr); err != nil {
|
||||
candidates.homeErr = err
|
||||
} else {
|
||||
candidates.legacy = filepath.Clean(filepath.Join(home, ".beads", "config.yaml"))
|
||||
candidates.documented = filepath.Clean(filepath.Join(home, ".config", "bd", "config.yaml"))
|
||||
}
|
||||
|
||||
if nativeDir, err := cleanAbsoluteUserDirectory("native user config directory", nativeConfigDir, nativeErr); err != nil {
|
||||
candidates.nativeErr = err
|
||||
} else {
|
||||
candidates.native = filepath.Clean(filepath.Join(nativeDir, "bd", "config.yaml"))
|
||||
}
|
||||
|
||||
return candidates
|
||||
}
|
||||
|
||||
func cleanAbsoluteUserDirectory(label, path string, resolutionErr error) (string, error) {
|
||||
if resolutionErr != nil {
|
||||
return "", fmt.Errorf("%s: %w", label, resolutionErr)
|
||||
}
|
||||
cleaned := filepath.Clean(path)
|
||||
if !filepath.IsAbs(cleaned) {
|
||||
return "", fmt.Errorf("%s %q is not an absolute native path", label, path)
|
||||
}
|
||||
return cleaned, nil
|
||||
}
|
||||
|
||||
// UserConfigYamlPath resolves the user-level config.yaml to a cleaned,
|
||||
// absolute path suitable for native filesystem APIs. It prefers the documented
|
||||
// <home>/.config/bd location when that file exists, then an existing native
|
||||
// os.UserConfigDir location. For a new file it keeps the documented location
|
||||
// as the creation target when possible, falling back to the native location
|
||||
// only when the home directory itself cannot be resolved safely.
|
||||
func UserConfigYamlPath() (string, error) {
|
||||
return selectUserConfigYamlPath(currentUserConfigYamlCandidates())
|
||||
}
|
||||
|
||||
func selectUserConfigYamlPath(candidates userConfigYamlCandidates) (string, error) {
|
||||
if userConfigPathExists(candidates.documented) {
|
||||
return candidates.documented, nil
|
||||
}
|
||||
if candidates.native != candidates.documented && userConfigPathExists(candidates.native) {
|
||||
return candidates.native, nil
|
||||
}
|
||||
if candidates.documented != "" {
|
||||
return candidates.documented, nil
|
||||
}
|
||||
if candidates.native != "" {
|
||||
return candidates.native, nil
|
||||
}
|
||||
|
||||
err := errors.Join(candidates.homeErr, candidates.nativeErr)
|
||||
if err == nil {
|
||||
err = errors.New("no absolute native user directory is available")
|
||||
}
|
||||
return "", fmt.Errorf("resolve user config.yaml: %w", err)
|
||||
}
|
||||
|
||||
// UserConfigYamlDisplayPath returns a human-readable location for command
|
||||
// output. The tilde form is deliberately confined to this display-only API and
|
||||
// must never be passed to a filesystem operation.
|
||||
func UserConfigYamlDisplayPath() string {
|
||||
return userConfigYamlDisplayPath(currentUserConfigYamlCandidates())
|
||||
}
|
||||
|
||||
func userConfigYamlDisplayPath(candidates userConfigYamlCandidates) string {
|
||||
if path, err := selectUserConfigYamlPath(candidates); err == nil {
|
||||
return path
|
||||
}
|
||||
return userConfigYamlDisplayFallback
|
||||
}
|
||||
|
||||
func userConfigPathExists(path string) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
247
internal/config/user_config_path_test.go
Normal file
247
internal/config/user_config_path_test.go
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSelectUserConfigYamlPathPrecedence(t *testing.T) {
|
||||
t.Run("existing documented path wins", func(t *testing.T) {
|
||||
home, native := userConfigTestRoots(t)
|
||||
candidates := buildUserConfigYamlCandidates(home, nil, native, nil)
|
||||
writeUserConfigPath(t, candidates.native)
|
||||
writeUserConfigPath(t, candidates.documented)
|
||||
|
||||
got, err := selectUserConfigYamlPath(candidates)
|
||||
if err != nil {
|
||||
t.Fatalf("selectUserConfigYamlPath: %v", err)
|
||||
}
|
||||
if got != candidates.documented {
|
||||
t.Fatalf("path = %q, want documented path %q", got, candidates.documented)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("existing native path wins over a missing documented path", func(t *testing.T) {
|
||||
home, native := userConfigTestRoots(t)
|
||||
candidates := buildUserConfigYamlCandidates(home, nil, native, nil)
|
||||
writeUserConfigPath(t, candidates.native)
|
||||
|
||||
got, err := selectUserConfigYamlPath(candidates)
|
||||
if err != nil {
|
||||
t.Fatalf("selectUserConfigYamlPath: %v", err)
|
||||
}
|
||||
if got != candidates.native {
|
||||
t.Fatalf("path = %q, want existing native path %q", got, candidates.native)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("documented path is the preferred creation target", func(t *testing.T) {
|
||||
home, native := userConfigTestRoots(t)
|
||||
candidates := buildUserConfigYamlCandidates(home, nil, native, nil)
|
||||
|
||||
got, err := selectUserConfigYamlPath(candidates)
|
||||
if err != nil {
|
||||
t.Fatalf("selectUserConfigYamlPath: %v", err)
|
||||
}
|
||||
if got != candidates.documented {
|
||||
t.Fatalf("path = %q, want documented creation target %q", got, candidates.documented)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("native path is the creation fallback when home is unsafe", func(t *testing.T) {
|
||||
_, native := userConfigTestRoots(t)
|
||||
candidates := buildUserConfigYamlCandidates("~", nil, native, nil)
|
||||
|
||||
got, err := selectUserConfigYamlPath(candidates)
|
||||
if err != nil {
|
||||
t.Fatalf("selectUserConfigYamlPath: %v", err)
|
||||
}
|
||||
if got != candidates.native {
|
||||
t.Fatalf("path = %q, want native creation target %q", got, candidates.native)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestUserConfigYamlCandidatesRequireAbsoluteNativeRoots(t *testing.T) {
|
||||
resolutionFailure := errors.New("not available")
|
||||
tests := []struct {
|
||||
name string
|
||||
home string
|
||||
homeErr error
|
||||
native string
|
||||
nativeErr error
|
||||
}{
|
||||
{name: "literal tilde", home: "~", native: "relative-config"},
|
||||
{name: "empty roots", home: "", native: ""},
|
||||
{name: "resolver errors", homeErr: resolutionFailure, nativeErr: resolutionFailure},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
candidates := buildUserConfigYamlCandidates(tt.home, tt.homeErr, tt.native, tt.nativeErr)
|
||||
if candidates.legacy != "" || candidates.documented != "" || candidates.native != "" {
|
||||
t.Fatalf("unsafe roots produced filesystem candidates: %#v", candidates)
|
||||
}
|
||||
if _, err := selectUserConfigYamlPath(candidates); err == nil {
|
||||
t.Fatal("selectUserConfigYamlPath returned nil error for unsafe roots")
|
||||
}
|
||||
if got := userConfigYamlDisplayPath(candidates); got != userConfigYamlDisplayFallback {
|
||||
t.Fatalf("display path = %q, want compatibility fallback %q", got, userConfigYamlDisplayFallback)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserConfigYamlCandidatesAreCleanAndAbsolute(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
home := filepath.Join(base, "profile", "..", "home")
|
||||
native := filepath.Join(base, "native", ".", "config")
|
||||
candidates := buildUserConfigYamlCandidates(home, nil, native, nil)
|
||||
|
||||
for name, path := range map[string]string{
|
||||
"legacy": candidates.legacy,
|
||||
"native": candidates.native,
|
||||
"documented": candidates.documented,
|
||||
} {
|
||||
if !filepath.IsAbs(path) {
|
||||
t.Errorf("%s path %q is not absolute", name, path)
|
||||
}
|
||||
if filepath.Clean(path) != path {
|
||||
t.Errorf("%s path %q is not clean", name, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelativeUserRootsNeverReachImplicitOrExplicitFilesystemPaths(t *testing.T) {
|
||||
ResetForTesting()
|
||||
t.Cleanup(ResetForTesting)
|
||||
sentinel := t.TempDir()
|
||||
t.Chdir(sentinel)
|
||||
t.Setenv("HOME", "~")
|
||||
t.Setenv("USERPROFILE", "~")
|
||||
t.Setenv("HOMEDRIVE", "")
|
||||
t.Setenv("HOMEPATH", "")
|
||||
t.Setenv("XDG_CONFIG_HOME", "relative-xdg")
|
||||
t.Setenv("APPDATA", "relative-appdata")
|
||||
|
||||
path, err := UserConfigYamlPath()
|
||||
if err == nil {
|
||||
t.Fatalf("UserConfigYamlPath() = %q, nil; want resolution error", path)
|
||||
}
|
||||
if path != "" {
|
||||
t.Fatalf("UserConfigYamlPath() returned unsafe path %q with error %v", path, err)
|
||||
}
|
||||
|
||||
if got := GetUserYamlConfig("metrics.disabled"); got != "" {
|
||||
t.Fatalf("implicit read = %q, want absent value on resolution failure", got)
|
||||
}
|
||||
if err := Initialize(); err != nil {
|
||||
t.Fatalf("Initialize should skip unsafe user roots, got: %v", err)
|
||||
}
|
||||
if err := SetUserYamlConfig("metrics.disabled", "true"); err == nil {
|
||||
t.Fatal("SetUserYamlConfig returned nil error for unsafe roots")
|
||||
}
|
||||
if err := UnsetUserYamlConfig("metrics.disabled"); err == nil {
|
||||
t.Fatal("UnsetUserYamlConfig returned nil error for unsafe roots")
|
||||
}
|
||||
|
||||
for _, relativeRoot := range []string{"~", "relative-xdg", "relative-appdata"} {
|
||||
if _, statErr := os.Stat(filepath.Join(sentinel, relativeRoot)); !os.IsNotExist(statErr) {
|
||||
t.Errorf("unsafe relative root %q was materialized: %v", relativeRoot, statErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeUserConfigPrecedence(t *testing.T) {
|
||||
ResetForTesting()
|
||||
t.Cleanup(ResetForTesting)
|
||||
restore := envSnapshot(t)
|
||||
defer restore()
|
||||
|
||||
root := t.TempDir()
|
||||
home := filepath.Join(root, "home")
|
||||
nativeRoot := filepath.Join(root, "native-config")
|
||||
projectRoot := filepath.Join(root, "project")
|
||||
projectConfig := filepath.Join(projectRoot, ".beads", "config.yaml")
|
||||
beadsConfig := filepath.Join(root, "explicit", ".beads", "config.yaml")
|
||||
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("APPDATA", nativeRoot)
|
||||
t.Setenv("XDG_CONFIG_HOME", nativeRoot)
|
||||
t.Setenv("BD_ACTOR", "")
|
||||
t.Setenv("BEADS_ACTOR", "")
|
||||
t.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "")
|
||||
|
||||
candidates := currentUserConfigYamlCandidates()
|
||||
if candidates.legacy == "" || candidates.native == "" || candidates.documented == "" {
|
||||
t.Fatalf("test environment did not resolve all user config candidates: %#v", candidates)
|
||||
}
|
||||
if candidates.native == candidates.documented {
|
||||
t.Fatalf("test requires distinct native and documented paths, both were %q", candidates.native)
|
||||
}
|
||||
|
||||
writeConfigActor(t, candidates.legacy, "legacy")
|
||||
writeConfigActor(t, candidates.native, "native")
|
||||
writeConfigActor(t, candidates.documented, "documented")
|
||||
writeConfigActor(t, projectConfig, "project")
|
||||
writeConfigActor(t, beadsConfig, "beads-dir")
|
||||
t.Chdir(projectRoot)
|
||||
t.Setenv("BEADS_DIR", filepath.Dir(beadsConfig))
|
||||
|
||||
assertInitializedActor(t, "beads-dir")
|
||||
t.Setenv("BEADS_DIR", "")
|
||||
assertInitializedActor(t, "project")
|
||||
removeConfigPath(t, projectConfig)
|
||||
assertInitializedActor(t, "documented")
|
||||
removeConfigPath(t, candidates.documented)
|
||||
assertInitializedActor(t, "native")
|
||||
removeConfigPath(t, candidates.native)
|
||||
assertInitializedActor(t, "legacy")
|
||||
}
|
||||
|
||||
func userConfigTestRoots(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
base := t.TempDir()
|
||||
return filepath.Join(base, "home"), filepath.Join(base, "native")
|
||||
}
|
||||
|
||||
func writeUserConfigPath(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("actor: test\n"), 0o600); err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeConfigActor(t *testing.T, path, actor string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("actor: "+actor+"\n"), 0o600); err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func removeConfigPath(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatalf("remove %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertInitializedActor(t *testing.T, want string) {
|
||||
t.Helper()
|
||||
ResetForTesting()
|
||||
if err := Initialize(); err != nil {
|
||||
t.Fatalf("Initialize: %v", err)
|
||||
}
|
||||
if got := GetString("actor"); got != want {
|
||||
t.Fatalf("actor = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
37
internal/config/user_config_path_windows_test.go
Normal file
37
internal/config/user_config_path_windows_test.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
//go:build windows
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWindowsUserConfigCandidatesRejectMSYSRoots(t *testing.T) {
|
||||
candidates := buildUserConfigYamlCandidates("/c/Users/tester", nil, "/c/Users/tester/AppData/Roaming", nil)
|
||||
if candidates.legacy != "" || candidates.documented != "" || candidates.native != "" {
|
||||
t.Fatalf("MSYS roots produced native filesystem candidates: %#v", candidates)
|
||||
}
|
||||
if _, err := selectUserConfigYamlPath(candidates); err == nil {
|
||||
t.Fatal("selectUserConfigYamlPath returned nil error for MSYS roots")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsUserConfigCandidatesAcceptUNCPaths(t *testing.T) {
|
||||
home := `\\server\profiles\tester`
|
||||
native := `\\server\profiles\tester\AppData\Roaming`
|
||||
candidates := buildUserConfigYamlCandidates(home, nil, native, nil)
|
||||
|
||||
for name, path := range map[string]string{
|
||||
"legacy": candidates.legacy,
|
||||
"native": candidates.native,
|
||||
"documented": candidates.documented,
|
||||
} {
|
||||
if !filepath.IsAbs(path) {
|
||||
t.Errorf("%s UNC path %q is not absolute", name, path)
|
||||
}
|
||||
}
|
||||
if candidates.documented != filepath.Join(home, ".config", "bd", "config.yaml") {
|
||||
t.Fatalf("documented UNC path = %q", candidates.documented)
|
||||
}
|
||||
}
|
||||
|
|
@ -341,7 +341,11 @@ func IsUserGlobalKey(key string) bool {
|
|||
// never re-enable metrics for a user who opted out, nor redirect where metrics
|
||||
// are sent. See MetricsDisabledByUserConfig / UserMetricsEndpoint.
|
||||
func readUserGlobalYamlValue(key string) (string, bool) {
|
||||
return readYamlValueAtPath(UserConfigYamlPath(), key)
|
||||
configPath, err := UserConfigYamlPath()
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return readYamlValueAtPath(configPath, key)
|
||||
}
|
||||
|
||||
// WorkspaceYamlValue reads a single dotted key out of ONE workspace's
|
||||
|
|
@ -453,10 +457,13 @@ func MetricsNoticeShownByUserConfig() bool {
|
|||
}
|
||||
|
||||
func UnsetUserYamlConfig(key string) error {
|
||||
configPath := UserConfigYamlPath()
|
||||
configPath, err := UserConfigYamlPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
normalizedKey := normalizeYamlKey(key)
|
||||
|
||||
content, err := os.ReadFile(configPath) //nolint:gosec // configPath is from UserConfigYamlPath
|
||||
content, err := os.ReadFile(configPath) //nolint:gosec // configPath is a validated absolute user config path
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
|
|
@ -480,7 +487,10 @@ func SetUserYamlConfig(key, value string) error {
|
|||
if err := validateYamlConfigValue(key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
configPath := UserConfigYamlPath()
|
||||
configPath, err := UserConfigYamlPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
|
||||
return fmt.Errorf("failed to create user config directory: %w", err)
|
||||
}
|
||||
|
|
@ -609,32 +619,6 @@ func projectConfigPathFromLoadedState() string {
|
|||
return configPath
|
||||
}
|
||||
|
||||
// UserConfigYamlPath returns the platform-appropriate path for the
|
||||
// user-level config.yaml file. On Linux this is typically
|
||||
// ~/.config/bd/config.yaml; on macOS it checks ~/.config/bd/ first
|
||||
// (the documented cross-platform path) and falls back to
|
||||
// ~/Library/Application Support/bd/.
|
||||
func UserConfigYamlPath() string {
|
||||
// Prefer ~/.config/bd/config.yaml — it's the documented path and
|
||||
// works on all platforms after GH#3532.
|
||||
if homeDir, err := os.UserHomeDir(); err == nil {
|
||||
xdgPath := filepath.Join(homeDir, ".config", "bd", "config.yaml")
|
||||
if _, err := os.Stat(xdgPath); err == nil {
|
||||
return xdgPath
|
||||
}
|
||||
// If it doesn't exist yet, still prefer it as the recommendation
|
||||
// unless the os.UserConfigDir() path already has a file.
|
||||
if configDir, err := os.UserConfigDir(); err == nil {
|
||||
osPath := filepath.Join(configDir, "bd", "config.yaml")
|
||||
if _, err := os.Stat(osPath); err == nil {
|
||||
return osPath
|
||||
}
|
||||
}
|
||||
return xdgPath // recommend the cross-platform path
|
||||
}
|
||||
return "~/.config/bd/config.yaml" // fallback display string
|
||||
}
|
||||
|
||||
func findProjectBeadsDir() string {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -17,9 +17,12 @@ import (
|
|||
var commentedMetricsRe = regexp.MustCompile(`(?m)^\s*#\s*metrics\s*:`)
|
||||
|
||||
func EnsureUserConfigDefaults() error {
|
||||
path := config.UserConfigYamlPath()
|
||||
path, err := config.UserConfigYamlPath()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ensure user config: %w", err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path) //nolint:gosec // path comes from config.UserConfigYamlPath
|
||||
data, err := os.ReadFile(path) //nolint:gosec // path is a validated absolute user config path
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return writeUserConfigBootstrap(path)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ func setupUserConfigHome(t *testing.T) string {
|
|||
t.Helper()
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming"))
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
return home
|
||||
}
|
||||
|
|
@ -197,3 +199,29 @@ func TestEnsureUserConfigDefaults_ConfigDirIsFile_FailsLoudly(t *testing.T) {
|
|||
t.Fatal("expected an error when ~/.config is a file, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureUserConfigDefaults_UnsafeRootsFailBeforeMutation(t *testing.T) {
|
||||
sentinel := t.TempDir()
|
||||
t.Chdir(sentinel)
|
||||
t.Setenv("HOME", "~")
|
||||
t.Setenv("USERPROFILE", "~")
|
||||
t.Setenv("HOMEDRIVE", "")
|
||||
t.Setenv("HOMEPATH", "")
|
||||
t.Setenv("XDG_CONFIG_HOME", "relative-xdg")
|
||||
t.Setenv("APPDATA", "relative-appdata")
|
||||
|
||||
err := EnsureUserConfigDefaults()
|
||||
if err == nil {
|
||||
t.Fatal("EnsureUserConfigDefaults returned nil error for unsafe user roots")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "resolve user config.yaml") ||
|
||||
!strings.Contains(err.Error(), "not an absolute native path") {
|
||||
t.Fatalf("EnsureUserConfigDefaults error = %v, want native path resolution context", err)
|
||||
}
|
||||
|
||||
for _, relativeRoot := range []string{"~", "relative-xdg", "relative-appdata"} {
|
||||
if _, statErr := os.Stat(filepath.Join(sentinel, relativeRoot)); !os.IsNotExist(statErr) {
|
||||
t.Errorf("unsafe relative root %q was materialized: %v", relativeRoot, statErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue