From 806e273bb19bfa570e3d5a2b73da651e01a0bcd4 Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Mon, 16 Nov 2026 14:35:15 +0530 Subject: [PATCH 01/16] fix(userconfig): expand environment placeholders in defaults --- CHANGELOG.md | 2 + docs/guide/user-config.md | 5 ++- docs/zh/guide/user-config.md | 4 +- internal/userconfig/apply.go | 12 +++++- internal/userconfig/apply_test.go | 61 +++++++++++++++++++++++++++++++ 5 files changed, 81 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db019f37..6293ad80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Code. ### Fixed +- Expand `${VAR}` references in user-config `env` defaults from the process + environment, preserving unset references and existing environment values. - Warn when a non-empty case-level `judge` has no `type` and its fields are ignored in favor of the eval judge. `validate` and `run` preserve the existing fallback behavior; omitted, empty and null blocks inherit without diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index d0cf70bd..c1e01f49 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -69,7 +69,10 @@ Semantics: is not already set**, so a value on the command line or in your shell always wins. - **`${VAR}` placeholders** in `env` values are expanded from the process - environment at load time, so secrets stay out of the file. + environment before defaults are applied. Unset variables remain literal; + variables set to an empty string expand to an empty string. Expansion is + single-pass and does not read other defaults from the same config. Bare + `$VAR` and shell expressions such as `${VAR:-fallback}` remain literal. - **`runtime_kwargs`** — defaults for `run` keyed by `environment.type` (e.g. `opensandbox`). `eval.yaml` values take precedence; missing keys fall back here. Keys mirror the environment provider's kwargs schema. diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index eba62545..c7fc9035 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -62,7 +62,9 @@ runtime_kwargs: # 按 environment.type 提 - **`telemetry` 与 `env`**:每个 key 对应一个 `OTEL_*` 或自定义环境变量,**仅在 对应环境变量未被设置时才会注入**——命令行或 shell 中已有的值优先。 -- **`env` 中的 `${VAR}`** 在加载时从当前进程环境展开,密钥不会被写进文件本身。 +- **`env` 中的 `${VAR}`** 在应用默认值之前从当前进程环境展开。未设置的变量保留原文, + 已设置为空字符串的变量展开为空字符串。只展开一次,不读取同一配置中的其他默认值。 + `$VAR` 和 `${VAR:-fallback}` 等 shell 表达式保留原文。 - **`runtime_kwargs`**:`run` 命令按 `environment.type`(如 `opensandbox`)查找 默认值。`eval.yaml` 中显式给的值优先;未提供的字段在这里兜底。Key 的形态与 对应 environment provider 的 kwargs 一致。 diff --git a/internal/userconfig/apply.go b/internal/userconfig/apply.go index 018320f2..1179c9bb 100644 --- a/internal/userconfig/apply.go +++ b/internal/userconfig/apply.go @@ -4,10 +4,13 @@ import ( "context" "maps" "os" + "regexp" "sort" "strings" ) +var envPlaceholderPattern = regexp.MustCompile(`\$\{[A-Za-z_][A-Za-z0-9_]*\}`) + const ( envOtelServiceName = "OTEL_SERVICE_NAME" envOtelTracesExporter = "OTEL_TRACES_EXPORTER" @@ -29,7 +32,14 @@ func ApplyEnv(c Config) ([]string, error) { continue } if _, exists := pending[k]; !exists { - pending[k] = v + // Resolve before setting any defaults, so config entries cannot + // become expansion sources based on map or key ordering. + pending[k] = envPlaceholderPattern.ReplaceAllStringFunc(v, func(ref string) string { + if value, exists := os.LookupEnv(ref[2 : len(ref)-1]); exists { + return value + } + return ref + }) } } diff --git a/internal/userconfig/apply_test.go b/internal/userconfig/apply_test.go index 6491d950..829943c1 100644 --- a/internal/userconfig/apply_test.go +++ b/internal/userconfig/apply_test.go @@ -68,6 +68,67 @@ func TestApplyEnv_ArbitraryEnv(t *testing.T) { } } +func TestApplyEnv_ExpandsPlaceholders(t *testing.T) { + t.Setenv("SKILL_UP_TEST_SOURCE", "example-value") + t.Setenv("SKILL_UP_TEST_EMPTY", "") + t.Setenv("SKILL_UP_TEST_NESTED", "${SKILL_UP_TEST_SOURCE}") + t.Setenv("SKILL_UP_TEST_ABSENT", "") + _ = os.Unsetenv("SKILL_UP_TEST_ABSENT") + for _, tc := range []struct{ name, value, want string }{ + {"embedded", "authorization=${SKILL_UP_TEST_SOURCE}", "authorization=example-value"}, + {"repeated", "${SKILL_UP_TEST_SOURCE}/${SKILL_UP_TEST_SOURCE}", "example-value/example-value"}, + {"unset", "${SKILL_UP_TEST_ABSENT}", "${SKILL_UP_TEST_ABSENT}"}, + {"empty", "${SKILL_UP_TEST_EMPTY}", ""}, + {"mixed", "${SKILL_UP_TEST_SOURCE}/${SKILL_UP_TEST_ABSENT}", "example-value/${SKILL_UP_TEST_ABSENT}"}, + {"single pass", "${SKILL_UP_TEST_NESTED}", "${SKILL_UP_TEST_SOURCE}"}, + {"bare reference", "$SKILL_UP_TEST_SOURCE", "$SKILL_UP_TEST_SOURCE"}, + {"shell syntax", "${SKILL_UP_TEST_ABSENT:-fallback}", "${SKILL_UP_TEST_ABSENT:-fallback}"}, + {"unclosed", "${SKILL_UP_TEST_SOURCE", "${SKILL_UP_TEST_SOURCE"}, + } { + t.Run(tc.name, func(t *testing.T) { + const target = "SKILL_UP_TEST_TARGET" + t.Setenv(target, "") + _ = os.Unsetenv(target) + cfg := Config{Env: map[string]string{target: tc.value}} + applied, err := ApplyEnv(cfg) + if err != nil { + t.Fatal(err) + } + if got, exists := os.LookupEnv(target); !exists || got != tc.want { + t.Fatalf("value = %q (set=%t), want %q", got, exists, tc.want) + } + if !slices.Contains(applied, target) || cfg.Env[target] != tc.value { + t.Fatal("applied keys or original config changed unexpectedly") + } + }) + } +} + +func TestApplyEnv_ExpansionPreservesPrecedence(t *testing.T) { + const source, target = "SKILL_UP_TEST_A", "SKILL_UP_TEST_Z" + t.Setenv(source, "") + _ = os.Unsetenv(source) + t.Setenv(target, "") + _ = os.Unsetenv(target) + cfg := Config{Env: map[string]string{source: "from-config", target: "${" + source + "}"}} + if _, err := ApplyEnv(cfg); err != nil { + t.Fatal(err) + } + if got := os.Getenv(target); got != "${"+source+"}" { + t.Fatalf("config defaults must not become expansion sources: %q", got) + } + t.Setenv(source, "from-shell") + for _, existing := range []string{"shell-target", ""} { + t.Setenv(target, existing) + if _, err := ApplyEnv(cfg); err != nil { + t.Fatal(err) + } + if got := os.Getenv(target); got != existing { + t.Fatalf("existing value overwritten: %q", got) + } + } +} + func TestMergeKwargs_EvalWins(t *testing.T) { c := Config{RuntimeKwargs: map[string]Kwargs{ "opensandbox": {"base_url": "from-config", "extensions": "ext"}, From 4e6b3761a893e4185622b89790cb93d7ad88eb65 Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Tue, 17 Nov 2026 15:51:31 +0530 Subject: [PATCH 02/16] fix(userconfig): restrict env expansion to trusted layers --- CHANGELOG.md | 4 +- docs/guide/user-config.md | 10 ++- docs/zh/guide/user-config.md | 6 +- internal/cli/root.go | 2 +- internal/userconfig/apply.go | 20 +++--- internal/userconfig/apply_test.go | 20 +++++- internal/userconfig/config.go | 15 +++- internal/userconfig/config_test.go | 12 ++-- internal/userconfig/loader.go | 19 +++-- internal/userconfig/loader_test.go | 109 +++++++++++++++++++++++++++++ 10 files changed, 188 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8867b86..2920183c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Expand `${VAR}` references in user-config `env` defaults from the process - environment, preserving unset references and existing environment values. + environment only for user-level or explicitly selected (`--config`) values. + Automatically discovered project values remain literal. Preserve unset + references and existing environment values. - Count primary cases consistently in Markdown and CLI summaries for benchmark runs, without counting baseline rows as extra cases or discarding their details. - Reject malformed `--include-case-name` and `--exclude-case-name` glob patterns diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index c1e01f49..7bf205f4 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -68,8 +68,14 @@ Semantics: environment variable. Values are only applied **if the corresponding env var is not already set**, so a value on the command line or in your shell always wins. -- **`${VAR}` placeholders** in `env` values are expanded from the process - environment before defaults are applied. Unset variables remain literal; +- **`${VAR}` placeholders** in `env` values from the `user` and `explicit` + layers are expanded from the process environment before defaults are applied. + Automatically discovered project values stay literal. To opt in for a trusted + project file, pass `--config ./.skill-up.yaml`. This grants that file access to + host environment variables, including secrets, so review it before opting in. + Permission follows each winning value: a project override of a user value + stays literal, and selecting a different explicit file does not enable + expansion for project entries it leaves unchanged. Unset variables remain literal; variables set to an empty string expand to an empty string. Expansion is single-pass and does not read other defaults from the same config. Bare `$VAR` and shell expressions such as `${VAR:-fallback}` remain literal. diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index c7fc9035..f7b2c52f 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -62,7 +62,11 @@ runtime_kwargs: # 按 environment.type 提 - **`telemetry` 与 `env`**:每个 key 对应一个 `OTEL_*` 或自定义环境变量,**仅在 对应环境变量未被设置时才会注入**——命令行或 shell 中已有的值优先。 -- **`env` 中的 `${VAR}`** 在应用默认值之前从当前进程环境展开。未设置的变量保留原文, +- **`env` 中的 `${VAR}`** 仅在值来自 `user` 或 `explicit` 层时,才在应用默认值之前 + 从当前进程环境展开。自动发现的项目配置保留原文。要允许可信的项目文件展开变量, + 请传入 `--config ./.skill-up.yaml`。这会授权该文件读取宿主进程的环境变量(包括密钥), + 因此应先审阅文件。权限跟随最终生效的值:项目层覆盖用户层的值仍保留原文; + 指定另一份显式配置不会授权其中未覆盖的项目条目。未设置的变量保留原文, 已设置为空字符串的变量展开为空字符串。只展开一次,不读取同一配置中的其他默认值。 `$VAR` 和 `${VAR:-fallback}` 等 shell 表达式保留原文。 - **`runtime_kwargs`**:`run` 命令按 `environment.type`(如 `opensandbox`)查找 diff --git a/internal/cli/root.go b/internal/cli/root.go index ab8e7ea7..887185d0 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -169,7 +169,7 @@ func init() { return err }) - rootCmd.PersistentFlags().String(configFlagName, "", "Path to skill-up user config (overrides discovered defaults)") + rootCmd.PersistentFlags().String(configFlagName, "", "Path to trusted skill-up user config (overrides defaults; allows ${VAR} expansion)") rootCmd.AddCommand(runCmd) rootCmd.AddCommand(validateCmd) diff --git a/internal/userconfig/apply.go b/internal/userconfig/apply.go index 1179c9bb..20fd3ae4 100644 --- a/internal/userconfig/apply.go +++ b/internal/userconfig/apply.go @@ -25,6 +25,7 @@ const ( // ApplyEnv writes telemetry and arbitrary env defaults from c into the process // environment, only setting keys that are currently unset. It returns the list // of keys that were actually applied (sorted) for logging and debugging. +// Only env values from the user or explicit discovery layer expand ${VAR}. func ApplyEnv(c Config) ([]string, error) { pending := telemetryEnv(c.Telemetry) for k, v := range c.Env { @@ -32,14 +33,17 @@ func ApplyEnv(c Config) ([]string, error) { continue } if _, exists := pending[k]; !exists { - // Resolve before setting any defaults, so config entries cannot - // become expansion sources based on map or key ordering. - pending[k] = envPlaceholderPattern.ReplaceAllStringFunc(v, func(ref string) string { - if value, exists := os.LookupEnv(ref[2 : len(ref)-1]); exists { - return value - } - return ref - }) + if source := c.envSources[k]; source == sourceUser || source == sourceExplicit { + // Resolve before setting any defaults, so config entries cannot + // become expansion sources based on map or key ordering. + v = envPlaceholderPattern.ReplaceAllStringFunc(v, func(ref string) string { + if value, exists := os.LookupEnv(ref[2 : len(ref)-1]); exists { + return value + } + return ref + }) + } + pending[k] = v } } diff --git a/internal/userconfig/apply_test.go b/internal/userconfig/apply_test.go index 829943c1..d4bbc05a 100644 --- a/internal/userconfig/apply_test.go +++ b/internal/userconfig/apply_test.go @@ -89,7 +89,8 @@ func TestApplyEnv_ExpandsPlaceholders(t *testing.T) { const target = "SKILL_UP_TEST_TARGET" t.Setenv(target, "") _ = os.Unsetenv(target) - cfg := Config{Env: map[string]string{target: tc.value}} + var cfg Config + cfg.overlay(Config{Env: map[string]string{target: tc.value}}, "user") applied, err := ApplyEnv(cfg) if err != nil { t.Fatal(err) @@ -110,7 +111,8 @@ func TestApplyEnv_ExpansionPreservesPrecedence(t *testing.T) { _ = os.Unsetenv(source) t.Setenv(target, "") _ = os.Unsetenv(target) - cfg := Config{Env: map[string]string{source: "from-config", target: "${" + source + "}"}} + var cfg Config + cfg.overlay(Config{Env: map[string]string{source: "from-config", target: "${" + source + "}"}}, "user") if _, err := ApplyEnv(cfg); err != nil { t.Fatal(err) } @@ -129,6 +131,20 @@ func TestApplyEnv_ExpansionPreservesPrecedence(t *testing.T) { } } +func TestApplyEnv_WithoutSourceKeepsPlaceholders(t *testing.T) { + const target = "SKILL_UP_TEST_TARGET" + t.Setenv("SKILL_UP_TEST_SOURCE", "example-value") + t.Setenv(target, "") + _ = os.Unsetenv(target) + cfg := Config{Env: map[string]string{target: "${SKILL_UP_TEST_SOURCE}"}} + if _, err := ApplyEnv(cfg); err != nil { + t.Fatal(err) + } + if got := os.Getenv(target); got != cfg.Env[target] { + t.Fatalf("config without a trusted source expanded: %q", got) + } +} + func TestMergeKwargs_EvalWins(t *testing.T) { c := Config{RuntimeKwargs: map[string]Kwargs{ "opensandbox": {"base_url": "from-config", "extensions": "ext"}, diff --git a/internal/userconfig/config.go b/internal/userconfig/config.go index 99a69aef..f3f39cbf 100644 --- a/internal/userconfig/config.go +++ b/internal/userconfig/config.go @@ -24,6 +24,8 @@ type Config struct { Telemetry Telemetry `yaml:"telemetry,omitempty"` Env map[string]string `yaml:"env,omitempty"` RuntimeKwargs map[string]Kwargs `yaml:"runtime_kwargs,omitempty"` + // Preserve provenance so project overrides cannot inherit user-layer trust. + envSources map[string]string } // Telemetry holds OpenTelemetry-related defaults. Each non-empty field maps to @@ -67,8 +69,9 @@ func (c *Config) Validate() error { } // overlay copies non-zero fields from other onto c. Maps are merged key-wise -// with other winning on conflicts. -func (c *Config) overlay(other Config) { +// with other winning on conflicts. sourceKind identifies the layer supplying +// the env values so ApplyEnv can limit expansion to trusted sources. +func (c *Config) overlay(other Config, sourceKind string) { if other.SchemaVersion != "" { c.SchemaVersion = other.SchemaVersion } @@ -94,6 +97,14 @@ func (c *Config) overlay(other Config) { } c.Telemetry.ResourceAttributes = mergeStringMap(c.Telemetry.ResourceAttributes, other.Telemetry.ResourceAttributes) c.Env = mergeStringMap(c.Env, other.Env) + if len(other.Env) > 0 { + if c.envSources == nil { + c.envSources = make(map[string]string) + } + for key := range other.Env { + c.envSources[key] = sourceKind + } + } if len(other.RuntimeKwargs) > 0 { if c.RuntimeKwargs == nil { diff --git a/internal/userconfig/config_test.go b/internal/userconfig/config_test.go index 37849b97..a46c2423 100644 --- a/internal/userconfig/config_test.go +++ b/internal/userconfig/config_test.go @@ -4,7 +4,7 @@ import "testing" func TestOverlay_ScalarOverwrite(t *testing.T) { c := Config{SchemaVersion: "v1alpha1", Telemetry: Telemetry{ServiceName: "a"}} - c.overlay(Config{Telemetry: Telemetry{ServiceName: "b"}}) + c.overlay(Config{Telemetry: Telemetry{ServiceName: "b"}}, "project") if c.Telemetry.ServiceName != "b" { t.Fatalf("expected b, got %q", c.Telemetry.ServiceName) } @@ -15,7 +15,7 @@ func TestOverlay_ScalarOverwrite(t *testing.T) { func TestOverlay_ZeroValueSkip(t *testing.T) { c := Config{Telemetry: Telemetry{ServiceName: "a", TracesExporter: "otlp"}} - c.overlay(Config{Telemetry: Telemetry{ServiceName: ""}}) + c.overlay(Config{Telemetry: Telemetry{ServiceName: ""}}, "project") if c.Telemetry.ServiceName != "a" { t.Fatalf("zero value should not overwrite, got %q", c.Telemetry.ServiceName) } @@ -26,7 +26,7 @@ func TestOverlay_ZeroValueSkip(t *testing.T) { func TestOverlay_MapMerge(t *testing.T) { c := Config{Env: map[string]string{"A": "1", "B": "2"}} - c.overlay(Config{Env: map[string]string{"B": "two", "C": "3"}}) + c.overlay(Config{Env: map[string]string{"B": "two", "C": "3"}}, "project") if c.Env["A"] != "1" || c.Env["B"] != "two" || c.Env["C"] != "3" { t.Fatalf("merged map wrong: %+v", c.Env) } @@ -34,7 +34,7 @@ func TestOverlay_MapMerge(t *testing.T) { func TestOverlay_RuntimeKwargsMerge(t *testing.T) { c := Config{RuntimeKwargs: map[string]Kwargs{"opensandbox": {"base_url": "x"}}} - c.overlay(Config{RuntimeKwargs: map[string]Kwargs{"opensandbox": {"extensions": "y"}, "custom": {"image": "ubuntu"}}}) + c.overlay(Config{RuntimeKwargs: map[string]Kwargs{"opensandbox": {"extensions": "y"}, "custom": {"image": "ubuntu"}}}, "project") if c.RuntimeKwargs["opensandbox"]["base_url"] != "x" || c.RuntimeKwargs["opensandbox"]["extensions"] != "y" { t.Fatalf("kwarg merge wrong: %+v", c.RuntimeKwargs["opensandbox"]) } @@ -48,14 +48,14 @@ func TestOverlay_VerboseExplicitOverridesEitherWay(t *testing.T) { // Higher-precedence layer can explicitly disable verbose. c := Config{Telemetry: Telemetry{Verbose: &tru}} - c.overlay(Config{Telemetry: Telemetry{Verbose: &fls}}) + c.overlay(Config{Telemetry: Telemetry{Verbose: &fls}}, "project") if c.Telemetry.Verbose == nil || *c.Telemetry.Verbose { t.Fatalf("verbose=false in overlay should win, got %v", c.Telemetry.Verbose) } // A nil verbose in the overlay leaves the lower-precedence value untouched. c2 := Config{Telemetry: Telemetry{Verbose: &tru}} - c2.overlay(Config{Telemetry: Telemetry{Verbose: nil}}) + c2.overlay(Config{Telemetry: Telemetry{Verbose: nil}}, "project") if c2.Telemetry.Verbose == nil || !*c2.Telemetry.Verbose { t.Fatalf("nil verbose in overlay should not clear existing true, got %v", c2.Telemetry.Verbose) } diff --git a/internal/userconfig/loader.go b/internal/userconfig/loader.go index e6bc89e3..5d011e9d 100644 --- a/internal/userconfig/loader.go +++ b/internal/userconfig/loader.go @@ -33,6 +33,13 @@ const UserConfigDir = "skill-up" // UserConfigFile is the default user-layer file name. const UserConfigFile = "config.yaml" +const ( + sourceEmbed = "embed" + sourceUser = "user" + sourceProject = "project" + sourceExplicit = "explicit" +) + // LoadOptions controls config discovery. type LoadOptions struct { ExplicitPath string @@ -65,14 +72,14 @@ func LoadEffective(opts LoadOptions) (Config, []Source, error) { } cfg := Config{} - sources := []Source{{Kind: "embed"}} + sources := []Source{{Kind: sourceEmbed}} // Auto-discovered layers (user, project) downgrade parse/validate errors to // warnings so a corrupt ~/.config/skill-up/config.yaml does not block // unrelated commands (run/validate/init/...). Only --config, which the user // explicitly opted into, treats errors as fatal. - sources = mergeOptionalLayer(&cfg, sources, "user", resolveUserConfigPath(opts, getenv), warn) - sources = mergeOptionalLayer(&cfg, sources, "project", resolveProjectConfigPath(opts), warn) + sources = mergeOptionalLayer(&cfg, sources, sourceUser, resolveUserConfigPath(opts, getenv), warn) + sources = mergeOptionalLayer(&cfg, sources, sourceProject, resolveProjectConfigPath(opts), warn) if opts.ExplicitPath != "" { loaded, ok, err := loadConfigFile(opts.ExplicitPath) @@ -82,8 +89,8 @@ func LoadEffective(opts LoadOptions) (Config, []Source, error) { if !ok { return Config{}, nil, fmt.Errorf("config file not found: %s", opts.ExplicitPath) } - cfg.overlay(loaded) - sources = append(sources, Source{Kind: "explicit", Path: opts.ExplicitPath}) + cfg.overlay(loaded, sourceExplicit) + sources = append(sources, Source{Kind: sourceExplicit, Path: opts.ExplicitPath}) } if err := cfg.Validate(); err != nil { @@ -117,7 +124,7 @@ func mergeOptionalLayer(cfg *Config, sources []Source, kind, path string, warn i if !ok { return sources } - cfg.overlay(loaded) + cfg.overlay(loaded, kind) return append(sources, Source{Kind: kind, Path: path}) } diff --git a/internal/userconfig/loader_test.go b/internal/userconfig/loader_test.go index e8a62c6e..529fb7cb 100644 --- a/internal/userconfig/loader_test.go +++ b/internal/userconfig/loader_test.go @@ -124,6 +124,115 @@ func TestLoadEffective_EnvVarPath(t *testing.T) { } } +type envExpansionCase struct { + name string + user string + project string + explicit string + explicitProject bool + userEnvPath bool + want map[string]string +} + +func TestLoadEffective_EnvExpansionTrust(t *testing.T) { + const secret = "test-token" + const literal = "leaked=${SKILL_UP_TEST_SECRET}" + const expanded = "leaked=" + secret + const userOnly = "SKILL_UP_TEST_USER_ONLY" + const explicitOnly = "SKILL_UP_TEST_EXPLICIT_ONLY" + const project = `env: + OTEL_EXPORTER_OTLP_ENDPOINT: https://collector.example.invalid + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_RESOURCE_ATTRIBUTES: leaked=${SKILL_UP_TEST_SECRET} +` + const user = `env: + OTEL_RESOURCE_ATTRIBUTES: leaked=${SKILL_UP_TEST_SECRET} + SKILL_UP_TEST_USER_ONLY: leaked=${SKILL_UP_TEST_SECRET} +` + const explicit = `env: + SKILL_UP_TEST_EXPLICIT_ONLY: leaked=${SKILL_UP_TEST_SECRET} +` + t.Setenv("SKILL_UP_TEST_SECRET", secret) + for _, tc := range []envExpansionCase{ + { + name: "automatic project stays literal", project: project, + want: map[string]string{envOtelResourceAttributes: literal}, + }, + { + name: "user defaults expand", user: user, + want: map[string]string{envOtelResourceAttributes: expanded, userOnly: expanded}, + }, + { + name: "project override loses user trust", user: user, project: project, + want: map[string]string{envOtelResourceAttributes: literal, userOnly: expanded}, + }, + { + name: "explicit config does not trust unrelated project keys", user: user, project: project, explicit: explicit, + want: map[string]string{envOtelResourceAttributes: literal, userOnly: expanded, explicitOnly: expanded}, + }, + { + name: "explicitly selected project expands", project: project, explicitProject: true, + want: map[string]string{envOtelResourceAttributes: expanded}, + }, + { + name: "explicit key overrides project trust", project: project, explicit: user, + want: map[string]string{envOtelResourceAttributes: expanded, userOnly: expanded}, + }, + { + name: "user environment path expands", user: user, userEnvPath: true, + want: map[string]string{envOtelResourceAttributes: expanded, userOnly: expanded}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + testEnvExpansionTrust(t, tc) + }) + } +} + +func testEnvExpansionTrust(t *testing.T, tc envExpansionCase) { + t.Helper() + for _, key := range []string{envOtelResourceAttributes, "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_PROTOCOL", "SKILL_UP_TEST_USER_ONLY", "SKILL_UP_TEST_EXPLICIT_ONLY"} { + t.Setenv(key, "") + _ = os.Unsetenv(key) + } + home, wd := t.TempDir(), t.TempDir() + userPath := filepath.Join(home, ".config", UserConfigDir, UserConfigFile) + if tc.userEnvPath { + userPath = filepath.Join(t.TempDir(), "user.yaml") + } + projectPath := filepath.Join(wd, ProjectConfigFile) + writeFile(t, userPath, tc.user) + writeFile(t, projectPath, tc.project) + opts := LoadOptions{HomeDir: home, WorkingDir: wd, Env: emptyEnv} + if tc.userEnvPath { + opts.Env = func(key string) string { + if key == ConfigEnvVar { + return userPath + } + return "" + } + } + if tc.explicit != "" { + opts.ExplicitPath = filepath.Join(t.TempDir(), "explicit.yaml") + writeFile(t, opts.ExplicitPath, tc.explicit) + } + if tc.explicitProject { + opts.ExplicitPath = projectPath + } + cfg, _, err := LoadEffective(opts) + if err != nil { + t.Fatal(err) + } + if _, err := ApplyEnv(cfg); err != nil { + t.Fatal(err) + } + for key, want := range tc.want { + if got := os.Getenv(key); got != want { + t.Errorf("%s = %q, want %q", key, got, want) + } + } +} + func TestLoadEffective_CorruptFile(t *testing.T) { tmp := t.TempDir() bad := filepath.Join(tmp, "bad.yaml") From 143360d37982405dfd2a3916cd13b7ce7c69d291 Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Tue, 17 Nov 2026 16:00:12 +0530 Subject: [PATCH 03/16] test(userconfig): cover CLI trust and document remaining limits --- README.md | 9 +++++- docs/guide/user-config.md | 8 +++++- docs/zh/guide/user-config.md | 6 +++- internal/cli/init.go | 3 +- internal/cli/root_test.go | 44 ++++++++++++++++++++++++++++++ internal/userconfig/loader_test.go | 8 ++++++ 6 files changed, 74 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ee7bd15c..25c7076a 100644 --- a/README.md +++ b/README.md @@ -391,7 +391,14 @@ For `runtime_kwargs`: explicit `--runtime-kwarg` on `run` > `eval.yaml` `environ ### Secrets -Prefer `${ENV_VAR}` references inside the config file rather than baking secret literals. The redaction mechanism (`userconfig.Redact`) masks fields tagged `secret:"true"` when printing; currently no Config field carries the tag, but the mechanism is in place for future fields. +Use `${ENV_VAR}` references in `env` values from user-level or explicitly selected +configuration. Automatically discovered project values stay literal; pass +`--config ./.skill-up.yaml` only after reviewing and trusting that file. See +[user-config semantics](docs/guide/user-config.md#schema) for precedence and +remaining trust limitations. + +The redaction mechanism (`userconfig.Redact`) masks fields tagged `secret:"true"` +when printing; currently no Config field carries the tag. ## Importing `evals.json` diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index 7bf205f4..aaa76157 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -75,7 +75,9 @@ Semantics: host environment variables, including secrets, so review it before opting in. Permission follows each winning value: a project override of a user value stays literal, and selecting a different explicit file does not enable - expansion for project entries it leaves unchanged. Unset variables remain literal; + expansion for project entries it leaves unchanged. If `SKILL_UP_CONFIG` points + to the same automatically discovered project file, the project layer still + wins and stays literal; use `--config` to opt in. Unset variables remain literal; variables set to an empty string expand to an empty string. Expansion is single-pass and does not read other defaults from the same config. Bare `$VAR` and shell expressions such as `${VAR:-fallback}` remain literal. @@ -83,6 +85,10 @@ Semantics: `opensandbox`). `eval.yaml` values take precedence; missing keys fall back here. Keys mirror the environment provider's kwargs schema. +Expansion permission does not bind credentials to a destination. Project files +can still override literal telemetry endpoints, so inspect their settings before +using credentials from your environment or user config. + --- ## Bootstrapping with `skill-up init` diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index f7b2c52f..67020a0c 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -66,13 +66,17 @@ runtime_kwargs: # 按 environment.type 提 从当前进程环境展开。自动发现的项目配置保留原文。要允许可信的项目文件展开变量, 请传入 `--config ./.skill-up.yaml`。这会授权该文件读取宿主进程的环境变量(包括密钥), 因此应先审阅文件。权限跟随最终生效的值:项目层覆盖用户层的值仍保留原文; - 指定另一份显式配置不会授权其中未覆盖的项目条目。未设置的变量保留原文, + 指定另一份显式配置不会授权其中未覆盖的项目条目。如果 `SKILL_UP_CONFIG` 指向同一份 + 自动发现的项目文件,项目层仍优先且保留原文;请用 `--config` 显式授权。未设置的变量保留原文, 已设置为空字符串的变量展开为空字符串。只展开一次,不读取同一配置中的其他默认值。 `$VAR` 和 `${VAR:-fallback}` 等 shell 表达式保留原文。 - **`runtime_kwargs`**:`run` 命令按 `environment.type`(如 `opensandbox`)查找 默认值。`eval.yaml` 中显式给的值优先;未提供的字段在这里兜底。Key 的形态与 对应 environment provider 的 kwargs 一致。 +展开权限不会将凭据绑定到特定目标。项目文件仍能覆盖字面量形式的遥测端点, +因此在使用环境变量或用户配置中的凭据前,应先检查项目配置。 + --- ## 用 `skill-up init` 初始化 diff --git a/internal/cli/init.go b/internal/cli/init.go index b15bb501..c60fde90 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -157,7 +157,8 @@ telemetry: # verbose: false # Arbitrary additional env vars. Same only-if-unset semantics as telemetry. -# Use ${VAR} placeholders for secrets so they are not baked into the file. +# ${VAR} expands only in user-level or explicitly selected (--config) files. +# Project files stay literal unless trusted with --config ./.skill-up.yaml. # env: # OTEL_EXPORTER_OTLP_HEADERS: authorization=${OTLP_TOKEN} diff --git a/internal/cli/root_test.go b/internal/cli/root_test.go index 44532647..d19ac185 100644 --- a/internal/cli/root_test.go +++ b/internal/cli/root_test.go @@ -2,6 +2,8 @@ package cli import ( "bytes" + "os" + "path/filepath" "strings" "testing" @@ -47,6 +49,48 @@ func TestExecuteArgsVersionInitializesRoot(t *testing.T) { } } +func TestExecuteArgsProjectEnvTrust(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("SKILL_UP_CONFIG", "") + t.Setenv("SKILL_UP_TEST_SECRET", "test-token") + t.Setenv("OTEL_TRACES_EXPORTER", "none") + t.Setenv("OTEL_METRICS_EXPORTER", "none") + wd := t.TempDir() + t.Chdir(wd) + project := filepath.Join(wd, ".skill-up.yaml") + if err := os.WriteFile(project, []byte(`env: + OTEL_EXPORTER_OTLP_ENDPOINT: https://collector.example.invalid + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_RESOURCE_ATTRIBUTES: leaked=${SKILL_UP_TEST_SECRET} +`), 0o600); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + args []string + want string + }{ + {"automatic", []string{"--version"}, "leaked=${SKILL_UP_TEST_SECRET}"}, + {"explicit", []string{"--version", "--config", project}, "leaked=test-token"}, + {"explicit equals", []string{"--version", "--config=" + project}, "leaked=test-token"}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, key := range []string{"OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_PROTOCOL", "OTEL_RESOURCE_ATTRIBUTES"} { + t.Setenv(key, "") + _ = os.Unsetenv(key) + } + if _, err := captureStdout(t, func() error { + return ExecuteArgs("test-version", tc.args) + }); err != nil { + t.Fatal(err) + } + if got := os.Getenv("OTEL_RESOURCE_ATTRIBUTES"); got != tc.want { + t.Fatalf("resource attributes = %q, want %q", got, tc.want) + } + }) + } +} + func TestIsInitInvocation(t *testing.T) { cases := []struct { name string diff --git a/internal/userconfig/loader_test.go b/internal/userconfig/loader_test.go index 529fb7cb..83d9ebd8 100644 --- a/internal/userconfig/loader_test.go +++ b/internal/userconfig/loader_test.go @@ -131,6 +131,7 @@ type envExpansionCase struct { explicit string explicitProject bool userEnvPath bool + userIsProject bool want map[string]string } @@ -182,6 +183,10 @@ func TestLoadEffective_EnvExpansionTrust(t *testing.T) { name: "user environment path expands", user: user, userEnvPath: true, want: map[string]string{envOtelResourceAttributes: expanded, userOnly: expanded}, }, + { + name: "user path also discovered as project stays literal", project: project, userEnvPath: true, userIsProject: true, + want: map[string]string{envOtelResourceAttributes: literal}, + }, } { t.Run(tc.name, func(t *testing.T) { testEnvExpansionTrust(t, tc) @@ -201,6 +206,9 @@ func testEnvExpansionTrust(t *testing.T, tc envExpansionCase) { userPath = filepath.Join(t.TempDir(), "user.yaml") } projectPath := filepath.Join(wd, ProjectConfigFile) + if tc.userIsProject { + userPath = projectPath + } writeFile(t, userPath, tc.user) writeFile(t, projectPath, tc.project) opts := LoadOptions{HomeDir: home, WorkingDir: wd, Env: emptyEnv} From ddd9ecc37ced52056ca24bf5b3572a2be889dac5 Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Tue, 17 Nov 2026 16:06:22 +0530 Subject: [PATCH 04/16] test(cli): pin config trust exception for init --- docs/guide/cli-reference.md | 5 ++++- docs/guide/user-config.md | 7 ++++--- docs/zh/guide/cli-reference.md | 4 +++- docs/zh/guide/user-config.md | 5 +++-- internal/cli/root_test.go | 36 ++++++++++++++++++++++++++-------- 5 files changed, 42 insertions(+), 15 deletions(-) diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index ca0d704d..79867c43 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -408,7 +408,10 @@ skill-up init [flags] | `--print` | `false` | Print to stdout instead of writing to disk | | `--force` | `false` | Overwrite an existing target | -> Note: for `init`, `--config` names the *source* to read. For every other subcommand (`run`, `validate`, …) it is the *load-path override* sitting at the top of the discovery chain. +> For `init`, `--config` names the source to copy without expanding placeholders. +> For other subcommands it selects the highest-precedence config and permits +> `${VAR}` expansion in that file's `env` values. Use it only with trusted files; +> see [user configuration](./user-config.md#schema) for the trust boundary. ### Examples diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index aaa76157..887c97f8 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -85,9 +85,10 @@ Semantics: `opensandbox`). `eval.yaml` values take precedence; missing keys fall back here. Keys mirror the environment provider's kwargs schema. -Expansion permission does not bind credentials to a destination. Project files -can still override literal telemetry endpoints, so inspect their settings before -using credentials from your environment or user config. +Expansion permission does not bind credentials to a destination. Expanding a +token in user-level telemetry headers makes it available to the exporter, and +a project's literal endpoint override can receive that token. Inspect project +settings before using credentials from your environment or user config. --- diff --git a/docs/zh/guide/cli-reference.md b/docs/zh/guide/cli-reference.md index 630293cd..a2f560d4 100644 --- a/docs/zh/guide/cli-reference.md +++ b/docs/zh/guide/cli-reference.md @@ -242,7 +242,9 @@ skill-up init [flags] | `--print` | `false` | 输出到 stdout,而不是写盘 | | `--force` | `false` | 覆盖已存在的目标文件 | -> 注意:对 `init` 子命令,`--config` 是**读取源**;对其他子命令(`run`、`validate` …),`--config` 是加载链最顶层的覆盖路径。 +> 对 `init`,`--config` 指定要复制的源文件,不展开占位符。对其他子命令,它选择 +> 优先级最高的配置,并允许展开该文件 `env` 值中的 `${VAR}`。仅应指定可信文件; +> 信任边界见[用户配置](./user-config.md#schema)。 ### 示例 diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index 67020a0c..2a985ee2 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -74,8 +74,9 @@ runtime_kwargs: # 按 environment.type 提 默认值。`eval.yaml` 中显式给的值优先;未提供的字段在这里兜底。Key 的形态与 对应 environment provider 的 kwargs 一致。 -展开权限不会将凭据绑定到特定目标。项目文件仍能覆盖字面量形式的遥测端点, -因此在使用环境变量或用户配置中的凭据前,应先检查项目配置。 +展开权限不会将凭据绑定到特定目标。用户级遥测请求头中的令牌展开后会提供给导出器, +而项目配置中的字面量端点覆盖可能接收到该令牌。因此在使用环境变量或用户配置中的 +凭据前,应先检查项目配置。 --- diff --git a/internal/cli/root_test.go b/internal/cli/root_test.go index d19ac185..13f0bed8 100644 --- a/internal/cli/root_test.go +++ b/internal/cli/root_test.go @@ -50,6 +50,20 @@ func TestExecuteArgsVersionInitializesRoot(t *testing.T) { } func TestExecuteArgsProjectEnvTrust(t *testing.T) { + configFlag := rootCmd.PersistentFlags().Lookup(configFlagName) + configValue, configChanged := configFlag.Value.String(), configFlag.Changed + printFlag := initCmd.Flags().Lookup("print") + printValue, printChanged := printFlag.Value.String(), printFlag.Changed + t.Cleanup(func() { + if err := configFlag.Value.Set(configValue); err != nil { + t.Error(err) + } + configFlag.Changed = configChanged + if err := printFlag.Value.Set(printValue); err != nil { + t.Error(err) + } + printFlag.Changed = printChanged + }) t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("SKILL_UP_CONFIG", "") t.Setenv("SKILL_UP_TEST_SECRET", "test-token") @@ -66,24 +80,30 @@ func TestExecuteArgsProjectEnvTrust(t *testing.T) { t.Fatal(err) } for _, tc := range []struct { - name string - args []string - want string + name string + args []string + want string + wantOutput string }{ - {"automatic", []string{"--version"}, "leaked=${SKILL_UP_TEST_SECRET}"}, - {"explicit", []string{"--version", "--config", project}, "leaked=test-token"}, - {"explicit equals", []string{"--version", "--config=" + project}, "leaked=test-token"}, + {"automatic", []string{"--version"}, "leaked=${SKILL_UP_TEST_SECRET}", "test-version"}, + {"explicit", []string{"--version", "--config", project}, "leaked=test-token", "test-version"}, + {"explicit equals", []string{"--version", "--config=" + project}, "leaked=test-token", "test-version"}, + {"init source", []string{"init", "--config", project, "--print"}, "leaked=${SKILL_UP_TEST_SECRET}", "leaked=${SKILL_UP_TEST_SECRET}"}, } { t.Run(tc.name, func(t *testing.T) { for _, key := range []string{"OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_PROTOCOL", "OTEL_RESOURCE_ATTRIBUTES"} { t.Setenv(key, "") _ = os.Unsetenv(key) } - if _, err := captureStdout(t, func() error { + output, err := captureStdout(t, func() error { return ExecuteArgs("test-version", tc.args) - }); err != nil { + }) + if err != nil { t.Fatal(err) } + if !strings.Contains(output, tc.wantOutput) { + t.Fatalf("command output = %q, want %q", output, tc.wantOutput) + } if got := os.Getenv("OTEL_RESOURCE_ATTRIBUTES"); got != tc.want { t.Fatalf("resource attributes = %q, want %q", got, tc.want) } From ea4ec3538c9bd183d816408ec6c7ba093548984b Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Wed, 18 Nov 2026 09:02:07 +0530 Subject: [PATCH 05/16] fix(config): require explicit trust for project defaults --- CHANGELOG.md | 7 +- README.md | 13 +-- docs/guide/cli-reference.md | 3 +- docs/guide/user-config.md | 55 +++++++----- docs/zh/guide/cli-reference.md | 3 +- docs/zh/guide/user-config.md | 45 +++++++--- internal/cli/init.go | 5 +- internal/cli/root.go | 14 +-- internal/cli/root_test.go | 88 ++++++++++++++++++- internal/userconfig/config.go | 2 +- internal/userconfig/loader.go | 35 +++++--- internal/userconfig/loader_test.go | 132 ++++++++++++++++++++++++++--- 12 files changed, 318 insertions(+), 84 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7478e5a..3a43f7bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,8 +14,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 delivery metadata and failing before execution if the file cannot be uploaded. - Expand `${VAR}` references in user-config `env` defaults from the process environment only for user-level or explicitly selected (`--config`) values. - Automatically discovered project values remain literal. Preserve unset - references and existing environment values. + Preserve unset references and existing environment values. Project + `.skill-up.yaml` files now require explicit selection with `--config` or + `SKILL_UP_CONFIG`; automatic discovery warns and ignores the entire file, + including runtime defaults, so project endpoints cannot redirect trusted + credentials. Review existing project configs before opting in. - Match environment variable names case-insensitively in the `none` runtime on native Windows. A host `Path` and a configured or probed `PATH` were both passed to the child, and which one it kept followed map order. Per-call diff --git a/README.md b/README.md index 25c7076a..1caeb427 100644 --- a/README.md +++ b/README.md @@ -331,17 +331,20 @@ skill-up auto-loads an optional user-level config that supplies default OpenTele ### Discovery chain (lowest to highest precedence) ``` -embed (empty) < user (~/.config/skill-up/config.yaml) < project ($PWD/.skill-up.yaml) < explicit (--config) +embed (empty) < user (~/.config/skill-up/config.yaml) < explicit (--config) ``` | Source | Path | | ---------- | ------------------------------------------------------------------------------------------------------- | | `embed` | empty `Config{}` — no vendor defaults baked in | | `user` | `$SKILL_UP_CONFIG`, else `$XDG_CONFIG_HOME/skill-up/config.yaml`, else `~/.config/skill-up/config.yaml` | -| `project` | `$PWD/.skill-up.yaml` | | `explicit` | `--config ` (must exist) | -Missing files at the `user` and `project` layers are silently skipped; a missing `--config` path is a hard error. A corrupt config at any layer also fails the run. +Missing user files are silently skipped; read or parse errors warn. A missing +or invalid `--config` path is a hard error. Automatically discovered +`$PWD/.skill-up.yaml` files are ignored with a warning. Review a project file, +then select it with `--config ./.skill-up.yaml` to trust all its defaults, +including runtime endpoints. ### Quickstart @@ -392,10 +395,10 @@ For `runtime_kwargs`: explicit `--runtime-kwarg` on `run` > `eval.yaml` `environ ### Secrets Use `${ENV_VAR}` references in `env` values from user-level or explicitly selected -configuration. Automatically discovered project values stay literal; pass +configuration. Automatically discovered project files are ignored; pass `--config ./.skill-up.yaml` only after reviewing and trusting that file. See [user-config semantics](docs/guide/user-config.md#schema) for precedence and -remaining trust limitations. +the endpoint trust policy. The redaction mechanism (`userconfig.Redact`) masks fields tagged `secret:"true"` when printing; currently no Config field carries the tag. diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 79867c43..ce205921 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -410,7 +410,8 @@ skill-up init [flags] > For `init`, `--config` names the source to copy without expanding placeholders. > For other subcommands it selects the highest-precedence config and permits -> `${VAR}` expansion in that file's `env` values. Use it only with trusted files; +> all its defaults and `${VAR}` expansion in its `env` values. Automatically +> discovered `.skill-up.yaml` files are ignored. Use `--config` only with trusted files; > see [user configuration](./user-config.md#schema) for the trust boundary. ### Examples diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index 887c97f8..cf6d1601 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -17,7 +17,6 @@ Layers are merged in order of increasing precedence: ```text embed (empty) < user (~/.config/skill-up/config.yaml, XDG-aware) - < project ($PWD/.skill-up.yaml) < explicit (--config ) ``` @@ -25,12 +24,16 @@ embed (empty) | :--------- | :------------------------------------------------------------------------------------------------------ | :------ | | `embed` | empty `Config{}` — no vendor defaults baked in | always | | `user` | `$SKILL_UP_CONFIG`, else `$XDG_CONFIG_HOME/skill-up/config.yaml`, else `~/.config/skill-up/config.yaml` | skipped | -| `project` | `$PWD/.skill-up.yaml` | skipped | | `explicit` | `--config ` passed to any command | error | -A missing or corrupt `user`/`project` file is downgraded to a `warning:` on -stderr — the command keeps running with whatever layers loaded. A missing or -invalid `--config` path is a hard error. +A missing `user` file is silently skipped; read or parse errors produce a +`warning:` on stderr. A missing or invalid `--config` path is a hard error. + +An automatically discovered `$PWD/.skill-up.yaml` is ignored with a warning. +After reviewing the file, select it with `--config ./.skill-up.yaml` to apply +its defaults. This opt-in covers the whole file, including `runtime_kwargs`. +Selecting a different explicit file does not trust the project file. A project +file selected through `SKILL_UP_CONFIG` is also trusted as the user layer. Higher-precedence layers overlay non-zero fields onto lower layers; map fields (`telemetry.resource_attributes`, `env`, `runtime_kwargs`) are merged key-wise @@ -70,14 +73,8 @@ Semantics: always wins. - **`${VAR}` placeholders** in `env` values from the `user` and `explicit` layers are expanded from the process environment before defaults are applied. - Automatically discovered project values stay literal. To opt in for a trusted - project file, pass `--config ./.skill-up.yaml`. This grants that file access to - host environment variables, including secrets, so review it before opting in. - Permission follows each winning value: a project override of a user value - stays literal, and selecting a different explicit file does not enable - expansion for project entries it leaves unchanged. If `SKILL_UP_CONFIG` points - to the same automatically discovered project file, the project layer still - wins and stays literal; use `--config` to opt in. Unset variables remain literal; + Selecting a file grants it access to host environment variables, including + secrets, so review it before opting in. Unset variables remain literal; variables set to an empty string expand to an empty string. Expansion is single-pass and does not read other defaults from the same config. Bare `$VAR` and shell expressions such as `${VAR:-fallback}` remain literal. @@ -85,10 +82,22 @@ Semantics: `opensandbox`). `eval.yaml` values take precedence; missing keys fall back here. Keys mirror the environment provider's kwargs schema. -Expansion permission does not bind credentials to a destination. Expanding a -token in user-level telemetry headers makes it available to the exporter, and -a project's literal endpoint override can receive that token. Inspect project -settings before using credentials from your environment or user config. +### Endpoint trust policy + +Only trusted user or explicitly selected config files may provide defaults. +An unselected project file cannot override a telemetry endpoint, inject a proxy +or agent base URL through `env`, or redirect an OpenSandbox runtime through +`runtime_kwargs`. This prevents it from redirecting credentials supplied by +trusted config or the process environment, even when its values are literal. + +This is a breaking change for projects that relied on automatic `.skill-up.yaml` +loading. Review the file and add `--config ./.skill-up.yaml` to each invocation, +or move trusted defaults to the user-level config. Inspect destinations as well +as credential references before opting in: an explicit file can combine its +endpoint with credentials from user config or the shell. + +This boundary covers user-config discovery. It does not sandbox `eval.yaml`, +scripts or agent execution; review an evaluation before running it with credentials. --- @@ -213,8 +222,14 @@ runtime_kwargs: base_url: http://sandbox.internal:9090 ``` -This adds an `opensandbox.base_url` default for this project only — your -`~/.config/skill-up/config.yaml` still applies elsewhere. +After reviewing it, select the file for this run: + +```bash +skill-up run ./evals/eval.yaml --config ./.skill-up.yaml +``` + +This adds an `opensandbox.base_url` default for this invocation. Without +`--config`, the project file is ignored and user-level defaults still apply. ### One-off override on the command line @@ -222,4 +237,4 @@ This adds an `opensandbox.base_url` default for this project only — your skill-up run ./evals/eval.yaml --config /tmp/debug-config.yaml ``` -`--config` overrides both user and project layers for this invocation. +`--config` overrides user-level defaults for this invocation. diff --git a/docs/zh/guide/cli-reference.md b/docs/zh/guide/cli-reference.md index a2f560d4..966a154a 100644 --- a/docs/zh/guide/cli-reference.md +++ b/docs/zh/guide/cli-reference.md @@ -243,7 +243,8 @@ skill-up init [flags] | `--force` | `false` | 覆盖已存在的目标文件 | > 对 `init`,`--config` 指定要复制的源文件,不展开占位符。对其他子命令,它选择 -> 优先级最高的配置,并允许展开该文件 `env` 值中的 `${VAR}`。仅应指定可信文件; +> 优先级最高的配置,启用全部默认值,并允许展开该文件 `env` 值中的 `${VAR}`。 +> 自动发现的 `.skill-up.yaml` 会被忽略。仅应使用 `--config` 选择可信文件; > 信任边界见[用户配置](./user-config.md#schema)。 ### 示例 diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index 2a985ee2..eaa68bb8 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -15,7 +15,6 @@ OpenTelemetry 默认值、共享的环境变量、以及不想在命令行或每 ```text embed (空) < user (~/.config/skill-up/config.yaml,遵循 XDG) - < project ($PWD/.skill-up.yaml) < explicit (--config ) ``` @@ -23,11 +22,15 @@ embed (空) | :--------- | :---------------------------------------------------------------------------------------------- | :------- | | `embed` | 空的 `Config{}`,不内嵌任何厂商默认值 | 永远存在 | | `user` | `$SKILL_UP_CONFIG` → `$XDG_CONFIG_HOME/skill-up/config.yaml` → `~/.config/skill-up/config.yaml` | 跳过 | -| `project` | `$PWD/.skill-up.yaml` | 跳过 | | `explicit` | 任意子命令的 `--config ` | 报错 | -`user` / `project` 层文件不存在或解析失败会降级为 stderr 上的 `warning:`,命令 -继续执行。`--config` 显式路径如果缺失或不合法则直接报错。 +`user` 文件不存在时静默跳过,读取或解析失败时在 stderr 上输出 `warning:`。 +`--config` 显式路径如果缺失或不合法则直接报错。 + +自动发现的 `$PWD/.skill-up.yaml` 会被忽略并输出警告。审阅文件后,使用 +`--config ./.skill-up.yaml` 显式加载。这项授权覆盖整个文件,包括 `runtime_kwargs`。 +指定其他显式文件不会授权项目文件。通过 `SKILL_UP_CONFIG` 选择的项目文件也会作为 +可信的用户层加载。 高优先级层只**覆盖非零字段**;map 类字段(`telemetry.resource_attributes`、 `env`、`runtime_kwargs`)按 key 逐项合并,而不是整体替换。 @@ -63,20 +66,27 @@ runtime_kwargs: # 按 environment.type 提 - **`telemetry` 与 `env`**:每个 key 对应一个 `OTEL_*` 或自定义环境变量,**仅在 对应环境变量未被设置时才会注入**——命令行或 shell 中已有的值优先。 - **`env` 中的 `${VAR}`** 仅在值来自 `user` 或 `explicit` 层时,才在应用默认值之前 - 从当前进程环境展开。自动发现的项目配置保留原文。要允许可信的项目文件展开变量, - 请传入 `--config ./.skill-up.yaml`。这会授权该文件读取宿主进程的环境变量(包括密钥), - 因此应先审阅文件。权限跟随最终生效的值:项目层覆盖用户层的值仍保留原文; - 指定另一份显式配置不会授权其中未覆盖的项目条目。如果 `SKILL_UP_CONFIG` 指向同一份 - 自动发现的项目文件,项目层仍优先且保留原文;请用 `--config` 显式授权。未设置的变量保留原文, + 从当前进程环境展开。选择文件会授权其读取宿主环境变量(包括密钥),因此应先审阅。 + 未设置的变量保留原文, 已设置为空字符串的变量展开为空字符串。只展开一次,不读取同一配置中的其他默认值。 `$VAR` 和 `${VAR:-fallback}` 等 shell 表达式保留原文。 - **`runtime_kwargs`**:`run` 命令按 `environment.type`(如 `opensandbox`)查找 默认值。`eval.yaml` 中显式给的值优先;未提供的字段在这里兜底。Key 的形态与 对应 environment provider 的 kwargs 一致。 -展开权限不会将凭据绑定到特定目标。用户级遥测请求头中的令牌展开后会提供给导出器, -而项目配置中的字面量端点覆盖可能接收到该令牌。因此在使用环境变量或用户配置中的 -凭据前,应先检查项目配置。 +### 端点信任策略 + +只有可信的用户配置或显式选择的配置文件才能提供默认值。未选择的项目文件不能覆盖 +遥测端点、通过 `env` 注入代理或 agent 基础 URL,也不能通过 `runtime_kwargs` +重定向 OpenSandbox。即使项目值是字面量,也无法通过这些默认值将可信配置或进程 +环境中的凭据发送到项目指定的目标。 + +这是对自动加载 `.skill-up.yaml` 行为的不兼容变更。审阅文件后,为每次调用添加 +`--config ./.skill-up.yaml`,或将可信默认值移到用户配置中。授权前应同时检查目标 +地址和凭据引用:显式配置的端点可以与用户配置或 shell 中的凭据组合使用。 + +此边界仅针对用户配置发现,不会对 `eval.yaml`、脚本或 agent 执行提供沙箱保护。 +携带凭据运行评测前仍需审阅评测内容。 --- @@ -196,7 +206,14 @@ runtime_kwargs: base_url: http://sandbox.internal:9090 ``` -这样只对当前项目生效,`~/.config/skill-up/config.yaml` 在其他地方依然有效。 +审阅后,为本次运行显式选择文件: + +```bash +skill-up run ./evals/eval.yaml --config ./.skill-up.yaml +``` + +这会为本次调用提供 `opensandbox.base_url` 默认值。未传 `--config` 时,项目文件会被 +忽略,用户级默认值仍生效。 ### 命令行一次性覆盖 @@ -204,4 +221,4 @@ runtime_kwargs: skill-up run ./evals/eval.yaml --config /tmp/debug-config.yaml ``` -`--config` 在本次执行中覆盖 user 和 project 两层。 +`--config` 在本次执行中覆盖用户级默认值。 diff --git a/internal/cli/init.go b/internal/cli/init.go index c60fde90..f3935055 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -124,7 +124,8 @@ func resolveUserConfigTarget() (string, error) { // default behavior is a no-op. const initTemplateContent = `# skill-up user config -- auto-loaded by every command. # Discovery order (lowest to highest precedence): -# embedded defaults < ~/.config/skill-up/config.yaml < $PWD/.skill-up.yaml < --config +# embedded defaults < ~/.config/skill-up/config.yaml < --config +# Project files apply only when explicitly selected with --config or SKILL_UP_CONFIG. # Use ` + "`skill-up init --print`" + ` to regenerate this template. schema_version: v1alpha1 @@ -158,7 +159,7 @@ telemetry: # Arbitrary additional env vars. Same only-if-unset semantics as telemetry. # ${VAR} expands only in user-level or explicitly selected (--config) files. -# Project files stay literal unless trusted with --config ./.skill-up.yaml. +# Project files require --config ./.skill-up.yaml to apply any defaults. # env: # OTEL_EXPORTER_OTLP_HEADERS: authorization=${OTLP_TOKEN} diff --git a/internal/cli/root.go b/internal/cli/root.go index 887185d0..a13670f1 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -58,16 +58,8 @@ func ExecuteArgs(version string, args []string) error { return rootCmd.Execute() } -// loadUserConfig extracts --config from raw args and delegates to -// userconfig.LoadEffective. Only an explicit --config that is -// missing or corrupt is treated as fatal; auto-discovered user and -// project layers downgrade parse errors to stderr warnings inside -// LoadEffective and continue with a partial config. -// -// For the `init` subcommand --config names a WRITE target, not a load -// path, so we clear the explicit path before delegating. Discovery of -// existing user/project layers still runs but cannot block init -// because of the warning downgrade above. +// loadUserConfig loads trusted defaults before command execution. +// For init, --config is a copy source and must not grant environment access. func loadUserConfig(args []string) (userconfig.Config, []userconfig.Source, error) { explicit := extractConfigFlag(args) if isInitInvocation(args) { @@ -169,7 +161,7 @@ func init() { return err }) - rootCmd.PersistentFlags().String(configFlagName, "", "Path to trusted skill-up user config (overrides defaults; allows ${VAR} expansion)") + rootCmd.PersistentFlags().String(configFlagName, "", "Path to trusted skill-up config (enables all defaults and ${VAR} expansion; project files require opt-in)") rootCmd.AddCommand(runCmd) rootCmd.AddCommand(validateCmd) diff --git a/internal/cli/root_test.go b/internal/cli/root_test.go index 13f0bed8..b5a65b3f 100644 --- a/internal/cli/root_test.go +++ b/internal/cli/root_test.go @@ -2,12 +2,17 @@ package cli import ( "bytes" + "fmt" + "net/http" + "net/http/httptest" "os" "path/filepath" "strings" + "sync/atomic" "testing" "github.com/spf13/cobra" + "go.opentelemetry.io/otel" ) func TestUsageOnError_PrintsUsageForParseErrors(t *testing.T) { @@ -49,6 +54,85 @@ func TestExecuteArgsVersionInitializesRoot(t *testing.T) { } } +func TestExecuteArgsProjectCannotRedirectTrustedTelemetry(t *testing.T) { + provider, propagator := otel.GetTracerProvider(), otel.GetTextMapPropagator() + t.Cleanup(func() { + otel.SetTracerProvider(provider) + otel.SetTextMapPropagator(propagator) + }) + var trustedRequests, projectRequests, projectCredentials atomic.Int32 + trusted := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "synthetic-token" { + t.Errorf("trusted collector received incorrect authorization header") + } + trustedRequests.Add(1) + w.Header().Set("Content-Type", "application/x-protobuf") + })) + t.Cleanup(trusted.Close) + project := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + projectRequests.Add(1) + if r.Header.Get("Authorization") == "synthetic-token" { + projectCredentials.Add(1) + } + w.Header().Set("Content-Type", "application/x-protobuf") + })) + t.Cleanup(project.Close) + for _, tc := range []struct { + name, projectConfig string + }{ + {"generic endpoint", "env:\n OTEL_EXPORTER_OTLP_ENDPOINT: %s\n"}, + {"signal endpoint", "env:\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: %s\n"}, + {"telemetry endpoint", "telemetry:\n traces:\n endpoint: %s\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + keys := []string{"OTEL_TRACES_EXPORTER", "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "OTEL_EXPORTER_OTLP_PROTOCOL", "OTEL_EXPORTER_OTLP_HEADERS"} + for _, entry := range os.Environ() { + key, _, _ := strings.Cut(entry, "=") + if strings.HasPrefix(strings.ToUpper(key), "OTEL_") { + keys = append(keys, key) + } + } + for _, key := range keys { + t.Setenv(key, "") + _ = os.Unsetenv(key) + } + t.Setenv("OTEL_METRICS_EXPORTER", "none") + t.Setenv("SKILL_UP_TEST_SECRET", "synthetic-token") + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + wd := t.TempDir() + t.Chdir(wd) + userPath := filepath.Join(t.TempDir(), "user.yaml") + t.Setenv("SKILL_UP_CONFIG", userPath) + user := fmt.Sprintf(`env: + OTEL_TRACES_EXPORTER: otlp + OTEL_EXPORTER_OTLP_ENDPOINT: %s + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_HEADERS: authorization=${SKILL_UP_TEST_SECRET} +`, trusted.URL) + if err := os.WriteFile(userPath, []byte(user), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(wd, ".skill-up.yaml"), fmt.Appendf(nil, tc.projectConfig, project.URL), 0o600); err != nil { + t.Fatal(err) + } + trustedRequests.Store(0) + projectRequests.Store(0) + projectCredentials.Store(0) + if _, err := captureStdout(t, func() error { + return ExecuteArgs("test-version", []string{"--version"}) + }); err != nil { + t.Fatal(err) + } + if got := projectRequests.Load(); got != 0 { + t.Errorf("untrusted project collector received %d requests, %d with trusted credentials", got, projectCredentials.Load()) + } + if got := trustedRequests.Load(); got == 0 { + t.Error("trusted collector received no requests") + } + }) + } +} + func TestExecuteArgsProjectEnvTrust(t *testing.T) { configFlag := rootCmd.PersistentFlags().Lookup(configFlagName) configValue, configChanged := configFlag.Value.String(), configFlag.Changed @@ -85,10 +169,10 @@ func TestExecuteArgsProjectEnvTrust(t *testing.T) { want string wantOutput string }{ - {"automatic", []string{"--version"}, "leaked=${SKILL_UP_TEST_SECRET}", "test-version"}, + {"automatic", []string{"--version"}, "", "test-version"}, {"explicit", []string{"--version", "--config", project}, "leaked=test-token", "test-version"}, {"explicit equals", []string{"--version", "--config=" + project}, "leaked=test-token", "test-version"}, - {"init source", []string{"init", "--config", project, "--print"}, "leaked=${SKILL_UP_TEST_SECRET}", "leaked=${SKILL_UP_TEST_SECRET}"}, + {"init source", []string{"init", "--config", project, "--print"}, "", "leaked=${SKILL_UP_TEST_SECRET}"}, } { t.Run(tc.name, func(t *testing.T) { for _, key := range []string{"OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_PROTOCOL", "OTEL_RESOURCE_ATTRIBUTES"} { diff --git a/internal/userconfig/config.go b/internal/userconfig/config.go index f3f39cbf..879cbd66 100644 --- a/internal/userconfig/config.go +++ b/internal/userconfig/config.go @@ -24,7 +24,7 @@ type Config struct { Telemetry Telemetry `yaml:"telemetry,omitempty"` Env map[string]string `yaml:"env,omitempty"` RuntimeKwargs map[string]Kwargs `yaml:"runtime_kwargs,omitempty"` - // Preserve provenance so project overrides cannot inherit user-layer trust. + // Only values loaded through trusted discovery layers may expand ${VAR}. envSources map[string]string } diff --git a/internal/userconfig/loader.go b/internal/userconfig/loader.go index 5d011e9d..844710f5 100644 --- a/internal/userconfig/loader.go +++ b/internal/userconfig/loader.go @@ -3,11 +3,11 @@ // 1. embed — the empty Config{} (no vendor defaults baked in). // 2. user — $SKILL_UP_CONFIG, else $XDG_CONFIG_HOME/skill-up/config.yaml, // else ~/.config/skill-up/config.yaml. Missing = silent skip. -// 3. project — $WorkingDir/.skill-up.yaml. Missing = silent skip. -// 4. explicit — opts.ExplicitPath. Missing = ERROR. +// 3. explicit — opts.ExplicitPath. Missing = ERROR. // // Higher-precedence layers overlay non-zero fields onto lower layers; map // fields are merged key-wise rather than replaced. +// Project files require selection through --config or the user-layer path. package userconfig @@ -36,7 +36,6 @@ const UserConfigFile = "config.yaml" const ( sourceEmbed = "embed" sourceUser = "user" - sourceProject = "project" sourceExplicit = "explicit" ) @@ -46,8 +45,8 @@ type LoadOptions struct { WorkingDir string HomeDir string Env func(string) string - // Warnings receives one line per non-fatal issue (e.g. a corrupt user or - // project layer file). Defaults to os.Stderr when nil. + // Warnings receives non-fatal issues, including ignored project files. + // Defaults to os.Stderr when nil. Warnings io.Writer } @@ -74,12 +73,8 @@ func LoadEffective(opts LoadOptions) (Config, []Source, error) { cfg := Config{} sources := []Source{{Kind: sourceEmbed}} - // Auto-discovered layers (user, project) downgrade parse/validate errors to - // warnings so a corrupt ~/.config/skill-up/config.yaml does not block - // unrelated commands (run/validate/init/...). Only --config, which the user - // explicitly opted into, treats errors as fatal. + // Optional user-file read/parse errors must not block unrelated commands. sources = mergeOptionalLayer(&cfg, sources, sourceUser, resolveUserConfigPath(opts, getenv), warn) - sources = mergeOptionalLayer(&cfg, sources, sourceProject, resolveProjectConfigPath(opts), warn) if opts.ExplicitPath != "" { loaded, ok, err := loadConfigFile(opts.ExplicitPath) @@ -93,6 +88,7 @@ func LoadEffective(opts LoadOptions) (Config, []Source, error) { sources = append(sources, Source{Kind: sourceExplicit, Path: opts.ExplicitPath}) } + warnUntrustedProjectConfig(resolveProjectConfigPath(opts), sources, warn) if err := cfg.Validate(); err != nil { paths := make([]string, 0, len(sources)) for _, s := range sources { @@ -109,7 +105,7 @@ func LoadEffective(opts LoadOptions) (Config, []Source, error) { return cfg, sources, nil } -// mergeOptionalLayer loads a single auto-discovered layer (user or project), +// mergeOptionalLayer loads an optional trusted layer, // downgrading parse errors to warnings on warn and appending to sources when // the file existed and parsed cleanly. func mergeOptionalLayer(cfg *Config, sources []Source, kind, path string, warn io.Writer) []Source { @@ -128,6 +124,23 @@ func mergeOptionalLayer(cfg *Config, sources []Source, kind, path string, warn i return append(sources, Source{Kind: kind, Path: path}) } +func warnUntrustedProjectConfig(path string, sources []Source, warn io.Writer) { + project, err := os.Stat(path) + if errors.Is(err, os.ErrNotExist) || path == "" { + return + } + if err == nil { + for _, source := range sources { + trusted, statErr := os.Stat(source.Path) + if statErr == nil && os.SameFile(project, trusted) { + return + } + } + } + // Even literal endpoints or runtime kwargs can redirect trusted credentials. + _, _ = fmt.Fprintf(warn, "warning: ignoring project config %s; review it and select it with --config to trust its defaults\n", path) +} + func resolveUserConfigPath(opts LoadOptions, getenv func(string) string) string { if v := getenv(ConfigEnvVar); v != "" { return v diff --git a/internal/userconfig/loader_test.go b/internal/userconfig/loader_test.go index 83d9ebd8..fcfa362f 100644 --- a/internal/userconfig/loader_test.go +++ b/internal/userconfig/loader_test.go @@ -1,6 +1,8 @@ package userconfig import ( + "bytes" + "maps" "os" "path/filepath" "strings" @@ -55,18 +57,25 @@ func TestLoadEffective_UserLayer(t *testing.T) { } } -func TestLoadEffective_ProjectOverridesUser(t *testing.T) { +func TestLoadEffective_ProjectRequiresExplicitTrust(t *testing.T) { home := t.TempDir() wd := t.TempDir() - writeFile(t, filepath.Join(home, ".config", UserConfigDir, UserConfigFile), "telemetry:\n service_name: user\n") + writeFile(t, filepath.Join(home, ".config", UserConfigDir, UserConfigFile), "telemetry:\n service_name: trusted-service\n") writeFile(t, filepath.Join(wd, ProjectConfigFile), "telemetry:\n service_name: project\n") - cfg, _, err := LoadEffective(LoadOptions{HomeDir: home, WorkingDir: wd, Env: emptyEnv}) + var warnings bytes.Buffer + cfg, sources, err := LoadEffective(LoadOptions{HomeDir: home, WorkingDir: wd, Env: emptyEnv, Warnings: &warnings}) if err != nil { t.Fatal(err) } - if cfg.Telemetry.ServiceName != "project" { - t.Fatalf("project should win: %q", cfg.Telemetry.ServiceName) + if cfg.Telemetry.ServiceName != "trusted-service" { + t.Fatalf("untrusted project must not override user defaults: %q", cfg.Telemetry.ServiceName) + } + if len(sources) != 2 || sources[1].Kind != sourceUser { + t.Fatalf("ignored project must not contribute a source: %+v", sources) + } + if !strings.Contains(warnings.String(), "--config") { + t.Fatalf("warning must explain explicit opt-in: %q", warnings.String()) } } @@ -124,6 +133,102 @@ func TestLoadEffective_EnvVarPath(t *testing.T) { } } +func TestLoadEffective_ProjectCannotRedirectTrustedCredentials(t *testing.T) { + for _, source := range []string{"automatic", sourceExplicit} { + t.Run(source, func(t *testing.T) { + testProjectEndpointTrust(t, source) + }) + } +} + +func testProjectEndpointTrust(t *testing.T, source string) { + t.Helper() + explicit := source == sourceExplicit + const secret = "synthetic-token" + const trusted = "https://trusted.example.invalid" + const untrusted = "https://project.example.invalid" + projectEnv := map[string]string{ + "OTEL_EXPORTER_OTLP_ENDPOINT": untrusted, + "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT": untrusted, + "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT": untrusted, + "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": untrusted, + "HTTPS_PROXY": untrusted, + "http_proxy": untrusted, + "OPENAI_BASE_URL": untrusted, + "OPENSANDBOX_BASE_URL": untrusted, + "OTEL_TRACES_EXPORTER": "otlp", + } + t.Setenv("SKILL_UP_TEST_SECRET", secret) + for key := range projectEnv { + t.Setenv(key, "") + _ = os.Unsetenv(key) + } + t.Setenv("OTEL_EXPORTER_OTLP_HEADERS", "") + _ = os.Unsetenv("OTEL_EXPORTER_OTLP_HEADERS") + t.Setenv("OPENSANDBOX_API_KEY", "") + _ = os.Unsetenv("OPENSANDBOX_API_KEY") + home, wd := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(home, ".config", UserConfigDir, UserConfigFile), `telemetry: + traces: + endpoint: `+trusted+` +env: + OTEL_EXPORTER_OTLP_HEADERS: authorization=${SKILL_UP_TEST_SECRET} + OPENSANDBOX_API_KEY: ${SKILL_UP_TEST_SECRET} +runtime_kwargs: + opensandbox: + base_url: `+trusted+` +`) + var project strings.Builder + project.WriteString("telemetry:\n traces:\n endpoint: " + untrusted + "\nenv:\n") + for key, value := range projectEnv { + project.WriteString(" " + key + ": " + value + "\n") + } + project.WriteString("runtime_kwargs:\n opensandbox:\n base_url: " + untrusted + "\n request_timeout_seconds: 42\n") + path := filepath.Join(wd, ProjectConfigFile) + writeFile(t, path, project.String()) + var warnings bytes.Buffer + opts := LoadOptions{HomeDir: home, WorkingDir: wd, Env: emptyEnv, Warnings: &warnings} + if explicit { + opts.ExplicitPath = path + } + cfg, _, err := LoadEffective(opts) + if err != nil { + t.Fatal(err) + } + if _, err := ApplyEnv(cfg); err != nil { + t.Fatal(err) + } + if got := os.Getenv("OTEL_EXPORTER_OTLP_HEADERS"); got != "authorization="+secret { + t.Fatalf("trusted headers = %q", got) + } + for key, value := range projectEnv { + want := "" + if key == envOtelExporterOTLPTracesEndpt { + want = trusted + } + if explicit { + want = value + } + if got := os.Getenv(key); got != want { + t.Errorf("%s = %q, want %q", key, got, want) + } + } + if got := os.Getenv("OPENSANDBOX_API_KEY"); got != secret { + t.Fatalf("trusted sandbox key = %q", got) + } + wantKwargs := Kwargs{"base_url": trusted} + if explicit { + wantKwargs = Kwargs{"base_url": untrusted, "request_timeout_seconds": "42"} + } + kwargs := MergeKwargs(cfg, "opensandbox", nil) + if !maps.Equal(kwargs, wantKwargs) { + t.Errorf("runtime defaults = %v, want %v", kwargs, wantKwargs) + } + if got := warnings.Len() > 0; got == explicit { + t.Errorf("warning present = %t for %s config: %s", got, source, &warnings) + } +} + type envExpansionCase struct { name string user string @@ -137,7 +242,6 @@ type envExpansionCase struct { func TestLoadEffective_EnvExpansionTrust(t *testing.T) { const secret = "test-token" - const literal = "leaked=${SKILL_UP_TEST_SECRET}" const expanded = "leaked=" + secret const userOnly = "SKILL_UP_TEST_USER_ONLY" const explicitOnly = "SKILL_UP_TEST_EXPLICIT_ONLY" @@ -156,20 +260,20 @@ func TestLoadEffective_EnvExpansionTrust(t *testing.T) { t.Setenv("SKILL_UP_TEST_SECRET", secret) for _, tc := range []envExpansionCase{ { - name: "automatic project stays literal", project: project, - want: map[string]string{envOtelResourceAttributes: literal}, + name: "automatic project is ignored", project: project, + want: map[string]string{envOtelResourceAttributes: ""}, }, { name: "user defaults expand", user: user, want: map[string]string{envOtelResourceAttributes: expanded, userOnly: expanded}, }, { - name: "project override loses user trust", user: user, project: project, - want: map[string]string{envOtelResourceAttributes: literal, userOnly: expanded}, + name: "project cannot override trusted user defaults", user: user, project: project, + want: map[string]string{envOtelResourceAttributes: expanded, userOnly: expanded}, }, { name: "explicit config does not trust unrelated project keys", user: user, project: project, explicit: explicit, - want: map[string]string{envOtelResourceAttributes: literal, userOnly: expanded, explicitOnly: expanded}, + want: map[string]string{envOtelResourceAttributes: expanded, userOnly: expanded, explicitOnly: expanded}, }, { name: "explicitly selected project expands", project: project, explicitProject: true, @@ -184,8 +288,8 @@ func TestLoadEffective_EnvExpansionTrust(t *testing.T) { want: map[string]string{envOtelResourceAttributes: expanded, userOnly: expanded}, }, { - name: "user path also discovered as project stays literal", project: project, userEnvPath: true, userIsProject: true, - want: map[string]string{envOtelResourceAttributes: literal}, + name: "user selected project path is trusted", project: project, userEnvPath: true, userIsProject: true, + want: map[string]string{envOtelResourceAttributes: expanded}, }, } { t.Run(tc.name, func(t *testing.T) { @@ -305,7 +409,7 @@ func TestLoadEffective_ValidateErrorIncludesSources(t *testing.T) { tmp := t.TempDir() path := filepath.Join(tmp, ".skill-up.yaml") writeFile(t, path, "telemetry:\n traces:\n protocol: tcp\n") - _, _, err := LoadEffective(LoadOptions{HomeDir: tmp, WorkingDir: tmp, Env: emptyEnv}) + _, _, err := LoadEffective(LoadOptions{ExplicitPath: path, HomeDir: tmp, WorkingDir: tmp, Env: emptyEnv}) if err == nil { t.Fatal("expected validate error") } From ee2aba428d444020f3c79bf976d8693eb8b292cd Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Wed, 18 Nov 2026 09:02:54 +0530 Subject: [PATCH 06/16] test(config): separate trust fixtures from assertions --- internal/userconfig/loader_test.go | 47 +++++++++++++++++------------- 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/internal/userconfig/loader_test.go b/internal/userconfig/loader_test.go index fcfa362f..e3ce2a30 100644 --- a/internal/userconfig/loader_test.go +++ b/internal/userconfig/loader_test.go @@ -167,29 +167,11 @@ func testProjectEndpointTrust(t *testing.T, source string) { _ = os.Unsetenv("OTEL_EXPORTER_OTLP_HEADERS") t.Setenv("OPENSANDBOX_API_KEY", "") _ = os.Unsetenv("OPENSANDBOX_API_KEY") - home, wd := t.TempDir(), t.TempDir() - writeFile(t, filepath.Join(home, ".config", UserConfigDir, UserConfigFile), `telemetry: - traces: - endpoint: `+trusted+` -env: - OTEL_EXPORTER_OTLP_HEADERS: authorization=${SKILL_UP_TEST_SECRET} - OPENSANDBOX_API_KEY: ${SKILL_UP_TEST_SECRET} -runtime_kwargs: - opensandbox: - base_url: `+trusted+` -`) - var project strings.Builder - project.WriteString("telemetry:\n traces:\n endpoint: " + untrusted + "\nenv:\n") - for key, value := range projectEnv { - project.WriteString(" " + key + ": " + value + "\n") - } - project.WriteString("runtime_kwargs:\n opensandbox:\n base_url: " + untrusted + "\n request_timeout_seconds: 42\n") - path := filepath.Join(wd, ProjectConfigFile) - writeFile(t, path, project.String()) var warnings bytes.Buffer - opts := LoadOptions{HomeDir: home, WorkingDir: wd, Env: emptyEnv, Warnings: &warnings} + opts := writeEndpointTrustConfigs(t, trusted, untrusted, projectEnv) + opts.Warnings = &warnings if explicit { - opts.ExplicitPath = path + opts.ExplicitPath = filepath.Join(opts.WorkingDir, ProjectConfigFile) } cfg, _, err := LoadEffective(opts) if err != nil { @@ -229,6 +211,29 @@ runtime_kwargs: } } +func writeEndpointTrustConfigs(t *testing.T, trusted, untrusted string, projectEnv map[string]string) LoadOptions { + t.Helper() + home, wd := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(home, ".config", UserConfigDir, UserConfigFile), `telemetry: + traces: + endpoint: `+trusted+` +env: + OTEL_EXPORTER_OTLP_HEADERS: authorization=${SKILL_UP_TEST_SECRET} + OPENSANDBOX_API_KEY: ${SKILL_UP_TEST_SECRET} +runtime_kwargs: + opensandbox: + base_url: `+trusted+` +`) + var project strings.Builder + project.WriteString("telemetry:\n traces:\n endpoint: " + untrusted + "\nenv:\n") + for key, value := range projectEnv { + project.WriteString(" " + key + ": " + value + "\n") + } + project.WriteString("runtime_kwargs:\n opensandbox:\n base_url: " + untrusted + "\n request_timeout_seconds: 42\n") + writeFile(t, filepath.Join(wd, ProjectConfigFile), project.String()) + return LoadOptions{HomeDir: home, WorkingDir: wd, Env: emptyEnv} +} + type envExpansionCase struct { name string user string From a0272bf0ae896a071484853717881a67d5fb0ab5 Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Wed, 18 Nov 2026 09:11:07 +0530 Subject: [PATCH 07/16] fix(config): explain project trust migration at initialization --- CHANGELOG.md | 13 ++++++++----- docs/guide/cli-reference.md | 2 +- docs/guide/user-config.md | 11 +++++++++-- docs/zh/guide/cli-reference.md | 2 +- docs/zh/guide/user-config.md | 8 ++++++-- internal/cli/init.go | 13 +++++++++---- internal/cli/init_test.go | 6 +++++- internal/userconfig/config.go | 2 +- internal/userconfig/config_test.go | 12 ++++++------ skills/skill-upper/SKILL.md | 7 ++++++- skills/skill-upper/references/cli.md | 8 ++++++-- 11 files changed, 58 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a43f7bf..fa315dd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- **Breaking:** project `.skill-up.yaml` files now require explicit selection + with `--config` or `SKILL_UP_CONFIG`. Automatic discovery warns and ignores + the entire file, including runtime defaults, so project endpoints cannot + redirect trusted credentials. Review existing project configs before opting in. + ### Fixed - Use prompt-file delivery for resumed Claude Code and Qoder turns when the @@ -14,11 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 delivery metadata and failing before execution if the file cannot be uploaded. - Expand `${VAR}` references in user-config `env` defaults from the process environment only for user-level or explicitly selected (`--config`) values. - Preserve unset references and existing environment values. Project - `.skill-up.yaml` files now require explicit selection with `--config` or - `SKILL_UP_CONFIG`; automatic discovery warns and ignores the entire file, - including runtime defaults, so project endpoints cannot redirect trusted - credentials. Review existing project configs before opting in. + Preserve unset references and existing environment values. - Match environment variable names case-insensitively in the `none` runtime on native Windows. A host `Path` and a configured or probed `PATH` were both passed to the child, and which one it kept followed map order. Per-call diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index ce205921..6ccd18c7 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -403,7 +403,7 @@ skill-up init [flags] | Flag | Default | Description | | :--------: | :-------------------------------------------------: | :-------------------------------------------------------------------------------------------: | -| `--local` | `false` | Write target is `$PWD/.skill-up.yaml` instead of the XDG path | +| `--local` | `false` | Write `$PWD/.skill-up.yaml`; after review, select it on subsequent commands with `--config ./.skill-up.yaml` | | `--config` | — | **Source** file to read (validated, copied verbatim with comments). Without this, a commented template is written. | | `--print` | `false` | Print to stdout instead of writing to disk | | `--force` | `false` | Overwrite an existing target | diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index cf6d1601..0aa50765 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -34,6 +34,9 @@ After reviewing the file, select it with `--config ./.skill-up.yaml` to apply its defaults. This opt-in covers the whole file, including `runtime_kwargs`. Selecting a different explicit file does not trust the project file. A project file selected through `SKILL_UP_CONFIG` is also trusted as the user layer. +Use an absolute path when setting `SKILL_UP_CONFIG` persistently: a relative +path resolves from the working directory and can select a different file in +each repository. Higher-precedence layers overlay non-zero fields onto lower layers; map fields (`telemetry.resource_attributes`, `env`, `runtime_kwargs`) are merged key-wise @@ -96,8 +99,12 @@ or move trusted defaults to the user-level config. Inspect destinations as well as credential references before opting in: an explicit file can combine its endpoint with credentials from user config or the shell. -This boundary covers user-config discovery. It does not sandbox `eval.yaml`, -scripts or agent execution; review an evaluation before running it with credentials. +This boundary covers user-config discovery. `skill-up run` treats evaluation +configuration as executable input, whether supplied as a path or discovered +automatically. Its runtime and model endpoints can use credentials from user +config or the shell; its script judges can execute code. Review the evaluation +and its scripts before running it with credentials. This change does not add +endpoint restrictions or sandboxing to evaluation configuration. --- diff --git a/docs/zh/guide/cli-reference.md b/docs/zh/guide/cli-reference.md index 966a154a..58e9641f 100644 --- a/docs/zh/guide/cli-reference.md +++ b/docs/zh/guide/cli-reference.md @@ -237,7 +237,7 @@ skill-up init [flags] | Flag | 默认值 | 说明 | | :--------: | :----------: | :---------------------------------------------------------------------------------------------: | -| `--local` | `false` | 写到 `$PWD/.skill-up.yaml` 而不是 XDG 路径 | +| `--local` | `false` | 写到 `$PWD/.skill-up.yaml`;审阅后,在后续命令中用 `--config ./.skill-up.yaml` 显式加载 | | `--config` | — | **读取源**文件(先校验,再原样拷贝,注释保留)。未提供时写出带注释的模板 | | `--print` | `false` | 输出到 stdout,而不是写盘 | | `--force` | `false` | 覆盖已存在的目标文件 | diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index eaa68bb8..77193bf1 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -31,6 +31,8 @@ embed (空) `--config ./.skill-up.yaml` 显式加载。这项授权覆盖整个文件,包括 `runtime_kwargs`。 指定其他显式文件不会授权项目文件。通过 `SKILL_UP_CONFIG` 选择的项目文件也会作为 可信的用户层加载。 +长期设置 `SKILL_UP_CONFIG` 时应使用绝对路径:相对路径从当前工作目录解析, +在不同仓库中可能选择不同文件。 高优先级层只**覆盖非零字段**;map 类字段(`telemetry.resource_attributes`、 `env`、`runtime_kwargs`)按 key 逐项合并,而不是整体替换。 @@ -85,8 +87,10 @@ runtime_kwargs: # 按 environment.type 提 `--config ./.skill-up.yaml`,或将可信默认值移到用户配置中。授权前应同时检查目标 地址和凭据引用:显式配置的端点可以与用户配置或 shell 中的凭据组合使用。 -此边界仅针对用户配置发现,不会对 `eval.yaml`、脚本或 agent 执行提供沙箱保护。 -携带凭据运行评测前仍需审阅评测内容。 +此边界仅针对用户配置发现。`skill-up run` 将评测配置视为可执行输入,无论路径是 +显式提供还是自动发现。其运行时和模型端点可使用用户配置或 shell 中的凭据, +脚本裁判也可执行代码。携带凭据运行前,应审阅评测及其脚本。本次变更不会为 +评测配置增加端点限制或沙箱保护。 --- diff --git a/internal/cli/init.go b/internal/cli/init.go index f3935055..4be25583 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -27,12 +27,15 @@ contents to the target, preserving comments and formatting. Target selection: default $XDG_CONFIG_HOME/skill-up/config.yaml (or ~/.config/...) --local $PWD/.skill-up.yaml - --print stdout (no file written)`, + --print stdout (no file written) + +Project files are not loaded automatically. After reviewing a local file, +select it on subsequent commands with --config ./.skill-up.yaml.`, RunE: runInit, } func init() { - initCmd.Flags().Bool("local", false, "Write target is $PWD/.skill-up.yaml instead of the XDG path") + initCmd.Flags().Bool("local", false, "Write $PWD/.skill-up.yaml (requires --config to apply on subsequent commands)") initCmd.Flags().Bool("print", false, "Print to stdout instead of writing to disk") initCmd.Flags().Bool("force", false, "Overwrite an existing file") rootCmd.AddCommand(initCmd) @@ -74,6 +77,9 @@ func runInit(cmd *cobra.Command, _ []string) error { return err } _, _ = fmt.Fprintf(cmd.OutOrStdout(), "wrote %s\n", target) + if local { + _, _ = fmt.Fprintln(cmd.OutOrStdout(), "After reviewing this file, select it on subsequent commands with --config ./.skill-up.yaml") + } return nil } @@ -95,8 +101,7 @@ func resolveInitContent(sourcePath string) (string, error) { return string(data), nil } -// resolveProjectConfigTarget returns $PWD/.skill-up.yaml — the per-project -// config layer. +// resolveProjectConfigTarget returns $PWD/.skill-up.yaml. func resolveProjectConfigTarget() (string, error) { wd, err := os.Getwd() if err != nil { diff --git a/internal/cli/init_test.go b/internal/cli/init_test.go index b30c7048..5bfb25f7 100644 --- a/internal/cli/init_test.go +++ b/internal/cli/init_test.go @@ -56,11 +56,15 @@ func TestInit_LocalWritesTemplate(t *testing.T) { t.Chdir(tmp) cmd := newInitCmdForTest() - cmd.SetOut(&bytes.Buffer{}) + var out bytes.Buffer + cmd.SetOut(&out) cmd.SetArgs([]string{"--local"}) if err := cmd.Execute(); err != nil { t.Fatalf("init --local: %v", err) } + if !strings.Contains(out.String(), "--config ./.skill-up.yaml") { + t.Fatalf("missing local config opt-in hint: %q", out.String()) + } target := filepath.Join(tmp, ".skill-up.yaml") got, err := os.ReadFile(target) if err != nil { diff --git a/internal/userconfig/config.go b/internal/userconfig/config.go index 879cbd66..6c53ddc5 100644 --- a/internal/userconfig/config.go +++ b/internal/userconfig/config.go @@ -24,7 +24,7 @@ type Config struct { Telemetry Telemetry `yaml:"telemetry,omitempty"` Env map[string]string `yaml:"env,omitempty"` RuntimeKwargs map[string]Kwargs `yaml:"runtime_kwargs,omitempty"` - // Only values loaded through trusted discovery layers may expand ${VAR}. + // LoadFile and directly constructed configs must not gain expansion permission. envSources map[string]string } diff --git a/internal/userconfig/config_test.go b/internal/userconfig/config_test.go index a46c2423..eb3ac705 100644 --- a/internal/userconfig/config_test.go +++ b/internal/userconfig/config_test.go @@ -4,7 +4,7 @@ import "testing" func TestOverlay_ScalarOverwrite(t *testing.T) { c := Config{SchemaVersion: "v1alpha1", Telemetry: Telemetry{ServiceName: "a"}} - c.overlay(Config{Telemetry: Telemetry{ServiceName: "b"}}, "project") + c.overlay(Config{Telemetry: Telemetry{ServiceName: "b"}}, sourceExplicit) if c.Telemetry.ServiceName != "b" { t.Fatalf("expected b, got %q", c.Telemetry.ServiceName) } @@ -15,7 +15,7 @@ func TestOverlay_ScalarOverwrite(t *testing.T) { func TestOverlay_ZeroValueSkip(t *testing.T) { c := Config{Telemetry: Telemetry{ServiceName: "a", TracesExporter: "otlp"}} - c.overlay(Config{Telemetry: Telemetry{ServiceName: ""}}, "project") + c.overlay(Config{Telemetry: Telemetry{ServiceName: ""}}, sourceExplicit) if c.Telemetry.ServiceName != "a" { t.Fatalf("zero value should not overwrite, got %q", c.Telemetry.ServiceName) } @@ -26,7 +26,7 @@ func TestOverlay_ZeroValueSkip(t *testing.T) { func TestOverlay_MapMerge(t *testing.T) { c := Config{Env: map[string]string{"A": "1", "B": "2"}} - c.overlay(Config{Env: map[string]string{"B": "two", "C": "3"}}, "project") + c.overlay(Config{Env: map[string]string{"B": "two", "C": "3"}}, sourceExplicit) if c.Env["A"] != "1" || c.Env["B"] != "two" || c.Env["C"] != "3" { t.Fatalf("merged map wrong: %+v", c.Env) } @@ -34,7 +34,7 @@ func TestOverlay_MapMerge(t *testing.T) { func TestOverlay_RuntimeKwargsMerge(t *testing.T) { c := Config{RuntimeKwargs: map[string]Kwargs{"opensandbox": {"base_url": "x"}}} - c.overlay(Config{RuntimeKwargs: map[string]Kwargs{"opensandbox": {"extensions": "y"}, "custom": {"image": "ubuntu"}}}, "project") + c.overlay(Config{RuntimeKwargs: map[string]Kwargs{"opensandbox": {"extensions": "y"}, "custom": {"image": "ubuntu"}}}, sourceExplicit) if c.RuntimeKwargs["opensandbox"]["base_url"] != "x" || c.RuntimeKwargs["opensandbox"]["extensions"] != "y" { t.Fatalf("kwarg merge wrong: %+v", c.RuntimeKwargs["opensandbox"]) } @@ -48,14 +48,14 @@ func TestOverlay_VerboseExplicitOverridesEitherWay(t *testing.T) { // Higher-precedence layer can explicitly disable verbose. c := Config{Telemetry: Telemetry{Verbose: &tru}} - c.overlay(Config{Telemetry: Telemetry{Verbose: &fls}}, "project") + c.overlay(Config{Telemetry: Telemetry{Verbose: &fls}}, sourceExplicit) if c.Telemetry.Verbose == nil || *c.Telemetry.Verbose { t.Fatalf("verbose=false in overlay should win, got %v", c.Telemetry.Verbose) } // A nil verbose in the overlay leaves the lower-precedence value untouched. c2 := Config{Telemetry: Telemetry{Verbose: &tru}} - c2.overlay(Config{Telemetry: Telemetry{Verbose: nil}}, "project") + c2.overlay(Config{Telemetry: Telemetry{Verbose: nil}}, sourceExplicit) if c2.Telemetry.Verbose == nil || !*c2.Telemetry.Verbose { t.Fatalf("nil verbose in overlay should not clear existing true, got %v", c2.Telemetry.Verbose) } diff --git a/skills/skill-upper/SKILL.md b/skills/skill-upper/SKILL.md index 85898ca3..7f4e64b8 100644 --- a/skills/skill-upper/SKILL.md +++ b/skills/skill-upper/SKILL.md @@ -186,7 +186,12 @@ skill-up init --print skill-up init --force ``` -Precedence (low → high): embedded empty defaults < user config < project `.skill-up.yaml` < `--config`. `SKILL_UP_CONFIG` can point at the user config file (env var name is historical). See the upstream README "User config". +Precedence (low → high): embedded empty defaults < user config < `--config`. +Project `.skill-up.yaml` files are ignored unless explicitly selected. After +reviewing a local file, pass `--config ./.skill-up.yaml` to apply its defaults. +`SKILL_UP_CONFIG` selects the trusted user config file; use an absolute path +for a persistent setting. Only trusted config `env` values expand `${VAR}`. +See the upstream README "User config". ### Step 1: Locate the target Skill diff --git a/skills/skill-upper/references/cli.md b/skills/skill-upper/references/cli.md index 82b3bb48..8a2b956d 100644 --- a/skills/skill-upper/references/cli.md +++ b/skills/skill-upper/references/cli.md @@ -110,13 +110,17 @@ skill-up init [flags] | Flag | Description | | --- | --- | -| `--local` | Write `$PWD/.skill-up.yaml`; mutually exclusive with `--config`. | +| `--local` | Write `$PWD/.skill-up.yaml`; after review, select it on subsequent commands with `--config ./.skill-up.yaml`. | | `--print` | Print the template to stdout without writing a file. | | `--force` | Overwrite an existing file. | -| `--config ` | Explicit output path; mutually exclusive with `--local`. | +| `--config ` | Source file to validate and copy verbatim. May be combined with `--local`; placeholders are not expanded while copying. | The default path is `$XDG_CONFIG_HOME/skill-up/config.yaml` or `~/.config/skill-up/config.yaml`. `SKILL_UP_CONFIG` can also point to the user configuration file. +Project files are not loaded automatically. For commands other than `init`, +`--config` trusts the selected file's defaults, including endpoints and `${VAR}` +expansion in `env`. Review the file before selecting it. + ## skill-up debug Debug internal components during development or troubleshooting: From 31603dbf4489ee46b323a6cf2340694f6b2f4298 Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Wed, 18 Nov 2026 09:14:01 +0530 Subject: [PATCH 08/16] docs(config): clarify project config opt-in lifecycle --- README.md | 3 +++ docs/guide/user-config.md | 4 ++++ docs/zh/guide/user-config.md | 3 +++ internal/userconfig/loader_test.go | 4 ++-- 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1caeb427..3f180b93 100644 --- a/README.md +++ b/README.md @@ -357,6 +357,9 @@ skill-up init --config foo.yaml # reads foo.yaml, writes it to ~/.confi skill-up init --config foo.yaml --local # reads foo.yaml, writes it to $PWD/.skill-up.yaml ``` +Files written with `--local` require explicit selection. Review the file, then +use `--config ./.skill-up.yaml` on commands that should apply its defaults. + With `--config `, `init` reads that file (validating it as a skill-up config) and writes its raw bytes to the target — comments and formatting are preserved. Without `--config`, `init` writes a commented YAML template. diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index 0aa50765..36a772e5 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -98,6 +98,10 @@ loading. Review the file and add `--config ./.skill-up.yaml` to each invocation, or move trusted defaults to the user-level config. Inspect destinations as well as credential references before opting in: an explicit file can combine its endpoint with credentials from user config or the shell. +Trust applies to the selected path, not a saved copy of its contents. Review +changes before reusing that path after a repository update. For stable local +defaults, copy a reviewed file to user config with +`skill-up init --config ./.skill-up.yaml` or keep it outside the repository. This boundary covers user-config discovery. `skill-up run` treats evaluation configuration as executable input, whether supplied as a path or discovered diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index 77193bf1..b222f0b7 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -86,6 +86,9 @@ runtime_kwargs: # 按 environment.type 提 这是对自动加载 `.skill-up.yaml` 行为的不兼容变更。审阅文件后,为每次调用添加 `--config ./.skill-up.yaml`,或将可信默认值移到用户配置中。授权前应同时检查目标 地址和凭据引用:显式配置的端点可以与用户配置或 shell 中的凭据组合使用。 +信任针对所选路径,而非已审阅内容的快照。仓库更新后,再次使用该路径前应审阅变更。 +如需稳定的本地默认值,可用 `skill-up init --config ./.skill-up.yaml` 将已审阅的文件 +复制到用户配置,或将其保存在仓库之外。 此边界仅针对用户配置发现。`skill-up run` 将评测配置视为可执行输入,无论路径是 显式提供还是自动发现。其运行时和模型端点可使用用户配置或 shell 中的凭据, diff --git a/internal/userconfig/loader_test.go b/internal/userconfig/loader_test.go index e3ce2a30..11f5f07d 100644 --- a/internal/userconfig/loader_test.go +++ b/internal/userconfig/loader_test.go @@ -392,7 +392,7 @@ func TestLoadEffective_CorruptUserLayerDowngradedToWarning(t *testing.T) { } } -func TestLoadEffective_CorruptProjectLayerDowngradedToWarning(t *testing.T) { +func TestLoadEffective_IgnoresProjectBeforeParsing(t *testing.T) { tmp := t.TempDir() writeFile(t, filepath.Join(tmp, ".skill-up.yaml"), "telemetry: : :\n") @@ -403,7 +403,7 @@ func TestLoadEffective_CorruptProjectLayerDowngradedToWarning(t *testing.T) { Env: emptyEnv, Warnings: &warnings, }); err != nil { - t.Fatalf("expected corrupt project layer to be a warning, got error: %v", err) + t.Fatalf("unselected project contents must not be parsed: %v", err) } if !strings.Contains(warnings.String(), "warning: ignoring project config") { t.Errorf("expected project-config warning, got %q", warnings.String()) From f43e3dfe536a6d730e6b4138ff0d83e24da7602c Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Mon, 23 Nov 2026 15:00:47 +0530 Subject: [PATCH 09/16] fix(userconfig): satisfy env defaults lint checks --- internal/userconfig/apply.go | 67 ++++++++++++++++++------------- internal/userconfig/apply_test.go | 6 ++- 2 files changed, 44 insertions(+), 29 deletions(-) diff --git a/internal/userconfig/apply.go b/internal/userconfig/apply.go index 45227e28..d396e3dc 100644 --- a/internal/userconfig/apply.go +++ b/internal/userconfig/apply.go @@ -29,23 +29,7 @@ const ( // Newly expanded OTLP headers are withheld if project defaults supply routing. func ApplyEnv(c Config) ([]string, error) { pending := telemetryEnv(c.Telemetry) - projectRoute := false - for key, source := range map[string]string{ - envOtelExporterOTLPTracesEndpt: c.tracesEndpointSource, - envOtelExporterOTLPTracesProto: c.tracesProtocolSource, - } { - if _, exists := os.LookupEnv(key); !exists && source == sourceProject && pending[key] != "" { - projectRoute = true - } - } - for key, value := range c.Env { - if _, exists := os.LookupEnv(key); exists || value == "" { - continue - } - if _, exists := pending[key]; !exists && c.envSources[key] == sourceProject && isOTLPRouteDefault(key) { - projectRoute = true - } - } + projectRoute := hasProjectOTLPRoute(c, pending) for key, value := range c.Env { if _, exists := os.LookupEnv(key); exists || value == "" { continue @@ -54,16 +38,8 @@ func ApplyEnv(c Config) ([]string, error) { continue } if source := c.envSources[key]; source == sourceUser || source == sourceExplicit { - // Resolve before setting any defaults, so config entries cannot - // become expansion sources based on map or key ordering. - expanded := false - value = envPlaceholderPattern.ReplaceAllStringFunc(value, func(ref string) string { - if replacement, exists := os.LookupEnv(ref[2 : len(ref)-1]); exists { - expanded = true - return replacement - } - return ref - }) + var expanded bool + value, expanded = expandEnvDefault(value) // Keep project routing and pre-existing headers intact, but do // not add credentials derived by this new expansion to it. if expanded && projectRoute && isOTLPHeaderDefault(key) { @@ -92,6 +68,43 @@ func ApplyEnv(c Config) ([]string, error) { return applied, nil } +// hasProjectOTLPRoute checks structured and arbitrary defaults before any +// environment writes. Existing process variables and structured fields retain +// their usual precedence over defaults for the same key. +func hasProjectOTLPRoute(c Config, pending map[string]string) bool { + for key, source := range map[string]string{ + envOtelExporterOTLPTracesEndpt: c.tracesEndpointSource, + envOtelExporterOTLPTracesProto: c.tracesProtocolSource, + } { + if _, exists := os.LookupEnv(key); !exists && source == sourceProject && pending[key] != "" { + return true + } + } + for key, value := range c.Env { + if _, exists := os.LookupEnv(key); exists || value == "" { + continue + } + if _, exists := pending[key]; !exists && c.envSources[key] == sourceProject && isOTLPRouteDefault(key) { + return true + } + } + return false +} + +// Resolve against the process environment before installing any defaults, so +// config entries cannot become expansion sources based on map or key ordering. +func expandEnvDefault(value string) (string, bool) { + expanded := false + result := envPlaceholderPattern.ReplaceAllStringFunc(value, func(ref string) string { + if replacement, exists := os.LookupEnv(ref[2 : len(ref)-1]); exists { + expanded = true + return replacement + } + return ref + }) + return result, expanded +} + // A generic OTLP header can reach more than one signal's exporter. Treat // unshadowed project routing keys conservatively rather than depending on // every exporter or child agent to resolve endpoint precedence identically. diff --git a/internal/userconfig/apply_test.go b/internal/userconfig/apply_test.go index d39a41d0..c16714fc 100644 --- a/internal/userconfig/apply_test.go +++ b/internal/userconfig/apply_test.go @@ -277,8 +277,10 @@ func TestApplyEnv_ExpandedOTLPHeaderRouting(t *testing.T) { {name: "structured config wins over env", project: Config{Env: map[string]string{envOtelExporterOTLPTracesEndpt: "https://project.invalid"}}, explicit: Config{Telemetry: Telemetry{Traces: TracesConfig{Endpoint: "https://trusted.invalid"}}}, header: generic, wantHeader: "authorization=fixture", wantSet: true}, } { t.Run(tt.name, func(t *testing.T) { - for _, key := range []string{generic, traces, metrics, logs, endpoint, metricDest, proxy, - envOtelExporterOTLPTracesEndpt, "SKILL_UP_TEST_OTHER"} { + for _, key := range []string{ + generic, traces, metrics, logs, endpoint, metricDest, proxy, + envOtelExporterOTLPTracesEndpt, "SKILL_UP_TEST_OTHER", + } { t.Setenv(key, "") if err := os.Unsetenv(key); err != nil { t.Fatal(err) From 8f60435a223037cb628524c01e3e393ebc0de30c Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Wed, 25 Nov 2026 23:35:11 +0530 Subject: [PATCH 10/16] fix(userconfig): guard expanded OTLP headers per signal and on TLS roots A project-only metrics endpoint no longer withholds a newly expanded traces header whose own route is trusted. A signal header now follows that signal's effective route: its own endpoint, protocol and TLS options, then the shared ones it does not override from a trusted source. The shared header stays conservative. Project SSL_CERT_FILE and SSL_CERT_DIR defaults now count as transport inputs for every signal, like proxy settings. Loopback collector tests run the real start-up path and check which collector receives the synthetic token. --- CHANGELOG.md | 7 +- docs/guide/user-config.md | 2 +- docs/zh/guide/user-config.md | 10 +- internal/cli/otlp_loopback_test.go | 225 +++++++++++++++++++++++++++++ internal/userconfig/apply.go | 133 ++++++++++++++--- internal/userconfig/apply_test.go | 22 ++- 6 files changed, 369 insertions(+), 30 deletions(-) create mode 100644 internal/cli/otlp_loopback_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index b3303f82..feb0143a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,9 +46,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Expand environment placeholders only in trusted user or explicit config - defaults. Keep automatic project defaults, but withhold newly expanded OTLP - headers when project defaults can control telemetry routing. Reject repeated - `--config` and ignore relative `XDG_CONFIG_HOME` in discovery and initialization. + defaults. Keep automatic project defaults, but withhold a newly expanded OTLP + header when project defaults can control the route, proxy or TLS roots of a + signal that would carry it. Reject repeated `--config` and ignore relative + `XDG_CONFIG_HOME` in discovery and initialization. - Keep `agent_judge` review materials from reading as instructions. The judge prompt now states that inline excerpts and referenced files come from the diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index c23c931d..6915f2dc 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -73,7 +73,7 @@ Semantics: ### Credential boundary -Automatically discovered project files still supply defaults. Newly expanded OTLP headers are withheld when effective project settings can control the destination or transport. This protection applies only to headers produced by expansion; it does not change the treatment of literal headers, headers already in the process environment, or evaluation execution. Review any config before selecting it with `--config`, which trusts the file for expansion. For `init`, `--config` is only a copy source and is not used to supply defaults. +Automatically discovered project files still supply defaults. A newly expanded OTLP header is withheld when project defaults can control where the exporter that carries it sends data, or which peer that exporter accepts. The check is per signal: `OTEL_EXPORTER_OTLP_TRACES_HEADERS` follows the traces route, meaning the traces endpoint, protocol and TLS options, then the shared `OTEL_EXPORTER_OTLP_*` options that no trusted traces setting overrides. A project that only sets a metrics endpoint therefore does not withhold it. The shared `OTEL_EXPORTER_OTLP_HEADERS` can reach every signal, so any project route setting withholds it. Project proxy settings and TLS root settings (`SSL_CERT_FILE`, `SSL_CERT_DIR`) count for every signal. This protection applies only to headers produced by expansion; it does not change the treatment of literal headers, headers already in the process environment, or evaluation execution. Review any config before selecting it with `--config`, which trusts the file for expansion. For `init`, `--config` is only a copy source and is not used to supply defaults. --- diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index 23ba306b..d00fede0 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -71,8 +71,14 @@ runtime_kwargs: # 按 environment.type 提 ### 凭据信任边界 -自动发现的项目配置仍然提供默认值。如果生效的项目设置可以控制遥测目标或传输, -通过变量展开生成的 OTLP 请求头不会被应用。这仅约束新展开的请求头,不改变字面量 +自动发现的项目配置仍然提供默认值。如果项目默认值可以控制某个导出器的发送目标或 +它所信任的对端,由该导出器携带的、通过变量展开生成的 OTLP 请求头不会被应用。检查按 +信号进行:`OTEL_EXPORTER_OTLP_TRACES_HEADERS` 只取决于 traces 的生效路由,即 traces +自身的端点、协议和 TLS 选项,以及未被可信的 traces 设置覆盖的通用 +`OTEL_EXPORTER_OTLP_*` 选项,因此只设置 metrics 端点的项目不会影响它。通用的 +`OTEL_EXPORTER_OTLP_HEADERS` 可能被每个信号使用,只要项目提供了任一路由设置就不会被 +应用。项目提供的代理设置和 TLS 根证书设置(`SSL_CERT_FILE`、`SSL_CERT_DIR`)对所有 +信号生效。这仅约束新展开的请求头,不改变字面量 请求头、进程环境中已有的请求头或评测执行的处理方式。通过 `--config` 选择文件会 信任其变量展开,请先审阅文件。对于 `init`,`--config` 仅指定拷贝来源,不提供默认值。 diff --git a/internal/cli/otlp_loopback_test.go b/internal/cli/otlp_loopback_test.go new file mode 100644 index 00000000..469fe12e --- /dev/null +++ b/internal/cli/otlp_loopback_test.go @@ -0,0 +1,225 @@ +package cli + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "go.opentelemetry.io/otel" + + "github.com/alibaba/skill-up/internal/observability" +) + +const ( + otlpLoopbackToken = "synthetic-token" + otlpLoopbackTokenEnv = "SKILL_UP_TEST_OTLP_TOKEN" + otlpTracesPath = "/v1/traces" + otlpMetricsPath = "/v1/metrics" +) + +// otlpCollector is a loopback OTLP/HTTP endpoint that records the path and +// Authorization header of every export it receives. +type otlpCollector struct { + *httptest.Server + + mu sync.Mutex + authorizations map[string][]string +} + +func newOTLPCollector(t *testing.T) *otlpCollector { + t.Helper() + c := &otlpCollector{authorizations: map[string][]string{}} + c.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.mu.Lock() + c.authorizations[r.URL.Path] = append(c.authorizations[r.URL.Path], r.Header.Get("Authorization")) + c.mu.Unlock() + w.Header().Set("Content-Type", "application/x-protobuf") + })) + t.Cleanup(c.Close) + return c +} + +func (c *otlpCollector) received() map[string][]string { + c.mu.Lock() + defer c.mu.Unlock() + out := make(map[string][]string, len(c.authorizations)) + for path, values := range c.authorizations { + out[path] = append([]string(nil), values...) + } + return out +} + +// TestExecuteArgsExpandedOTLPHeaderReachesOnlyTrustedRoutes runs the real +// start-up path (config discovery, env defaults, exporter initialization and +// shutdown flush) against two loopback collectors. The trusted collector is +// named by the user config; the other by an automatically discovered project +// config. +func TestExecuteArgsExpandedOTLPHeaderReachesOnlyTrustedRoutes(t *testing.T) { + previousTracer, previousMeter := otel.GetTracerProvider(), otel.GetMeterProvider() + t.Cleanup(func() { + otel.SetTracerProvider(previousTracer) + otel.SetMeterProvider(previousMeter) + }) + + const ( + toTrusted = "trusted" + toProject = "project" + ) + type export struct { + collector string + path string + authorization string + } + for _, tc := range []struct { + name string + user string + project string + // want lists every export path that must arrive, with the header + // value each request on that path must carry. Any other export + // fails the test. + want []export + }{ + { + name: "project traces endpoint gets no expanded header", + user: `env: + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_HEADERS: authorization=${SKILL_UP_TEST_OTLP_TOKEN} +`, + project: `telemetry: + traces: + endpoint: PROJECT/v1/traces +`, + want: []export{{toProject, otlpTracesPath, ""}}, + }, + { + name: "trusted endpoint keeps the header beside ordinary project defaults", + user: `env: + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_ENDPOINT: TRUSTED + OTEL_EXPORTER_OTLP_HEADERS: authorization=${SKILL_UP_TEST_OTLP_TOKEN} +`, + project: `env: + SKILL_UP_TEST_PROJECT_DEFAULT: project +`, + want: []export{{toTrusted, otlpTracesPath, otlpLoopbackToken}}, + }, + { + name: "project metrics endpoint with metrics off keeps the traces header", + user: `env: + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: TRUSTED/v1/traces + OTEL_EXPORTER_OTLP_TRACES_HEADERS: authorization=${SKILL_UP_TEST_OTLP_TOKEN} +`, + project: `env: + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: PROJECT/v1/metrics +`, + want: []export{{toTrusted, otlpTracesPath, otlpLoopbackToken}}, + }, + { + name: "mixed signals send the header to the trusted route only", + user: `env: + OTEL_METRICS_EXPORTER: otlp + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: TRUSTED/v1/traces + OTEL_EXPORTER_OTLP_TRACES_HEADERS: authorization=${SKILL_UP_TEST_OTLP_TOKEN} + OTEL_EXPORTER_OTLP_METRICS_HEADERS: authorization=${SKILL_UP_TEST_OTLP_TOKEN} +`, + project: `env: + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: PROJECT/v1/metrics +`, + want: []export{ + {toTrusted, otlpTracesPath, otlpLoopbackToken}, + {toProject, otlpMetricsPath, ""}, + }, + }, + { + name: "project TLS roots withhold the header on a trusted endpoint", + user: `env: + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: TRUSTED/v1/traces + OTEL_EXPORTER_OTLP_TRACES_HEADERS: authorization=${SKILL_UP_TEST_OTLP_TOKEN} +`, + project: `env: + SSL_CERT_FILE: project-roots.pem +`, + want: []export{{toTrusted, otlpTracesPath, ""}}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + collectors := map[string]*otlpCollector{ + toTrusted: newOTLPCollector(t), + toProject: newOTLPCollector(t), + } + placeholders := strings.NewReplacer( + "TRUSTED", collectors[toTrusted].URL, + "PROJECT", collectors[toProject].URL, + ) + + for _, key := range []string{ + "OTEL_TRACES_EXPORTER", "OTEL_METRICS_EXPORTER", + "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_PROTOCOL", "OTEL_EXPORTER_OTLP_HEADERS", + "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL", "OTEL_EXPORTER_OTLP_TRACES_HEADERS", + "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL", "OTEL_EXPORTER_OTLP_METRICS_HEADERS", + "SSL_CERT_FILE", "SSL_CERT_DIR", "SKILL_UP_TEST_PROJECT_DEFAULT", + } { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + t.Setenv(otlpLoopbackTokenEnv, otlpLoopbackToken) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + userPath := filepath.Join(t.TempDir(), "user.yaml") + t.Setenv("SKILL_UP_CONFIG", userPath) + t.Chdir(t.TempDir()) + if err := os.WriteFile(userPath, []byte(placeholders.Replace(tc.user)), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(".skill-up.yaml", []byte(placeholders.Replace(tc.project)), 0o600); err != nil { + t.Fatal(err) + } + + // ExecuteArgs flushes both exporters before it returns. + if _, err := captureStdout(t, func() error { + return ExecuteArgs("test-version", []string{"--version"}) + }); err != nil { + t.Fatal(err) + } + + expected := map[string]map[string]string{toTrusted: {}, toProject: {}} + for _, want := range tc.want { + expected[want.collector][want.path] = want.authorization + } + for name, collector := range collectors { + received := collector.received() + for path, wantAuthorization := range expected[name] { + if len(received[path]) == 0 { + t.Errorf("%s collector received no export on %s", name, path) + } + for _, got := range received[path] { + if got != wantAuthorization { + t.Errorf("%s collector %s Authorization = %q, want %q", name, path, got, wantAuthorization) + } + } + } + for path := range received { + if _, ok := expected[name][path]; !ok { + t.Errorf("%s collector received an unexpected export on %s", name, path) + } + } + } + }) + } + + // Leave the cached exporter settings disabled for the tests that follow. + t.Setenv("OTEL_TRACES_EXPORTER", "none") + t.Setenv("OTEL_METRICS_EXPORTER", "none") + if _, _, err := observability.Init(context.Background(), "test-version"); err != nil { + t.Fatal(err) + } +} diff --git a/internal/userconfig/apply.go b/internal/userconfig/apply.go index d396e3dc..14913f34 100644 --- a/internal/userconfig/apply.go +++ b/internal/userconfig/apply.go @@ -26,10 +26,11 @@ const ( // environment, only setting keys that are currently unset. It returns the list // of keys that were actually applied (sorted) for logging and debugging. // Only env values from the user or explicit discovery layer expand ${VAR}. -// Newly expanded OTLP headers are withheld if project defaults supply routing. +// A newly expanded OTLP header is withheld when project defaults supply +// routing or transport settings for an exporter that would carry it. func ApplyEnv(c Config) ([]string, error) { pending := telemetryEnv(c.Telemetry) - projectRoute := hasProjectOTLPRoute(c, pending) + routes := projectOTLPRouting(c, pending) for key, value := range c.Env { if _, exists := os.LookupEnv(key); exists || value == "" { continue @@ -42,7 +43,7 @@ func ApplyEnv(c Config) ([]string, error) { value, expanded = expandEnvDefault(value) // Keep project routing and pre-existing headers intact, but do // not add credentials derived by this new expansion to it. - if expanded && projectRoute && isOTLPHeaderDefault(key) { + if expanded && routes.withholds(c, pending, key) { continue } } @@ -68,29 +69,99 @@ func ApplyEnv(c Config) ([]string, error) { return applied, nil } -// hasProjectOTLPRoute checks structured and arbitrary defaults before any +// projectOTLPRoutes records the project defaults that will reach the process +// environment and decide where an OTLP exporter sends data or which peer it +// accepts. +type projectOTLPRoutes struct { + // transport is set by proxy and TLS root settings, which every exporter + // in this process and in child agents can pick up. + transport bool + // options maps a signal ("" for the settings shared by all signals) to + // the endpoint, protocol and TLS options the project supplies for it. + options map[string]map[string]bool +} + +// projectOTLPRouting checks structured and arbitrary defaults before any // environment writes. Existing process variables and structured fields retain // their usual precedence over defaults for the same key. -func hasProjectOTLPRoute(c Config, pending map[string]string) bool { +func projectOTLPRouting(c Config, pending map[string]string) projectOTLPRoutes { + routes := projectOTLPRoutes{options: map[string]map[string]bool{}} for key, source := range map[string]string{ envOtelExporterOTLPTracesEndpt: c.tracesEndpointSource, envOtelExporterOTLPTracesProto: c.tracesProtocolSource, } { if _, exists := os.LookupEnv(key); !exists && source == sourceProject && pending[key] != "" { - return true + routes.add(key) } } for key, value := range c.Env { if _, exists := os.LookupEnv(key); exists || value == "" { continue } - if _, exists := pending[key]; !exists && c.envSources[key] == sourceProject && isOTLPRouteDefault(key) { + if _, exists := pending[key]; !exists && c.envSources[key] == sourceProject { + routes.add(key) + } + } + return routes +} + +func (r *projectOTLPRoutes) add(key string) { + key = strings.ToUpper(key) + if isTransportDefault(key) { + r.transport = true + return + } + signal, option, ok := parseOTLPOption(key) + if !ok || option == otlpOptionHeaders { + return + } + if r.options[signal] == nil { + r.options[signal] = map[string]bool{} + } + r.options[signal][option] = true +} + +// withholds reports whether a newly expanded header default must not be +// applied. A signal's own header follows that signal's effective route: its +// own options, then the shared ones it does not override from a trusted +// source. The shared header can reach more than one signal's exporter, so any +// project route withholds it rather than depending on every exporter or child +// agent to resolve precedence identically. +func (r *projectOTLPRoutes) withholds(c Config, pending map[string]string, key string) bool { + signal, option, ok := parseOTLPOption(strings.ToUpper(key)) + if !ok || option != otlpOptionHeaders { + return false + } + if r.transport { + return true + } + if signal == "" { + return len(r.options) > 0 + } + if len(r.options[signal]) > 0 { + return true + } + for shared := range r.options[""] { + if !hasTrustedSignalOption(c, pending, signal, shared) { return true } } return false } +// hasTrustedSignalOption reports whether the signal's own option is set, so +// the shared project value does not apply to it. Project values for the +// signal's own option are recorded in projectOTLPRoutes and never reach here. +func hasTrustedSignalOption(c Config, pending map[string]string, signal, option string) bool { + key := otlpEnvPrefix + signal + "_" + option + // An exporter treats an empty variable as unset and falls back to the + // shared one. + if value, exists := os.LookupEnv(key); exists { + return value != "" + } + return pending[key] != "" || c.Env[key] != "" +} + // Resolve against the process environment before installing any defaults, so // config entries cannot become expansion sources based on map or key ordering. func expandEnvDefault(value string) (string, bool) { @@ -105,24 +176,42 @@ func expandEnvDefault(value string) (string, bool) { return result, expanded } -// A generic OTLP header can reach more than one signal's exporter. Treat -// unshadowed project routing keys conservatively rather than depending on -// every exporter or child agent to resolve endpoint precedence identically. -func isOTLPRouteDefault(key string) bool { - key = strings.ToUpper(key) - switch key { - case "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "GRPC_PROXY", "NO_GRPC_PROXY", "REQUEST_METHOD": - return true +const ( + otlpEnvPrefix = "OTEL_EXPORTER_OTLP_" + otlpOptionHeaders = "HEADERS" +) + +// otlpRouteOptions lists the option suffixes this guard reads. A longer +// suffix precedes the suffix it ends with. +var otlpRouteOptions = []string{ + "CLIENT_CERTIFICATE", "CERTIFICATE", "ENDPOINT", "PROTOCOL", "INSECURE", otlpOptionHeaders, +} + +// parseOTLPOption splits an upper-case OTEL_EXPORTER_OTLP_[_]