Skip to content

fix(autoresearch): allowlist COMn before interpolating into PowerShell - #3874

Merged
zackees merged 3 commits into
masterfrom
fix/usb-power-powershell-injection
Aug 7, 2026
Merged

zackees merged 3 commits into
masterfrom
fix/usb-power-powershell-injection

Conversation

@zackees

@zackees zackees commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #3873. Those review fixes were pushed to the branch after #3873 had already been squash-merged, so they never reached master — this carries them over, rebased onto master.

The security fix is the reason this matters. It is currently live on master.

1. PowerShell injection via --upload-port

port was interpolated straight into a single-quoted PowerShell literal:

Where-Object { $_.FriendlyName -match '\(COM17\)' }

A value containing ' closes that string and runs arbitrary PowerShell as the invoking user. Now refused by allowlist (^COM\d+$); rejected values never spawn the subprocess at all.

Allowlist rather than [regex]::Escape, deliberately. Escaping here needs two independent layers to be correct — PowerShell quoting and regex metacharacters, since the value lands inside -match — and getting either wrong reintroduces the hole silently. A COM port name has no legitimate reason to contain anything outside COM\d+.

The same pattern existed in hub_chain_power_off from #3872; guarded too.

It also fixes a real bug, which is what makes it more than hardening. --upload-port legitimately accepts UF2=E:\ for a board already in BOOTSEL. That trailing backslash would have corrupted the -match regex. It names a volume rather than a COM device, so there is nothing to look up — it now returns "unknown", and because unknown is permissive, a UF2 deploy is never blocked by the preflight.

2. Typed PortPresence instead of a tuple

parse_presence/port_presence returned a bare (Optional[bool], Optional[int]) that absent_port_error unpacked positionally. Both fields are optional and neither is self-describing, so swapping them would still type-check while silently inverting the meaning of the check — on the one function that decides whether to abort a run.

PortPresence is frozen and @typechecked, matching the ChipDetectionResult convention in ci/util/port_utils.py. Its docstring now carries the tri-state rule that was buried in parse_presence: present=None means "the host could not say" and must never be read as "absent".

Also sets the text language on the diagnostic fence in hardware-autoresearch.md (markdownlint MD040).

Validation

Live, against the real bench — not only the injected fakes:

COM17   -> PortPresence(present=False, last_seen_secs=483088)   # absent, 5d
COM9    -> PortPresence(present=True,  last_seen_secs=32196)    # attached C6
UF2=E:\ -> PortPresence(present=None,  last_seen_secs=None)     # refused
COM1'); calc; (' -> PortPresence(present=None, last_seen_secs=None)

Four new regression tests: a quote-bearing port, the UF2= form, the hub-chain path, and one pinning that real ports (COM9, COM17, com3, COM255) still resolve — a guard that broke the actual use case would be worse than the bug. The hostile-input tests assert the runner is never invoked, not merely that the result is empty.

uv run pytest ci/tests/test_usb_power.py — 20 passed. bash lint clean.

Expected CI

Two reds are pre-existing on master, not from this PR (which touches only Python and one markdown file):

Refs #3864

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved USB power monitoring with clearer presence and last-seen status reporting.
    • Added safeguards to reject invalid or unsafe port names before system checks.
    • Prevented absent-port handling from failing for supported non-COM configurations.
    • Improved validation of USB hub-chain queries.
    • Added stronger handling for unknown or incomplete device-presence information.
  • Documentation

    • Corrected syntax highlighting for the documented upload-port preflight error.

zackees and others added 2 commits August 7, 2026 12:39
Addresses both CodeRabbit findings on #3873.

`parse_presence`/`port_presence` returned a bare `(Optional[bool],
Optional[int])` that `absent_port_error` unpacked positionally. Both fields
are optional and neither is self-describing at the call site, so a swap
would type-check and silently invert the meaning of the check — on a
function whose entire job is deciding whether to abort a run.

`PortPresence` is frozen and `@typechecked`, matching the dataclass-result
convention already used by `ChipDetectionResult` in ci/util/port_utils.py.
Its docstring now carries the tri-state rule that was previously buried in
`parse_presence`: `present=None` means "the host could not say" and must
never be read as "absent".

Also sets the `text` language on the diagnostic fence in
hardware-autoresearch.md (markdownlint MD040).

Re-verified live after the refactor, not just against the fakes:

    COM17: PortPresence(present=False, last_seen_secs=482667)   # 5d, absent
    COM9 : PortPresence(present=True,  last_seen_secs=31776)    # attached

`uv run pytest ci/tests/test_usb_power.py` — 16 passed. `bash lint` clean
(warn-only checkers unchanged).

Refs #3864

Co-Authored-By: Claude <[email protected]>
Addresses the third CodeRabbit finding on #3873 (Security, Major).

`port` came from `--upload-port` and was interpolated straight into a
single-quoted PowerShell literal:

    Where-Object { $_.FriendlyName -match '\(COM17\)' }

