beads/internal/execenv/execenv.go
ecuthiell 79631656c0
fix(config): pin role writes to a fresh common-config context (#6454)
* fix(exec): match Windows environment key identity (#5618)

Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* fix(worktree): scrub inherited Git routing state

Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.

Fixes #5531

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* refactor(worktree): explain owned filtering and remove an unused shim

Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.

Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): isolate identity and tracked-file Git probes from routing

Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.

Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning

* test(execenv): exercise every environment operation under both host rules

Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.

Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning

* docs(worktree): explain startup Git environment scope (saa-cgh.23)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(execenv): exercise exported host policy wiring (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): share subprocess key identity for Git routing (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): isolate role commands from Git routing (saa-cgh.99)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(env): exercise shared key helpers on native Windows (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(config): explain role command routing policy (saa-cgh.99)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): retain legitimate inherited tracking context (saa-cgh.98)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(hooks): isolate trusted global configuration fixture (saa-cgh.98)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): isolate role cleanup in the selected repository (saa-cgh.109.4)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): reset only common local role configuration (saa-cgh.109.10)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): scope hooks-path cleanup to selected common config (saa-cgh.109.11)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(hooks): make worktree role preservation independent (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Report selected config read failures during hook reset (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): keep successful config stdout separate from diagnostics (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): pin role writes to fresh common context (GH#6384) (saa-cgh.120.3)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): retain Git diagnostics from role writes (saa-cgh.120.3)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(config): assert the actual Git lock diagnostic (saa-cgh.120.3)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config,hooks): restore the inherited-tracking fallback in the secret guard

Maintainer review fixes for PR #6454 (adopt-pr iteration 1). The scorecard
approved at 913/1000 with no blocker or major surviving synthesis; these are
the non-gating findings that were cheap to close while the fixup was open.

Finding 1 (minor, security) is the only in-range regression in the report. The
range switched internal/config.isGitTracked from the inherited environment to
gitenv.ScrubRouting only, so a config.yaml tracked solely through legitimate
routing -- a bare repository whose work tree is named by GIT_DIR/GIT_WORK_TREE
-- reported untracked, and a secret-key write that upstream-base refused was
silently allowed. Restores the scrubbed-then-inherited union the same stack
already gave cmd/bd.isGitTrackedFile.

Finding 4 (nit) composes with it rather than conflicting, so both land as one
change: the inherited probe now runs only when the scrubbed probe failed for a
configuration reason. git's exit codes discriminate exactly -- 0 tracked, 1
repository reached but path untracked (final), 128 no reachable repository --
so the ordinary untracked-hook miss no longer spawns a second `git ls-files`
while the bare-work-tree fallback is preserved.

Finding 2 (minor). scrubWorktreeRemovalGitEnvForOS keyed its stricter
no-optional-locks policy on strings.ToUpper while the rest of the PR uses
execenv key identity. The two disagree in both directions on Windows:
GIT_OPTIONAL_LOCKS with a dotted capital I (U+0130) survived the scrub although
Git honors it, and GIT_OPTIONAL_LOCK with a long s (U+017F) was dropped
although os/exec keeps it distinct. normalizeWorktreeGitEnvKey is deleted in
favour of execenv.KeyEqualForOS. Base applied ToUpper on all platforms, so this
is a consistency fix in newly rewritten code, not a regression.

Finding 5 (nit). The comment above resetHooksPathIfBeadsManaged's probe
asserted that repoRoot and commonDir share the cached Git context. Probed
false: with cwd A and GIT_DIR=B/.git, `git rev-parse --git-common-dir
--show-toplevel` prints B/.git and A. Restated as intent.

Finding 3 (scrubGitHookEnv is a fifth, strictly weaker routing scrubber) is
deliberately not taken here: cmd/bd/export_auto.go is untouched by this range,
so the hazard is byte-identical at base, and the synthesis scoped it to a
follow-up bead rather than growing this stack.

Each fix is mutation-proved. Reverting isGitTracked reds only the new
TestSecretGitTrackingHonorsInheritedBareWorkTree -- including "refusal = <nil>",
the actual security consequence -- while the incumbent decoy test stays green,
so the pin adds coverage rather than duplicating it. Restoring ToUpper reds
only the new Windows row, showing both directions at once.
TestGuardHookWritePathHonorsInheritedRepository gains a fixture guard asserting
its scrubbed probe fails for a configuration reason rather than exit 1, so a
future fixture change cannot silently make the fallback unreachable.
scrubWorktreeRemovalGitEnvForOS had no test at all before this.

Green locally: ./internal/config, ./internal/execenv, ./internal/gitenv,
./internal/githooksenv, ./internal/gittraceenv, ./internal/metrics, ./scripts,
./internal/beads (the GIT_CONFIG_GLOBAL blast radius neither reviewer ran), and
a blast-radius cmd/bd run over the hooks, worktree, role and uninstall suites.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-27 02:00:16 -07:00

155 lines
5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package execenv provides helpers for constructing explicit subprocess
// environments with the same key identity rules as os/exec.
package execenv
import (
"runtime"
"strings"
)
// A single host seam lets package tests exercise the exported wrappers for
// both key policies without changing the process environment.
// Process-wide seam: tests that swap it must not run in parallel.
var hostOS = runtime.GOOS
// KeyIdentityForOS returns the key identity used by os/exec on goos. Callers
// doing repeated membership checks can normalize once; POSIX keys stay exact.
func KeyIdentityForOS(key, goos string) string {
return keyIdentityForWindows(key, goos == "windows")
}
// KeyEqual reports whether left and right identify the same environment key
// for a subprocess on the current host. Windows keys are case-insensitive;
// keys on other hosts are exact.
func KeyEqual(left, right string) bool {
return KeyEqualForOS(left, right, hostOS)
}
// KeyEqualForOS compares environment keys using goos subprocess semantics.
func KeyEqualForOS(left, right, goos string) bool {
return keyEqualForWindows(left, right, goos == "windows")
}
// KeyHasPrefixForOS compares a key, rather than an environment entry, with a
// prefix using goos subprocess semantics. Valueless-entry policy belongs to
// the caller.
func KeyHasPrefixForOS(key, prefix, goos string) bool {
windows := goos == "windows"
return strings.HasPrefix(keyIdentityForWindows(key, windows), keyIdentityForWindows(prefix, windows))
}
func keyEqualForWindows(left, right string, windows bool) bool {
return keyIdentityForWindows(left, windows) == keyIdentityForWindows(right, windows)
}
// ContainsKeyWithPrefix reports whether env contains a key beginning with one
// of prefixes, using the current host's environment-key semantics.
func ContainsKeyWithPrefix(env []string, prefixes ...string) bool {
return containsKeyWithPrefixForWindows(env, hostOS == "windows", prefixes...)
}
func containsKeyWithPrefixForWindows(env []string, windows bool, prefixes ...string) bool {
identities := make([]string, len(prefixes))
for i, prefix := range prefixes {
identities[i] = keyIdentityForWindows(prefix, windows)
}
for _, entry := range env {
key, _, ok := split(entry)
if !ok {
continue
}
key = keyIdentityForWindows(key, windows)
for _, prefix := range identities {
if strings.HasPrefix(key, prefix) {
return true
}
}
}
return false
}
// Lookup returns the last value for key in env, matching os/exec's last-wins
// handling of duplicate effective keys.
func Lookup(env []string, key string) (string, bool) {
return lookupForWindows(env, key, hostOS == "windows")
}
func lookupForWindows(env []string, key string, windows bool) (string, bool) {
wanted := keyIdentityForWindows(key, windows)
var value string
var found bool
for _, entry := range env {
entryKey, entryValue, ok := split(entry)
if ok && keyIdentityForWindows(entryKey, windows) == wanted {
value, found = entryValue, true
}
}
return value, found
}
// Without returns a copy of env without entries matching keys. Unrelated
// duplicates, malformed entries, and Windows drive pseudo-variables are
// preserved in their original order. The input slice is not modified.
func Without(env []string, keys ...string) []string {
return WithoutForOS(env, hostOS, keys...)
}
// WithoutForOS is Without with explicit goos environment-key semantics.
func WithoutForOS(env []string, goos string, keys ...string) []string {
return withoutForWindows(env, goos == "windows", keys...)
}
func withoutForWindows(env []string, windows bool, keys ...string) []string {
drop := make(map[string]struct{}, len(keys))
for _, key := range keys {
drop[keyIdentityForWindows(key, windows)] = struct{}{}
}
out := make([]string, 0, len(env))
for _, entry := range env {
key, _, ok := split(entry)
if ok {
if _, remove := drop[keyIdentityForWindows(key, windows)]; remove {
continue
}
}
out = append(out, entry)
}
return out
}
// keyIdentityForWindows mirrors the key normalization in os/exec.dedupEnvCase.
// strings.ToLower is intentional: EqualFold would collapse Unicode
// near-collisions such as s and ſ that os/exec keeps distinct.
func keyIdentityForWindows(key string, windows bool) string {
if windows {
return strings.ToLower(key)
}
return key
}
// EntryKey returns an entry's key using the same split rule as os/exec,
// including drive pseudo-variables. A bare entry is returned unchanged so
// callers retain authority over their valueless-entry policy.
func EntryKey(entry string) string {
if key, _, ok := split(entry); ok {
return key
}
return entry
}
// split mirrors os/exec's handling of Windows drive pseudo-variables such as
// =C:=C:\work, whose key includes the leading equals sign.
func split(entry string) (key, value string, ok bool) {
separator := strings.IndexByte(entry, '=')
if separator == 0 {
next := strings.IndexByte(entry[1:], '=')
if next >= 0 {
separator = next + 1
}
}
if separator < 0 {
return "", "", false
}
return entry[:separator], entry[separator+1:], true
}