Repository navigation
fix(agent): defend against @ in var names at all template-split sites - #16469
Conversation
While fixing infiniflow#16467 (IterationItem crash on `@` in user-defined output keys), a follow-up audit of `agent/**/*.py` revealed three additional sites that unpack `str.split("@")` without `maxsplit=1`. They look safe under the current `variable_ref_patt` regex but will raise `ValueError: too many values to unpack` if the var_nm ever contains `@` (e.g. user-defined output keys like `user@email`, or a future relaxation of the var-name character class). This is defense-in-depth hardening, not a behavior change: the regex still constrains var_nm to `[A-Za-z0-9_.-]+` for inputs that flow through `get_value_with_variable`, so single-`@` templates resolve exactly as before. The `maxsplit=1` only kicks in when the trailing side itself contains `@`, which is currently unreachable from the public DSL surface. Sites hardened (all use `split("@", 1)` so the trailing var keeps any embedded `@`): - agent/canvas.py:201 Graph.get_variable_value - agent/canvas.py:254 Graph.set_variable_value - agent/component/base.py:538 ComponentBase.get_input_elements_from_text - agent/component/iterationitem.py:82 IterationItem.output_collation Sites already safe (left alone): - agent/canvas.py:708 Graph.is_reff (uses `len(arr) != 2` guard) - other call sites use `rsplit` or pre-validate via regex Regression tests added (9 total, all `pytest.mark.p2`): - test/unit_test/agent/test_canvas_at_split.py (6 tests) - test/unit_test/agent/component/test_iterationitem_at_split.py (3 tests) Each test was verified to fail with `ValueError: too many values to unpack (expected 2)` when the corresponding fix is reverted, confirming they actually catch the bug rather than just exercising the happy path. Closes infiniflow#16467
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThree agent parsing paths now split ChangesDefensive @ splitting across agent parsing sites
Estimated code review effort: 2 (Simple) | ~10 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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.
🧹 Nitpick comments (1)
agent/component/base.py (1)
538-543: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a direct regression test for this split site.
The new suites here exercise
GraphandIterationItem, but nothing in the provided tests hitsComponentBase.get_input_elements_from_text, so this hardening can regress silently. A small isolated test around this method would close the gap.🤖 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 `@agent/component/base.py` around lines 538 - 543, Add a direct regression test for ComponentBase.get_input_elements_from_text to cover the exp.split("@", 1) hardening path. The current Graph and IterationItem tests do not exercise this split site, so add a focused unit test that invokes get_input_elements_from_text with input containing an @ in the trailing portion and asserts it does not raise or misparse. Use the ComponentBase method name and the exp parsing branch as the target for locating the fix.
🤖 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.
Nitpick comments:
In `@agent/component/base.py`:
- Around line 538-543: Add a direct regression test for
ComponentBase.get_input_elements_from_text to cover the exp.split("@", 1)
hardening path. The current Graph and IterationItem tests do not exercise this
split site, so add a focused unit test that invokes get_input_elements_from_text
with input containing an @ in the trailing portion and asserts it does not raise
or misparse. Use the ComponentBase method name and the exp parsing branch as the
target for locating the fix.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 92feac7e-77c1-496f-b396-be05ab9b0963
📒 Files selected for processing (5)
agent/canvas.pyagent/component/base.pyagent/component/iterationitem.pytest/unit_test/agent/component/test_iterationitem_at_split.pytest/unit_test/agent/test_canvas_at_split.py
Auto-formatting cleanup for the files touched by the previous hardening commit (78f823b). No semantic changes: - agent/canvas.py: quote style, whitespace, multi-line collapse, blank-line normalization, regex char-class unicode case - agent/component/base.py: import sort order, blank lines, quote style, multi-line collapse - agent/component/iterationitem.py: blank lines, one spacing fix - test/unit_test/agent/test_canvas_at_split.py: quote style, multi-line collapse, trailing newline - test/unit_test/agent/component/test_iterationitem_at_split.py: multi-line collapse, trailing newline All 4 `split("@", 1)` hardening sites and the 9 regression tests remain functionally identical (9 passed).
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
agent/component/base.py (1)
512-520: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winThis hardening still misses
@inside template variable names.Line 512 still filters refs through
variable_ref_patt, and that pattern only allows[A-Za-z0-9_.-]+on the right-hand side. So{{cpn@foo@bar}}never reaches Line 519, which means the text-template path remains unhandled even though the split is now bounded. Please widen the matcher (or stop relying on it for tokenization) in the same fix.🤖 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 `@agent/component/base.py` around lines 512 - 520, The tokenization in the variable-reference parsing path still excludes template variable names containing @ because variable_ref_patt only matches the old restricted form. Update the parsing logic in the same area as the re.finditer loop and exp.split("@", 1) handling so refs like cpn@foo@bar are matched and preserved instead of being dropped, either by widening variable_ref_patt or by parsing the token without relying on that matcher.agent/canvas.py (1)
169-206: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winKeep reference recognition consistent with the new bounded split.
Line 206 preserves
var_nmvalues containing@, but direct input refs can still be rejected before reaching this method:ComponentBase.get_inputgates throughGraph.is_reff, whosesplit("@")/len(arr) == 2logic still treats{cpn@foo@bar}as non-reference. The regex on Line 170 also won’t match template refs with embedded@in the trailing side.🐛 Proposed fix
- pat = re.compile(r"\{* *\{([a-zA-Z:0-9]+@[A-Za-z0-9_.-]+|sys\.[A-Za-z0-9_.]+|env\.[A-Za-z0-9_.]+)\} *\}*") + pat = re.compile(r"\{* *\{([a-zA-Z:0-9]+@[^\s{}]+|sys\.[A-Za-z0-9_.]+|env\.[A-Za-z0-9_.]+)\} *\}*")def is_reff(self, exp: str) -> bool: exp = exp.strip("{").strip("}") if exp.find("@") < 0: return exp in self.globals - arr = exp.split("@") - if len(arr) != 2: + cpn_id, var_nm = exp.split("@", 1) + if not cpn_id or not var_nm: return False - if self.get_component(arr[0]) is None: + if self.get_component(cpn_id) is None: return False return True🤖 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 `@agent/canvas.py` around lines 169 - 206, Keep reference parsing consistent with the new get_variable_value split logic: get_value_with_variable currently won’t recognize template refs whose trailing variable part contains “@”, and Graph.is_reff / ComponentBase.get_input still reject them by using a strict two-part split. Update the reference detection and regex handling so inputs like cpn@foo@bar are treated as valid references and flow through to get_variable_value without being filtered out early.
🤖 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.
Outside diff comments:
In `@agent/canvas.py`:
- Around line 169-206: Keep reference parsing consistent with the new
get_variable_value split logic: get_value_with_variable currently won’t
recognize template refs whose trailing variable part contains “@”, and
Graph.is_reff / ComponentBase.get_input still reject them by using a strict
two-part split. Update the reference detection and regex handling so inputs like
cpn@foo@bar are treated as valid references and flow through to
get_variable_value without being filtered out early.
In `@agent/component/base.py`:
- Around line 512-520: The tokenization in the variable-reference parsing path
still excludes template variable names containing @ because variable_ref_patt
only matches the old restricted form. Update the parsing logic in the same area
as the re.finditer loop and exp.split("@", 1) handling so refs like cpn@foo@bar
are matched and preserved instead of being dropped, either by widening
variable_ref_patt or by parsing the token without relying on that matcher.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: cd6102d7-8e7e-4607-8fe7-7ce931019ada
📒 Files selected for processing (5)
agent/canvas.pyagent/component/base.pyagent/component/iterationitem.pytest/unit_test/agent/component/test_iterationitem_at_split.pytest/unit_test/agent/test_canvas_at_split.py
🚧 Files skipped from review as they are similar to previous changes (3)
- agent/component/iterationitem.py
- test/unit_test/agent/component/test_iterationitem_at_split.py
- test/unit_test/agent/test_canvas_at_split.py
Bring test_canvas_at_split.py from 62% to 87% and test_iterationitem_at_split.py from 50% to 100% docstring coverage, clearing the CodeRabbit docstring-coverage warning. Docstrings added (Google-style Args/Returns where applicable): - _load_canvas_module + nested _stub_module + _ComponentBaseStub - _load_iterationitem_module + nested _RetCode, _ComponentBaseStub, _ComponentParamBaseStub - output/set_output on _ParentStub, output/set_output/get_parent on _ChildStub, get_component_obj on _CanvasStub No production code changes; all 9 tests still pass.
|
Addressed all three CodeRabbit warnings in commit 1. Docstring Coverage 15% → 87% / 100%Added Google-style docstrings to all helpers and inline stubs in both test files:
Docstrings added on 2. Linked IssuesRemoved 3. Out of Scope ChangesSame fix as #2 — the body now explicitly states the primary fix lives in #16468 and frames this PR as a hardening sweep found during that audit. All 9 tests still pass: |
|
@skbs-eng Cloud you fix conflicts? |
Resolve conflicts introduced by main's agent token-usage reporting additions while keeping PR infiniflow#16469's @-split hardening intact: - agent/canvas.py: keep both 'common.misc_utils' and the new 'common.token_utils' imports; preserve 'usage: self._run_usage_payload()' in both 'workflow_finished' emit sites; preserve the new '_run_usage_payload()' helper method. - agent/component/base.py: restore PEP-8 blank lines between import groups (origin/main had them; this PR's ruff-format pass had removed them). - test/unit_test/agent/test_canvas_at_split.py: stub the new 'common.token_utils' module so the canvas loader stub graph matches the post-merge import surface; the token_utils module pulls in tiktoken at import time and is unused by get_variable_value / set_variable_value. All 9 regression tests pass.
|
Conflicts fixed — merged Resolved blocks (4 total):
All 9 regression tests pass ( |
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 `@agent/canvas.py`:
- Around line 162-176: The close() cleanup path in Canvas is swallowing
MCPToolCallSession.close_sync() failures with a bare except, which hides
shutdown problems. Update close() to log the exception when
tool.close_sync(timeout=3) fails, using the existing logging pattern in
agent/canvas.py or a Canvas logger if available. Keep the deduping logic with
seen and the MCPToolCallSession check intact, but replace the silent pass with a
warning/error that includes the tool/session context and exception details.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 35f6a501-1280-41c5-871a-bf80d403337e
📒 Files selected for processing (2)
agent/canvas.pyagent/component/base.py
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
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 `@agent/canvas.py`:
- Around line 162-176: The close() cleanup path in Canvas is swallowing
MCPToolCallSession.close_sync() failures with a bare except, which hides
shutdown problems. Update close() to log the exception when
tool.close_sync(timeout=3) fails, using the existing logging pattern in
agent/canvas.py or a Canvas logger if available. Keep the deduping logic with
seen and the MCPToolCallSession check intact, but replace the silent pass with a
warning/error that includes the tool/session context and exception details.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 35f6a501-1280-41c5-871a-bf80d403337e
📒 Files selected for processing (2)
agent/canvas.pyagent/component/base.py
🛑 Comments failed to post (1)
agent/canvas.py (1)
162-176: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Silent exception swallowing in
close()— no logging on cleanup failure.
except Exception: passhidesclose_syncfailures entirely. Per coding guidelines, new flows should add logging; this makes MCP session leaks/close failures invisible in production. Static analysis also flags this as blind-except/try-except-pass.🪵 Proposed fix
try: tool.close_sync(timeout=3) - except Exception: - pass + except Exception: + logging.warning("Graph.close: failed to close MCP tool session %s", id(tool), exc_info=True)As per coding guidelines, "Add logging for new flows" (
**/*.py).📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.def close(self): from common.mcp_tool_call_conn import MCPToolCallSession seen = set() for cpn in self.components.values(): obj = cpn.get("obj") if obj and hasattr(obj, "tools"): for tool in obj.tools.values(): if isinstance(tool, MCPToolCallSession) and id(tool) not in seen: seen.add(id(tool)) try: tool.close_sync(timeout=3) except Exception: logging.warning("Graph.close: failed to close MCP tool session %s", id(tool), exc_info=True)🧰 Tools
🪛 Ruff (0.15.20)
[error] 174-175:
try-except-passdetected, consider logging the exception(S110)
[warning] 174-174: Do not catch blind exception:
Exception(BLE001)
🤖 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 `@agent/canvas.py` around lines 162 - 176, The close() cleanup path in Canvas is swallowing MCPToolCallSession.close_sync() failures with a bare except, which hides shutdown problems. Update close() to log the exception when tool.close_sync(timeout=3) fails, using the existing logging pattern in agent/canvas.py or a Canvas logger if available. Keep the deduping logic with seen and the MCPToolCallSession check intact, but replace the silent pass with a warning/error that includes the tool/session context and exception details.Source: Coding guidelines
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16469 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…es (infiniflow#16469) ## Summary While fixing infiniflow#16467 (IterationItem crash on `@` in user-defined output keys), an audit of `agent/**/*.py` revealed **three additional sites** with the same vulnerability. This PR hardens all of them with `maxsplit=1` and adds regression tests. This is **defense-in-depth hardening**, not a behavior change. The current `variable_ref_patt` regex constrains `var_nm` to `[A-Za-z0-9_.-]+`, so single-`@` templates resolve exactly as before. The `maxsplit=1` only kicks in if the trailing side itself contains `@` — currently unreachable from the public DSL surface, but trivially exploitable the moment a user-defined output key happens to contain `@` (e.g. `user@email`) or the regex is ever relaxed. > **Note on issue scope**: The primary fix for infiniflow#16467 (the `list_tenant_added_models` `ValueError` crash on `@` in model names) is in PR infiniflow#16468. This PR is a **follow-up hardening sweep** of the same vulnerability class found in `agent/` during that audit; it does not duplicate or replace infiniflow#16468. ## Sites hardened | File | Line | Method | |------|------|--------| | `agent/canvas.py` | 206 | `Graph.get_variable_value` | | `agent/canvas.py` | 256 | `Graph.set_variable_value` | | `agent/component/base.py` | 533 | `ComponentBase.get_input_elements_from_text` | | `agent/component/iterationitem.py` | 88 | `IterationItem.output_collation` | All now use `split("@", 1)` with an inline comment explaining the rationale. The trailing side keeps any embedded `@`. ## Sites already safe (audited but left alone) | File | Reason safe | |------|------------| | `agent/canvas.py:708` (`is_reff`) | Pre-checks `len(arr) != 2` | | `agent/component/categorize.py` | Uses `rsplit` | | `agent/component/iteration.py` | Pre-validates via regex | | Other call sites | `rsplit` or regex pre-validation | ## Regression tests 9 new tests across 2 files, all `pytest.mark.p2`: | File | Tests | |------|-------| | `test/unit_test/agent/test_canvas_at_split.py` | 6 — `get_variable_value`, `set_variable_value`, round-trip, single-`@`, missing-component | | `test/unit_test/agent/component/test_iterationitem_at_split.py` | 3 — `output_collation` with `@` in var, single-`@`, non-matching cid | Each test was **verified to fail with `ValueError: too many values to unpack (expected 2)`** when the corresponding fix is temporarily reverted, confirming the tests actually catch the bug rather than just exercising the happy path. ## Test results ``` 9 passed in 0.04s ``` Full agent unit suite also clean (38 passed, 3 skipped; 6 unrelated pre-existing collection errors from missing `peewee`/`requests` in local venv — not caused by this PR). ## Related - Issue: infiniflow#16467 - Primary fix PR: infiniflow#16468 (closes the issue) - This PR: defense-in-depth follow-up, intentionally non-blocking on infiniflow#16467 --------- Co-authored-by: skbs-eng <[email protected]>
…es (infiniflow#16469) ## Summary While fixing infiniflow#16467 (IterationItem crash on `@` in user-defined output keys), an audit of `agent/**/*.py` revealed **three additional sites** with the same vulnerability. This PR hardens all of them with `maxsplit=1` and adds regression tests. This is **defense-in-depth hardening**, not a behavior change. The current `variable_ref_patt` regex constrains `var_nm` to `[A-Za-z0-9_.-]+`, so single-`@` templates resolve exactly as before. The `maxsplit=1` only kicks in if the trailing side itself contains `@` — currently unreachable from the public DSL surface, but trivially exploitable the moment a user-defined output key happens to contain `@` (e.g. `user@email`) or the regex is ever relaxed. > **Note on issue scope**: The primary fix for infiniflow#16467 (the `list_tenant_added_models` `ValueError` crash on `@` in model names) is in PR infiniflow#16468. This PR is a **follow-up hardening sweep** of the same vulnerability class found in `agent/` during that audit; it does not duplicate or replace infiniflow#16468. ## Sites hardened | File | Line | Method | |------|------|--------| | `agent/canvas.py` | 206 | `Graph.get_variable_value` | | `agent/canvas.py` | 256 | `Graph.set_variable_value` | | `agent/component/base.py` | 533 | `ComponentBase.get_input_elements_from_text` | | `agent/component/iterationitem.py` | 88 | `IterationItem.output_collation` | All now use `split("@", 1)` with an inline comment explaining the rationale. The trailing side keeps any embedded `@`. ## Sites already safe (audited but left alone) | File | Reason safe | |------|------------| | `agent/canvas.py:708` (`is_reff`) | Pre-checks `len(arr) != 2` | | `agent/component/categorize.py` | Uses `rsplit` | | `agent/component/iteration.py` | Pre-validates via regex | | Other call sites | `rsplit` or regex pre-validation | ## Regression tests 9 new tests across 2 files, all `pytest.mark.p2`: | File | Tests | |------|-------| | `test/unit_test/agent/test_canvas_at_split.py` | 6 — `get_variable_value`, `set_variable_value`, round-trip, single-`@`, missing-component | | `test/unit_test/agent/component/test_iterationitem_at_split.py` | 3 — `output_collation` with `@` in var, single-`@`, non-matching cid | Each test was **verified to fail with `ValueError: too many values to unpack (expected 2)`** when the corresponding fix is temporarily reverted, confirming the tests actually catch the bug rather than just exercising the happy path. ## Test results ``` 9 passed in 0.04s ``` Full agent unit suite also clean (38 passed, 3 skipped; 6 unrelated pre-existing collection errors from missing `peewee`/`requests` in local venv — not caused by this PR). ## Related - Issue: infiniflow#16467 - Primary fix PR: infiniflow#16468 (closes the issue) - This PR: defense-in-depth follow-up, intentionally non-blocking on infiniflow#16467 --------- Co-authored-by: skbs-eng <[email protected]>
Summary
While fixing #16467 (IterationItem crash on
@in user-defined output keys), an audit ofagent/**/*.pyrevealed three additional sites with the same vulnerability. This PR hardens all of them withmaxsplit=1and adds regression tests.This is defense-in-depth hardening, not a behavior change. The current
variable_ref_pattregex constrainsvar_nmto[A-Za-z0-9_.-]+, so single-@templates resolve exactly as before. Themaxsplit=1only kicks in if the trailing side itself contains@— currently unreachable from the public DSL surface, but trivially exploitable the moment a user-defined output key happens to contain@(e.g.user@email) or the regex is ever relaxed.Sites hardened
agent/canvas.pyGraph.get_variable_valueagent/canvas.pyGraph.set_variable_valueagent/component/base.pyComponentBase.get_input_elements_from_textagent/component/iterationitem.pyIterationItem.output_collationAll now use
split("@", 1)with an inline comment explaining the rationale. The trailing side keeps any embedded@.Sites already safe (audited but left alone)
agent/canvas.py:708(is_reff)len(arr) != 2agent/component/categorize.pyrsplitagent/component/iteration.pyrsplitor regex pre-validationRegression tests
9 new tests across 2 files, all
pytest.mark.p2:test/unit_test/agent/test_canvas_at_split.pyget_variable_value,set_variable_value, round-trip, single-@, missing-componenttest/unit_test/agent/component/test_iterationitem_at_split.pyoutput_collationwith@in var, single-@, non-matching cidEach test was verified to fail with
ValueError: too many values to unpack (expected 2)when the corresponding fix is temporarily reverted, confirming the tests actually catch the bug rather than just exercising the happy path.Test results
Full agent unit suite also clean (38 passed, 3 skipped; 6 unrelated pre-existing collection errors from missing
peewee/requestsin local venv — not caused by this PR).Related