A value containing `'` closes that string and runs arbitrary PowerShell as
the invoking user. Now refused by allowlist (`^COM\d+$`) rather than
escaped, and the subprocess is never spawned for a rejected value.

Allowlist over escaping on purpose. Escaping here needs two independent
layers to be correct — PowerShell quoting *and* regex metacharacters, since
the value lands inside `-match` — and getting either wrong reintroduces the
hole silently. A COM port name has no legitimate reason to contain anything
outside `COM\d+`.

It is also a correctness fix, which is what makes it more than hardening:
`--upload-port` legitimately accepts `UF2=E:\` for a board already in
BOOTSEL. That trailing backslash would corrupt the `-match` regex. It names
a volume, not a COM device, so there is nothing to look up — it now returns
"unknown" and, because unknown is permissive, a UF2 deploy is never blocked
by the preflight. Verified: `port_presence("UF2=E:\\")` -> unknown.

Applied the same guard to `hub_chain_power_off`, which had the identical
pattern from #3872.

Four regression tests: a quote-bearing port, the `UF2=` form, the hub-chain
path, and one pinning that real ports (`COM9`, `COM17`, `com3`, `COM255`)
still work — a guard that broke the actual use case would be worse than the
bug. The hostile-input tests assert the runner is never called at all, not
merely that the result is empty.

Live: COM17 -> present=False/482925s, COM9 -> present=True/32035s.
20 tests pass; `bash lint` clean.

Refs #3864

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7c6426ae-7741-43ae-9d60-ee3cbbde9409

📥 Commits

Reviewing files that changed from the base of the PR and between 9dce3be and 51baf5e.

📒 Files selected for processing (2)
  • ci/autoresearch/usb_power.py
  • ci/tests/test_usb_power.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • ci/autoresearch/usb_power.py

📝 Walkthrough

Walkthrough

The USB power helpers now return typed presence results, validate plain COMn names before shell execution, and update consumers and tests for the new result structure. The hardware documentation labels a diagnostic output block as text.

Changes

USB presence validation

Layer / File(s) Summary
Structured presence contract
ci/autoresearch/usb_power.py
Adds frozen PortPresence results with tri-state presence and nullable arrival age. Parsing and port queries return this structure and reject invalid port inputs before PowerShell execution.
Guarded consumers and validation
ci/autoresearch/usb_power.py, ci/tests/test_usb_power.py, agents/docs/hardware-autoresearch.md
Consumers read structured presence fields. Hub-chain queries validate COM names. Tests cover unknown results, hostile names, non-COM ports, and valid case-insensitive COM names. The diagnostic code block uses text highlighting.

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

Possibly related PRs

  • FastLED/FastLED#3872: Extends the USB presence and COM-port validation logic, including hub-chain queries and tests.
  • FastLED/FastLED#3873: Updates USB presence consumers and tests for validated PortPresence objects and COM-port allowlisting.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main security fix: validating COMn ports before PowerShell interpolation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/usb-power-powershell-injection

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.

@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 `@ci/autoresearch/usb_power.py`:
- Around line 37-39: Update the COM-port validation in both port_presence() and
hub_ports() to use full-string matching so values such as "COM1\n" are rejected
while valid plain COMn names remain accepted. Add no-shell-out coverage for
trailing-newline inputs.
🪄 Autofix

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: 26878eeb-d832-4c03-8964-87f86b054161

📥 Commits

Reviewing files that changed from the base of the PR and between 6a120de and 9dce3be.

📒 Files selected for processing (3)
  • agents/docs/hardware-autoresearch.md
  • ci/autoresearch/usb_power.py
  • ci/tests/test_usb_power.py

Comment thread ci/autoresearch/usb_power.py Resolved
CodeRabbit caught a hole in the allowlist from the previous commit.

In Python `$` matches before a final newline, so:

    re.match(r"^COM\d+$", "COM1\n")      -> match
    re.fullmatch(r"^COM\d+$", "COM1\n")  -> None

Both callers used `match`, so `COM1\n` was accepted and reached the
PowerShell script construction it was supposed to be barred from.

Routed both through a single `_is_com_port()` helper using `fullmatch`,
rather than fixing the two call sites independently — one guard is harder
to get inconsistently wrong than two, and the next caller inherits it. The
`^`/`$` anchors stay as belt-and-braces for anyone who reaches for `match`
out of habit, with the reason recorded next to the pattern.

The regression test covers the whole shape of the mistake, not just the
reported input: `COM1\n`, `COM1\r\n`, and leading/trailing space and tab.
It also asserts the runner is never invoked, so a future "fix" that merely
returns empty after shelling out still fails.

Verified: `port_presence("COM1\n")` -> unknown, `port_presence("COM17")`
-> present=False/486027s (still absent, unchanged). 21 tests pass; lint
clean.

Refs #3864

Co-Authored-By: Claude <[email protected]>
@zackees
zackees merged commit 2e2ae7a into master Aug 7, 2026
19 of 21 checks passed
@zackees
zackees deleted the fix/usb-power-powershell-injection branch August 7, 2026 21:15
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant