Skip to content
Merged
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
1 change: 1 addition & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ All external binaries run through `run_subprocess` / `run_subprocess_async` (`de
- Explicit bounded timeouts (default 1800 s) with standardized `TimeoutExpired` domain error translation.
- An audit-record writer (`devops_cli.core.audit.record_audit_event`, `.data/logs/audit.jsonl`) records each write of a config file (`save_settings`). It is not yet called from command or subprocess execution.
- Deterministic mock isolation protocols for fast offline unit testing, dry-run reporting, environment isolation, and OpenTelemetry spans.
- **Child environment**: `build_subprocess_env` gives a child the allowed keys of the environment without credentials, and the `env` of the caller on top. It refuses a caller key that makes the loader or the shell of the child load code (`CONST_CODE_LOADING_ENV_PATTERNS`: `LD_PRELOAD`, `LD_AUDIT`, every `DYLD_` key, `BASH_ENV`, every `BASH_FUNC_` key and more), and a null byte, with `SecurityError`. Give a child only the keys that it needs, never a copy of `os.environ`.
- **Subprocess spans**: A subprocess span holds the program and the number of its arguments. It holds the arguments only when `telemetry.capture_command_args` turns them on ([docs/TELEMETRY.md](docs/TELEMETRY.md)).
- **LLM inference spans**: AI inference spans omit prompt and response previews by default, and Logfire scrubs private host patterns. They record previews only when `telemetry.capture_llm_content` turns them on ([docs/TELEMETRY.md](docs/TELEMETRY.md)).
- **Process groups**: Start a child with `start_new_session=True`, and stop it by its process group (`os.killpg`), as `_terminate_process_group` in `src/devops_cli/sandbox/host.py` does. Do not signal a pid below 2, the own process group (`os.getpgrp()`) or a process group below 2.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-28
21 changes: 21 additions & 0 deletions openspec/changes/2205-refuse-code-loading-env-keys/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Design

## Decisions

- **One constant of `fnmatch` patterns.** `CONST_CODE_LOADING_ENV_PATTERNS` holds exact names (`LD_AUDIT`, `ENV`) and family patterns (`DYLD_*`, `BASH_FUNC_*`) in one tuple. `build_subprocess_env` already matches the credential patterns with `_is_env_var_denied`, which runs `fnmatch.fnmatchcase` on the upper-case key. The guard calls the same helper with the new constant, so one rule matches both kinds of entry and the case of the key has no effect.
- **The constant is in `config/constants.py`.** CONTRIBUTING.md says to declare each tuple that matches or filters values there, with the `CONST_` prefix. The issue proposed `src/devops_cli/core/process.py`, but the project rule decides. The constant is not a tunable value, so it is not in `config/defaults.py`.
- **The glibc keys are the four that choose which code loads.** `ld.so(8)` says that `LD_PRELOAD` and `LD_AUDIT` name objects to load and that `LD_LIBRARY_PATH` names the directories to search. `LD_ORIGIN_PATH` sets `$ORIGIN`, which the loader expands in the run path of a binary, in `LD_LIBRARY_PATH`, in `LD_PRELOAD` and in `LD_AUDIT`. glibc uses it when `/proc/self/exe` cannot be read (`sysdeps/unix/sysv/linux/dl-origin.c`). It thus chooses the library directory in a child that has no `/proc`.
- **Every `DYLD_` key.** All 20 variables of `dyld(1)` start with `DYLD_`. Most of them choose the code that loads. The others only print diagnostics. A pattern for the family also covers a key that a later macOS adds.
- **Every `BASH_FUNC_` key.** bash 5.3 writes `export -f <name>` as `BASH_FUNC_<name>%%`. Earlier patched forms of bash 4.3 used other suffixes. The pattern `BASH_FUNC_*` covers each suffix.
- **The Semgrep call gives only its own key.** `run_rule_pack_tests` gave `{**os.environ, "SEMGREP_ENABLE_VERSION_CHECK": "0"}` as the override. The guard checks each override key, so an exported bash function in the environment of the person stopped the call. The call now gives only `SEMGREP_ENABLE_VERSION_CHECK`. `semgrep 1.179.0 --version` and `semgrep --test --metrics off src/devops_cli/review/rules` passed with the environment that `build_subprocess_env` builds, which holds `PATH`, `HOME` and the other allowed keys and no credential.

## Rejected alternatives

- **Two constants: a set of exact keys and a tuple of prefixes.** The issue asks for one constant. Two constants need two match rules. The credential patterns of the same module show that one `fnmatch` tuple holds both kinds.
- **Refuse every `LD_` key.** `ld.so(8)` lists keys that do not load code, for example `LD_BIND_NOW`, `LD_DEBUG` and `LD_WARN`. They change the output or the time of symbol binding. `LD_PROFILE` names an object that is already loaded, and `LD_DEBUG_OUTPUT` and `LD_PROFILE_OUTPUT` name output files. The issue asks for the keys that load code.
- **Refuse the keys in the ambient environment too.** With `isolate_env=True`, the allowlist already removes every key of these families from the ambient environment. With `isolate_env=False`, the caller asks for the environment of the person as it is, and the person chose it.
- **Accept an override when its value is the same as the ambient value.** This keeps the full copy of the environment in `run_rule_pack_tests`, and the copy also gives Semgrep the credentials of the person. The cause is the full copy, so the change removes it.

## Non-goals

- Keys outside the loader and shell families that also load code, for example `GCONV_PATH` of glibc `iconv`, `PYTHONPATH`, `PERL5LIB` and `NODE_OPTIONS`. The issue limits the guard to the families of `ld.so(8)`, `dyld(1)` and bash.
46 changes: 46 additions & 0 deletions openspec/changes/2205-refuse-code-loading-env-keys/proposal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Proposal

## Why

Issue #2205: the subprocess environment guard refuses only six keys that make a child load or run code that its caller did not choose.

- `build_subprocess_env` in `src/devops_cli/core/process.py` refuses a caller override of `LD_PRELOAD`, `LD_LIBRARY_PATH`, `DYLD_INSERT_LIBRARIES`, `DYLD_LIBRARY_PATH`, `BASH_ENV` or `ENV`. The set is a local variable of the function.
- The guard accepts other keys of the same families. glibc loads each object that `LD_AUDIT` names into the child. The macOS loader reads more `DYLD_` keys, for example `DYLD_FRAMEWORK_PATH` and `DYLD_FALLBACK_LIBRARY_PATH`. A bash child defines a function from each `BASH_FUNC_<name>%%` key, and that function replaces a command of the same name.
- `run_rule_pack_tests` in `src/devops_cli/review/rules_pack.py` gives Semgrep the full ambient environment as its override (`{**os.environ, ...}`). Thus the guard checks every ambient key of that call. On a host where bash exports a function, such as `which` on Fedora and RHEL, the wider guard refuses `devops review rules test`. The full copy also gives Semgrep the credentials that `build_subprocess_env` removes from the environment of a child.

## What Changes

- The constant `CONST_CODE_LOADING_ENV_PATTERNS` in `src/devops_cli/config/constants.py` holds the refused key families as `fnmatch` patterns: `LD_AUDIT`, `LD_LIBRARY_PATH`, `LD_ORIGIN_PATH`, `LD_PRELOAD`, `DYLD_*`, `BASH_ENV`, `ENV` and `BASH_FUNC_*`. Its comment names the sources: glibc `ld.so(8)`, macOS `dyld(1)` and the function export of bash.
- `build_subprocess_env` matches the upper-case key of each caller override against that constant, with the same `fnmatchcase` helper that it uses for the credential patterns. A match raises the same `SecurityError` and error code as before. The local set in the function is deleted.
- `run_rule_pack_tests` gives Semgrep only its own override, `SEMGREP_ENABLE_VERSION_CHECK=0`. `build_subprocess_env` gives the rest of the environment, without credentials.
- `ARCHITECTURE.md` describes the guard in its section on safe subprocess execution.
- A caller override that the guard refuses is a message that a consumer sees, so the change carries a spec delta: the new capability `subprocess-environment`.
- This change fits one pull request.

## Capabilities

### New Capabilities

- `subprocess-environment`: which caller overrides of a child environment devops-cli refuses, and what a refusal reports.

### Modified Capabilities

None.

## Impact

- `src/devops_cli/config/constants.py`, `src/devops_cli/core/process.py`, `src/devops_cli/review/rules_pack.py`.
- `tests/test_subprocess_env_boundary.py`, `tests/test_review_rules_pack.py`.
- `ARCHITECTURE.md`.

## Feasibility

- The guard accepts the keys today. On `origin/main` at `bb46660c`, `build_subprocess_env(env={key: "x"})` returned the key for `LD_AUDIT`, `ld_audit`, `DYLD_FRAMEWORK_PATH`, `DYLD_FALLBACK_LIBRARY_PATH`, `DYLD_FALLBACK_FRAMEWORK_PATH` and `BASH_FUNC_x%%`, and raised `SecurityError` for `LD_PRELOAD`.
- glibc 2.43 (Debian 2.43-7) loads the object that `LD_AUDIT` names: `LD_AUDIT=/nonexistent/libaudit.so /bin/true` printed "ERROR: ld.so: object '/nonexistent/libaudit.so' cannot be loaded as audit interface". The `ld.so(8)` page of that system says that `LD_AUDIT` and `LD_PRELOAD` name objects to load, and that `LD_LIBRARY_PATH` names the directories to search. It says that `LD_ORIGIN_PATH` is the "Path where the binary is found". The glibc source (`sysdeps/unix/sysv/linux/dl-origin.c`) uses that value for `$ORIGIN` when `/proc/self/exe` cannot be read.
- bash 5.3.15 writes `export -f f` as the environment key `BASH_FUNC_f%%`. `env 'BASH_FUNC_git%%=() { echo "function ran instead of git"; }' bash -c 'git --version'` printed "function ran instead of git". `bash(1)` says that bash reads the file that `BASH_ENV` names before a script, and `ENV` in posix mode.
- The `dyld(1)` page of Apple (`apple-oss-distributions/dyld`, `doc/man/man1/dyld.1`) documents 20 variables, and all start with `DYLD_`. Among them, `DYLD_FRAMEWORK_PATH`, `DYLD_FALLBACK_FRAMEWORK_PATH`, `DYLD_FALLBACK_LIBRARY_PATH`, `DYLD_VERSIONED_LIBRARY_PATH`, `DYLD_VERSIONED_FRAMEWORK_PATH` and `DYLD_IMAGE_SUFFIX` select the code that loads. This system has no macOS loader, so the change cites the page and does not run it.
- `src/devops_cli/review/rules_pack.py` line 236 passes `{**os.environ, "SEMGREP_ENABLE_VERSION_CHECK": "0"}` as `env` to `run_subprocess`, which gives it to `build_subprocess_env` as the caller override.

## Existing Tool Considered

The family list is a closed domain that three manual pages define, so the change uses no parser. The match uses `fnmatch.fnmatchcase` of the standard library, as the credential patterns of the same module do. No maintained library publishes the set of environment keys that load code. The change deletes the local set `dangerous_env_keys` in `build_subprocess_env` and the full copy of the environment in `run_rule_pack_tests`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
## Purpose

Which caller overrides of the environment of a child process devops-cli refuses, because they make the dynamic loader or the shell of the child load or run code that the caller did not choose, and what a refusal reports.

## ADDED Requirements

### Requirement: A caller override that loads code into the child is refused
`build_subprocess_env` SHALL raise `SecurityError` with the message "Prohibited dangerous environment variable override: '<key>'" and the error code `SECURITY_ERROR` when the upper-case form of a key of the caller override is `LD_AUDIT`, `LD_LIBRARY_PATH`, `LD_ORIGIN_PATH`, `LD_PRELOAD`, `BASH_ENV` or `ENV`, or starts with `DYLD_` or `BASH_FUNC_`. It SHALL do this with environment isolation on and off.

#### Scenario: A glibc audit library
- **WHEN** a caller builds a child environment with the override `LD_AUDIT` or `ld_audit`
- **THEN** `build_subprocess_env` raises `SecurityError` that names the key, with the error code `SECURITY_ERROR`

#### Scenario: A macOS loader key
- **WHEN** a caller builds a child environment with the override `DYLD_FRAMEWORK_PATH`, `DYLD_FALLBACK_LIBRARY_PATH` or `DYLD_FALLBACK_FRAMEWORK_PATH`, in upper or lower case
- **THEN** `build_subprocess_env` raises `SecurityError` that names the key, with the error code `SECURITY_ERROR`

#### Scenario: An exported bash function
- **WHEN** a caller builds a child environment with the override `BASH_FUNC_x%%` or `bash_func_x%%`
- **THEN** `build_subprocess_env` raises `SecurityError` that names the key, with the error code `SECURITY_ERROR`

### Requirement: A caller override outside the refused families reaches the child
`build_subprocess_env` SHALL put each other key of the caller override in the child environment with its value, also a key that contains a refused name but does not start with it.

#### Scenario: Usual keys and keys that look like a refused key
- **WHEN** a caller builds a child environment with the overrides `PATH`, `HOME`, `ENVIRONMENT`, `EXAMPLE_DYLD_FLAG` and `BASH_FUNCTIONS`
- **THEN** the child environment holds each of these keys with its value

### Requirement: The rule pack test gives Semgrep only its own setting
`run_rule_pack_tests` SHALL give `semgrep --version` and `semgrep --test` the override `SEMGREP_ENABLE_VERSION_CHECK=0` and no other key, so the child gets the isolated environment that `build_subprocess_env` builds.

#### Scenario: An exported bash function and a token in the environment of the person
- **WHEN** the environment holds `BASH_FUNC_which%%` and `GITHUB_TOKEN`, and `run_rule_pack_tests` runs on a copy of the rule pack
- **THEN** `semgrep --version` and `semgrep --test` each start with the caller override `{"SEMGREP_ENABLE_VERSION_CHECK": "0"}` and no other key
26 changes: 26 additions & 0 deletions openspec/changes/2205-refuse-code-loading-env-keys/tasks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Tasks

## 1. The guard refuses every key of the loader and shell families

- [x] Add failing tests: a caller override of `LD_AUDIT`, `LD_ORIGIN_PATH`, `DYLD_FRAMEWORK_PATH`, `DYLD_FALLBACK_LIBRARY_PATH`, `DYLD_FALLBACK_FRAMEWORK_PATH` or `BASH_FUNC_x%%`, in upper and lower case, raises `SecurityError`; `PATH`, `HOME`, `ENVIRONMENT`, `EXAMPLE_DYLD_FLAG` and `BASH_FUNCTIONS` reach the child
- Verification: `uv run devops ci test tests/test_subprocess_env_boundary.py`
- [x] Add `CONST_CODE_LOADING_ENV_PATTERNS` with its sources to `config/constants.py`, match each override key against it in `build_subprocess_env`, and delete the local set `dangerous_env_keys`
- Verification: `uv run devops ci test tests/test_subprocess_env_boundary.py`

## 2. The rule pack test gives Semgrep only its own setting

- [x] Add a failing test: with `BASH_FUNC_which%%` and `GITHUB_TOKEN` in the environment, `run_rule_pack_tests` starts `semgrep --version` and `semgrep --test` with the caller override `SEMGREP_ENABLE_VERSION_CHECK=0` and no other key
- Verification: `uv run devops ci test tests/test_review_rules_pack.py`
- [x] Give `semgrep --version` and `semgrep --test` only the override `SEMGREP_ENABLE_VERSION_CHECK=0`, and delete the full copy of the environment
- Verification: `uv run devops ci test tests/test_review_rules_pack.py`

## 3. Documentation

- [x] Describe the guard in the safe subprocess execution section of `ARCHITECTURE.md`
- Verification: `uv run devops docs generate --sync-readme` and `uv run devops ci docs`

## 4. Archive

- [ ] Archive the change
- Verification: `uv run devops openspec archive 2205-refuse-code-loading-env-keys`
- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD).
17 changes: 17 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1572,6 +1572,23 @@ class WebhookExposure(StrEnum):
CONST_EXIT_ERROR_INFERENCE: int = 10
# The status the subprocess runners report when the program is not on PATH, as POSIX shells do.
CONST_EXIT_COMMAND_NOT_FOUND: int = 127
# The environment keys that make the dynamic loader or the shell of a child load or run code that
# its caller did not choose, as `fnmatch` patterns of the upper-case key. `build_subprocess_env`
# refuses a caller override that matches one (#2205). Sources: glibc ld.so(8), whose LD_AUDIT and
# LD_PRELOAD name objects to load, LD_LIBRARY_PATH the directories to search, and LD_ORIGIN_PATH
# the value of $ORIGIN; macOS dyld(1), whose variables all start with DYLD_; and bash(1), which
# reads the start-up file that BASH_ENV (ENV in posix mode) names and defines a function from each
# key that `export -f <name>` writes as BASH_FUNC_<name>%%.
CONST_CODE_LOADING_ENV_PATTERNS: Final[tuple[str, ...]] = (
"LD_AUDIT",
"LD_LIBRARY_PATH",
"LD_ORIGIN_PATH",
"LD_PRELOAD",
"DYLD_*",
"BASH_ENV",
"ENV",
"BASH_FUNC_*",
)
# uv's exit status for a check that ran and failed; it exits 2 when it could not run.
CONST_UV_EXIT_FAILURE: int = 1
# zizmor audits whose findings fail `devops scan workflows` and the `devops ci` gate (#861).
Expand Down
13 changes: 3 additions & 10 deletions src/devops_cli/core/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from typing import Any, Protocol

from devops_cli.config.constants import (
CONST_CODE_LOADING_ENV_PATTERNS,
CONST_EXIT_COMMAND_NOT_FOUND,
CONST_GH_AUTH_SUBCOMMAND,
CONST_GH_CLI,
Expand Down Expand Up @@ -131,7 +132,7 @@
def _is_env_var_denied(
key: str, denied_patterns: tuple[str, ...] = DEFAULT_DENIED_ENV_PATTERNS
) -> bool:
"""Predicate determining if an environment variable key matches sensitive credential patterns."""
"""Whether the upper-case key matches one of `denied_patterns`, by default the credentials."""
upper_key = key.upper()
return any(fnmatch.fnmatchcase(upper_key, pat) for pat in denied_patterns)

Expand Down Expand Up @@ -181,16 +182,8 @@ def build_subprocess_env(
if env:
from devops_cli.exceptions.security import SecurityError

dangerous_env_keys = {
"LD_PRELOAD",
"LD_LIBRARY_PATH",
"DYLD_INSERT_LIBRARIES",
"DYLD_LIBRARY_PATH",
"BASH_ENV",
"ENV",
}
for k, v in env.items():
if k.upper() in dangerous_env_keys:
if _is_env_var_denied(k, CONST_CODE_LOADING_ENV_PATTERNS):
raise SecurityError(f"Prohibited dangerous environment variable override: '{k}'")
if "\x00" in k or "\x00" in str(v):
raise SecurityError(f"Null byte in environment variable prohibited: '{k}'")
Expand Down
2 changes: 1 addition & 1 deletion src/devops_cli/review/rules_pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ def run_rule_pack_tests(
"""Run `semgrep --test` on `rules_dir` and write (or `--check` verify) `rules.lock`."""
if is_dry_run():
return build_rules_lock(rules_dir)
env = {**os.environ, "SEMGREP_ENABLE_VERSION_CHECK": "0"}
env = {"SEMGREP_ENABLE_VERSION_CHECK": "0"}
binary = _resolve_semgrep_binary()
version = _detect_semgrep_version(binary, env)
res = run_subprocess(
Expand Down
24 changes: 24 additions & 0 deletions tests/test_review_rules_pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
verify_rules_lock,
)
from devops_cli.security.semgrep import _files_command, parse_semgrep_json
from tests.support.fakes.process import ProcessAnswer, ProcessFake
from tests.support.paths import FIXTURES, REPO_ROOT

RECALL_SET_PATH = FIXTURES / "review_recall" / "recall_set.json"
Expand Down Expand Up @@ -213,6 +214,29 @@ def fake_fail(cmd: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str
) == (0, [], 2, RULE_ID, True, True)


def test_semgrep_gets_only_its_own_setting_and_not_the_environment_of_the_person(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, process_fake: ProcessFake
) -> None:
"""`semgrep --version` and `semgrep --test` get only `SEMGREP_ENABLE_VERSION_CHECK=0` as the
caller override, so an exported bash function or a token of the person neither reaches
Semgrep nor trips the guard on loader and shell keys (#2205)."""
pack_copy = tmp_path / "rules"
shutil.copytree(RULE_PACK_DIR, pack_copy)
monkeypatch.setenv("BASH_FUNC_which%%", '() { /usr/bin/which "$@"\n}')
monkeypatch.setenv("GITHUB_TOKEN", "example-token")
process_fake.answer(
lambda call: "--version" in call.argv,
ProcessAnswer(stdout=f"{pinned_semgrep_version()}\n"),
)

run_rule_pack_tests(pack_copy)

assert [(call.argv[1], call.env) for call in process_fake.calls] == [
("--version", {"SEMGREP_ENABLE_VERSION_CHECK": "0"}),
("--test", {"SEMGREP_ENABLE_VERSION_CHECK": "0"}),
]


def test_ci_workflow_runs_rule_pack_tests_when_rules_change() -> None:
"""`.github/workflows/ci.yml` defines a path-filtered `rule-pack` job outside `devops ci`."""
workflow = yaml.safe_load((REPO_ROOT / ".github" / "workflows" / "ci.yml").read_text("utf-8"))
Expand Down
Loading
Loading