Skip to content

feat(packagesettings): add ExternalCommands model for env filtering - #1266

Merged
mergify[bot] merged 1 commit into
python-wheel-build:mainfrom
tiran:external-commands-env-filter
Jul 27, 2026
Merged

feat(packagesettings): add ExternalCommands model for env filtering#1266
mergify[bot] merged 1 commit into
python-wheel-build:mainfrom
tiran:external-commands-env-filter

Conversation

@tiran

@tiran tiran commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator

Pull Request Description

What

Add ExternalCommands Pydantic model with keep_env / delete_env pattern lists, a filter_env() method, and a DEFAULT_KEEP_ENV class variable for essential variables (HOME, PATH, LC_*, etc.).

Not yet wired into external_commands.run().

Why

See: #1083

@tiran
tiran requested a review from a team as a code owner July 24, 2026 08:45
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds ExternalCommands with configurable environment-variable keep and delete patterns, regex-based matching, validation, and filtering behavior. Integrates the model into SettingsFile and Settings, re-exports it publicly, and adds tests and documentation covering configuration parsing, validation, and filtering semantics.

Estimated code review effort: 3 (Moderate) | ~25 minutes

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: adding an ExternalCommands model for environment filtering.
Description check ✅ Passed The description is directly related and summarizes the new ExternalCommands model and env filtering behavior.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify mergify Bot added the ci label Jul 24, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fromager/packagesettings/_models.py`:
- Around line 176-182: Add a concise docstring to the public
ExternalCommands.model_post_init override describing its environment-pattern
initialization, while preserving the existing delete_env and keep_env behavior.

In `@tests/test_packagesettings.py`:
- Around line 970-988: Update test_external_commands_valid to verify
ExternalCommands instances are frozen by attempting to assign a field and
asserting pydantic.ValidationError is raised. Keep the existing
valid-configuration assertions unchanged and retain the docstring’s
frozen-behavior claim.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 453aa429-40c9-4b5e-8ec1-c72cd6118d4d

📥 Commits

Reviewing files that changed from the base of the PR and between 79a9e08 and 3e3c63a.

📒 Files selected for processing (4)
  • src/fromager/packagesettings/__init__.py
  • src/fromager/packagesettings/_models.py
  • src/fromager/packagesettings/_settings.py
  • tests/test_packagesettings.py

Comment thread src/fromager/packagesettings/_models.py Outdated
Comment thread tests/test_packagesettings.py
@rd4398
rd4398 requested a review from smoparth July 24, 2026 13:06

@rd4398 rd4398 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This looks good! I have left couple of suggestions that are non blocking and can be done in a follow up

Comment thread src/fromager/packagesettings/_models.py
Comment thread src/fromager/packagesettings/_models.py
@tiran
tiran force-pushed the external-commands-env-filter branch from 3e3c63a to 062cd8e Compare July 24, 2026 13:55
@tiran

tiran commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator Author

@Mergifyio rebase

@mergify

mergify Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

rebase

🛑 The pull request rule doesn't match anymore

Details

This action has been cancelled.

@tiran
tiran force-pushed the external-commands-env-filter branch 2 times, most recently from eef968a to 5edf620 Compare July 24, 2026 14:34
@tiran
tiran requested a review from rd4398 July 24, 2026 14:52
Comment thread src/fromager/packagesettings/_models.py
Comment thread src/fromager/packagesettings/_models.py Outdated
Comment thread src/fromager/packagesettings/_models.py
Comment thread src/fromager/packagesettings/_models.py
Comment thread src/fromager/packagesettings/_models.py
rd4398
rd4398 previously approved these changes Jul 24, 2026

@rd4398 rd4398 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This looks good to me! I am moving forward and approving this.
cc @LalatenduMohanty @smoparth

@tiran

tiran commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator Author

@Mergifyio rebase

@mergify

mergify Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

rebase

🛑 The pull request rule doesn't match anymore

Details

This action has been cancelled.

@tiran
tiran force-pushed the external-commands-env-filter branch from 5edf620 to 951de65 Compare July 24, 2026 15:24

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fromager/packagesettings/_models.py`:
- Around line 155-172: Update validate_delete_env to detect wildcard pattern
overlaps between delete_env and DEFAULT_KEEP_ENV or keep_env, not only exact
string matches. Use the same full-match semantics as _keep_re to identify any
delete entry that would also be retained by a keep pattern, and raise the
existing validation error with the conflicting entries; preserve the bare-* and
non-overlapping behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c15c95c8-f8a9-4ac3-b739-4cb5e098e86b

