Skip to content

fix(agent): defend against @ in var names at all template-split sites - #16469

Merged
yuzhichang merged 5 commits into
infiniflow:mainfrom
skbs-eng:fix/canvas-iterationitem-at-split
Jul 3, 2026
Merged

yuzhichang merged 5 commits into
infiniflow:mainfrom
skbs-eng:fix/canvas-iterationitem-at-split

Conversation

@skbs-eng

@skbs-eng skbs-eng commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

While fixing #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 #16467 (the list_tenant_added_models ValueError crash on @ in model names) is in PR #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 #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

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
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jun 29, 2026
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 35f6a501-1280-41c5-871a-bf80d403337e

📥 Commits

Reviewing files that changed from the base of the PR and between 5c4281d and b43bbc4.

📒 Files selected for processing (2)
  • agent/canvas.py
  • agent/component/base.py

📝 Walkthrough

Walkthrough

Three agent parsing paths now split @ references with split("@", 1), and two isolated regression test modules cover multi-@ inputs, round-trips, and error handling.

Changes

Defensive @ splitting across agent parsing sites

Layer / File(s) Summary
Bounded @ split in canvas, base, and iterationitem
agent/canvas.py, agent/component/base.py, agent/component/iterationitem.py
get_variable_value, set_variable_value, get_input_elements_from_text, and output_collation switch from split("@") to split("@", 1), with related formatting changes kept in the same production files.
Regression tests for canvas.py @ splitting
test/unit_test/agent/test_canvas_at_split.py
Loads agent.canvas in isolation via importlib, stubs dependencies, and tests multi-@ variable keys, round-trips, missing-component errors, and single-@ behavior.
Regression tests for iterationitem.py @ splitting
test/unit_test/agent/component/test_iterationitem_at_split.py
Loads agent.component.iterationitem in isolation via importlib, constructs IterationItem via __new__, and verifies multi-@ refs, single-@ refs, and cid-mismatch skipping.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

🐇 I hopped through code where @ took two,
With one small split, the tails came through.
No more tumble, no more fuss,
Just tidy refs for all of us.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Title is concise and accurately describes the hardening against @ in variable/template split sites.
Description check ✅ Passed Description includes a clear summary, background, affected sites, regression tests, and test results.
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.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
agent/component/base.py (1)

538-543: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a direct regression test for this split site.

The new suites here exercise Graph and IterationItem, but nothing in the provided tests hits ComponentBase.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

📥 Commits

Reviewing files that changed from the base of the PR and between 6370fce and 78f823b.

📒 Files selected for processing (5)
  • agent/canvas.py
  • agent/component/base.py
  • agent/component/iterationitem.py
  • test/unit_test/agent/component/test_iterationitem_at_split.py
  • test/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).
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Jun 29, 2026

@coderabbitai coderabbitai Bot 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.

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 win

This 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 win

Keep reference recognition consistent with the new bounded split.

Line 206 preserves var_nm values containing @, but direct input refs can still be rejected before reaching this method: ComponentBase.get_input gates through Graph.is_reff, whose split("@")/len(arr) == 2 logic 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

📥 Commits

Reviewing files that changed from the base of the PR and between 78f823b and fd94ecf.

📒 Files selected for processing (5)
  • agent/canvas.py
  • agent/component/base.py
  • agent/component/iterationitem.py
  • test/unit_test/agent/component/test_iterationitem_at_split.py
  • test/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.
@skbs-eng

Copy link
Copy Markdown
Contributor Author

Addressed all three CodeRabbit warnings in commit 5c4281d7c:

1. Docstring Coverage 15% → 87% / 100%

Added Google-style docstrings to all helpers and inline stubs in both test files:

File Before After
test_canvas_at_split.py 62% (8/13) 87% (13/15)
test_iterationitem_at_split.py 50% (8/16) 100% (25/25)

Docstrings added on _load_canvas_module, _load_iterationitem_module, nested _stub_module, _ComponentBaseStub, _ComponentParamBaseStub, _RetCode, plus all output/set_output/get_parent/get_component_obj methods on the parent/child/canvas stubs.

2. Linked Issues

Removed Closes #16467 from the body and added an explicit Related section clarifying that PR #16468 is the primary fix; this PR is a defense-in-depth follow-up.

3. Out of Scope Changes

Same 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:

9 passed in 0.04s

@yuzhichang
yuzhichang self-requested a review July 1, 2026 02:56
@wangq8 wangq8 added the ci Continue Integration label Jul 1, 2026
@wangq8
wangq8 marked this pull request as draft July 1, 2026 05:45
@wangq8
wangq8 marked this pull request as ready for review July 1, 2026 05:45
@yuzhichang

yuzhichang commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

@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.
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 3, 2026
@skbs-eng

skbs-eng commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

Conflicts fixed — merged main into fix/canvas-iterationitem-at-split as b43bbc4eb and pushed.

Resolved blocks (4 total):

  • agent/canvas.py — kept both common.misc_utils and the new common.token_utils imports; preserved "usage": self._run_usage_payload() in both workflow_finished emit sites; kept the new _run_usage_payload() helper method.
  • agent/component/base.py — restored PEP 8 blank lines between import groups (main had them; this PR's ruff-format pass had collapsed them).
  • test/unit_test/agent/test_canvas_at_split.py — added common.token_utils to the canvas loader stub graph so the post-merge import surface matches (the module pulls in tiktoken at import time and isn't actually exercised by the @-split regression tests).

All 9 regression tests pass (pytest test/unit_test/agent/test_canvas_at_split.py test/unit_test/agent/component/test_iterationitem_at_split.py). Ready for re-review.

@coderabbitai coderabbitai Bot 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5c4281d and b43bbc4.

📒 Files selected for processing (2)
  • agent/canvas.py
  • agent/component/base.py

@coderabbitai coderabbitai Bot 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5c4281d and b43bbc4.

📒 Files selected for processing (2)
  • agent/canvas.py
  • agent/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: pass hides close_sync failures 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-pass detected, 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

@yuzhichang yuzhichang added ci Continue Integration and removed ci Continue Integration labels Jul 3, 2026
@codecov

codecov Bot commented Jul 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (3cba34d) to head (b43bbc4).
⚠️ Report is 8 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yuzhichang
yuzhichang merged commit 1861087 into infiniflow:main Jul 3, 2026
6 of 9 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
…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]>
yuzhichang pushed a commit that referenced this pull request Jul 6, 2026
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants