diff --git a/CHANGELOG.md b/CHANGELOG.md index ef780de8..647b5eca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,13 @@ 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 a newly expanded OTLP + header when project defaults can control the route, proxy or TLS roots of a + signal that would carry it. Withhold the header when an exporter can fall + back to a shared project option, including when loading TLS files. + Reject repeated `--config` and ignore relative `XDG_CONFIG_HOME` in + discovery and initialization. - `skill-up run --dry-run` now prints the planned case executions as cases times configurations times iterations. A benchmark over four cases with `--iteration 5` previously reported only `Would run 4 case(s)` for 40 diff --git a/README.md b/README.md index 9080db2c..f9840939 100644 --- a/README.md +++ b/README.md @@ -341,7 +341,7 @@ embed (empty) < user (~/.config/skill-up/config.yaml) < project ($PWD/.skill-up. | `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 files at the `user` and `project` layers are silently skipped; a missing `--config` path is a hard error. Specify `--config` at most once. Relative `XDG_CONFIG_HOME` values are ignored for discovery and the default `init` write target. ### Quickstart @@ -391,7 +391,7 @@ 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}` in `env` values from user-level or explicitly selected config files instead of storing secret literals. Automatically discovered project defaults still apply, but their values remain literal. Newly expanded OTLP headers are withheld when project defaults control telemetry routing. See [User Configuration](docs/guide/user-config.md#credential-boundary) for the scope of this protection. ## Importing `evals.json` diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 8479f92e..329aea07 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -469,7 +469,7 @@ 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. +> Specify `--config` at most once. For `init`, it names the copy source only. For other subcommands it selects an explicit layer trusted for variable expansion. See the [credential boundary](./user-config#credential-boundary). A relative `XDG_CONFIG_HOME` does not change the default write target. ### Examples diff --git a/docs/guide/user-config.md b/docs/guide/user-config.md index d0cf70bd..37417468 100644 --- a/docs/guide/user-config.md +++ b/docs/guide/user-config.md @@ -28,9 +28,7 @@ embed (empty) | `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. +Missing `user` and `project` files are skipped. Optional files that cannot be read or parsed produce a warning. A missing or invalid `--config` path is a hard error. Specify `--config` at most once. The XDG path is used only when `XDG_CONFIG_HOME` is absolute; otherwise discovery and the default `init` write target fall back to the home directory. Higher-precedence layers overlay non-zero fields onto lower layers; map fields (`telemetry.resource_attributes`, `env`, `runtime_kwargs`) are merged key-wise @@ -68,12 +66,17 @@ 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 at load time, so secrets stay out of the file. +- **`${VAR}` placeholders** expand only in `env` values supplied by the user or explicit layer, in one pass against the process environment before any defaults are applied. Unset references remain literal, and automatically discovered project values are never expanded. - **`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. +### Credential boundary + +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. + +A trusted per-signal HTTP(S) endpoint must parse as an absolute URL with a host before it can override a project-supplied shared endpoint for this check. A signal-specific certificate or key path cannot establish that a shared project TLS setting has been displaced. Exporters read those files at initialization, possibly in a child process, and can fall back to the shared setting if loading fails. In that combination the expanded header is withheld. These rules apply equally to trusted config and process environment overrides. + --- ## Bootstrapping with `skill-up init` diff --git a/docs/zh/guide/cli-reference.md b/docs/zh/guide/cli-reference.md index f42ecce5..dfa74fa4 100644 --- a/docs/zh/guide/cli-reference.md +++ b/docs/zh/guide/cli-reference.md @@ -291,7 +291,7 @@ skill-up init [flags] | `--print` | `false` | 输出到 stdout,而不是写盘 | | `--force` | `false` | 覆盖已存在的目标文件 | -> 注意:对 `init` 子命令,`--config` 是**读取源**;对其他子命令(`run`、`validate` …),`--config` 是加载链最顶层的覆盖路径。 +> `--config` 只能指定一次。对 `init`,它仅指定拷贝来源;对其他子命令,它选择可信任变量展开的显式配置层。见[凭据信任边界](./user-config.md#凭据信任边界)。相对路径的 `XDG_CONFIG_HOME` 不影响默认写入位置。 ### 示例 diff --git a/docs/zh/guide/user-config.md b/docs/zh/guide/user-config.md index eba62545..6b87a19d 100644 --- a/docs/zh/guide/user-config.md +++ b/docs/zh/guide/user-config.md @@ -26,8 +26,9 @@ embed (空) | `project` | `$PWD/.skill-up.yaml` | 跳过 | | `explicit` | 任意子命令的 `--config ` | 报错 | -`user` / `project` 层文件不存在或解析失败会降级为 stderr 上的 `warning:`,命令 -继续执行。`--config` 显式路径如果缺失或不合法则直接报错。 +`user` / `project` 层文件不存在时会跳过;无法读取或解析时会输出警告。 +`--config` 显式路径如果缺失或不合法则直接报错,且只能指定一次。只有绝对路径的 +`XDG_CONFIG_HOME` 才会生效;否则配置发现和 `init` 的默认写入位置都回退到用户主目录。 高优先级层只**覆盖非零字段**;map 类字段(`telemetry.resource_attributes`、 `env`、`runtime_kwargs`)按 key 逐项合并,而不是整体替换。 @@ -62,11 +63,27 @@ runtime_kwargs: # 按 environment.type 提 - **`telemetry` 与 `env`**:每个 key 对应一个 `OTEL_*` 或自定义环境变量,**仅在 对应环境变量未被设置时才会注入**——命令行或 shell 中已有的值优先。 -- **`env` 中的 `${VAR}`** 在加载时从当前进程环境展开,密钥不会被写进文件本身。 +- **`env` 中的 `${VAR}`** 只在值来自用户层或显式配置层时展开。在应用任何默认值前, + 使用进程环境展开一次。未设置的引用保留原样;自动发现的项目配置值不展开。 - **`runtime_kwargs`**:`run` 命令按 `environment.type`(如 `opensandbox`)查找 默认值。`eval.yaml` 中显式给的值优先;未提供的字段在这里兜底。Key 的形态与 对应 environment provider 的 kwargs 一致。 +### 凭据信任边界 + +自动发现的项目配置仍然提供默认值。如果项目默认值可以控制某个导出器的发送目标或 +它所信任的对端,由该导出器携带的、通过变量展开生成的 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` 仅指定拷贝来源,不提供默认值。 + +要在此检查中覆盖项目提供的通用端点,可信的信号级 HTTP(S) 端点必须能解析为包含主机名的绝对 URL。信号级证书或密钥路径不能证明项目提供的通用 TLS 设置已被覆盖。导出器会在初始化时读取文件,有时会在子进程中读取。如果加载失败,导出器可能会回退到通用设置,因此这种组合不会应用展开后的请求头。可信配置和进程环境变量遵循相同的规则。 + --- ## 用 `skill-up init` 初始化 diff --git a/internal/cli/configflag_test.go b/internal/cli/configflag_test.go new file mode 100644 index 00000000..be39d700 --- /dev/null +++ b/internal/cli/configflag_test.go @@ -0,0 +1,71 @@ +package cli + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestResolveConfigFlag(t *testing.T) { + for _, tc := range []struct { + name string + args []string + want string + }{ + {name: "absent", args: []string{"run", "eval.yaml"}}, + {name: "space before command", args: []string{"--config", "trusted.yaml", "run", "eval.yaml"}, want: "trusted.yaml"}, + {name: "equals after command", args: []string{"run", "eval.yaml", "--config=trusted.yaml"}, want: "trusted.yaml"}, + {name: "literal after separator", args: []string{"run", "--", "--config=literal.yaml"}}, + {name: "second literal after separator", args: []string{"run", "--config=trusted.yaml", "--", "--config=literal.yaml"}, want: "trusted.yaml"}, + {name: "another flag consumes lookalike", args: []string{"run", "--api-key", "--config=literal.yaml", "--config", "trusted.yaml"}, want: "trusted.yaml"}, + {name: "delimiter consumed by a flag", args: []string{"run", "--api-key", "--", "--config=trusted.yaml"}, want: "trusted.yaml"}, + {name: "short option and normalizer", args: []string{"run", "-vv", "--rk", "name=value", "--config=trusted.yaml"}, want: "trusted.yaml"}, + {name: "source named init", args: []string{"--config", "init", "run"}, want: "init"}, + {name: "completion flags are invocation data", args: []string{"__complete", "run", "--config=proposed.yaml", ""}}, + {name: "init copy source before command", args: []string{"--config", "source.yaml", "init", "--print"}}, + {name: "init copy source after command", args: []string{"init", "--config=source.yaml", "--print"}}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := resolveConfigFlag(tc.args) + if err != nil || got != tc.want { + t.Fatalf("resolveConfigFlag(%q) = %q, %v; want %q", tc.args, got, err, tc.want) + } + }) + } +} + +func TestResolveConfigFlagRejectsRepeated(t *testing.T) { + for _, args := range [][]string{ + {"run", "--config=one.yaml", "--config", "two.yaml"}, + {"--config", "one.yaml", "run", "--config=two.yaml"}, + {"--config=", "run", "--config=two.yaml"}, + {"init", "--print", "--config=one.yaml", "--config=two.yaml"}, + } { + got, err := resolveConfigFlag(args) + if err == nil || !strings.Contains(err.Error(), "--config may only be specified once") || got != "" { + t.Errorf("resolveConfigFlag(%q) = %q, %v; want duplicate error", args, got, err) + } + } +} + +func TestExecuteArgsRejectsRepeatedConfigBeforeApplyingDefaults(t *testing.T) { + const marker = "SKILL_UP_TEST_CONFIG_PREFLIGHT" + t.Setenv(marker, "") + if err := os.Unsetenv(marker); err != nil { + t.Fatal(err) + } + t.Chdir(t.TempDir()) + user := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(user, []byte("env:\n "+marker+": user-default\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("SKILL_UP_CONFIG", user) + err := ExecuteArgs("test-version", []string{"--config", user, "--config=" + user, "--version"}) + if err == nil || !strings.Contains(err.Error(), "--config may only be specified once") { + t.Fatalf("ExecuteArgs = %v, want duplicate error", err) + } + if _, present := os.LookupEnv(marker); present { + t.Fatalf("duplicate flag must be rejected before applying environment defaults") + } +} diff --git a/internal/cli/init.go b/internal/cli/init.go index b15bb501..e6d39951 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "os" "path/filepath" @@ -25,14 +26,17 @@ reads that file (validating it as a skill-up config) and writes its raw contents to the target, preserving comments and formatting. Target selection: - default $XDG_CONFIG_HOME/skill-up/config.yaml (or ~/.config/...) + default absolute $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 defaults are loaded automatically. To enable environment expansion in +a project file after reviewing it, select it explicitly 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 (loaded automatically as project defaults)") 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 +78,9 @@ func runInit(cmd *cobra.Command, _ []string) error { return err } _, _ = fmt.Fprintf(cmd.OutOrStdout(), "wrote %s\n", target) + if local { + _, _ = fmt.Fprintln(cmd.OutOrStdout(), "Project defaults load automatically. After reviewing this file, use --config ./.skill-up.yaml to enable env expansion.") + } return nil } @@ -95,8 +102,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 { @@ -105,18 +111,13 @@ func resolveProjectConfigTarget() (string, error) { return filepath.Join(wd, userconfig.ProjectConfigFile), nil } -// resolveUserConfigTarget returns the XDG-aware user config path -// ($XDG_CONFIG_HOME/skill-up/config.yaml, falling back to -// ~/.config/skill-up/config.yaml). +// resolveUserConfigTarget uses the same absolute-XDG rule as config discovery. func resolveUserConfigTarget() (string, error) { - if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" { - return filepath.Join(xdg, userconfig.UserConfigDir, userconfig.UserConfigFile), nil - } - home, err := os.UserHomeDir() - if err != nil { - return "", err + target := userconfig.DefaultConfigPath("", os.Getenv) + if target == "" { + return "", errors.New("cannot determine the default user config path: home directory unavailable") } - return filepath.Join(home, ".config", userconfig.UserConfigDir, userconfig.UserConfigFile), nil + return target, nil } // initTemplateContent is the commented YAML template used by `init` when no @@ -124,7 +125,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 < user config < .skill-up.yaml < --config +# User config uses SKILL_UP_CONFIG, absolute XDG_CONFIG_HOME, or ~/.config. # Use ` + "`skill-up init --print`" + ` to regenerate this template. schema_version: v1alpha1 @@ -157,7 +159,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. +# Automatically loaded project env values remain literal. # env: # OTEL_EXPORTER_OTLP_HEADERS: authorization=${OTLP_TOKEN} diff --git a/internal/cli/init_test.go b/internal/cli/init_test.go index b30c7048..619a34c0 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 { @@ -169,3 +173,25 @@ func TestInit_ConfigSourceInvalid(t *testing.T) { t.Fatal("expected error for invalid source") } } + +func TestInit_DefaultTargetIgnoresRelativeXDG(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", "relative-xdg") + t.Chdir(t.TempDir()) + + cmd := newInitCmdForTest() + cmd.SetOut(&bytes.Buffer{}) + cmd.SetArgs([]string{}) + if err := cmd.Execute(); err != nil { + t.Fatalf("init: %v", err) + } + want := filepath.Join(home, ".config", "skill-up", "config.yaml") + if _, err := os.Stat(want); err != nil { + t.Fatalf("init did not write %s: %v", want, err) + } + if _, err := os.Stat("relative-xdg"); !os.IsNotExist(err) { + t.Fatalf("init unexpectedly used relative XDG (stat error: %v)", err) + } +} diff --git a/internal/cli/otlp_loopback_test.go b/internal/cli/otlp_loopback_test.go new file mode 100644 index 00000000..5690c429 --- /dev/null +++ b/internal/cli/otlp_loopback_test.go @@ -0,0 +1,337 @@ +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" + "github.com/alibaba/skill-up/internal/userconfig" +) + +const ( + otlpLoopbackHeader = "synthetic-value" + otlpLoopbackHeaderEnv = "SKILL_UP_TEST_OTLP_HEADER" + otlpLoopbackEmptyEnv = "SKILL_UP_TEST_OTLP_EMPTY" + otlpTracesPath = "/v1/traces" + otlpMetricsPath = "/v1/metrics" + otlpTrustedCollector = "trusted" + otlpProjectCollector = "project" +) + +// 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) { + if r.Header.Get("X-Test-Marker") != "" { + t.Error("collector received a withheld test marker") + } + 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 +} + +// otlpExport names an export path that must arrive at a collector, with the +// Authorization value every request on that path must carry. +type otlpExport struct { + collector string + path string + authorization string +} + +type otlpLoopbackCase struct { + name string + user string + project string + verifyBeforeExport bool + // want lists every expected export. Any other export fails the test. + want []otlpExport +} + +// otlpLoopbackCases name the trusted collector in the user config and the +// other one in an automatically discovered project config. +var otlpLoopbackCases = []otlpLoopbackCase{ + { + name: "rejected traces endpoint uses shared route without expanded header", + user: `env: + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "https://[invalid" + OTEL_EXPORTER_OTLP_TRACES_HEADERS: x-test-marker=${SKILL_UP_TEST_OTLP_HEADER} +`, + project: `env: + OTEL_EXPORTER_OTLP_ENDPOINT: {{project}} +`, + verifyBeforeExport: true, + want: []otlpExport{{otlpProjectCollector, otlpTracesPath, ""}}, + }, + { + 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_HEADER} +`, + project: `telemetry: + traces: + endpoint: {{project}}/v1/traces +`, + want: []otlpExport{{otlpProjectCollector, 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_HEADER} +`, + project: `env: + SKILL_UP_TEST_PROJECT_DEFAULT: project +`, + want: []otlpExport{{otlpTrustedCollector, otlpTracesPath, otlpLoopbackHeader}}, + }, + { + 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_HEADER} +`, + project: `env: + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: {{project}}/v1/metrics +`, + want: []otlpExport{{otlpTrustedCollector, otlpTracesPath, otlpLoopbackHeader}}, + }, + { + 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_HEADER} + OTEL_EXPORTER_OTLP_METRICS_HEADERS: authorization=${SKILL_UP_TEST_OTLP_HEADER} +`, + project: `env: + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: {{project}}/v1/metrics +`, + want: []otlpExport{ + {otlpTrustedCollector, otlpTracesPath, otlpLoopbackHeader}, + {otlpProjectCollector, otlpMetricsPath, ""}, + }, + }, + { + name: "traces endpoint that expands to nothing falls back to the project endpoint", + user: `env: + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${SKILL_UP_TEST_OTLP_EMPTY} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: authorization=${SKILL_UP_TEST_OTLP_HEADER} +`, + project: `env: + OTEL_EXPORTER_OTLP_ENDPOINT: {{project}} +`, + want: []otlpExport{{otlpProjectCollector, otlpTracesPath, ""}}, + }, + { + name: "blank project traces endpoint that replaces the trusted one withholds the header", + user: `env: + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_ENDPOINT: {{trusted}} + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: {{trusted}}/custom/traces + OTEL_EXPORTER_OTLP_TRACES_HEADERS: authorization=${SKILL_UP_TEST_OTLP_HEADER} +`, + project: `env: + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: " " +`, + want: []otlpExport{{otlpTrustedCollector, otlpTracesPath, ""}}, + }, + { + name: "empty project traces endpoint that replaces the trusted one withholds the header", + user: `env: + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_ENDPOINT: {{trusted}} + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: {{trusted}}/custom/traces + OTEL_EXPORTER_OTLP_TRACES_HEADERS: authorization=${SKILL_UP_TEST_OTLP_HEADER} +`, + project: `env: + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "" +`, + want: []otlpExport{{otlpTrustedCollector, otlpTracesPath, ""}}, + }, + { + 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_HEADER} +`, + project: `env: + SSL_CERT_FILE: project-roots.pem +`, + want: []otlpExport{{otlpTrustedCollector, otlpTracesPath, ""}}, + }, +} + +// TestExecuteArgsExpandedOTLPHeaderReachesOnlyTrustedRoutes checks which +// headers reach the trusted and project collectors. The fallback case also +// checks the environment before starting the exporter. +func TestExecuteArgsExpandedOTLPHeaderReachesOnlyTrustedRoutes(t *testing.T) { + previousTracer, previousMeter := otel.GetTracerProvider(), otel.GetMeterProvider() + t.Cleanup(func() { + otel.SetTracerProvider(previousTracer) + otel.SetMeterProvider(previousMeter) + }) + + for _, tc := range otlpLoopbackCases { + t.Run(tc.name, func(t *testing.T) { + collectors := map[string]*otlpCollector{ + otlpTrustedCollector: newOTLPCollector(t), + otlpProjectCollector: newOTLPCollector(t), + } + runOTLPLoopbackCase(t, tc, collectors) + checkOTLPExports(t, tc.want, collectors) + }) + } + + // 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) + } +} + +// runOTLPLoopbackCase writes the two config files and runs the CLI start-up +// path once. ExecuteArgs flushes both exporters before it returns. +func runOTLPLoopbackCase(t *testing.T, tc otlpLoopbackCase, collectors map[string]*otlpCollector) { + t.Helper() + // Telemetry settings inherited from the developer's shell must not + // decide what the collectors see. + for _, entry := range os.Environ() { + key, _, _ := strings.Cut(entry, "=") + if strings.HasPrefix(key, "OTEL_") { + unsetForTest(t, key) + } + } + for _, key := range []string{ + "OTEL_METRICS_EXPORTER", "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_PROTOCOL", + "OTEL_EXPORTER_OTLP_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_HEADERS", + "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "OTEL_EXPORTER_OTLP_METRICS_HEADERS", + "SSL_CERT_FILE", "SSL_CERT_DIR", "SKILL_UP_TEST_PROJECT_DEFAULT", + } { + unsetForTest(t, key) + } + t.Setenv("OTEL_TRACES_SAMPLER", "always_on") + t.Setenv(otlpLoopbackHeaderEnv, otlpLoopbackHeader) + t.Setenv(otlpLoopbackEmptyEnv, "") + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + userPath := filepath.Join(t.TempDir(), "user.yaml") + t.Setenv("SKILL_UP_CONFIG", userPath) + t.Chdir(t.TempDir()) + + placeholders := strings.NewReplacer( + "{{trusted}}", collectors[otlpTrustedCollector].URL, + "{{project}}", collectors[otlpProjectCollector].URL, + ) + 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) + } + if tc.verifyBeforeExport { + exportAfterHeaderCheck(t) + return + } + if _, err := captureStdout(t, func() error { + return ExecuteArgs("test-version", []string{"--version"}) + }); err != nil { + t.Fatal(err) + } +} + +func exportAfterHeaderCheck(t *testing.T) { + t.Helper() + cfg, _, err := loadUserConfig(nil) + if err != nil { + t.Fatal(err) + } + if _, err := userconfig.ApplyEnv(cfg); err != nil { + t.Fatal(err) + } + if _, present := os.LookupEnv("OTEL_EXPORTER_OTLP_TRACES_HEADERS"); present { + t.Fatal("expanded trace headers present before exporter initialization") + } + ctx, shutdown, err := observability.Init(context.Background(), "test-version") + if err != nil { + t.Fatal(err) + } + if err := shutdown(ctx); err != nil { + t.Fatal(err) + } +} + +// unsetForTest removes key for the test and restores it afterwards. +func unsetForTest(t *testing.T, key string) { + t.Helper() + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } +} + +func checkOTLPExports(t *testing.T, want []otlpExport, collectors map[string]*otlpCollector) { + t.Helper() + expected := map[string]map[string]string{} + for name := range collectors { + expected[name] = map[string]string{} + } + for _, export := range want { + expected[export.collector][export.path] = export.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) + } + } + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index ab8e7ea7..a2406397 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -3,11 +3,13 @@ package cli import ( "context" + "errors" "fmt" "os" "strings" "github.com/spf13/cobra" + "github.com/spf13/pflag" "github.com/alibaba/skill-up/internal/observability" "github.com/alibaba/skill-up/internal/userconfig" @@ -26,8 +28,8 @@ func Execute(version string) error { // // User-config is loaded BEFORE observability.Init so that any OTEL_* env vars // derived from the config are visible to the OTel SDK on first read. The -// persistent --config flag is parsed manually here because cobra has not yet -// processed flags by the time we need them. +// persistent --config flag is resolved without setting flag values before Cobra +// executes the selected command. func ExecuteArgs(version string, args []string) error { rootCmd.Version = version @@ -58,20 +60,12 @@ 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 defaults before command execution. +// For init, --config is a copy source and must not grant expansion permission. func loadUserConfig(args []string) (userconfig.Config, []userconfig.Source, error) { - explicit := extractConfigFlag(args) - if isInitInvocation(args) { - explicit = "" + explicit, err := resolveConfigFlag(args) + if err != nil { + return userconfig.Config{}, nil, err } return userconfig.LoadEffective(userconfig.LoadOptions{ ExplicitPath: explicit, @@ -79,81 +73,66 @@ func loadUserConfig(args []string) (userconfig.Config, []userconfig.Source, erro }) } -// persistentValueFlags lists the long names of root-level flags that consume -// a following positional argument as their value (e.g. `--config foo`). When -// adding a new persistent flag that takes a value, append its name here so the -// pre-cobra scanners below skip its value correctly. -var persistentValueFlags = map[string]struct{}{ - configFlagName: {}, -} - -// isInitInvocation reports whether args invokes the `init` subcommand. It -// must work before cobra has parsed the flag set, so it is a small POSIX-ish -// scanner that stops at `--` (end-of-flags) and only consumes values for the -// persistent flags it explicitly knows about. -func isInitInvocation(args []string) bool { - i := 0 - for i < len(args) { - a := args[i] - if a == "--" { - return false - } - if name, hasValue, consumed := parseLongFlag(a); name != "" { - if hasValue { - i += consumed - continue - } - if _, ok := persistentValueFlags[name]; ok && i+1 < len(args) { - i += 2 - continue - } - i++ - continue - } - if strings.HasPrefix(a, "-") { - i++ - continue - } - return a == "init" +// resolveConfigFlag preflights --config using Cobra's selected command and +// pflag's parser. A second occurrence is rejected before any config is applied. +// The parser callback only collects --config, without mutating any flag values. +func resolveConfigFlag(args []string) (string, error) { + // Shell completion receives the proposed invocation as data, not flags + // for an execution. Do not grant expansion based on that data. + if len(args) > 0 && (args[0] == cobra.ShellCompRequestCmd || args[0] == cobra.ShellCompNoDescRequestCmd) { + return "", nil } - return false -} + // Keep normal command parsing and error reporting unchanged when the + // invocation has no potential --config argument. + if !hasConfigFlagArg(args) { + return "", nil + } + rootCmd.InitDefaultHelpCmd() + rootCmd.InitDefaultCompletionCmd(args...) + cmd, flagArgs, err := rootCmd.Find(args) + if err != nil || cmd.DisableFlagParsing { + return "", err + } + cmd.InitDefaultHelpFlag() + cmd.InitDefaultVersionFlag() + _ = cmd.InheritedFlags() // Ensure Flags includes persistent definitions. + definitions := cmd.Flags() + flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError) + flags.SetNormalizeFunc(definitions.GetNormalizeFunc()) + flags.ParseErrorsAllowlist = pflag.ParseErrorsAllowlist(cmd.FParseErrWhitelist) + definitions.VisitAll(func(flag *pflag.Flag) { + definition := *flag + flags.AddFlag(&definition) + }) -// extractConfigFlag returns the value of --config in args, if present. Stops -// scanning at `--` so positional arguments after end-of-flags are not -// misinterpreted as flag values. -func extractConfigFlag(args []string) string { - for i := range args { - a := args[i] - if a == "--" { - return "" - } - name, hasValue, _ := parseLongFlag(a) - if name != configFlagName { - continue + var explicit string + var seen bool + err = flags.ParseAll(flagArgs, func(flag *pflag.Flag, value string) error { + if flag.Name != configFlagName { + return nil } - if hasValue { - return strings.TrimPrefix(a, "--"+configFlagName+"=") - } - if i+1 < len(args) { - return args[i+1] + if seen { + return errors.New("--config may only be specified once") } + seen = true + explicit = value + return nil + }) + if err != nil || cmd == initCmd { + return "", err } - return "" + return explicit, nil } -// parseLongFlag returns the long-flag name (if any), whether it has an inline -// `=value`, and how many args it consumed (always 1 here; callers handle the -// 2-token form themselves to keep the value lookup explicit). -func parseLongFlag(a string) (name string, hasValue bool, consumed int) { - if !strings.HasPrefix(a, "--") || a == "--" { - return "", false, 0 - } - body := a[2:] - if k, _, ok := strings.Cut(body, "="); ok { - return k, true, 1 +func hasConfigFlagArg(args []string) bool { + for _, arg := range args { + // Do not stop at --: it may be the value of a preceding flag. + // The actual parser distinguishes a value from the delimiter. + if arg == "--"+configFlagName || strings.HasPrefix(arg, "--"+configFlagName+"=") { + return true + } } - return body, false, 1 + return false } var rootCmd = &cobra.Command{ @@ -169,7 +148,7 @@ func init() { return err }) - rootCmd.PersistentFlags().String(configFlagName, "", "Path to skill-up user config (overrides discovered defaults)") + rootCmd.PersistentFlags().String(configFlagName, "", "Path to a trusted skill-up config (enables ${VAR} expansion in its env defaults)") rootCmd.AddCommand(runCmd) rootCmd.AddCommand(validateCmd) diff --git a/internal/cli/root_test.go b/internal/cli/root_test.go index 44532647..fde57ccb 100644 --- a/internal/cli/root_test.go +++ b/internal/cli/root_test.go @@ -2,10 +2,14 @@ package cli import ( "bytes" + "os" + "path/filepath" "strings" "testing" "github.com/spf13/cobra" + + "github.com/alibaba/skill-up/internal/userconfig" ) func TestUsageOnError_PrintsUsageForParseErrors(t *testing.T) { @@ -47,49 +51,112 @@ func TestExecuteArgsVersionInitializesRoot(t *testing.T) { } } -func TestIsInitInvocation(t *testing.T) { - cases := []struct { - name string - args []string - want bool - }{ - {"empty", nil, false}, - {"bare init", []string{"init"}, true}, - {"with --config space", []string{"--config", "/tmp/c.yaml", "init"}, true}, - {"with --config=", []string{"--config=/tmp/c.yaml", "init"}, true}, - {"end-of-flags before init still finds", []string{"--config", "/tmp/c.yaml", "--", "init"}, false}, - {"run command", []string{"run", "/tmp/eval.yaml"}, false}, - {"flag-only", []string{"--help"}, false}, - {"init after non-value flag", []string{"--quiet", "init"}, true}, - {"unknown -X flag followed by init", []string{"-X", "init"}, true}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := isInitInvocation(tc.args); got != tc.want { - t.Errorf("isInitInvocation(%v) = %v, want %v", tc.args, got, tc.want) - } - }) +func TestLoadUserConfigPreservesProjectDefaultsWithoutApplyingExpandedOTLPHeaders(t *testing.T) { + t.Setenv("SKILL_UP_TEST_HEADER_VALUE", "synthetic-value") + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Chdir(t.TempDir()) + userPath := filepath.Join(t.TempDir(), "user.yaml") + t.Setenv("SKILL_UP_CONFIG", userPath) + if err := os.WriteFile(userPath, []byte(`env: + OTEL_EXPORTER_OTLP_HEADERS: authorization=${SKILL_UP_TEST_HEADER_VALUE} +`), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(".skill-up.yaml", []byte(`telemetry: + traces: + endpoint: https://project.example.invalid +env: + SKILL_UP_TEST_PROJECT_DEFAULT: project +`), 0o600); err != nil { + t.Fatal(err) + } + for _, key := range []string{"OTEL_EXPORTER_OTLP_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "SKILL_UP_TEST_PROJECT_DEFAULT"} { + t.Setenv(key, "") + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + cfg, _, err := loadUserConfig([]string{"--version"}) + if err != nil { + t.Fatal(err) + } + // Inspect defaults before SDK initialization. No collector or transport needed. + if _, err := userconfig.ApplyEnv(cfg); err != nil { + t.Fatal(err) + } + if _, ok := os.LookupEnv("OTEL_EXPORTER_OTLP_HEADERS"); ok { + t.Error("a newly expanded header default was applied with project routing") + } + if got := os.Getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"); got != "https://project.example.invalid" { + t.Errorf("project route default = %q", got) + } + if got := os.Getenv("SKILL_UP_TEST_PROJECT_DEFAULT"); got != "project" { + t.Errorf("ordinary project default = %q", got) } } -func TestExtractConfigFlag(t *testing.T) { - cases := []struct { - name string - args []string - want string +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") + 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") + const projectContents = `env: + OTEL_EXPORTER_OTLP_ENDPOINT: https://collector.example.invalid + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_RESOURCE_ATTRIBUTES: source=${SKILL_UP_TEST_SECRET} +` + if err := os.WriteFile(project, []byte(projectContents), 0o600); err != nil { + t.Fatal(err) + } + copySource := filepath.Join(t.TempDir(), "copy.yaml") + if err := os.WriteFile(copySource, []byte(strings.Replace(projectContents, "source=", "copy-only=", 1)), 0o600); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + args []string + want string + wantOutput string }{ - {"absent", []string{"run", "x"}, ""}, - {"space form", []string{"--config", "/a.yaml", "run"}, "/a.yaml"}, - {"equals form", []string{"--config=/a.yaml", "run"}, "/a.yaml"}, - {"empty equals", []string{"--config=", "run"}, ""}, - {"trailing --config has no value", []string{"run", "--config"}, ""}, - {"after -- terminator is positional", []string{"--", "--config", "/a.yaml"}, ""}, - {"first wins", []string{"--config", "/first.yaml", "--config", "/second.yaml"}, "/first.yaml"}, - } - for _, tc := range cases { + {"automatic", []string{"--version"}, "source=${SKILL_UP_TEST_SECRET}", "test-version"}, + {"explicit", []string{"--version", "--config", project}, "source=test-token", "test-version"}, + {"explicit equals", []string{"--version", "--config=" + project}, "source=test-token", "test-version"}, + {"init source", []string{"init", "--config", copySource, "--print"}, "source=${SKILL_UP_TEST_SECRET}", "copy-only=${SKILL_UP_TEST_SECRET}"}, + } { t.Run(tc.name, func(t *testing.T) { - if got := extractConfigFlag(tc.args); got != tc.want { - t.Errorf("extractConfigFlag(%v) = %q, want %q", tc.args, got, tc.want) + for _, key := range []string{"OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_PROTOCOL", "OTEL_RESOURCE_ATTRIBUTES"} { + t.Setenv(key, "") + _ = os.Unsetenv(key) + } + output, err := captureStdout(t, func() error { + return ExecuteArgs("test-version", tc.args) + }) + 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) } }) } diff --git a/internal/userconfig/apply.go b/internal/userconfig/apply.go index 018320f2..fefb6931 100644 --- a/internal/userconfig/apply.go +++ b/internal/userconfig/apply.go @@ -3,11 +3,17 @@ package userconfig import ( "context" "maps" + "net/url" "os" + "regexp" + "slices" "sort" + "strconv" "strings" ) +var envPlaceholderPattern = regexp.MustCompile(`\$\{[A-Za-z_][A-Za-z0-9_]*\}`) + const ( envOtelServiceName = "OTEL_SERVICE_NAME" envOtelTracesExporter = "OTEL_TRACES_EXPORTER" @@ -22,23 +28,56 @@ 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}. +// 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) - for k, v := range c.Env { - if v == "" { + // Resolve every default first, so the guard reads the values an exporter + // will see rather than their templates. + defaults := make(map[string]envDefault, len(c.Env)) + for key, value := range c.Env { + if _, exists := os.LookupEnv(key); exists || value == "" { + continue + } + if _, exists := pending[key]; exists { continue } - if _, exists := pending[k]; !exists { - pending[k] = v + resolved := envDefault{value: value} + if source := c.envSources[key]; source == sourceUser || source == sourceExplicit { + resolved.value, resolved.expanded = expandEnvDefault(value) } + defaults[key] = resolved } - keys := make([]string, 0, len(pending)) - for k := range pending { - keys = append(keys, k) + routes := projectOTLPRouting(c, pending) + headers := make(map[string]string) + for key, resolved := range defaults { + // Keep project routing and pre-existing headers intact, but do + // not add credentials derived by this new expansion to it. + if _, option, ok := parseOTLPOption(strings.ToUpper(key)); resolved.expanded && ok && option == otlpOptionHeaders { + if routes.withholds(pending, defaults, key) { + continue + } + headers[key] = resolved.value + } else { + pending[key] = resolved.value + } } - sort.Strings(keys) + // Install expanded headers only after all transport defaults succeed. + applied, err := applyDefaults(pending) + if err != nil { + return applied, err + } + appliedHeaders, err := applyDefaults(headers) + applied = append(applied, appliedHeaders...) + sort.Strings(applied) + return applied, err +} + +func applyDefaults(pending map[string]string) ([]string, error) { + keys := slices.Sorted(maps.Keys(pending)) applied := make([]string, 0, len(keys)) for _, k := range keys { if _, ok := os.LookupEnv(k); ok { @@ -52,6 +91,189 @@ func ApplyEnv(c Config) ([]string, error) { return applied, nil } +// envDefault is an env default after ${VAR} expansion. +type envDefault struct { + value string + expanded bool +} + +// 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 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] != "" { + routes.add(key) + } + } + // An empty or blank project value counts too. It is not applied, or is + // read as unset, but in the merged config it has already replaced a + // trusted value for the same key, so the exporter falls back to another + // route. + for key := range c.Env { + if _, exists := os.LookupEnv(key); exists { + continue + } + 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(pending map[string]string, defaults map[string]envDefault, 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(pending, defaults, signal, shared) { + return true + } + } + return false +} + +// hasTrustedSignalOption checks whether a trusted override displaces the +// shared project option. Exporters ignore options they cannot parse or load. +func hasTrustedSignalOption(pending map[string]string, defaults map[string]envDefault, signal, option string) bool { + key := otlpEnvPrefix + signal + "_" + option + value, exists := os.LookupEnv(key) + if !exists { + value, exists = pending[key] + if !exists { + value = defaults[key].value + } + } + switch option { + case "ENDPOINT": + return usableOTLPEndpoint(value) + case "PROTOCOL": + return value == "grpc" || value == "http/protobuf" + case "INSECURE": + return value == "true" || value == "false" + default: + // Exporters, including child processes, load TLS files themselves. + // Checking a path here cannot guarantee that a later load succeeds. + return false + } +} + +func usableOTLPEndpoint(value string) bool { + u, err := url.Parse(value) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || strings.Contains(u.Hostname(), "%") { + return false + } + if u.Port() == "" { + return true + } + port, err := strconv.ParseUint(u.Port(), 10, 16) + return err == nil && port != 0 +} + +// 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 +} + +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", "CLIENT_KEY", "CERTIFICATE", "ENDPOINT", "PROTOCOL", "INSECURE", otlpOptionHeaders, +} + +// parseOTLPOption splits an upper-case OTEL_EXPORTER_OTLP_[_]