Repository navigation
fix(autoresearch): allowlist COMn before interpolating into PowerShell - #3874
Conversation
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]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe USB power helpers now return typed presence results, validate plain ChangesUSB presence validation
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
agents/docs/hardware-autoresearch.mdci/autoresearch/usb_power.pyci/tests/test_usb_power.py
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]>
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-portportwas interpolated straight into a single-quoted PowerShell literal: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 outsideCOM\d+.The same pattern existed in
hub_chain_power_offfrom #3872; guarded too.It also fixes a real bug, which is what makes it more than hardening.
--upload-portlegitimately acceptsUF2=E:\for a board already in BOOTSEL. That trailing backslash would have corrupted the-matchregex. 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
PortPresenceinstead of a tupleparse_presence/port_presencereturned a bare(Optional[bool], Optional[int])thatabsent_port_errorunpacked 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.PortPresenceis frozen and@typechecked, matching theChipDetectionResultconvention inci/util/port_utils.py. Its docstring now carries the tri-state rule that was buried inparse_presence:present=Nonemeans "the host could not say" and must never be read as "absent".Also sets the
textlanguage on the diagnostic fence inhardware-autoresearch.md(markdownlint MD040).Validation
Live, against the real bench — not only the injected fakes:
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 lintclean.Expected CI
Two reds are pre-existing on master, not from this PR (which touches only Python and one markdown file):
teensy41 all—undefined reference to SPIClass::*; master's owncheck_teensy41_sizefails with "no .bin/.uf2 file found" (ci(teensy41): all-examples link omits Audio and Adafruit_NeoPixel implementations #3838, fix(teensy): select framework libraries from generated sketches fbuild#1265).esp32s3 all— hits its 45-minute bound; cancelled on 10 of the last 10 master runs (ci: every esp32s3 run since 20:39Z hangs in_progress and never completes (all branches, incl. master) #3791, data posted there).Refs #3864
🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Documentation