Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 119 additions & 14 deletions internal/envmanifest/shellexports.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,33 @@ var envNameRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
//
// A plain assignment with no command ("NAME=value" alone, or "readonly
// NAME=value") is shell-local and is not reported, nor is a prefix
// assignment on a shell builtin ("IFS= read"). Assignment-shaped text
// assignment on a shell builtin ("IFS= read"). "export -n NAME" removes
// the export attribute, so a name the scripts un-export after exporting
// it is not reported; scripts are read in order as one shell, and an
// "sh -c" script is its own shell whose un-exports do not reach its
// parent. Prefix assignments affect only their command's process, and a
// name exported when a process launches stays in that process's
// environment, so a later "export -n" does not retract either. "export
// -f" works on functions, so "export -fn NAME" leaves variable NAME
// exported. An "export" with an option other than -f, -n or -p
// changes nothing, and "command -v" only looks a command up and
// "builtin" runs only a shell builtin, so neither launches a process.
// Parentheses are only separators, so an "export -n" inside a
// ( ... ) subshell is treated as if it ran in the parent shell.
// Assignment-shaped text
// inside a quoted value is data, not a binding, and a command
// substitution's exports stay in its subshell. The parser is a tokenizer,
// not a shell: it handles single and double quotes, backslash escapes,
// $(...) nesting, comments, and the ; && || | & ( ) { } newline
// separators, which is the subset the runner's emitters generate.
func ExportedNames(scripts ...string) []string {
seen := map[string]bool{}
exported := map[string]bool{}
for _, script := range scripts {
collectExportedNames(script, seen, 0)
collectExportedNames(script, seen, exported, 0)
}
for name := range exported {
seen[name] = true
}
names := make([]string, 0, len(seen))
for name := range seen {
Expand All @@ -48,6 +65,10 @@ var shellBuiltins = map[string]bool{
"echo": true, "eval": true, "exit": true, "false": true, "printf": true,
"read": true, "return": true, "set": true, "shift": true, "test": true,
"true": true, "unset": true,
"readonly": true, "local": true, "declare": true, "typeset": true,
"let": true, "pwd": true, "wait": true, "trap": true, "umask": true,
"getopts": true, "source": true, ".": true, "alias": true,
"hash": true, "type": true, "ulimit": true, "builtin": true,
}

// maxShellDepth bounds sh -c recursion so a malformed input cannot loop.
Expand All @@ -74,17 +95,21 @@ func (w shellWord) assignmentName() string {
return name
}

func collectExportedNames(script string, seen map[string]bool, depth int) {
// collectExportedNames records the names script exports. seen collects
// names that reach a child process for certain (prefix and env
// assignments, and a finished child shell's exports); exported holds the
// current shell's export attributes, which a later "export -n" can clear.
func collectExportedNames(script string, seen, exported map[string]bool, depth int) {
if depth > maxShellDepth {
return
}
for _, words := range shellCommands(script) {
collectFromCommand(words, seen, depth)
collectFromCommand(words, seen, exported, depth)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] edge-case

All tokenized commands share one mutable export set while the tokenizer treats parentheses as plain command separators, so export X=1; (export -n X) returns no X although Bash runs the un-export in a subshell and X stays exported in the parent. This is consistent with the documented 'tokenizer, not a shell' limits; the pre-PR code had the same scope loss in the other direction ((export X=1) was over-reported).

Suggested fix: Add a regression test and either isolate export mutations inside parenthesized subshells or document this as a known tokenizer limitation.

}
}

// collectFromCommand records the names one simple command exports.
func collectFromCommand(words []shellWord, seen map[string]bool, depth int) {
func collectFromCommand(words []shellWord, seen, exported map[string]bool, depth int) {
// Leading NAME=value words are prefix assignments when a command
// follows them, and shell-local assignments when nothing does.
i := 0
Expand All @@ -99,17 +124,55 @@ func collectFromCommand(words []shellWord, seen map[string]bool, depth int) {
for _, w := range words[:i] {
seen[w.assignmentName()] = true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] logic-error

Prefix assignments are added to seen before it is known whether export, command or exec launches a process, so "Y=1 command -v true" and "Y=1 export -n Y" report Y. The new builtin forwarding re-dispatches the prefix words and inherits this. Over-reporting only; the command case exists on the base branch.

Suggested fix: Carry temporary prefix bindings through dispatch and record them only when the resolved operation launches a process; add tests for prefix assignments on lookup-only command and on export -n.

}
// Launching a process hands it the shell's current export
// attributes, so a later "export -n" cannot retract them. "export"
// and "command" run inside the shell (command may run a builtin),
// and "exec" with no command launches nothing.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] logic-error

Previously reported finding remains open: low logic-error in internal/envmanifest/shellexports.go:130.

if cmd != "export" && cmd != "command" && (cmd != "exec" || len(args) > 0) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] logic-error

The process-launch snapshot still treats unlisted shell builtins as external commands. For example, export X=1; builtin true; export -n X reports X even though builtin true launches no child and X is later un-exported. builtin is not in shellBuiltins, and no case in collectFromCommand handles it.

Suggested fix: Add the builtin dispatcher to collectFromCommand and process its target with builtin semantics. Add a regression test that un-exports a variable after builtin true.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] logic-error

The exec launch check treats any argument as a command, including options alone. ExportedNames("export X=1; exec --; export -n X") returns X, although Bash exec -- launches nothing and the later export -n removes X.

Suggested fix: Skip exec options (at least --, and -a/-c/-l) before deciding whether a command remains, and add an options-only exec regression test.

for name := range exported {
seen[name] = true
}
}
}
switch cmd {
case "export":
// Options precede the operands and end at "--" or the first
// operand (a lone "-" is an operand); -n (alone or combined, as in
// -pn) switches the command to removing the export attribute. -f
// selects the function namespace, so function-mode operands never
// change a variable's export attribute.
unexport, funcMode, optsDone := false, false, false
for _, a := range args {
if strings.HasPrefix(a.text, "-") {
if !optsDone && a.text != "-" && strings.HasPrefix(a.text, "-") {
if a.text == "--" {
optsDone = true
} else {
// An option the builtin rejects makes the whole
// command a no-op, so no export state changes.
if strings.Trim(a.text[1:], "fnp") != "" {
return
}
if strings.Contains(a.text[1:], "n") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] logic-error

Any export option containing 'n' sets un-export mode, even when Bash rejects the option as invalid. For example export X=1; export -notvalid X leaves X exported in Bash (the builtin errors out without acting), but this parser deletes X from the export set, so the manifest would omit an exported variable. Needs malformed input the runner's emitters do not generate, hence low.

Suggested fix: Validate the option characters (only the letters export accepts, e.g. f, n, p) before changing export state, and add a regression test for an invalid option containing 'n'.

unexport = true
}
if strings.Contains(a.text[1:], "f") {
funcMode = true
}
}
continue
}
if name := a.assignmentName(); name != "" {
seen[name] = true
} else if envNameRe.MatchString(a.text) {
seen[a.text] = true
optsDone = true
name := a.assignmentName()
if name == "" && envNameRe.MatchString(a.text) {
name = a.text
}
switch {
case name == "":
case funcMode:
case unexport:
delete(exported, name)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] logic-error

export -n deletes a name from the exported set without recording whether a child process already inherited it. For example export X=1; bash -c 'printenv X'; export -n X returns no names although the child received X. Prefix and env assignments are copied into seen, but ordinary shell-level exports are never snapshotted when a non-builtin command launches, which contradicts the function's documented child-environment contract.

Suggested fix: Before processing a non-builtin command launch, copy the currently exported names into seen. Keep the final export attributes separate so export X=1; export -n X with no intervening launch still returns no X. Add tests for an intervening external command and an intervening child shell.

default:
exported[name] = true
}
}
case "env":
Expand All @@ -119,17 +182,59 @@ func collectFromCommand(words []shellWord, seen map[string]bool, depth int) {
}
name := a.assignmentName()
if name == "" {
collectFromCommand(args[j:], seen, depth)
// env launches an external program, which cannot run the
// export builtin, so the command gets an isolated set.
collectFromCommand(args[j:], seen, map[string]bool{}, depth)
return
}
seen[name] = true
}
case "exec", "command", "nohup":
collectFromCommand(args, seen, depth)
case "builtin":
// builtin runs only a shell builtin, never an external program, so
// it launches no process itself. A target outside the shell's
// own export/command/exec/builtin dispatchers has no effect on
// export attributes, and a non-builtin target is an error.
if len(args) > 0 && args[0].text == "--" {
args = args[1:]
}
// The dispatched command keeps this command's prefix assignments,
// so "Y=1 builtin exec prog" still hands Y to prog.
if len(args) > 0 {
switch args[0].text {
case "export", "command", "exec", "builtin":

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] logic-error

The builtin dispatcher drops prefix assignments even when its target launches an external process (e.g. Y=1 builtin exec /usr/bin/env returns no names, whereas Bash passes Y to env). New low finding on a verified re-review, so advisory and not routed to the fix agent.

Suggested fix: Propagate prefix assignments through builtin dispatch and record them when the resolved target launches a process; add tests for prefixed builtin exec and builtin command.

target := append(slices.Clone(words[:i]), args...)
collectFromCommand(target, seen, exported, depth)
}
}
case "exec", "nohup":
collectFromCommand(args, seen, map[string]bool{}, depth)
case "command":
// Options end at "--" or the first non-option word. -v and -V
// only look the command up, and an option the builtin rejects
// runs nothing, so neither launches a process.
for j, a := range args {
if a.text == "--" {
collectFromCommand(args[j+1:], seen, exported, depth)
return
}
if !strings.HasPrefix(a.text, "-") || a.text == "-" {
collectFromCommand(args[j:], seen, exported, depth)
return
}
if strings.Trim(a.text[1:], "pvV") != "" || strings.ContainsAny(a.text[1:], "vV") {
return
}
}
case "sh", "bash", "/bin/sh", "/bin/bash":
for j, a := range args {
if strings.HasPrefix(a.text, "-") && strings.Contains(a.text, "c") && j+1 < len(args) {
collectExportedNames(args[j+1].text, seen, depth+1)
// The child shell has its own export attributes: its
// "export -n" cannot un-export a name in this shell.
child := map[string]bool{}
collectExportedNames(args[j+1].text, seen, child, depth+1)
for name := range child {
seen[name] = true
}
return
}
}
Expand Down
43 changes: 42 additions & 1 deletion internal/envmanifest/shellexports_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,48 @@ func TestExportedNames(t *testing.T) {
{"export with value", []string{"export FOO=bar"}, []string{"FOO"}},
{"bare re-export", []string{"export OPENCODE_CONFIG_CONTENT"}, []string{"OPENCODE_CONFIG_CONTENT"}},
{"several names in one export", []string{"export A=1 B C=3"}, []string{"A", "B", "C"}},
{"export flags are skipped", []string{"export -n FOO"}, []string{"FOO"}},
{"export -p flag is skipped", []string{"export -p BAR"}, []string{"BAR"}},
{"export -n does not export", []string{"export -n FOO"}, []string{}},
{"export -n retracts an earlier export", []string{"export FOO=bar; export -n FOO"}, []string{}},
{"export -n with a value retracts", []string{"export FOO=1", "export -n FOO=2"}, []string{}},
{"combined flags with n retract", []string{"export A B; export -pn A"}, []string{"B"}},
{"export after export -n exports", []string{"export -n FOO; export FOO=1"}, []string{"FOO"}},
{"export -n removes only its operands", []string{"export A B; export -n A"}, []string{"B"}},
{"double dash ends export options", []string{"export -n -- A; export -- B"}, []string{"B"}},
{"export -n keeps prefix assignments", []string{"FOO=1 cmd; export -n FOO"}, []string{"FOO"}},
{"export -n inside sh -c", []string{`sh -c 'export X=1; export -n X'`}, []string{}},
{"sh -c export -n does not reach the parent", []string{`export X=1; sh -c 'export -n X'`}, []string{"X"}},
{"export -n after an external command keeps the name", []string{"export X=1; cmd; export -n X"}, []string{"X"}},
{"export -n after a child shell keeps the name", []string{"export X=1; bash -c 'printenv X'; export -n X"}, []string{"X"}},
{"export -n after a builtin still retracts", []string{"export X=1; echo hi; readonly Y=2; export -n X"}, []string{}},
{"export -n after command export still retracts", []string{"export X=1; command export -n X"}, []string{}},
{"export -fn leaves the variable exported", []string{"export X=1; export -fn X"}, []string{"X"}},
{"export -f -n leaves the variable exported", []string{"export X=1; export -f -n X"}, []string{"X"}},
{"plain export -f does not export a variable", []string{"export -f FUNC"}, []string{}},
{"exec with no command launches nothing", []string{"export X=1; exec; export -n X"}, []string{}},
{"exec with a command launches a process", []string{"export X=1; exec true; export -n X"}, []string{"X"}},
{"export lone dash is an operand", []string{"export X=1; export - -n X"}, []string{"X"}},
{"invalid export option is a no-op", []string{"export X=1; export -notvalid X"}, []string{"X"}},
{"invalid export option does not export", []string{"export -xp X"}, []string{}},
{"command -v launches nothing", []string{"export X=1; command -v bash; export -n X"}, []string{}},
{"command -V launches nothing", []string{"export X=1; command -V bash; export -n X"}, []string{}},
{"command with invalid option launches nothing", []string{"export X=1; command -z bash; export -n X"}, []string{}},
{"command -p runs the command", []string{"export X=1; command -p cmd; export -n X"}, []string{"X"}},
{"command -- runs the command", []string{"export X=1; command -- cmd; export -n X"}, []string{"X"}},
{"command -p skips option words for export", []string{"export X=1; command -p export -n X"}, []string{}},
{"command with only options runs nothing", []string{"export X=1; command -p; export -n X"}, []string{}},
{"command after a lone dash runs it", []string{"export X=1; command - ; export -n X"}, []string{"X"}},
{"builtin true launches nothing", []string{"export X=1; builtin true; export -n X"}, []string{}},
{"builtin -- true launches nothing", []string{"export X=1; builtin -- true; export -n X"}, []string{}},
{"builtin export -n retracts", []string{"export X=1; builtin export -n X"}, []string{}},
{"builtin with a non-builtin launches nothing", []string{"export X=1; builtin cmd; export -n X"}, []string{}},
{"builtin exec runs a process", []string{"export X=1; builtin exec cmd; export -n X"}, []string{"X"}},
{"prefix assignment on builtin is not exported", []string{"Y=1 builtin true"}, []string{}},
{"prefix assignment on builtin exec reaches the process", []string{"Y=1 builtin exec /usr/bin/env"}, []string{"Y"}},
{"prefix assignment on builtin command reaches the process", []string{"Y=1 builtin command cmd"}, []string{"Y"}},
{"prefix assignment on nested builtin exec reaches the process", []string{"Y=1 builtin builtin exec cmd"}, []string{"Y"}},
{"prefix assignment on builtin -- true is not exported", []string{"Y=1 builtin -- true"}, []string{}},
{"env cannot run the export builtin", []string{"export X=1; env export -n X"}, []string{"X"}},
{"plain assignment is shell-local", []string{"FOO=bar"}, []string{}},
{"readonly assignment is shell-local", []string{"readonly FOO=bar"}, []string{}},
{"dropping export drops the name", []string{"PI_OFFLINE=1 && export PI_TELEMETRY=0"}, []string{"PI_TELEMETRY"}},
Expand Down
Loading