From 6bf1f31f56e4060f1bc2ccc0bcf069e04ab4f418 Mon Sep 17 00:00:00 2001 From: Rob Zolkos Date: Fri, 13 Nov 2026 11:42:47 -0500 Subject: [PATCH 1/3] Ignore a local config's api_url and token until it is trusted A .fizzy.yaml is found by walking up from the working directory, so a cloned repo supplies one. Its api_url and token were applied as written, which let a repo choose the host a saved token is sent to. An untrusted local config now sets only the account and the board. Its api_url and token apply after `fizzy config trust`, which records a digest of those two values: changing either leaves the file untrusted until it is trusted again. `fizzy setup` trusts the local file it writes, `fizzy config untrust` removes the trust, and doctor reports ignored settings. With no profile chosen, the configured account names the credential. A stored profile's token now goes to that profile's own host rather than the host the YAML config or the default names. --- AGENTS.md | 8 + README.md | 7 + SURFACE.txt | 34 ++++ internal/commands/config_cmd.go | 60 ++++++- internal/commands/config_cmd_test.go | 108 ++++++++++++ internal/commands/doctor.go | 29 +++- internal/commands/doctor_test.go | 3 + internal/commands/root.go | 25 +++ internal/commands/setup.go | 5 + internal/config/config.go | 54 +++--- internal/config/config_test.go | 2 + internal/config/trust.go | 251 +++++++++++++++++++++++++++ internal/config/trust_test.go | 193 ++++++++++++++++++++ skills/fizzy/SKILL.md | 5 + 14 files changed, 760 insertions(+), 24 deletions(-) create mode 100644 internal/config/trust.go create mode 100644 internal/config/trust_test.go diff --git a/AGENTS.md b/AGENTS.md index 1a057f2d..479bb3de 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,6 +90,14 @@ The CLI reads config from multiple sources with this priority: `FIZZY_ACCOUNT` is accepted as a deprecated alias for `FIZZY_PROFILE`. +**Local config trust.** A `.fizzy.yaml` is found by walking up from the working +directory, so a cloned repo supplies one. It sets `account` and `board` whoever wrote +it. Its `api_url` and `token` decide where a credential is sent and which one, so +`config.LoadLocal` (`internal/config/trust.go`) drops them, with a warning, unless +`fizzy config trust` recorded a digest of those two values that still matches. Anything +that reads the local file for its settings goes through `LoadLocal`, never around it, +and a new key that can redirect or replace a credential joins `trustDigest`. + **`--board` is command-scoped, not global.** `fizzy --board X ...` fails with `unknown flag`; it is declared per-command, by nineteen of them across the activity, board, card, column and webhook groups. So `fizzy card list --board X` works while diff --git a/README.md b/README.md index f0fb9877..ac97e450 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,13 @@ Configuration priority (highest to lowest): `FIZZY_ACCOUNT` is accepted as a deprecated alias for `FIZZY_PROFILE`. +A local `.fizzy.yaml` sets the account and the board. Its `api_url` and `token` decide +where your credentials are sent, so they are ignored, with a warning, until you trust the +file: read it, then run `fizzy config trust` in that directory. Trust covers those two +settings as they are: if either changes, as a pull can change them, the file needs trusting +again. `fizzy setup` trusts the local file it writes, and `fizzy config untrust` removes +the trust. + Profiles created by `fizzy setup` use the account slug as their name and continue to work without changes. A profile can also use a distinct name by storing its account in the profile's `extra` settings. This supports separate credentials for multiple users of the same account: ```bash diff --git a/SURFACE.txt b/SURFACE.txt index 9a425555..4c5fc33d 100644 --- a/SURFACE.txt +++ b/SURFACE.txt @@ -13,6 +13,8 @@ ARG fizzy comment attachments help 00 [command] ARG fizzy comment help 00 [command] ARG fizzy completion 00 [bash|zsh|fish|powershell] ARG fizzy config help 00 [command] +ARG fizzy config trust 00 [path] +ARG fizzy config untrust 00 [path] ARG fizzy help 00 [command] ARG fizzy identity help 00 [command] ARG fizzy migrate help 00 [command] @@ -138,6 +140,8 @@ CMD fizzy config CMD fizzy config explain CMD fizzy config help CMD fizzy config show +CMD fizzy config trust +CMD fizzy config untrust CMD fizzy config view CMD fizzy doctor CMD fizzy help @@ -1897,6 +1901,34 @@ FLAG fizzy config show --quiet type=bool FLAG fizzy config show --styled type=bool FLAG fizzy config show --token type=string FLAG fizzy config show --verbose type=bool +FLAG fizzy config trust --agent type=bool +FLAG fizzy config trust --api-url type=string +FLAG fizzy config trust --count type=bool +FLAG fizzy config trust --help type=bool +FLAG fizzy config trust --ids-only type=bool +FLAG fizzy config trust --jq type=string +FLAG fizzy config trust --json type=bool +FLAG fizzy config trust --limit type=int +FLAG fizzy config trust --markdown type=bool +FLAG fizzy config trust --profile type=string +FLAG fizzy config trust --quiet type=bool +FLAG fizzy config trust --styled type=bool +FLAG fizzy config trust --token type=string +FLAG fizzy config trust --verbose type=bool +FLAG fizzy config untrust --agent type=bool +FLAG fizzy config untrust --api-url type=string +FLAG fizzy config untrust --count type=bool +FLAG fizzy config untrust --help type=bool +FLAG fizzy config untrust --ids-only type=bool +FLAG fizzy config untrust --jq type=string +FLAG fizzy config untrust --json type=bool +FLAG fizzy config untrust --limit type=int +FLAG fizzy config untrust --markdown type=bool +FLAG fizzy config untrust --profile type=string +FLAG fizzy config untrust --quiet type=bool +FLAG fizzy config untrust --styled type=bool +FLAG fizzy config untrust --token type=string +FLAG fizzy config untrust --verbose type=bool FLAG fizzy config view --agent type=bool FLAG fizzy config view --api-url type=string FLAG fizzy config view --count type=bool @@ -3463,6 +3495,8 @@ SUB fizzy config SUB fizzy config explain SUB fizzy config help SUB fizzy config show +SUB fizzy config trust +SUB fizzy config untrust SUB fizzy config view SUB fizzy doctor SUB fizzy help diff --git a/internal/commands/config_cmd.go b/internal/commands/config_cmd.go index a2798d00..60cee968 100644 --- a/internal/commands/config_cmd.go +++ b/internal/commands/config_cmd.go @@ -93,10 +93,68 @@ from flags, environment variables, profile settings, local config, and global co }, } +var configTrustCmd = &cobra.Command{ + Use: "trust [path]", + Short: "Trust a local config's api_url and token", + Long: `Trust the api_url and token in a local config (.fizzy.yaml), so they apply. + +A local config sets the account and the board without trust. Its api_url and +token decide where your credentials are sent, so they are ignored until you +trust the file. Trust covers those two settings as they are now: if either +changes, as a pull or a checkout can change them, the file is untrusted again. + +Without a path, trusts the nearest .fizzy.yaml, in this directory or a parent. +Read the file first.`, + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + entry, err := cfgpkg.TrustLocal(firstArg(args)) + if err != nil { + return &output.Error{Code: output.CodeUsage, Message: err.Error()} + } + printDetail(map[string]any{"path": entry.Path, "trusted": true}, "Trusted "+entry.Path, []Breadcrumb{ + breadcrumb("show", "fizzy config show", "Show the effective config"), + breadcrumb("untrust", "fizzy config untrust", "Remove the trust"), + }) + return nil + }, +} + +var configUntrustCmd = &cobra.Command{ + Use: "untrust [path]", + Short: "Remove trust from a local config", + Long: `Remove trust from a local config (.fizzy.yaml), so its api_url and token are ignored again. + +Without a path, untrusts the nearest .fizzy.yaml, in this directory or a parent.`, + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + path, removed, err := cfgpkg.UntrustLocal(firstArg(args)) + if err != nil { + return &output.Error{Code: output.CodeUsage, Message: err.Error()} + } + summary := "Removed trust from " + path + if !removed { + summary = path + " was not trusted" + } + printDetail(map[string]any{"path": path, "trusted": false}, summary, []Breadcrumb{ + breadcrumb("trust", "fizzy config trust", "Trust it again"), + }) + return nil + }, +} + +func firstArg(args []string) string { + if len(args) == 0 { + return "" + } + return args[0] +} + func init() { rootCmd.AddCommand(configCmd) configCmd.AddCommand(configShowCmd) configCmd.AddCommand(configExplainCmd) + configCmd.AddCommand(configTrustCmd) + configCmd.AddCommand(configUntrustCmd) } func configShowData(verbose bool) map[string]any { @@ -150,7 +208,7 @@ func configShowData(verbose bool) map[string]any { func configExplainData() map[string]any { eff := resolveDoctorEffectiveConfig() globalCfg, _ := loadDoctorConfigFile(globalConfigPathForDoctor()) - localCfg, _ := loadDoctorConfigFile(cfgpkg.LocalConfigPath()) + localCfg := appliedLocalConfig() resolvedProfile, profileCfg := resolveDoctorProfileContext() _, defaultProfile := profileStoreInfo() binding, _ := resolveProfileAccountBinding(resolvedProfile, profileCfg) diff --git a/internal/commands/config_cmd_test.go b/internal/commands/config_cmd_test.go index 93db128c..08ae0be7 100644 --- a/internal/commands/config_cmd_test.go +++ b/internal/commands/config_cmd_test.go @@ -341,3 +341,111 @@ func TestConfigExplainStyledOutput(t *testing.T) { t.Fatalf("expected next steps section, got:\n%s", raw) } } + +// `fizzy config trust` is what lets a local config's api_url apply, and +// `fizzy config untrust` takes it away again. +func TestConfigTrustAndUntrust(t *testing.T) { + workDir := t.TempDir() + config.SetTestConfigDir(t.TempDir()) + config.SetTestWorkingDir(workDir) + defer config.ResetTestConfigDir() + defer config.ResetTestWorkingDir() + t.Setenv("FIZZY_API_URL", "") + + if err := os.WriteFile(filepath.Join(workDir, config.LocalConfigFile), []byte("api_url: https://fizzy.example.com\n"), 0o600); err != nil { + t.Fatalf("write local config: %v", err) + } + if got := config.Load().APIURL; got != config.DefaultAPIURL { + t.Fatalf("before trust: want the default api_url, got %q", got) + } + + result := SetTestModeWithSDK(NewMockClient()) + defer resetTest() + + assertExitCode(t, configTrustCmd.RunE(configTrustCmd, []string{}), 0) + data, _ := result.Response.Data.(map[string]any) + if data["trusted"] != true || !strings.HasSuffix(data["path"].(string), config.LocalConfigFile) { + t.Fatalf("trust: got %#v", result.Response.Data) + } + if got := config.Load().APIURL; got != "https://fizzy.example.com" { + t.Fatalf("after trust: got %q", got) + } + + assertExitCode(t, configUntrustCmd.RunE(configUntrustCmd, []string{}), 0) + if got := config.Load().APIURL; got != config.DefaultAPIURL { + t.Fatalf("after untrust: want the default api_url, got %q", got) + } +} + +func TestConfigTrustWithoutALocalConfigIsAUsageError(t *testing.T) { + config.SetTestConfigDir(t.TempDir()) + config.SetTestWorkingDir(t.TempDir()) + defer config.ResetTestConfigDir() + defer config.ResetTestWorkingDir() + + SetTestModeWithSDK(NewMockClient()) + defer resetTest() + + err := configTrustCmd.RunE(configTrustCmd, []string{}) + if err == nil || !strings.Contains(err.Error(), config.LocalConfigFile) { + t.Fatalf("want an error naming the file, got %v", err) + } +} + +// Doctor says when a local config's api_url and token are being ignored, and +// does not attribute the effective values to it. +func TestDoctorWarnsOnAnUntrustedLocalConfig(t *testing.T) { + workDir := t.TempDir() + config.SetTestWorkingDir(workDir) + config.SetTestConfigDir(t.TempDir()) + defer config.ResetTestWorkingDir() + defer config.ResetTestConfigDir() + + if err := os.WriteFile(filepath.Join(workDir, config.LocalConfigFile), []byte("api_url: https://evil.example.com\ntoken: planted\n"), 0o600); err != nil { + t.Fatalf("write local config: %v", err) + } + + check := checkDoctorLocalConfig(false) + if check.Status != "warn" || !strings.Contains(check.Message, "api_url and token ignored") || !strings.Contains(check.Hint, "fizzy config trust") { + t.Fatalf("got %#v", check) + } + if local := appliedLocalConfig(); local == nil || local.APIURL != "" || local.Token != "" { + t.Fatalf("the ignored values are not reported as the local config's, got %#v", local) + } +} + +// With several profiles and no default, no profile is chosen and the +// configured account names the credential. A cloned repo's local config can +// set that account, so the token it selects goes to its own profile's host, +// not to the host the YAML config or the default would give it. +func TestAnAccountNamedProfileKeepsItsTokenOnItsOwnHost(t *testing.T) { + t.Setenv("FIZZY_API_URL", "") + t.Setenv("FIZZY_PROFILE", "") + t.Setenv("FIZZY_ACCOUNT", "") + + // The profile store as logging out of the default profile leaves it. + storePath := filepath.Join(t.TempDir(), "config.json") + stored := `{"profiles":{"acme":{"base_url":"https://fizzy.acme.example"},"other":{"base_url":"https://app.fizzy.do"}}}` + if err := os.WriteFile(storePath, []byte(stored), 0o600); err != nil { + t.Fatalf("write profile store: %v", err) + } + profileStore := profile.NewStore(storePath) + + SetTestModeWithSDK(NewMockClient()) + SetTestProfiles(profileStore) + SetTestConfig("", "acme", "https://app.fizzy.do") + defer resetTest() + + if err := resolveProfile(); err != nil { + t.Fatalf("resolve profile: %v", err) + } + if activeProfile != "" { + t.Fatalf("want no profile chosen, got %q", activeProfile) + } + if currentProfileName() != "acme" { + t.Fatalf("the account names the credential, got %q", currentProfileName()) + } + if cfg.APIURL != "https://fizzy.acme.example" { + t.Errorf("want the profile's own host, got %q", cfg.APIURL) + } +} diff --git a/internal/commands/doctor.go b/internal/commands/doctor.go index c0bd1c9c..c381ad81 100644 --- a/internal/commands/doctor.go +++ b/internal/commands/doctor.go @@ -409,7 +409,28 @@ func checkDoctorLocalConfig(verbose bool) DoctorCheck { if path == "" { return DoctorCheck{Name: "Local Config", Status: "skip", Message: "Not found"} } - return validateDoctorConfigFile(path, "Local Config", verbose) + check := validateDoctorConfigFile(path, "Local Config", verbose) + if local := config.LoadLocal(); check.Status == "pass" && local != nil && len(local.Ignored) > 0 { + check.Status = "warn" + check.Message = fmt.Sprintf("%s: %s ignored, the file is not trusted", path, strings.Join(local.Ignored, " and ")) + check.Hint = "Review the file, then run: fizzy config trust" + } + return check +} + +func allProfilesForDoctor() map[string]*profile.Profile { + all, _ := profileStoreInfo() + return all +} + +// appliedLocalConfig is the local config as config.Load applies it: without +// the api_url and token of a file that is not trusted. +func appliedLocalConfig() *config.Config { + local := config.LoadLocal() + if local == nil { + return nil + } + return &local.Config } func validateDoctorConfigFile(path, name string, verbose bool) DoctorCheck { @@ -486,7 +507,7 @@ func resolveDoctorEffectiveConfig() doctorEffectiveConfig { } globalCfg, _ := loadDoctorConfigFile(globalConfigPathForDoctor()) - localCfg, _ := loadDoctorConfigFile(config.LocalConfigPath()) + localCfg := appliedLocalConfig() resolvedProfile, profileCfg := resolveDoctorProfileContext() if eff.ProfileName == "" { eff.ProfileName = firstNonEmpty(resolvedProfile, cfg.Account) @@ -516,6 +537,8 @@ func resolveDoctorEffectiveConfig() doctorEffectiveConfig { eff.APIURLSource = "env FIZZY_API_URL" case profileCfg != nil && profileCfg.BaseURL != "": eff.APIURLSource = "profile store" + case accountProfileBaseURL(allProfilesForDoctor()) != "": + eff.APIURLSource = "profile store" case localCfg != nil && localCfg.APIURL != "": eff.APIURLSource = "local config" case globalCfg != nil && globalCfg.APIURL != "": @@ -1275,7 +1298,7 @@ func doctorTargetsFromProfileStore() []doctorEffectiveConfig { return nil } globalCfg, _ := loadDoctorConfigFile(globalConfigPathForDoctor()) - localCfg, _ := loadDoctorConfigFile(config.LocalConfigPath()) + localCfg := appliedLocalConfig() names := make([]string, 0, len(allProfiles)) for name := range allProfiles { diff --git a/internal/commands/doctor_test.go b/internal/commands/doctor_test.go index 9315d170..eff3b7ce 100644 --- a/internal/commands/doctor_test.go +++ b/internal/commands/doctor_test.go @@ -206,6 +206,9 @@ func TestDoctorWarnsOnLocalTokenStorage(t *testing.T) { if err := os.WriteFile(filepath.Join(workDir, config.LocalConfigFile), []byte(localConfig), 0o600); err != nil { t.Fatalf("write local config: %v", err) } + if _, err := config.TrustLocal(""); err != nil { + t.Fatalf("trust local config: %v", err) + } cfg = config.Load() defer resetTest() diff --git a/internal/commands/root.go b/internal/commands/root.go index 28526350..283445c8 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -1231,9 +1231,11 @@ func resolveProfile() error { return err } // Otherwise (ambiguous default, etc.) — not fatal, just skip profile + applyAccountProfileHost(allProfiles) return nil } if resolved == "" { + applyAccountProfileHost(allProfiles) return nil } @@ -1266,6 +1268,29 @@ func resolveProfile() error { return nil } +// applyAccountProfileHost keeps a stored profile's credential on that +// profile's host. With no profile chosen, the configured account names the +// credential (currentProfileName), and a local config in a cloned repo can set +// the account: the token it selects must not go to whatever host the YAML +// config or the default names instead. +func applyAccountProfileHost(allProfiles map[string]*profile.Profile) { + if baseURL := accountProfileBaseURL(allProfiles); baseURL != "" && os.Getenv("FIZZY_API_URL") == "" { + cfg.APIURL = baseURL + } +} + +// accountProfileBaseURL is the host of the stored profile the configured +// account names, when no profile is active. +func accountProfileBaseURL(allProfiles map[string]*profile.Profile) string { + if activeProfile != "" || cfg == nil || cfg.Account == "" { + return "" + } + if p := allProfiles[cfg.Account]; p != nil { + return p.BaseURL + } + return "" +} + // profileEnvVar returns the FIZZY_PROFILE env var, falling back to FIZZY_ACCOUNT // for backward compatibility. func profileEnvVar() string { diff --git a/internal/commands/setup.go b/internal/commands/setup.go index d19c3f07..34fa5e64 100644 --- a/internal/commands/setup.go +++ b/internal/commands/setup.go @@ -296,6 +296,11 @@ func runSetup(cmd *cobra.Command, args []string) error { if err := newConfig.SaveLocal(); err != nil { return err } + // The person just wrote this file's api_url and token themselves. + if _, err := config.TrustLocal(""); err != nil { + fmt.Printf("Warning: could not trust .fizzy.yaml, so its api_url and token are ignored: %v\n", err) + fmt.Println("Run: fizzy config trust") + } fmt.Println() fmt.Println("✓ Configuration saved to .fizzy.yaml") fmt.Println() diff --git a/internal/config/config.go b/internal/config/config.go index b8a030ac..e8b57882 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "strings" + "sync" "gopkg.in/yaml.v3" ) @@ -124,7 +125,9 @@ func findLocalConfig() string { // overwrites values that Load() set from YAML — but preserves env var values. // // Local config (.fizzy.yaml) is searched for in the current directory and parent -// directories. Values from local config override global config values. +// directories. Values from local config override global config values, except +// that its api_url and token are ignored, with a warning, until the file is +// trusted with `fizzy config trust`. func Load() *Config { cfg := &Config{ APIURL: DefaultAPIURL, @@ -138,26 +141,23 @@ func Load() *Config { } } - // Override with local config (walks up directory tree) - if localPath := findLocalConfig(); localPath != "" { - if data, err := os.ReadFile(localPath); err == nil { - var localCfg Config - if yaml.Unmarshal(data, &localCfg) == nil { - // Only override non-empty values from local config - if localCfg.Token != "" { - cfg.Token = localCfg.Token - } - if localCfg.Account != "" { - cfg.Account = localCfg.Account - } - if localCfg.APIURL != "" { - cfg.APIURL = localCfg.APIURL - } - if localCfg.Board != "" { - cfg.Board = localCfg.Board - } - } + // Override with local config (walks up directory tree). Its api_url and + // token apply only while the file is trusted (trust.go). + if local := LoadLocal(); local != nil { + // Only override non-empty values from local config + if local.Config.Token != "" { + cfg.Token = local.Config.Token + } + if local.Config.Account != "" { + cfg.Account = local.Config.Account + } + if local.Config.APIURL != "" { + cfg.APIURL = local.Config.APIURL } + if local.Config.Board != "" { + cfg.Board = local.Config.Board + } + warnUntrustedLocal(local) } // Override with environment variables @@ -178,6 +178,20 @@ func Load() *Config { return cfg } +// warnedUntrustedLocal keeps the warning to one per file in a process. +var warnedUntrustedLocal sync.Map + +func warnUntrustedLocal(local *LocalConfig) { + if len(local.Ignored) == 0 { + return + } + if _, warned := warnedUntrustedLocal.LoadOrStore(local.Path, true); warned { + return + } + fmt.Fprintf(os.Stderr, "Warning: ignoring %s in %s: the file is not trusted. Review it, then run: fizzy config trust\n", + strings.Join(local.Ignored, " and "), local.Path) +} + // LoadGlobal loads configuration only from the global config file(s) and defaults. // It does not apply local project config or environment variables. func LoadGlobal() *Config { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c66c2500..ec139048 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -421,6 +421,7 @@ board: local-board // Set working directory to project SetTestWorkingDir(projectDir) defer ResetTestWorkingDir() + trustLocalConfig(t) cfg := Load() @@ -467,6 +468,7 @@ api_url: https://parent.api.url // Set working directory to deep subdirectory SetTestWorkingDir(deepDir) defer ResetTestWorkingDir() + trustLocalConfig(t) cfg := Load() diff --git a/internal/config/trust.go b/internal/config/trust.go new file mode 100644 index 00000000..9debf635 --- /dev/null +++ b/internal/config/trust.go @@ -0,0 +1,251 @@ +package config + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "time" + + "gopkg.in/yaml.v3" +) + +// trustFileName is the trust store's file, kept beside the global config. +const trustFileName = "trusted-configs.json" + +// TrustEntry records one trusted local config: its path, when it was trusted, +// and a digest of the trust-gated settings it held then. +type TrustEntry struct { + Path string `json:"path"` + TrustedAt string `json:"trusted_at"` + Digest string `json:"digest"` +} + +type trustFile struct { + Trusted []TrustEntry `json:"trusted"` +} + +// LocalConfig is the nearest .fizzy.yaml and what applies from it. A local +// config sets the account and the board whoever wrote it. Its api_url and +// token decide where a credential is sent and which one, so they apply only +// while the file is trusted: a checkout or pull that changes either leaves the +// file untrusted until it is trusted again. +type LocalConfig struct { + Path string + // Config holds the settings that apply: without trust, APIURL and Token + // are empty. + Config Config + // Gated reports whether the file sets api_url or token. + Gated bool + // Trusted reports whether those settings are trusted as they are now. + Trusted bool + // Ignored names the gated keys the file sets that were not applied. + Ignored []string +} + +// LoadLocal reads the nearest local config, or returns nil when there is none +// or it cannot be read as one. +func LoadLocal() *LocalConfig { + path := findLocalConfig() + if path == "" { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return nil + } + var file Config + if yaml.Unmarshal(data, &file) != nil { + return nil + } + + local := &LocalConfig{Path: path, Config: file} + local.Gated = file.APIURL != "" || file.Token != "" + if !local.Gated { + return local + } + local.Trusted = isTrusted(path, file) + if !local.Trusted { + if file.APIURL != "" { + local.Ignored = append(local.Ignored, "api_url") + } + if file.Token != "" { + local.Ignored = append(local.Ignored, "token") + } + local.Config.APIURL = "" + local.Config.Token = "" + } + return local +} + +// TrustLocal trusts the local config at path, or the nearest one when path is +// empty, with the api_url and token it holds now. +func TrustLocal(path string) (*TrustEntry, error) { + if path == "" { + if path = findLocalConfig(); path == "" { + return nil, fmt.Errorf("no %s found here or in a parent directory", LocalConfigFile) + } + } + canon, err := canonicalPath(path) + if err != nil { + return nil, err + } + data, err := os.ReadFile(canon) + if err != nil { + return nil, fmt.Errorf("cannot read config: %w", err) + } + var file Config + if err := yaml.Unmarshal(data, &file); err != nil { + return nil, fmt.Errorf("cannot trust %s: %w", path, err) + } + + entry := TrustEntry{ + Path: canon, + TrustedAt: time.Now().UTC().Format(time.RFC3339), + Digest: trustDigest(file), + } + tf := loadTrustFile() + found := false + for i := range tf.Trusted { + if tf.Trusted[i].Path == canon { + tf.Trusted[i] = entry + found = true + break + } + } + if !found { + tf.Trusted = append(tf.Trusted, entry) + } + if err := saveTrustFile(tf); err != nil { + return nil, err + } + return &entry, nil +} + +// UntrustLocal removes trust from the local config at path, or the nearest one +// when path is empty. It reports whether the file was trusted. +func UntrustLocal(path string) (string, bool, error) { + if path == "" { + if path = findLocalConfig(); path == "" { + return "", false, fmt.Errorf("no %s found here or in a parent directory", LocalConfigFile) + } + } + canon, err := canonicalPath(path) + if err != nil { + // A file that is gone can still be untrusted by the path it had. + if canon, err = filepath.Abs(path); err != nil { + return "", false, err + } + } + tf := loadTrustFile() + kept := tf.Trusted[:0] + removed := false + for _, e := range tf.Trusted { + if e.Path == canon { + removed = true + continue + } + kept = append(kept, e) + } + if !removed { + return canon, false, nil + } + tf.Trusted = kept + return canon, true, saveTrustFile(tf) +} + +// TrustedLocals lists the trusted local configs. +func TrustedLocals() []TrustEntry { + return loadTrustFile().Trusted +} + +func isTrusted(path string, file Config) bool { + canon, err := canonicalPath(path) + if err != nil { + return false + } + digest := trustDigest(file) + for _, e := range loadTrustFile().Trusted { + if e.Path == canon { + return e.Digest == digest + } + } + return false +} + +// trustDigest is the SHA-256 of a local config's trust-gated settings. A +// setting that trust gates must be part of it, or changing that setting would +// keep the trust. +func trustDigest(file Config) string { + gated, _ := json.Marshal(struct { + APIURL string `json:"api_url"` + Token string `json:"token"` + }{file.APIURL, file.Token}) + sum := sha256.Sum256(gated) + return hex.EncodeToString(sum[:]) +} + +func canonicalPath(path string) (string, error) { + abs, err := filepath.Abs(path) + if err != nil { + return "", fmt.Errorf("cannot resolve path %s: %w", path, err) + } + resolved, err := filepath.EvalSymlinks(abs) + if err != nil { + return "", fmt.Errorf("cannot resolve path %s: %w", path, err) + } + return filepath.Clean(resolved), nil +} + +// trustFilePath is the trust store beside the global config in use, or beside +// the preferred one when there is none yet. +func trustFilePath() (string, error) { + paths := globalConfigPaths() + if len(paths) == 0 { + return "", errors.New("unable to determine config path") + } + for _, path := range paths { + if _, err := os.Stat(path); err == nil { + return filepath.Join(filepath.Dir(path), trustFileName), nil + } + } + return filepath.Join(filepath.Dir(paths[0]), trustFileName), nil +} + +func loadTrustFile() trustFile { + var tf trustFile + path, err := trustFilePath() + if err != nil { + return tf + } + data, err := os.ReadFile(path) + if err != nil { + return tf + } + if json.Unmarshal(data, &tf) != nil { + return trustFile{} + } + return tf +} + +func saveTrustFile(tf trustFile) error { + path, err := trustFilePath() + if err != nil { + return err + } + if err = os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + data, err := json.MarshalIndent(tf, "", " ") + if err != nil { + return err + } + tmp := path + ".tmp" + if err = os.WriteFile(tmp, append(data, '\n'), 0o600); err != nil { + return err + } + return os.Rename(tmp, path) +} diff --git a/internal/config/trust_test.go b/internal/config/trust_test.go new file mode 100644 index 00000000..9428712f --- /dev/null +++ b/internal/config/trust_test.go @@ -0,0 +1,193 @@ +package config + +import ( + "bytes" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +// trustLocalConfig trusts the nearest local config, as `fizzy config trust` does. +func trustLocalConfig(t *testing.T) { + t.Helper() + if _, err := TrustLocal(""); err != nil { + t.Fatalf("trust local config: %v", err) + } +} + +// localConfigHere points config loading at a fresh global config directory and +// a working directory holding a .fizzy.yaml with contents, and returns the +// file's path. +func localConfigHere(t *testing.T, contents string) string { + t.Helper() + for _, name := range []string{"FIZZY_TOKEN", "FIZZY_ACCOUNT", "FIZZY_API_URL", "FIZZY_BOARD"} { + t.Setenv(name, "") + } + SetTestConfigDir(t.TempDir()) + t.Cleanup(ResetTestConfigDir) + workDir := t.TempDir() + SetTestWorkingDir(workDir) + t.Cleanup(ResetTestWorkingDir) + + path := filepath.Join(workDir, LocalConfigFile) + writeLocalConfig(t, path, contents) + return path +} + +func writeLocalConfig(t *testing.T, path, contents string) { + t.Helper() + if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { + t.Fatalf("write local config: %v", err) + } +} + +// loadWithWarnings is Load and what it wrote to stderr. +func loadWithWarnings(t *testing.T) (*Config, string) { + t.Helper() + warnedUntrustedLocal.Clear() + orig := os.Stderr + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("pipe: %v", err) + } + os.Stderr = w + cfg := Load() + os.Stderr = orig + w.Close() + var buf bytes.Buffer + io.Copy(&buf, r) + return cfg, buf.String() +} + +// A local config that nobody trusted, as a cloned repo's is, sets the account +// and the board. Its api_url and token are ignored: they decide where a +// credential goes and which one. +func TestAnUntrustedLocalConfigSetsNoAPIURLOrToken(t *testing.T) { + path := localConfigHere(t, "account: acme\nboard: roadmap\napi_url: https://evil.example.com\ntoken: planted\n") + + cfg, warning := loadWithWarnings(t) + + if cfg.APIURL != DefaultAPIURL { + t.Errorf("api_url: want the default, got %q", cfg.APIURL) + } + if cfg.Token != "" { + t.Errorf("token: want none, got %q", cfg.Token) + } + if cfg.Account != "acme" || cfg.Board != "roadmap" { + t.Errorf("account and board apply without trust, got %q and %q", cfg.Account, cfg.Board) + } + for _, want := range []string{"api_url and token", path, "fizzy config trust"} { + if !strings.Contains(warning, want) { + t.Errorf("warning %q does not name %q", warning, want) + } + } + if strings.Contains(warning, "planted") { + t.Errorf("warning %q prints the token", warning) + } +} + +// Trust is given to what the file says, not where it is. A pull request that +// rewrites a trusted local config to name another host leaves it untrusted. +func TestARewrittenTrustedLocalConfigIsUntrusted(t *testing.T) { + path := localConfigHere(t, "account: acme\napi_url: https://fizzy.example.com\n") + trustLocalConfig(t) + + cfg, warning := loadWithWarnings(t) + if cfg.APIURL != "https://fizzy.example.com" || warning != "" { + t.Fatalf("a trusted api_url applies quietly, got %q and warning %q", cfg.APIURL, warning) + } + + writeLocalConfig(t, path, "account: acme\napi_url: https://evil.example.com\n") + cfg, warning = loadWithWarnings(t) + if cfg.APIURL != DefaultAPIURL { + t.Errorf("the rewritten api_url is ignored, got %q", cfg.APIURL) + } + if !strings.Contains(warning, "not trusted") { + t.Errorf("want a warning, got %q", warning) + } + + trustLocalConfig(t) + if cfg, _ = loadWithWarnings(t); cfg.APIURL != "https://evil.example.com" { + t.Errorf("until it is trusted again, got %q", cfg.APIURL) + } + if got := len(TrustedLocals()); got != 1 { + t.Errorf("trusting again updates the entry, got %d entries", got) + } +} + +// A token added to a trusted file is as much a change as a new host. +func TestATokenAddedToATrustedLocalConfigIsUntrusted(t *testing.T) { + path := localConfigHere(t, "api_url: https://fizzy.example.com\n") + trustLocalConfig(t) + + writeLocalConfig(t, path, "api_url: https://fizzy.example.com\ntoken: planted\n") + cfg, _ := loadWithWarnings(t) + if cfg.Token != "" || cfg.APIURL != DefaultAPIURL { + t.Errorf("want neither applied, got token %q and api_url %q", cfg.Token, cfg.APIURL) + } +} + +// Changing what an untrusted file may set anyway, or its layout, keeps trust. +func TestChangingAccountOrBoardKeepsTrust(t *testing.T) { + path := localConfigHere(t, "account: acme\napi_url: https://fizzy.example.com\n") + trustLocalConfig(t) + + writeLocalConfig(t, path, "# moved\nboard: roadmap\napi_url: \"https://fizzy.example.com\"\naccount: other\n") + cfg, warning := loadWithWarnings(t) + if cfg.APIURL != "https://fizzy.example.com" || warning != "" { + t.Errorf("want the api_url still applied, got %q and warning %q", cfg.APIURL, warning) + } +} + +// A file with no api_url and no token has nothing to trust, and says nothing. +func TestALocalConfigWithoutGatedKeysNeedsNoTrust(t *testing.T) { + localConfigHere(t, "account: acme\nboard: roadmap\n") + + cfg, warning := loadWithWarnings(t) + if cfg.Account != "acme" || cfg.Board != "roadmap" || warning != "" { + t.Errorf("got account %q, board %q, warning %q", cfg.Account, cfg.Board, warning) + } +} + +func TestUntrustLocalRemovesTrust(t *testing.T) { + path := localConfigHere(t, "api_url: https://fizzy.example.com\n") + trustLocalConfig(t) + + if _, removed, err := UntrustLocal(""); err != nil || !removed { + t.Fatalf("untrust: removed %v, err %v", removed, err) + } + if cfg, _ := loadWithWarnings(t); cfg.APIURL != DefaultAPIURL { + t.Errorf("api_url is ignored again, got %q", cfg.APIURL) + } + if _, removed, err := UntrustLocal(path); err != nil || removed { + t.Errorf("untrusting twice: removed %v, err %v", removed, err) + } +} + +// Trust follows the file, not the name it was reached by. +func TestTrustFollowsASymlinkedPath(t *testing.T) { + path := localConfigHere(t, "api_url: https://fizzy.example.com\n") + link := filepath.Join(t.TempDir(), "link") + if err := os.Symlink(filepath.Dir(path), link); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if _, err := TrustLocal(filepath.Join(link, LocalConfigFile)); err != nil { + t.Fatalf("trust: %v", err) + } + if cfg, _ := loadWithWarnings(t); cfg.APIURL != "https://fizzy.example.com" { + t.Errorf("want the api_url applied, got %q", cfg.APIURL) + } +} + +func TestTrustLocalWithoutALocalConfigFails(t *testing.T) { + SetTestConfigDir(t.TempDir()) + t.Cleanup(ResetTestConfigDir) + SetTestWorkingDir(t.TempDir()) + t.Cleanup(ResetTestWorkingDir) + + if _, err := TrustLocal(""); err == nil { + t.Error("want an error") + } +} diff --git a/skills/fizzy/SKILL.md b/skills/fizzy/SKILL.md index ff4908be..11f7bbf9 100644 --- a/skills/fizzy/SKILL.md +++ b/skills/fizzy/SKILL.md @@ -187,6 +187,11 @@ account: 123456789 board: 03foq1hqmyy91tuyz3ghugg6c ``` +`account` and `board` apply from any `.fizzy.yaml`. An `api_url` or `token` in one is +ignored, with a warning on stderr, until the person trusts the file with +`fizzy config trust`, and again whenever either value changes. Never run +`fizzy config trust` on a file you did not write unless the person asked you to. + **Priority (highest to lowest):** 1. CLI flags (`--token`, `--profile`, `--api-url`, `--board`) 2. Environment variables (`FIZZY_TOKEN`, `FIZZY_PROFILE`, `FIZZY_API_URL`, `FIZZY_BOARD`) From db0f189bd1ce9a6b79e790adefcfb31e4cb50dc4 Mon Sep 17 00:00:00 2001 From: Rob Zolkos Date: Fri, 13 Nov 2026 12:37:37 -0500 Subject: [PATCH 2/3] Tighten local config trust after review The host of an account-named profile now follows its credential: it applies only when that profile holds a token, so a token from another source is not carried over to it. `config explain` shows that host as the selected candidate, and shows what an untrusted local config sets as ignored. The trust store stays in the preferred config directory rather than following the global config file, and its read, change and save run under a lock with a temporary file of their own. `config untrust` finds the entry of a file or link target that is gone. `config trust` and `config untrust` run whatever the profile, account and token settings are, skip the warning about the file they act on, and report read and write failures as such rather than as usage errors. `fizzy setup` fails when it cannot trust the file it wrote. Paths in messages drop control characters. --- AGENTS.md | 13 +- internal/commands/config_cmd.go | 53 ++++++-- internal/commands/config_cmd_test.go | 141 ++++++++++++++++++-- internal/commands/doctor.go | 2 +- internal/commands/root.go | 29 +++-- internal/commands/setup.go | 7 +- internal/config/config.go | 16 ++- internal/config/trust.go | 186 +++++++++++++++++++++------ internal/config/trust_test.go | 98 +++++++++++++- skills/fizzy/SKILL.md | 2 +- 10 files changed, 463 insertions(+), 84 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 479bb3de..82d8cd52 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,12 +91,13 @@ The CLI reads config from multiple sources with this priority: `FIZZY_ACCOUNT` is accepted as a deprecated alias for `FIZZY_PROFILE`. **Local config trust.** A `.fizzy.yaml` is found by walking up from the working -directory, so a cloned repo supplies one. It sets `account` and `board` whoever wrote -it. Its `api_url` and `token` decide where a credential is sent and which one, so -`config.LoadLocal` (`internal/config/trust.go`) drops them, with a warning, unless -`fizzy config trust` recorded a digest of those two values that still matches. Anything -that reads the local file for its settings goes through `LoadLocal`, never around it, -and a new key that can redirect or replace a credential joins `trustDigest`. +directory, so a cloned repo can supply one. Its `account` and `board` apply without +trust. Its `api_url` and `token` decide where a credential is sent and which one, so +`config.LoadLocal` (`internal/config/trust.go`) drops them and lists them in `Ignored`, +and `config.Load` prints the warning, unless `fizzy config trust` recorded a digest of +those two values that still matches. Anything that reads the local file for its settings +goes through `LoadLocal`, never around it, and a new key that can redirect or replace a +credential joins `trustDigest`. **`--board` is command-scoped, not global.** `fizzy --board X ...` fails with `unknown flag`; it is declared per-command, by nineteen of them across the activity, diff --git a/internal/commands/config_cmd.go b/internal/commands/config_cmd.go index 60cee968..e5d3c2ce 100644 --- a/internal/commands/config_cmd.go +++ b/internal/commands/config_cmd.go @@ -1,6 +1,7 @@ package commands import ( + "errors" "fmt" "os" "sort" @@ -109,9 +110,9 @@ Read the file first.`, RunE: func(cmd *cobra.Command, args []string) error { entry, err := cfgpkg.TrustLocal(firstArg(args)) if err != nil { - return &output.Error{Code: output.CodeUsage, Message: err.Error()} + return localTrustError(err) } - printDetail(map[string]any{"path": entry.Path, "trusted": true}, "Trusted "+entry.Path, []Breadcrumb{ + printDetail(map[string]any{"path": entry.Path, "trusted": true}, "Trusted "+cfgpkg.DisplayPath(entry.Path), []Breadcrumb{ breadcrumb("show", "fizzy config show", "Show the effective config"), breadcrumb("untrust", "fizzy config untrust", "Remove the trust"), }) @@ -129,11 +130,11 @@ Without a path, untrusts the nearest .fizzy.yaml, in this directory or a parent. RunE: func(cmd *cobra.Command, args []string) error { path, removed, err := cfgpkg.UntrustLocal(firstArg(args)) if err != nil { - return &output.Error{Code: output.CodeUsage, Message: err.Error()} + return localTrustError(err) } - summary := "Removed trust from " + path + summary := "Removed trust from " + cfgpkg.DisplayPath(path) if !removed { - summary = path + " was not trusted" + summary = cfgpkg.DisplayPath(path) + " was not trusted" } printDetail(map[string]any{"path": path, "trusted": false}, summary, []Breadcrumb{ breadcrumb("trust", "fizzy config trust", "Trust it again"), @@ -142,6 +143,26 @@ Without a path, untrusts the nearest .fizzy.yaml, in this directory or a parent. }, } +// localTrustError tells a request that names no usable file, which is the +// caller's to fix, from a failure to read or write, which is not. +func localTrustError(err error) error { + switch { + case errors.Is(err, cfgpkg.ErrNoLocalConfig): + return &output.Error{Code: output.CodeUsage, Message: err.Error()} + case errors.Is(err, os.ErrNotExist): + return &output.Error{Code: output.CodeNotFound, Message: err.Error()} + default: + return &output.Error{Code: output.CodeAPI, Message: err.Error()} + } +} + +// isLocalTrustCommand reports whether cmd only changes local trust records, +// so it runs whatever the profile, account and token settings are. +func isLocalTrustCommand(cmd *cobra.Command) bool { + return cmd.Name() != "" && cmd.Parent() != nil && cmd.Parent().Name() == "config" && + (cmd.Name() == "trust" || cmd.Name() == "untrust") +} + func firstArg(args []string) string { if len(args) == 0 { return "" @@ -209,6 +230,22 @@ func configExplainData() map[string]any { eff := resolveDoctorEffectiveConfig() globalCfg, _ := loadDoctorConfigFile(globalConfigPathForDoctor()) localCfg := appliedLocalConfig() + localAPIURL := unsetString(fieldValue(localCfg, func(c *cfgpkg.Config) string { return c.APIURL })) + localToken := configuredString(localCfg != nil && localCfg.Token != "", "configured in local config") + if local := cfgpkg.LoadLocal(); local != nil { + // What an untrusted file sets is shown, as ignored, so the reader sees + // why another source applies. + if raw, err := loadDoctorConfigFile(local.Path); err == nil { + for _, key := range local.Ignored { + switch key { + case "api_url": + localAPIURL = raw.APIURL + " (ignored: the file is not trusted)" + case "token": + localToken = "ignored: the file is not trusted" + } + } + } + } resolvedProfile, profileCfg := resolveDoctorProfileContext() _, defaultProfile := profileStoreInfo() binding, _ := resolveProfileAccountBinding(resolvedProfile, profileCfg) @@ -250,8 +287,8 @@ func configExplainData() map[string]any { Candidates: []configExplainCandidate{ {Source: "flag --api-url", Value: unsetString(cfgAPIURL), Selected: eff.APIURLSource == "flag --api-url"}, {Source: "env FIZZY_API_URL", Value: unsetString(strings.TrimSpace(getEnv("FIZZY_API_URL"))), Selected: eff.APIURLSource == "env FIZZY_API_URL"}, - {Source: profileSourceLabel(resolvedProfile, eff.ProfileName), Value: unsetString(profileBaseURL(profileCfg)), Selected: eff.APIURLSource == "profile store"}, - {Source: "local config", Value: unsetString(fieldValue(localCfg, func(c *cfgpkg.Config) string { return c.APIURL })), Selected: eff.APIURLSource == "local config"}, + {Source: profileSourceLabel(resolvedProfile, eff.ProfileName), Value: unsetString(firstNonEmpty(profileBaseURL(profileCfg), accountProfileBaseURL(allProfilesForDoctor()))), Selected: eff.APIURLSource == "profile store"}, + {Source: "local config", Value: localAPIURL, Selected: eff.APIURLSource == "local config"}, {Source: "global config", Value: unsetString(fieldValue(globalCfg, func(c *cfgpkg.Config) string { return c.APIURL })), Selected: eff.APIURLSource == "global config"}, {Source: "default", Value: cfgpkg.DefaultAPIURL, Selected: eff.APIURLSource == "default"}, }, @@ -276,7 +313,7 @@ func configExplainData() map[string]any { {Source: "flag --token", Value: configuredString(cfgToken != "", "configured via flag"), Selected: eff.TokenSourceRaw == "flag"}, {Source: "env FIZZY_TOKEN", Value: configuredString(strings.TrimSpace(getEnv("FIZZY_TOKEN")) != "", "configured in environment"), Selected: eff.TokenSourceRaw == "env"}, {Source: profileTokenSourceLabel(resolvedProfile, eff.ProfileName), Value: configuredString(profileToken != "", profileCredentialValue(eff.TokenSourceRaw, profileToken != "")), Selected: eff.TokenSourceRaw == "keyring" || eff.TokenSourceRaw == "fallback-file" || eff.TokenSourceRaw == "legacy-keyring" || eff.TokenSourceRaw == "legacy-fallback"}, - {Source: "local config", Value: configuredString(localCfg != nil && localCfg.Token != "", "configured in local config"), Selected: eff.TokenSourceRaw == "local-config"}, + {Source: "local config", Value: localToken, Selected: eff.TokenSourceRaw == "local-config"}, {Source: "global config", Value: configuredString(globalCfg != nil && globalCfg.Token != "", "configured in global config"), Selected: eff.TokenSourceRaw == "global-config"}, }, } diff --git a/internal/commands/config_cmd_test.go b/internal/commands/config_cmd_test.go index 08ae0be7..8c552ca2 100644 --- a/internal/commands/config_cmd_test.go +++ b/internal/commands/config_cmd_test.go @@ -2,14 +2,17 @@ package commands import ( "encoding/json" + "errors" "os" "path/filepath" "strings" "testing" + "github.com/basecamp/cli/credstore" "github.com/basecamp/cli/output" "github.com/basecamp/cli/profile" "github.com/basecamp/fizzy-cli/internal/config" + "github.com/spf13/cobra" ) func TestConfigShow(t *testing.T) { @@ -414,38 +417,154 @@ func TestDoctorWarnsOnAnUntrustedLocalConfig(t *testing.T) { } } -// With several profiles and no default, no profile is chosen and the -// configured account names the credential. A cloned repo's local config can -// set that account, so the token it selects goes to its own profile's host, -// not to the host the YAML config or the default would give it. -func TestAnAccountNamedProfileKeepsItsTokenOnItsOwnHost(t *testing.T) { +// accountNamedProfiles sets up several stored profiles with no default, as +// logging out of the default profile leaves them, and the account "acme" +// configured. +func accountNamedProfiles(t *testing.T) { + t.Helper() t.Setenv("FIZZY_API_URL", "") t.Setenv("FIZZY_PROFILE", "") t.Setenv("FIZZY_ACCOUNT", "") + t.Setenv("FIZZY_TOKEN", "") + t.Setenv("FIZZY_ACCOUNT_HOST_NO_KR", "1") + config.SetTestConfigDir(t.TempDir()) + config.SetTestWorkingDir(t.TempDir()) + t.Cleanup(config.ResetTestConfigDir) + t.Cleanup(config.ResetTestWorkingDir) - // The profile store as logging out of the default profile leaves it. storePath := filepath.Join(t.TempDir(), "config.json") stored := `{"profiles":{"acme":{"base_url":"https://fizzy.acme.example"},"other":{"base_url":"https://app.fizzy.do"}}}` if err := os.WriteFile(storePath, []byte(stored), 0o600); err != nil { t.Fatalf("write profile store: %v", err) } - profileStore := profile.NewStore(storePath) + store := credstore.NewStore(credstore.StoreOptions{ + ServiceName: "fizzy-account-host-test", + DisableEnvVar: "FIZZY_ACCOUNT_HOST_NO_KR", + FallbackDir: t.TempDir(), + }) SetTestModeWithSDK(NewMockClient()) - SetTestProfiles(profileStore) + SetTestProfiles(profile.NewStore(storePath)) + SetTestCreds(store) SetTestConfig("", "acme", "https://app.fizzy.do") - defer resetTest() + t.Cleanup(resetTest) +} + +// With several profiles and no default, no profile is chosen and the +// configured account names the credential. A cloned repo's local config can +// set that account, so the token it selects goes to its own profile's host, +// not to the host the YAML config or the default would give it. +func TestAnAccountNamedProfileKeepsItsTokenOnItsOwnHost(t *testing.T) { + accountNamedProfiles(t) + if err := credsSaveProfileToken("acme", "acme-token"); err != nil { + t.Fatalf("save token: %v", err) + } if err := resolveProfile(); err != nil { t.Fatalf("resolve profile: %v", err) } + resolveToken() if activeProfile != "" { t.Fatalf("want no profile chosen, got %q", activeProfile) } - if currentProfileName() != "acme" { - t.Fatalf("the account names the credential, got %q", currentProfileName()) + if cfg.Token != "acme-token" { + t.Fatalf("the account names the credential, got token %q", cfg.Token) } if cfg.APIURL != "https://fizzy.acme.example" { t.Errorf("want the profile's own host, got %q", cfg.APIURL) } + + // config explain shows that host as the selected candidate. + field := configExplainData()["api_url"].(configExplainField) + var selected []string + for _, c := range field.Candidates { + if c.Selected { + selected = append(selected, c.Value) + } + } + if len(selected) != 1 || selected[0] != "https://fizzy.acme.example" { + t.Errorf("explain: want the profile's host selected, got %v", selected) + } +} + +// The host follows the credential. A profile with no token of its own does +// not pull a token from another source over to its host. +func TestAnAccountNamedProfileWithoutATokenDoesNotSetTheHost(t *testing.T) { + accountNamedProfiles(t) + + if err := resolveProfile(); err != nil { + t.Fatalf("resolve profile: %v", err) + } + if cfg.APIURL != "https://app.fizzy.do" { + t.Errorf("want the configured host kept, got %q", cfg.APIURL) + } +} + +// config explain shows what an untrusted local config sets, as ignored. +func TestConfigExplainShowsIgnoredLocalSettings(t *testing.T) { + accountNamedProfiles(t) + workDir := t.TempDir() + config.SetTestWorkingDir(workDir) + if err := os.WriteFile(filepath.Join(workDir, config.LocalConfigFile), []byte("api_url: https://other.example.com\ntoken: planted\n"), 0o600); err != nil { + t.Fatalf("write local config: %v", err) + } + + data := configExplainData() + for _, name := range []string{"api_url", "token"} { + var local configExplainCandidate + for _, c := range data[name].(configExplainField).Candidates { + if c.Source == "local config" { + local = c + } + } + if local.Selected || !strings.Contains(local.Value, "ignored: the file is not trusted") { + t.Errorf("%s: got %#v", name, local) + } + if strings.Contains(local.Value, "planted") { + t.Errorf("%s: the token is shown: %q", name, local.Value) + } + } +} + +// Trusting a file that cannot be read is not a usage error: only a request +// that names no file is. +func TestConfigTrustErrorCodes(t *testing.T) { + config.SetTestConfigDir(t.TempDir()) + config.SetTestWorkingDir(t.TempDir()) + defer config.ResetTestConfigDir() + defer config.ResetTestWorkingDir() + SetTestModeWithSDK(NewMockClient()) + defer resetTest() + + code := func(err error) string { + var e *output.Error + if !errors.As(err, &e) { + t.Fatalf("want an output error, got %v", err) + } + return e.Code + } + if got := code(configTrustCmd.RunE(configTrustCmd, []string{})); got != output.CodeUsage { + t.Errorf("no local config: got %q", got) + } + missing := filepath.Join(t.TempDir(), config.LocalConfigFile) + if got := code(configTrustCmd.RunE(configTrustCmd, []string{missing})); got != output.CodeNotFound { + t.Errorf("missing file: got %q", got) + } + bad := filepath.Join(t.TempDir(), config.LocalConfigFile) + if err := os.WriteFile(bad, []byte("api_url: [\n"), 0o600); err != nil { + t.Fatalf("write: %v", err) + } + if got := code(configTrustCmd.RunE(configTrustCmd, []string{bad})); got != output.CodeAPI { + t.Errorf("unreadable config: got %q", got) + } +} + +// The trust commands only change local trust records, so the profile, account +// and token checks do not apply to them. +func TestTrustCommandsAreLocal(t *testing.T) { + for cmd, want := range map[*cobra.Command]bool{configTrustCmd: true, configUntrustCmd: true, configShowCmd: false, rootCmd: false} { + if got := isLocalTrustCommand(cmd); got != want { + t.Errorf("%s: got %v", cmd.CommandPath(), got) + } + } } diff --git a/internal/commands/doctor.go b/internal/commands/doctor.go index c381ad81..512fa38d 100644 --- a/internal/commands/doctor.go +++ b/internal/commands/doctor.go @@ -412,7 +412,7 @@ func checkDoctorLocalConfig(verbose bool) DoctorCheck { check := validateDoctorConfigFile(path, "Local Config", verbose) if local := config.LoadLocal(); check.Status == "pass" && local != nil && len(local.Ignored) > 0 { check.Status = "warn" - check.Message = fmt.Sprintf("%s: %s ignored, the file is not trusted", path, strings.Join(local.Ignored, " and ")) + check.Message = fmt.Sprintf("%s: %s ignored, the file is not trusted", config.DisplayPath(path), strings.Join(local.Ignored, " and ")) check.Hint = "Review the file, then run: fizzy config trust" } return check diff --git a/internal/commands/root.go b/internal/commands/root.go index 283445c8..06b91f7b 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -125,7 +125,11 @@ var rootCmd = &cobra.Command{ // In test mode, cfg is already set by SetTestConfig - don't overwrite if cfg == nil { // Load config from file/env - cfg = config.Load() + if isLocalTrustCommand(cmd) { + cfg = config.LoadWithoutTrustWarning() + } else { + cfg = config.Load() + } } // Initialize credential store (skip in test mode) @@ -168,18 +172,19 @@ var rootCmd = &cobra.Command{ } else if activeProfile == "" { return &output.Error{Code: output.CodeUsage, Message: err.Error()} } - } else if cmd != authSwitchCmd && !doctorAllProfiles { + } else if cmd != authSwitchCmd && !doctorAllProfiles && !isLocalTrustCommand(cmd) { return &output.Error{Code: output.CodeUsage, Message: err.Error()} } } - if cfg.Account != "" && cmd != authLogoutCmd && cmd != authSwitchCmd && !doctorAllProfiles { + if cfg.Account != "" && cmd != authLogoutCmd && cmd != authSwitchCmd && !doctorAllProfiles && !isLocalTrustCommand(cmd) { if err := validateAccountIdentifier(cfg.Account); err != nil { return &output.Error{Code: output.CodeUsage, Message: err.Error()} } } // Commands that replace or remove credentials do not resolve or migrate // an existing token first. Profile sweeps resolve each target separately. - if cmd != authLoginCmd && cmd != authLogoutCmd && cmd != authSwitchCmd && !doctorAllProfiles { + // Trusting a local config sends nothing, so it resolves no token either. + if cmd != authLoginCmd && cmd != authLogoutCmd && cmd != authSwitchCmd && !doctorAllProfiles && !isLocalTrustCommand(cmd) { resolveToken() } @@ -1280,15 +1285,21 @@ func applyAccountProfileHost(allProfiles map[string]*profile.Profile) { } // accountProfileBaseURL is the host of the stored profile the configured -// account names, when no profile is active. +// account names, when no profile is active and that profile holds a token. +// The host follows the credential: a profile with no token of its own does +// not pull a token from another source over to its host. func accountProfileBaseURL(allProfiles map[string]*profile.Profile) string { - if activeProfile != "" || cfg == nil || cfg.Account == "" { + if activeProfile != "" || cfg == nil || cfg.Account == "" || creds == nil { + return "" + } + p := allProfiles[cfg.Account] + if p == nil || p.BaseURL == "" { return "" } - if p := allProfiles[cfg.Account]; p != nil { - return p.BaseURL + if t, err := credsLoadProfileToken(cfg.Account); err != nil || t == "" { + return "" } - return "" + return p.BaseURL } // profileEnvVar returns the FIZZY_PROFILE env var, falling back to FIZZY_ACCOUNT diff --git a/internal/commands/setup.go b/internal/commands/setup.go index 34fa5e64..b0098aea 100644 --- a/internal/commands/setup.go +++ b/internal/commands/setup.go @@ -298,8 +298,11 @@ func runSetup(cmd *cobra.Command, args []string) error { } // The person just wrote this file's api_url and token themselves. if _, err := config.TrustLocal(""); err != nil { - fmt.Printf("Warning: could not trust .fizzy.yaml, so its api_url and token are ignored: %v\n", err) - fmt.Println("Run: fizzy config trust") + return &output.Error{ + Code: output.CodeAPI, + Message: fmt.Sprintf("saved .fizzy.yaml but could not trust it, so its api_url and token are ignored: %v", err), + Hint: "Run: fizzy config trust", + } } fmt.Println() fmt.Println("✓ Configuration saved to .fizzy.yaml") diff --git a/internal/config/config.go b/internal/config/config.go index e8b57882..690268ff 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -129,6 +129,16 @@ func findLocalConfig() string { // that its api_url and token are ignored, with a warning, until the file is // trusted with `fizzy config trust`. func Load() *Config { + return load(true) +} + +// LoadWithoutTrustWarning is Load without the warning about an untrusted local +// config, for the commands that trust or untrust one. +func LoadWithoutTrustWarning() *Config { + return load(false) +} + +func load(warnUntrusted bool) *Config { cfg := &Config{ APIURL: DefaultAPIURL, } @@ -157,7 +167,9 @@ func Load() *Config { if local.Config.Board != "" { cfg.Board = local.Config.Board } - warnUntrustedLocal(local) + if warnUntrusted { + warnUntrustedLocal(local) + } } // Override with environment variables @@ -189,7 +201,7 @@ func warnUntrustedLocal(local *LocalConfig) { return } fmt.Fprintf(os.Stderr, "Warning: ignoring %s in %s: the file is not trusted. Review it, then run: fizzy config trust\n", - strings.Join(local.Ignored, " and "), local.Path) + strings.Join(local.Ignored, " and "), DisplayPath(local.Path)) } // LoadGlobal loads configuration only from the global config file(s) and defaults. diff --git a/internal/config/trust.go b/internal/config/trust.go index 9debf635..db0a1767 100644 --- a/internal/config/trust.go +++ b/internal/config/trust.go @@ -8,7 +8,9 @@ import ( "fmt" "os" "path/filepath" + "strings" "time" + "unicode" "gopkg.in/yaml.v3" ) @@ -24,6 +26,9 @@ type TrustEntry struct { Digest string `json:"digest"` } +// ErrNoLocalConfig reports that there is no local config to act on. +var ErrNoLocalConfig = fmt.Errorf("no %s found here or in a parent directory", LocalConfigFile) + type trustFile struct { Trusted []TrustEntry `json:"trusted"` } @@ -86,7 +91,7 @@ func LoadLocal() *LocalConfig { func TrustLocal(path string) (*TrustEntry, error) { if path == "" { if path = findLocalConfig(); path == "" { - return nil, fmt.Errorf("no %s found here or in a parent directory", LocalConfigFile) + return nil, ErrNoLocalConfig } } canon, err := canonicalPath(path) @@ -98,7 +103,7 @@ func TrustLocal(path string) (*TrustEntry, error) { return nil, fmt.Errorf("cannot read config: %w", err) } var file Config - if err := yaml.Unmarshal(data, &file); err != nil { + if err = yaml.Unmarshal(data, &file); err != nil { return nil, fmt.Errorf("cannot trust %s: %w", path, err) } @@ -107,19 +112,17 @@ func TrustLocal(path string) (*TrustEntry, error) { TrustedAt: time.Now().UTC().Format(time.RFC3339), Digest: trustDigest(file), } - tf := loadTrustFile() - found := false - for i := range tf.Trusted { - if tf.Trusted[i].Path == canon { - tf.Trusted[i] = entry - found = true - break + err = updateTrustFile(func(tf *trustFile) bool { + for i := range tf.Trusted { + if tf.Trusted[i].Path == canon { + tf.Trusted[i] = entry + return true + } } - } - if !found { tf.Trusted = append(tf.Trusted, entry) - } - if err := saveTrustFile(tf); err != nil { + return true + }) + if err != nil { return nil, err } return &entry, nil @@ -130,31 +133,81 @@ func TrustLocal(path string) (*TrustEntry, error) { func UntrustLocal(path string) (string, bool, error) { if path == "" { if path = findLocalConfig(); path == "" { - return "", false, fmt.Errorf("no %s found here or in a parent directory", LocalConfigFile) + return "", false, ErrNoLocalConfig } } - canon, err := canonicalPath(path) + // A file that is gone, or a link whose target is, can still be untrusted + // by the paths it could have been trusted under. + candidates := unresolvedPaths(path) + if canon, err := canonicalPath(path); err == nil { + candidates = []string{canon} + } + if len(candidates) == 0 { + return "", false, fmt.Errorf("cannot resolve path %s", path) + } + shown := candidates[0] + removed := false + err := updateTrustFile(func(tf *trustFile) bool { + kept := tf.Trusted[:0] + for _, e := range tf.Trusted { + if containsPath(candidates, e.Path) { + removed = true + shown = e.Path + continue + } + kept = append(kept, e) + } + tf.Trusted = kept + return removed + }) + return shown, removed, err +} + +// unresolvedPaths lists the canonical paths a local config that no longer +// resolves could have had: its own, with its directory's links resolved, and, +// for a dangling link, its target's. +func unresolvedPaths(path string) []string { + abs, err := filepath.Abs(path) if err != nil { - // A file that is gone can still be untrusted by the path it had. - if canon, err = filepath.Abs(path); err != nil { - return "", false, err + return nil + } + paths := []string{abs} + add := func(p string) { + if dir, err := filepath.EvalSymlinks(filepath.Dir(p)); err == nil { + p = filepath.Join(dir, filepath.Base(p)) + } + if !containsPath(paths, p) { + paths = append(paths, p) } } - tf := loadTrustFile() - kept := tf.Trusted[:0] - removed := false - for _, e := range tf.Trusted { - if e.Path == canon { - removed = true - continue + add(abs) + if target, err := os.Readlink(abs); err == nil { + if !filepath.IsAbs(target) { + target = filepath.Join(filepath.Dir(abs), target) } - kept = append(kept, e) + add(filepath.Clean(target)) } - if !removed { - return canon, false, nil + return paths +} + +func containsPath(paths []string, path string) bool { + for _, p := range paths { + if p == path { + return true + } } - tf.Trusted = kept - return canon, true, saveTrustFile(tf) + return false +} + +// DisplayPath is path without control characters, for messages: a directory +// name can hold a newline, and a message must not let it forge output. +func DisplayPath(path string) string { + return strings.Map(func(r rune) rune { + if unicode.IsControl(r) { + return -1 + } + return r + }, path) } // TrustedLocals lists the trusted local configs. @@ -200,18 +253,14 @@ func canonicalPath(path string) (string, error) { return filepath.Clean(resolved), nil } -// trustFilePath is the trust store beside the global config in use, or beside -// the preferred one when there is none yet. +// trustFilePath is the trust store, in the preferred config directory. It does +// not follow the global config file to a legacy directory: trust must not move +// when that file is created or removed. func trustFilePath() (string, error) { paths := globalConfigPaths() if len(paths) == 0 { return "", errors.New("unable to determine config path") } - for _, path := range paths { - if _, err := os.Stat(path); err == nil { - return filepath.Join(filepath.Dir(path), trustFileName), nil - } - } return filepath.Join(filepath.Dir(paths[0]), trustFileName), nil } @@ -231,7 +280,11 @@ func loadTrustFile() trustFile { return tf } -func saveTrustFile(tf trustFile) error { +// updateTrustFile applies change to the trust store and saves it when change +// reports a difference. A lock file serializes the read, the change and the +// save across processes, so one command cannot write back entries another +// just removed. +func updateTrustFile(change func(*trustFile) bool) error { path, err := trustFilePath() if err != nil { return err @@ -239,13 +292,64 @@ func saveTrustFile(tf trustFile) error { if err = os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err } + unlock, err := lockTrustFile(path + ".lock") + if err != nil { + return err + } + defer unlock() + + tf := loadTrustFile() + if !change(&tf) { + return nil + } + return saveTrustFile(path, tf) +} + +const ( + trustLockWait = 5 * time.Second + trustLockStale = 30 * time.Second +) + +// lockTrustFile takes the lock by creating lockPath, which only one process +// can do. A lock left by a process that died is taken over once it is stale. +func lockTrustFile(lockPath string) (func(), error) { + deadline := time.Now().Add(trustLockWait) + for { + f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err == nil { + _ = f.Close() + return func() { _ = os.Remove(lockPath) }, nil + } + if !errors.Is(err, os.ErrExist) { + return nil, fmt.Errorf("cannot lock the trust store: %w", err) + } + if info, statErr := os.Stat(lockPath); statErr == nil && time.Since(info.ModTime()) > trustLockStale { + _ = os.Remove(lockPath) + continue + } + if time.Now().After(deadline) { + return nil, fmt.Errorf("the trust store is locked by another fizzy command (%s)", lockPath) + } + time.Sleep(25 * time.Millisecond) + } +} + +func saveTrustFile(path string, tf trustFile) error { data, err := json.MarshalIndent(tf, "", " ") if err != nil { return err } - tmp := path + ".tmp" - if err = os.WriteFile(tmp, append(data, '\n'), 0o600); err != nil { + tmp, err := os.CreateTemp(filepath.Dir(path), trustFileName+".*.tmp") + if err != nil { + return err + } + defer func() { _ = os.Remove(tmp.Name()) }() + if _, err = tmp.Write(append(data, '\n')); err != nil { + _ = tmp.Close() + return err + } + if err = tmp.Close(); err != nil { return err } - return os.Rename(tmp, path) + return os.Rename(tmp.Name(), path) } diff --git a/internal/config/trust_test.go b/internal/config/trust_test.go index 9428712f..b449e883 100644 --- a/internal/config/trust_test.go +++ b/internal/config/trust_test.go @@ -52,10 +52,15 @@ func loadWithWarnings(t *testing.T) (*Config, string) { if err != nil { t.Fatalf("pipe: %v", err) } + defer r.Close() os.Stderr = w - cfg := Load() - os.Stderr = orig - w.Close() + cfg := func() *Config { + defer func() { + os.Stderr = orig + w.Close() + }() + return Load() + }() var buf bytes.Buffer io.Copy(&buf, r) return cfg, buf.String() @@ -191,3 +196,90 @@ func TestTrustLocalWithoutALocalConfigFails(t *testing.T) { t.Error("want an error") } } + +// The trust store stays in the preferred config directory: it does not follow +// the global config file to a legacy directory, where removing that file +// would leave every trusted entry behind. +func TestTheTrustStoreDoesNotFollowALegacyGlobalConfig(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + legacy := filepath.Join(home, ".fizzy", "config.yaml") + if err := os.MkdirAll(filepath.Dir(legacy), 0o700); err != nil { + t.Fatalf("mkdir: %v", err) + } + writeLocalConfig(t, legacy, "account: acme\n") + + want := filepath.Join(home, ".config", "fizzy", trustFileName) + if got, err := trustFilePath(); err != nil || got != want { + t.Fatalf("with a legacy global config: got %q, %v", got, err) + } + if err := os.Remove(legacy); err != nil { + t.Fatalf("remove: %v", err) + } + if got, err := trustFilePath(); err != nil || got != want { + t.Fatalf("without it: got %q, %v", got, err) + } +} + +// Commands that trust and untrust at the same time each keep what the others +// wrote: none saves a copy of the store it read before another's change. +func TestConcurrentTrustChangesKeepEachOther(t *testing.T) { + localConfigHere(t, "account: acme\n") + const files = 8 + paths := make([]string, files) + for i := range paths { + paths[i] = filepath.Join(t.TempDir(), LocalConfigFile) + writeLocalConfig(t, paths[i], "api_url: https://fizzy.example.com\n") + } + + errs := make(chan error, files) + for _, path := range paths { + go func() { + _, err := TrustLocal(path) + errs <- err + }() + } + for range paths { + if err := <-errs; err != nil { + t.Fatalf("trust: %v", err) + } + } + if got := len(TrustedLocals()); got != files { + t.Fatalf("want %d trusted files, got %d", files, got) + } + if left, _ := filepath.Glob(filepath.Join(testConfigDir, trustFileName+".*")); len(left) != 0 { + t.Fatalf("temporary or lock files left behind: %v", left) + } +} + +// A trusted file reached through a link is untrusted by that link even after +// its target is gone. +func TestUntrustThroughALinkWhoseTargetIsGone(t *testing.T) { + localConfigHere(t, "account: acme\n") + target := filepath.Join(t.TempDir(), LocalConfigFile) + writeLocalConfig(t, target, "api_url: https://fizzy.example.com\n") + link := filepath.Join(t.TempDir(), LocalConfigFile) + if err := os.Symlink(target, link); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + + if _, err := TrustLocal(link); err != nil { + t.Fatalf("trust: %v", err) + } + if err := os.Remove(target); err != nil { + t.Fatalf("remove: %v", err) + } + if _, removed, err := UntrustLocal(link); err != nil || !removed { + t.Fatalf("untrust: removed=%v, %v", removed, err) + } + if got := TrustedLocals(); len(got) != 0 { + t.Fatalf("trust left behind: %#v", got) + } +} + +func TestDisplayPathDropsControlCharacters(t *testing.T) { + if got := DisplayPath("/tmp/a\nTrusted /etc\x1b[2K/.fizzy.yaml"); got != "/tmp/aTrusted /etc[2K/.fizzy.yaml" { + t.Fatalf("got %q", got) + } +} diff --git a/skills/fizzy/SKILL.md b/skills/fizzy/SKILL.md index 11f7bbf9..09a9b7a2 100644 --- a/skills/fizzy/SKILL.md +++ b/skills/fizzy/SKILL.md @@ -187,7 +187,7 @@ account: 123456789 board: 03foq1hqmyy91tuyz3ghugg6c ``` -`account` and `board` apply from any `.fizzy.yaml`. An `api_url` or `token` in one is +`account` and `board` apply from the nearest `.fizzy.yaml`. An `api_url` or `token` in it is ignored, with a warning on stderr, until the person trusts the file with `fizzy config trust`, and again whenever either value changes. Never run `fizzy config trust` on a file you did not write unless the person asked you to. From f72a8985dbdb67b402fe61b8050261b9ec025b45 Mon Sep 17 00:00:00 2001 From: Rob Zolkos Date: Fri, 13 Nov 2026 12:45:17 -0500 Subject: [PATCH 3/3] Keep the profile host for the profile's own token only A token from FIZZY_TOKEN or --token replaces the account-named profile's own, so it stays on the configured host as well. A stale trust lock that cannot be removed no longer spins: the wait runs to its deadline. `config explain` and `fizzy setup` drop control characters from the local config's values and paths they print. --- internal/commands/config_cmd.go | 2 +- internal/commands/config_cmd_test.go | 38 ++++++++++++++++++++++++++-- internal/commands/root.go | 10 +++++--- internal/commands/setup.go | 2 +- internal/config/trust.go | 10 +++++--- 5 files changed, 51 insertions(+), 11 deletions(-) diff --git a/internal/commands/config_cmd.go b/internal/commands/config_cmd.go index e5d3c2ce..3bbab8ae 100644 --- a/internal/commands/config_cmd.go +++ b/internal/commands/config_cmd.go @@ -239,7 +239,7 @@ func configExplainData() map[string]any { for _, key := range local.Ignored { switch key { case "api_url": - localAPIURL = raw.APIURL + " (ignored: the file is not trusted)" + localAPIURL = cfgpkg.DisplayPath(raw.APIURL) + " (ignored: the file is not trusted)" case "token": localToken = "ignored: the file is not trusted" } diff --git a/internal/commands/config_cmd_test.go b/internal/commands/config_cmd_test.go index 8c552ca2..17de9ae3 100644 --- a/internal/commands/config_cmd_test.go +++ b/internal/commands/config_cmd_test.go @@ -492,9 +492,36 @@ func TestAnAccountNamedProfileKeepsItsTokenOnItsOwnHost(t *testing.T) { func TestAnAccountNamedProfileWithoutATokenDoesNotSetTheHost(t *testing.T) { accountNamedProfiles(t) + t.Setenv("FIZZY_TOKEN", "env-token") + + if err := resolveProfile(); err != nil { + t.Fatalf("resolve profile: %v", err) + } + resolveToken() + if cfg.Token != "env-token" { + t.Fatalf("want the token from the environment, got %q", cfg.Token) + } + if cfg.APIURL != "https://app.fizzy.do" { + t.Errorf("want the configured host kept, got %q", cfg.APIURL) + } +} + +// A token from the environment replaces the profile's own, so it stays on the +// configured host too. +func TestAnAccountNamedProfileDoesNotSetTheHostForAnotherToken(t *testing.T) { + accountNamedProfiles(t) + if err := credsSaveProfileToken("acme", "acme-token"); err != nil { + t.Fatalf("save token: %v", err) + } + t.Setenv("FIZZY_TOKEN", "env-token") + if err := resolveProfile(); err != nil { t.Fatalf("resolve profile: %v", err) } + resolveToken() + if cfg.Token != "env-token" { + t.Fatalf("want the token from the environment, got %q", cfg.Token) + } if cfg.APIURL != "https://app.fizzy.do" { t.Errorf("want the configured host kept, got %q", cfg.APIURL) } @@ -526,8 +553,8 @@ func TestConfigExplainShowsIgnoredLocalSettings(t *testing.T) { } } -// Trusting a file that cannot be read is not a usage error: only a request -// that names no file is. +// Trusting a file that is missing, malformed or unreadable is not a usage +// error: only a request that names no file is. func TestConfigTrustErrorCodes(t *testing.T) { config.SetTestConfigDir(t.TempDir()) config.SetTestWorkingDir(t.TempDir()) @@ -555,6 +582,13 @@ func TestConfigTrustErrorCodes(t *testing.T) { t.Fatalf("write: %v", err) } if got := code(configTrustCmd.RunE(configTrustCmd, []string{bad})); got != output.CodeAPI { + t.Errorf("malformed config: got %q", got) + } + dir := filepath.Join(t.TempDir(), config.LocalConfigFile) + if err := os.Mkdir(dir, 0o700); err != nil { + t.Fatalf("mkdir: %v", err) + } + if got := code(configTrustCmd.RunE(configTrustCmd, []string{dir})); got != output.CodeAPI { t.Errorf("unreadable config: got %q", got) } } diff --git a/internal/commands/root.go b/internal/commands/root.go index 06b91f7b..89720560 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -1285,13 +1285,17 @@ func applyAccountProfileHost(allProfiles map[string]*profile.Profile) { } // accountProfileBaseURL is the host of the stored profile the configured -// account names, when no profile is active and that profile holds a token. -// The host follows the credential: a profile with no token of its own does -// not pull a token from another source over to its host. +// account names, when no profile is active and that profile's own token is +// the one in use. The host follows the credential: a token from another +// source, whether the profile has none or FIZZY_TOKEN or --token replaces it, +// is not pulled over to the profile's host. func accountProfileBaseURL(allProfiles map[string]*profile.Profile) string { if activeProfile != "" || cfg == nil || cfg.Account == "" || creds == nil { return "" } + if os.Getenv("FIZZY_TOKEN") != "" || cfgToken != "" { + return "" + } p := allProfiles[cfg.Account] if p == nil || p.BaseURL == "" { return "" diff --git a/internal/commands/setup.go b/internal/commands/setup.go index b0098aea..831b0479 100644 --- a/internal/commands/setup.go +++ b/internal/commands/setup.go @@ -300,7 +300,7 @@ func runSetup(cmd *cobra.Command, args []string) error { if _, err := config.TrustLocal(""); err != nil { return &output.Error{ Code: output.CodeAPI, - Message: fmt.Sprintf("saved .fizzy.yaml but could not trust it, so its api_url and token are ignored: %v", err), + Message: "saved .fizzy.yaml but could not trust it, so its api_url and token are ignored: " + config.DisplayPath(err.Error()), Hint: "Run: fizzy config trust", } } diff --git a/internal/config/trust.go b/internal/config/trust.go index db0a1767..1be13ebc 100644 --- a/internal/config/trust.go +++ b/internal/config/trust.go @@ -199,8 +199,9 @@ func containsPath(paths []string, path string) bool { return false } -// DisplayPath is path without control characters, for messages: a directory -// name can hold a newline, and a message must not let it forge output. +// DisplayPath is a path, or other text a local config or its location +// supplies, without control characters, for messages: a directory name can +// hold a newline, and a message must not let it forge output. func DisplayPath(path string) string { return strings.Map(func(r rune) rune { if unicode.IsControl(r) { @@ -324,8 +325,9 @@ func lockTrustFile(lockPath string) (func(), error) { return nil, fmt.Errorf("cannot lock the trust store: %w", err) } if info, statErr := os.Stat(lockPath); statErr == nil && time.Since(info.ModTime()) > trustLockStale { - _ = os.Remove(lockPath) - continue + if os.Remove(lockPath) == nil { + continue + } } if time.Now().After(deadline) { return nil, fmt.Errorf("the trust store is locked by another fizzy command (%s)", lockPath)