📥 Commits

Reviewing files that changed from the base of the PR and between 3e3c63a and 951de65.

📒 Files selected for processing (4)
  • src/fromager/packagesettings/__init__.py
  • src/fromager/packagesettings/_models.py
  • src/fromager/packagesettings/_settings.py
  • tests/test_packagesettings.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/fromager/packagesettings/init.py
  • tests/test_packagesettings.py
  • src/fromager/packagesettings/_settings.py

Comment thread src/fromager/packagesettings/_models.py
@tiran
tiran force-pushed the external-commands-env-filter branch from 951de65 to 3cabc3f Compare July 27, 2026 08:57
@tiran

tiran commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator Author

@smoparth Thanks for the feedback! I have deviated slightly from my original proposal to address some design flaws. I like to protect users from misconfiguration. For example I included the POSIX compliance check for env var names to prevent typos like delete_env: [BOT-PAT].

Here is a full diff between the initial commit and the current implementation (generated by Claude)

Proxy variables removed from DEFAULT_KEEP_ENV

http_proxy, https_proxy, and no_proxy were removed from the
always-keep set. These variables can contain basic-auth credentials
(e.g. http_proxy=http://user:password@proxy.example:3128/) and
should not be passed to untrusted build scripts by default. Add them
to keep_env explicitly if your environment requires proxy access
during builds.

Additional variables added to DEFAULT_KEEP_ENV

  • TERM -- controls terminal capability detection; without it
    programs using ncurses/readline can produce garbled output.
  • TZ -- timezone; affects timestamps in logs and build metadata.
  • TEMP, TMP, TMPDIR -- honoured by Python's tempfile module
    and many build tools for temporary file placement.

Non-POSIX environment variable keys are always removed

filter_env() unconditionally strips keys that are not valid POSIX
names ([A-Za-z_][A-Za-z0-9_]*). This removes keys with dashes,
dots, embedded spaces, or bash-exported function definitions
(BASH_FUNC_*%%).

In practice a user has to go out of their way to create such variables
-- common shells refuse them:

$ export invalid-example=value
bash: export: `invalid-example=value': not a valid identifier

They can only appear when a program manipulates the environment
directly (e.g. via os.environ in Python or setenv() in C). No
legitimate build tool relies on non-POSIX keys.

delete_env matching is case-insensitive

delete_env patterns are matched case-insensitively for convenience
and security. A pattern like aws_* removes AWS_SECRET_ACCESS_KEY
regardless of casing, so credentials cannot slip through due to
unexpected capitalisation.

keep_env and the always-keep set remain case-sensitive, matching the
exact variable names used in practice.

@smoparth smoparth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Left a non-blocking comment from maintenance perspective.

Comment thread src/fromager/packagesettings/_models.py
Comment thread src/fromager/packagesettings/_models.py
Add `ExternalCommands` Pydantic model with `keep_env` / `delete_env`
pattern lists, a `filter_env()` method, and a `DEFAULT_KEEP_ENV`
class variable for essential variables (HOME, PATH, LC_*, TERM, TZ,
TMPDIR, etc.).

`delete_env` matching is case-insensitive so credentials cannot slip
through due to unexpected capitalisation.  Non-POSIX env var keys are
always stripped by `filter_env()`.

Not yet wired into `external_commands.run()`.

See: python-wheel-build#1083
Co-Authored-By: Claude <claude@anthropic.com>
Signed-off-by: Christian Heimes <cheimes@redhat.com>
@tiran
tiran force-pushed the external-commands-env-filter branch from 3cabc3f to 680d644 Compare July 27, 2026 14:06

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/fromager/packagesettings/_models.py (1)

170-192: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Overlap check still only catches exact-string collisions, not wildcard conflicts.

This is the same gap flagged in a previous review round: delete_env=["AWS_SECRET_KEY"] combined with keep_env=["AWS_*"] (or any DEFAULT_KEEP_ENV wildcard) passes validation, but at runtime _keep_re will fullmatch AWS_SECRET_KEY and filter_env keeps it anyway — silently defeating the user's explicit intent to strip that variable. The added comment (lines 180-184) documents the limitation but doesn't fix it.

🔐 Proposed fix: detect pattern-level overlap, not just exact matches
+def _patterns_conflict(a: str, b: str) -> bool:
+    """True if pattern *a* would also match anything pattern *b* matches (or vice versa)."""
+    a_base, a_wild = a.rstrip("*"), a.endswith("*")
+    b_base, b_wild = b.rstrip("*"), b.endswith("*")
+    if a_wild and b_wild:
+        return a_base.startswith(b_base) or b_base.startswith(a_base)
+    if a_wild:
+        return b_base.startswith(a_base)
+    if b_wild:
+        return a_base.startswith(b_base)
+    return a_base == b_base
+
+
 `@pydantic.model_validator`(mode="after")
 def validate_delete_env(self) -> typing.Self:
     """Validate ``delete_env`` for conflicts and redundancy."""
     if not self.delete_env:
         return self
     if "*" in self.delete_env and len(self.delete_env) > 1:
         raise ValueError(
             "delete_env: bare '*' must be the only entry, "
             "additional patterns are redundant"
         )
     keep = set(self.DEFAULT_KEEP_ENV) | set(self.keep_env)
-    overlap = keep & set(self.delete_env)
+    overlap = {
+        d for d in self.delete_env if any(_patterns_conflict(k, d) for k in keep)
+    }
     if overlap:
         raise ValueError(
             f"delete_env overlaps with keep_env / DEFAULT_KEEP_ENV: "
             f"{sorted(overlap)}"
         )
     return self
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fromager/packagesettings/_models.py` around lines 170 - 192, Update
validate_delete_env in the package settings model to detect wildcard pattern
conflicts, not only exact-string overlap. Compare each delete_env entry against
keep_env and DEFAULT_KEEP_ENV using the same fullmatch semantics as _keep_re, so
values such as AWS_SECRET_KEY conflict with AWS_* and equivalent wildcard
combinations are rejected while preserving the existing bare-* validation and
error behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/proposals/filter-env.md`:
- Around line 83-86: Update the no-configuration behavior in the proposal to
state that empty keep_env and delete_env settings still sanitize the environment
by removing keys that are not valid POSIX names, while leaving valid keys
unfiltered. Reconcile the earlier “no filtering” wording with this default
sanitization behavior and retain the existing unconditional-removal rule.

---

Duplicate comments:
In `@src/fromager/packagesettings/_models.py`:
- Around line 170-192: Update validate_delete_env in the package settings model
to detect wildcard pattern conflicts, not only exact-string overlap. Compare
each delete_env entry against keep_env and DEFAULT_KEEP_ENV using the same
fullmatch semantics as _keep_re, so values such as AWS_SECRET_KEY conflict with
AWS_* and equivalent wildcard combinations are rejected while preserving the
existing bare-* validation and error behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 10260aed-ec3b-452e-a3e7-8a66dd7d0368

📥 Commits

Reviewing files that changed from the base of the PR and between 951de65 and 680d644.

📒 Files selected for processing (5)
  • docs/proposals/filter-env.md
  • src/fromager/packagesettings/__init__.py
  • src/fromager/packagesettings/_models.py
  • src/fromager/packagesettings/_settings.py
  • tests/test_packagesettings.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/fromager/packagesettings/init.py
  • src/fromager/packagesettings/_settings.py
  • tests/test_packagesettings.py

Comment thread docs/proposals/filter-env.md

@smoparth smoparth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Thanks for bearing with me and all detailed explanations ; )

@rd4398 rd4398 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

@mergify
mergify Bot merged commit ebbd889 into python-wheel-build:main Jul 27, 2026
39 checks passed
@mergify

mergify Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants