Skip to content

Port 14 upstream agent security / correctness fixes to Go canvas - #16455

Merged
yuzhichang merged 2 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port
Jun 30, 2026
Merged

yuzhichang merged 2 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port

Conversation

@yuzhichang

@yuzhichang yuzhichang commented Jun 29, 2026 •

Copy link
Copy Markdown
Member

Mirrors 14 merged upstream PRs into the Go agent port.

PRs ported:

40 files, +2355 / -58 lines. 33 new tests, all targeted package suites pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 29, 2026
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds SSRF hardening, a new PipelineChunker component, document and webhook authorization changes, beta-auth and agentbot logs wiring, SSE event forwarding, and several service and handler contract updates.

Changes

SSRF Hardening

Layer / File(s) Summary
SSRF hardening and host pinning
internal/utility/ssrf.go, internal/service/agent_dbcheck.go, internal/agent/component/invoke.go, internal/agent/component/invoke_test.go, internal/agent/tool/ssrf.go, internal/agent/tool/exesql.go, internal/agent/tool/exesql_ssrf_test.go, internal/agent/tool/http_timeout_guard_test.go, internal/agent/tool/exesql_*test.go
Adds test-only SSRF bypass support, validates outbound URLs and DB hosts before network or SQL use, pins proxy/direct dialing, and expands SSRF and timeout coverage.

PipelineChunker Component

Layer / File(s) Summary
PipelineChunker implementation
internal/agent/component/pipeline_chunker.go, internal/agent/component/verify_p1_test.go
Defines the PipelineChunker component, parser whitelist and split strategy mapping, input decoding, chunk execution, output shaping, and registration, with the registration-count test update.
PipelineChunker tests
internal/agent/component/pipeline_chunker_test.go
Covers constructor validation, empty and text input, content aliasing, file bytes and file refs, base64 and UTF-8 rejection, parser strategy selection, output schema, and Stream consistency.

Component, Handler, and Service Updates

Layer / File(s) Summary
Component contracts and routing
internal/agent/component/base.go, internal/agent/component/base_test.go, internal/agent/component/switch.go, internal/agent/component/switch_test.go, internal/agent/component/llm.go, internal/agent/component/llm_test.go
Adds canonical output wrapping, changes empty Switch clause groups to non-matching, and propagates the LLM thinking field through request construction and parameter merge logic.
Webhook security fail-closed
internal/handler/agent_webhook_security.go, internal/handler/agent_webhook_security_test.go, internal/handler/agent_webhook_test.go
Rejects empty or none-auth security configs unless allow_anonymous is explicitly truthy, and updates webhook test scaffolding and coverage.
Document access authorization
internal/dao/user_canvas.go, internal/service/document.go, internal/service/document_test.go, internal/handler/document.go, internal/handler/document_test.go, internal/handler/agent.go, internal/handler/agent_test.go, cmd/server_main.go
Adds canvas access checks, user-scoped artifact lookup, sandbox artifact dialog resolution, handler wiring for authenticated user IDs, rerun authorization gating, and the corresponding auth-gate tests.
Beta auth and agentbot logs
internal/handler/auth.go, internal/service/user.go, internal/handler/bot.go, internal/router/bot_routes.go, internal/router/router.go, internal/handler/bot_test.go, internal/agent/tool/deepl_test.go
Extends beta auth to populate agent and token context, adds APIToken lookup by beta authorization, implements the agentbot logs handler, and wires route middleware and tests.
SSE forwarding, IDOR, and session validation
internal/service/bot_completion.go, internal/service/bot_completion_history_test.go, internal/service/agent_test.go, internal/service/chat_session.go
Adds an event field to chatbot SSE frames, forwards run event types through SSE output, adds cross-tenant and agent-session IDOR tests, and tightens session message and reference validation.
CodeQL annotations
internal/entity/models/openai.go, internal/entity/models/openrouter.go, internal/entity/models/xiaomi.go, internal/entity/models/zhipu-ai.go
Adds or repositions path-injection suppression comments around ASR request helpers.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related issues

Possibly related PRs

Suggested labels

ci, 💞 feature, ☯️ refactor, size:XXL

Suggested reviewers

  • Haruko386

Poem

🐇 I hopped through hosts and chunks with care,
No sneaky redirects prowled the air.
With logs and gates and SSE light,
The carrot path looks clean and bright.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: porting upstream security and correctness fixes to the Go canvas.
Description check ✅ Passed The description includes the required Summary context and adequately explains the scope of the ported fixes.
Docstring Coverage ✅ Passed Docstring coverage is 85.16% which is sufficient. The required threshold is 80.00%.
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.

@yuzhichang yuzhichang changed the title Port Wave 1-4 of python agent PR review plan to Go Port 14 upstream agent security / correctness fixes to Go canvas Jun 29, 2026
@yuzhichang yuzhichang added the ci Continue Integration label 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.

Actionable comments posted: 19

🧹 Nitpick comments (3)
internal/agent/component/verify_p1_test.go (1)

47-48: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert PipelineChunker directly instead of widening the max count.

This bound will keep drifting and still won't fail if the new component stops registering, because the required-name list never mentions it. Add an explicit have["pipelinechunker"] or New("PipelineChunker", nil) assertion and treat the total count as informational at most.

🤖 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 `@internal/agent/component/verify_p1_test.go` around lines 47 - 48, The
registration test in verify_p1_test.go should assert the PipelineChunker
component explicitly instead of relying on a looser name count. Update the test
around the names/have map logic to check for have["pipelinechunker"] or an
equivalent New("PipelineChunker", nil) registration, and keep the total count as
informational only so the test fails if PipelineChunker stops registering.
internal/handler/agent.go (1)

77-91: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a narrow interface for the rerun access gate.

RerunAgent only needs Accessible(docID, userID) bool. Keeping the field concrete forces tests to use nil or a real DB-backed DocumentService, which is why the deny-all helper in agent_test.go cannot be wired.

♻️ Proposed refactor
+type documentAccessChecker interface {
+	Accessible(docID, userID string) bool
+}
+
 type AgentHandler struct {
 	agentService *service.AgentService
 	chatRunner   chatAgentService
 	fileService  agentFileService
 	loader       canvasLoader
@@
-	documentService *service.DocumentService
+	documentService documentAccessChecker
 }
@@
-func (h *AgentHandler) WithDocumentService(s *service.DocumentService) *AgentHandler {
+func (h *AgentHandler) WithDocumentService(s documentAccessChecker) *AgentHandler {
 	h.documentService = s
 	return h
 }
🤖 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 `@internal/handler/agent.go` around lines 77 - 91, The
AgentHandler.documentService field is too concrete for RerunAgent’s access
check, which only needs an Accessible(docID, userID) bool capability. Introduce
a narrow interface for that method and change WithDocumentService and the
handler field to depend on it instead of *service.DocumentService, so tests can
inject deny-all or mock implementations without a real DB-backed service. Keep
RerunAgent using the injected accessor, and update any wiring in
AgentHandler/server_main to pass the concrete service as the interface.
internal/handler/bot_test.go (1)

1091-1151: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a happy-path test for middleware-populated agent_id.

The new negative tests don’t exercise BetaAuthMiddleware setting "agent_id" from APIToken.DialogID; a test with DialogID: &id would catch the current pointer/string contract break before GetAgentbotLogs runs.

🤖 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 `@internal/handler/bot_test.go` around lines 1091 - 1151, The current tests
only cover failure cases and do not verify the middleware-populated agent_id
flow. Add a happy-path test around GetAgentbotLogs that goes through
BetaAuthMiddleware (or otherwise seeds the context the same way) with an
APIToken whose DialogID is set, then assert the handler succeeds using that
agent_id rather than any shared_id path segment. Use the existing
TestGetAgentbotLogs_* cases and the BetaAuthMiddleware/GetAgentbotLogs symbols
to locate the right setup and catch the DialogID-to-agent_id contract break.
🤖 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 `@internal/agent/component/invoke_test.go`:
- Around line 335-340: The DNS pin regression check in the test should fail
instead of only logging when the expected pinned address is missing. Update the
assertion in the affected test in invoke_test.go so that the branch using
err.Error() and strings.Contains on pinnedProxyIP and 1.1.1.1 causes the test to
fail when neither address appears, keeping the existing dial-path validation in
the same test helper.
- Around line 224-234: The unsafe proxy test only checks the absence of a server
side effect, which does not verify the proxy guard output. In the Invoke test
that calls c.Invoke with the proxy value, capture the returned out map and
assert the _ERROR field equals "URL not valid" so the test proves the guard
blocked the request before dialing; keep the existing serverHit check only as a
secondary safeguard.

In `@internal/agent/component/invoke.go`:
- Around line 184-214: The proxy handling in invoke.go still lets hostname-based
targets reach the proxy via rawURL, which leaves SSRF/DNS-rebinding possible.
Update the proxy branch in the HTTP client setup and request path so proxied
requests either fail closed for hostname targets or are rewritten to the
validated target IP while preserving the original Host/SNI. Use the existing
proxy-specific logic around mustParseProxy, proxyURL, proxyIP, and the
http.Client/Transport construction to keep the fix localized.

In `@internal/agent/component/llm_test.go`:
- Around line 201-255: The test currently only validates mergeLLMParam and does
not cover the ChatInvokeRequest path it describes, so regressions in the
request-building logic in llm.go can slip through. Update
TestLLM_ThinkingFieldRoundTrip to stub the invoker used by the agent component
and assert the captured ChatInvokeRequest.Thinking value for enabled, disabled,
and default cases. Also add coverage for the structured-output retry branch so
the same thinking value is verified when the request is rebuilt during retry.

In `@internal/agent/component/llm.go`:
- Around line 862-870: Normalize the merged thinking field in llm.go’s
ChatInvokeRequest assembly so the final p.Thinking always follows the documented
tri-state contract. The current stringFrom(inputs, "thinking") override check
only validates the DSL input, but it leaves inherited base.Thinking untouched,
so empty overrides cannot clear a prior value and invalid base values can still
propagate. Update the merge logic around p := base and the thinking handling to
validate or normalize the effective p.Thinking value itself, ensuring only the
known sentinels survive and empty input can explicitly clear the setting.

In `@internal/agent/component/pipeline_chunker_test.go`:
- Around line 447-469: The current test only verifies that
PipelineChunker.Invoke succeeds, so it does not confirm the base64 decode path
was actually used. Update TestPipelineChunker_FileRefBase64AlphabetTextRejected
to assert on the produced chunk content from the Invoke result, specifically
that the chunk text is "foo", so the behavior in newConcretePipelineChunker and
PipelineChunker.Invoke is pinned against falling back to raw text.

In `@internal/agent/component/pipeline_chunker.go`:
- Around line 138-141: The parser_config handling in the pipeline chunker should
reject non-object values instead of replacing them with an empty map, because
that hides malformed DSL and bypasses the later shape validation. Update the
logic around p.ParserConfig in the pipeline chunking/config parsing path so that
only a map[string]any is accepted and any other type returns an error or fails
validation immediately. Keep the existing shape check that follows, but ensure
it can actually fire by preserving invalid input rather than normalizing it
away.
- Around line 397-401: The file_bytes handling in pipeline_chunker.go only
accepts []byte, but it is documented as sharing the same encoding contract as
file_ref and must also accept the base64 string path. Update the input parsing
branch in the file_bytes path to handle the same base64-encoded string format
that file_ref supports, then pass the decoded bytes through
validateAndDecodeBytes so JSON callers with file_bytes do not fall through to
the no input text error.

In `@internal/agent/component/switch_test.go`:
- Around line 430-456: The switch fallthrough tests only verify that
WRONG_TARGET is not selected, but they do not assert that the default target is
actually returned. Update TestSwitch_EmptyAndConditionFallsThrough and the
related switch test to explicitly check nextTargets(out) contains DEFAULT and
that _next is not empty or redirected elsewhere, using the existing
Switch.Invoke and nextTargets helpers to lock in the intended fallback behavior.

In `@internal/agent/tool/exesql.go`:
- Around line 280-284: `ValidateDBHost` is returning a safe IPv6 literal that
gets assigned directly to `conn.Host`, which later breaks DSN assembly in
`ExeSQL`/`buildMySQLDSN` when formatted as `tcp(%s:%d)`. Update the
MySQL/OceanBase connection string construction to use IPv6-safe host formatting
(for example via `net.JoinHostPort`) or keep the pinned host separate from the
value used for the DSN, and add a regression test covering a public IPv6 host to
verify `ExeSQL` handles it correctly.

In `@internal/agent/tool/http_timeout_guard_test.go`:
- Around line 52-57: The test currently inspects h.client.Transport, which is
wrapped by otelhttp.NewTransport and prevents asserting the stage timeout
fields. Update TestHTTPHelper_DefaultTransportHasStageTimeouts to check
h.baseTransport directly in HTTPHelper, and make the test fail if
h.baseTransport is nil instead of skipping when the wrapped transport type does
not match.
- Around line 108-130: The http timeout guard test is matching the wrong
identifier and missing nested selector calls. Update the allow-list in the test
around ast.Inspect so it checks the source filename rather than file.Name.Name,
and recurse through SelectorExpr chains in the matcher to catch cases like
http.DefaultClient.Do/Get/Post, not just bare http selectors. Keep the existing
banned-call detection logic in http_timeout_guard_test.go but make it robust for
nested selectors and the http_helper.go exemption.

In `@internal/dao/user_canvas.go`:
- Around line 139-147: The Accessible method in UserCanvasDAO is currently
treating permission = "team" as globally valid, which bypasses tenant scoping.
Update the query logic in Accessible to mirror GetByIDForUser by only allowing
team canvases when the caller belongs to the owner’s tenant membership, using
the same tenant membership check and relevant symbols in this DAO rather than a
blanket permission match.

In `@internal/handler/agent_test.go`:
- Around line 1046-1078: The test is exercising the nil-documentService fallback
instead of the intended inaccessible-document denial path. Update
TestRerunAgent_RejectsInaccessibleDocument to use the deny-all stubDocService
(or make WithDocumentService accept a narrow Accessible interface so the stub
can be injected) and assert the CodeDataError/"Document not found." response
from RerunAgent. Keep the focus on the document access gate in
NewAgentHandler/WithDocumentService rather than nil-service behavior so the test
fails if the deny branch is removed.

In `@internal/handler/agent_webhook_security.go`:
- Around line 98-99: The fail-closed webhook validation in
agent_webhook_security.go uses different error messages in the missing-security
and anonymous-without-opt-in branches, which leaks behavior details. Update the
relevant validation path(s) to return the same sentinel error/message from both
branches, reusing the shared error in the webhook security check logic rather
than constructing branch-specific strings. Then add or adjust tests around the
webhook security validation to assert the exact same error is returned in both
cases.

In `@internal/handler/auth.go`:
- Around line 95-97: The beta-auth path in h.userService.GetAPITokenByBeta
currently stores tok.DialogID directly into the context, but GetAgentbotLogs
expects agent_id to be a string. Update the auth handling in the token branch to
dereference tok.DialogID, validate it is non-nil before setting
c.Set("agent_id", ...), and only store the actual string value so the later
agentID.(string) check succeeds.

In `@internal/handler/bot.go`:
- Around line 299-303: The log retrieval path in bot.go currently treats Redis
and JSON decode failures as success, so update the logic around redis.Get().Get
and the json.Unmarshal step to surface those errors instead of returning an
empty data map. In the handler that builds the logs response, branch on rerr and
unmarshal errors separately, return a failure response with the underlying
error, and only emit success when payload is fetched and decoded cleanly.

In `@internal/service/document_test.go`:
- Around line 1904-1977: Add the missing authorized-user success case in
TestGetDocumentArtifact_AuthGate: after seeding the owner’s UserCanvas and
API4Conversation, assert that svc.GetDocumentArtifact("result.png", "user-1")
does not return ErrArtifactNotFound. Use the existing GetDocumentArtifact,
ErrArtifactNotFound, and the seeded sess-1/agent-1 records to verify the
positive gate path directly, while keeping the current denial cases intact.

In `@internal/service/document.go`:
- Around line 316-322: The authorization check in document lookup is matching
the raw filename with SQL LIKE, so `%` and `_` can be treated as wildcards.
Update the query building in the document service code around the dialog lookup
to escape the user-supplied filename before using it in the LIKE predicates, and
use the escaped value for both message filters. Add and reuse the suggested
helper (escapeSQLLike) near the relevant function so the logic in the
authorization path is consistent and easy to find.

---

Nitpick comments:
In `@internal/agent/component/verify_p1_test.go`:
- Around line 47-48: The registration test in verify_p1_test.go should assert
the PipelineChunker component explicitly instead of relying on a looser name
count. Update the test around the names/have map logic to check for
have["pipelinechunker"] or an equivalent New("PipelineChunker", nil)
registration, and keep the total count as informational only so the test fails
if PipelineChunker stops registering.

In `@internal/handler/agent.go`:
- Around line 77-91: The AgentHandler.documentService field is too concrete for
RerunAgent’s access check, which only needs an Accessible(docID, userID) bool
capability. Introduce a narrow interface for that method and change
WithDocumentService and the handler field to depend on it instead of
*service.DocumentService, so tests can inject deny-all or mock implementations
without a real DB-backed service. Keep RerunAgent using the injected accessor,
and update any wiring in AgentHandler/server_main to pass the concrete service
as the interface.

In `@internal/handler/bot_test.go`:
- Around line 1091-1151: The current tests only cover failure cases and do not
verify the middleware-populated agent_id flow. Add a happy-path test around
GetAgentbotLogs that goes through BetaAuthMiddleware (or otherwise seeds the
context the same way) with an APIToken whose DialogID is set, then assert the
handler succeeds using that agent_id rather than any shared_id path segment. Use
the existing TestGetAgentbotLogs_* cases and the
BetaAuthMiddleware/GetAgentbotLogs symbols to locate the right setup and catch
the DialogID-to-agent_id contract break.
🪄 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: 8548ca47-9da5-4d97-81c4-66e48106a148

📥 Commits

Reviewing files that changed from the base of the PR and between c0f6429 and bf42bcd.

📒 Files selected for processing (39)
  • cmd/server_main.go
  • internal/agent/component/base.go
  • internal/agent/component/base_test.go
  • internal/agent/component/invoke.go
  • internal/agent/component/invoke_test.go
  • internal/agent/component/llm.go
  • internal/agent/component/llm_test.go
  • internal/agent/component/pipeline_chunker.go
  • internal/agent/component/pipeline_chunker_test.go
  • internal/agent/component/switch.go
  • internal/agent/component/switch_test.go
  • internal/agent/component/verify_p1_test.go
  • internal/agent/tool/deepl_test.go
  • internal/agent/tool/exesql.go
  • internal/agent/tool/exesql_ssrf_test.go
  • internal/agent/tool/exesql_test.go
  • internal/agent/tool/exesql_trino_test.go
  • internal/agent/tool/exesql_unsupported_test.go
  • internal/agent/tool/http_timeout_guard_test.go
  • internal/agent/tool/ssrf.go
  • internal/dao/user_canvas.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/handler/agent_webhook_security.go
  • internal/handler/agent_webhook_security_test.go
  • internal/handler/agent_webhook_test.go
  • internal/handler/auth.go
  • internal/handler/bot.go
  • internal/handler/bot_test.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/bot_routes.go
  • internal/service/agent_test.go
  • internal/service/bot_completion.go
  • internal/service/bot_completion_history_test.go
  • internal/service/document.go
  • internal/service/document_test.go
  • internal/service/user.go
  • internal/utility/ssrf.go

Comment thread internal/agent/component/invoke_test.go Resolved
Comment thread internal/agent/component/invoke_test.go Resolved
Comment thread internal/agent/component/invoke.go Resolved
Comment thread internal/agent/component/llm_test.go Resolved
Comment on lines +862 to +870
if v, ok := stringFrom(inputs, "thinking"); ok {
// Only allow the two known sentinels through; an arbitrary
// string from the DSL is dropped to avoid surprising the LLM
// driver. Mirrors python llm.py:78-79 which gates on the
// same {"enabled","disabled"} set.
if v == "enabled" || v == "disabled" {
p.Thinking = v
}
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Normalize the merged thinking value, not just the override.

Because p := base preserves any existing value, the guard at Line 862 only validates inputs["thinking"]. An explicit thinking: "" therefore cannot clear an inherited setting, and any invalid non-empty base.Thinking still flows into ChatInvokeRequest, which breaks the documented tri-state contract.

Suggested fix
-	if v, ok := stringFrom(inputs, "thinking"); ok {
-		// Only allow the two known sentinels through; an arbitrary
-		// string from the DSL is dropped to avoid surprising the LLM
-		// driver. Mirrors python llm.py:78-79 which gates on the
-		// same {"enabled","disabled"} set.
-		if v == "enabled" || v == "disabled" {
-			p.Thinking = v
-		}
-	}
+	if raw, ok := inputs["thinking"]; ok {
+		if v, ok := raw.(string); ok {
+			// Allow explicit "" so callers can clear an inherited value
+			// back to provider default.
+			p.Thinking = v
+		}
+	}
+	switch p.Thinking {
+	case "", "enabled", "disabled":
+	default:
+		p.Thinking = ""
+	}
📝 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.

Suggested change
if v, ok := stringFrom(inputs, "thinking"); ok {
// Only allow the two known sentinels through; an arbitrary
// string from the DSL is dropped to avoid surprising the LLM
// driver. Mirrors python llm.py:78-79 which gates on the
// same {"enabled","disabled"} set.
if v == "enabled" || v == "disabled" {
p.Thinking = v
}
}
if raw, ok := inputs["thinking"]; ok {
if v, ok := raw.(string); ok {
// Allow explicit "" so callers can clear an inherited value
// back to provider default.
p.Thinking = v
}
}
switch p.Thinking {
case "", "enabled", "disabled":
default:
p.Thinking = ""
}
🤖 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 `@internal/agent/component/llm.go` around lines 862 - 870, Normalize the merged
thinking field in llm.go’s ChatInvokeRequest assembly so the final p.Thinking
always follows the documented tri-state contract. The current stringFrom(inputs,
"thinking") override check only validates the DSL input, but it leaves inherited
base.Thinking untouched, so empty overrides cannot clear a prior value and
invalid base values can still propagate. Update the merge logic around p := base
and the thinking handling to validate or normalize the effective p.Thinking
value itself, ensuring only the known sentinels survive and empty input can
explicitly clear the setting.

Comment thread internal/handler/auth.go Resolved
Comment thread internal/handler/bot.go Resolved
Comment on lines +1904 to +1977
// TestGetDocumentArtifact_AuthGate mirrors PR #16169: the sandbox
// artifact download endpoint must be gated on the caller owning
// (or having team access to) an agent session whose `message`
// references the filename. Three cases:
// - empty userID -> ErrArtifactNotFound
// - filename referenced by another user's session -> ErrArtifactNotFound
// - filename referenced by the caller's own session, with
// accessible canvas -> no error (storage layer short-circuits
// in this test because no real storage is wired)
func TestGetDocumentArtifact_AuthGate(t *testing.T) {
db := setupServiceTestDB(t)
if err := db.AutoMigrate(
&entity.UserCanvas{},
&entity.API4Conversation{},
); err != nil {
t.Fatalf("migrate: %v", err)
}
orig := dao.DB
dao.DB = db
t.Cleanup(func() { dao.DB = orig })

// Seed a canvas owned by user-1.
if err := db.Create(&entity.UserCanvas{
ID: "agent-1",
UserID: "user-1",
Title: sptr("Agent"),
CanvasCategory: "agent_canvas",
}).Error; err != nil {
t.Fatalf("seed canvas: %v", err)
}
// Seed an API4Conversation whose message references the filename.
if err := db.Create(&entity.API4Conversation{
ID: "sess-1",
DialogID: "agent-1",
UserID: "user-1",
Message: json.RawMessage(`[{"role":"assistant","content":"saved as documents/artifact/result.png"}]`),
}).Error; err != nil {
t.Fatalf("seed conv: %v", err)
}

svc := testDocumentService(t)

// Case 1: empty user -> not allowed.
if _, err := svc.GetDocumentArtifact("result.png", ""); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("empty user: want ErrArtifactNotFound, got %v", err)
}

// Case 2: another user without any session reference -> not allowed.
if _, err := svc.GetDocumentArtifact("result.png", "user-2"); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("unrelated user: want ErrArtifactNotFound, got %v", err)
}

// Case 3: another user who has their own (unrelated) session for a
// different agent that does NOT mention the filename -> not allowed.
if err := db.Create(&entity.UserCanvas{
ID: "agent-2",
UserID: "user-2",
Title: sptr("Other Agent"),
CanvasCategory: "agent_canvas",
}).Error; err != nil {
t.Fatalf("seed canvas 2: %v", err)
}
if err := db.Create(&entity.API4Conversation{
ID: "sess-2",
DialogID: "agent-2",
UserID: "user-2",
Message: json.RawMessage(`[{"role":"user","content":"hello"}]`),
}).Error; err != nil {
t.Fatalf("seed conv 2: %v", err)
}
if _, err := svc.GetDocumentArtifact("result.png", "user-2"); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("user-2 with unrelated session: want ErrArtifactNotFound, got %v", err)
}
}

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.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Add the authorized-user case this test advertises.

Lines 1910-1912 describe the owner-access success path, but the assertions only cover denials. A regression where the owner’s message reference is never found would still pass. Assert the positive gate directly, or configure storage and verify the result is not ErrArtifactNotFound.

🧪 Minimal positive assertion
 	svc := testDocumentService(t)
+
+	if !svc.sandboxArtifactAccessible("result.png", "user-1") {
+		t.Fatalf("owner with referenced artifact: want accessible")
+	}
 
 	// Case 1: empty user -> not allowed.
📝 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.

Suggested change
// TestGetDocumentArtifact_AuthGate mirrors PR #16169: the sandbox
// artifact download endpoint must be gated on the caller owning
// (or having team access to) an agent session whose `message`
// references the filename. Three cases:
// - empty userID -> ErrArtifactNotFound
// - filename referenced by another user's session -> ErrArtifactNotFound
// - filename referenced by the caller's own session, with
// accessible canvas -> no error (storage layer short-circuits
// in this test because no real storage is wired)
func TestGetDocumentArtifact_AuthGate(t *testing.T) {
db := setupServiceTestDB(t)
if err := db.AutoMigrate(
&entity.UserCanvas{},
&entity.API4Conversation{},
); err != nil {
t.Fatalf("migrate: %v", err)
}
orig := dao.DB
dao.DB = db
t.Cleanup(func() { dao.DB = orig })
// Seed a canvas owned by user-1.
if err := db.Create(&entity.UserCanvas{
ID: "agent-1",
UserID: "user-1",
Title: sptr("Agent"),
CanvasCategory: "agent_canvas",
}).Error; err != nil {
t.Fatalf("seed canvas: %v", err)
}
// Seed an API4Conversation whose message references the filename.
if err := db.Create(&entity.API4Conversation{
ID: "sess-1",
DialogID: "agent-1",
UserID: "user-1",
Message: json.RawMessage(`[{"role":"assistant","content":"saved as documents/artifact/result.png"}]`),
}).Error; err != nil {
t.Fatalf("seed conv: %v", err)
}
svc := testDocumentService(t)
// Case 1: empty user -> not allowed.
if _, err := svc.GetDocumentArtifact("result.png", ""); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("empty user: want ErrArtifactNotFound, got %v", err)
}
// Case 2: another user without any session reference -> not allowed.
if _, err := svc.GetDocumentArtifact("result.png", "user-2"); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("unrelated user: want ErrArtifactNotFound, got %v", err)
}
// Case 3: another user who has their own (unrelated) session for a
// different agent that does NOT mention the filename -> not allowed.
if err := db.Create(&entity.UserCanvas{
ID: "agent-2",
UserID: "user-2",
Title: sptr("Other Agent"),
CanvasCategory: "agent_canvas",
}).Error; err != nil {
t.Fatalf("seed canvas 2: %v", err)
}
if err := db.Create(&entity.API4Conversation{
ID: "sess-2",
DialogID: "agent-2",
UserID: "user-2",
Message: json.RawMessage(`[{"role":"user","content":"hello"}]`),
}).Error; err != nil {
t.Fatalf("seed conv 2: %v", err)
}
if _, err := svc.GetDocumentArtifact("result.png", "user-2"); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("user-2 with unrelated session: want ErrArtifactNotFound, got %v", err)
}
}
// TestGetDocumentArtifact_AuthGate mirrors PR `#16169`: the sandbox
// artifact download endpoint must be gated on the caller owning
// (or having team access to) an agent session whose `message`
// references the filename. Three cases:
// - empty userID -> ErrArtifactNotFound
// - filename referenced by another user's session -> ErrArtifactNotFound
// - filename referenced by the caller's own session, with
// accessible canvas -> no error (storage layer short-circuits
// in this test because no real storage is wired)
func TestGetDocumentArtifact_AuthGate(t *testing.T) {
db := setupServiceTestDB(t)
if err := db.AutoMigrate(
&entity.UserCanvas{},
&entity.API4Conversation{},
); err != nil {
t.Fatalf("migrate: %v", err)
}
orig := dao.DB
dao.DB = db
t.Cleanup(func() { dao.DB = orig })
// Seed a canvas owned by user-1.
if err := db.Create(&entity.UserCanvas{
ID: "agent-1",
UserID: "user-1",
Title: sptr("Agent"),
CanvasCategory: "agent_canvas",
}).Error; err != nil {
t.Fatalf("seed canvas: %v", err)
}
// Seed an API4Conversation whose message references the filename.
if err := db.Create(&entity.API4Conversation{
ID: "sess-1",
DialogID: "agent-1",
UserID: "user-1",
Message: json.RawMessage(`[{"role":"assistant","content":"saved as documents/artifact/result.png"}]`),
}).Error; err != nil {
t.Fatalf("seed conv: %v", err)
}
svc := testDocumentService(t)
if !svc.sandboxArtifactAccessible("result.png", "user-1") {
t.Fatalf("owner with referenced artifact: want accessible")
}
// Case 1: empty user -> not allowed.
if _, err := svc.GetDocumentArtifact("result.png", ""); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("empty user: want ErrArtifactNotFound, got %v", err)
}
// Case 2: another user without any session reference -> not allowed.
if _, err := svc.GetDocumentArtifact("result.png", "user-2"); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("unrelated user: want ErrArtifactNotFound, got %v", err)
}
// Case 3: another user who has their own (unrelated) session for a
// different agent that does NOT mention the filename -> not allowed.
if err := db.Create(&entity.UserCanvas{
ID: "agent-2",
UserID: "user-2",
Title: sptr("Other Agent"),
CanvasCategory: "agent_canvas",
}).Error; err != nil {
t.Fatalf("seed canvas 2: %v", err)
}
if err := db.Create(&entity.API4Conversation{
ID: "sess-2",
DialogID: "agent-2",
UserID: "user-2",
Message: json.RawMessage(`[{"role":"user","content":"hello"}]`),
}).Error; err != nil {
t.Fatalf("seed conv 2: %v", err)
}
if _, err := svc.GetDocumentArtifact("result.png", "user-2"); !errors.Is(err, ErrArtifactNotFound) {
t.Errorf("user-2 with unrelated session: want ErrArtifactNotFound, got %v", err)
}
}
🤖 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 `@internal/service/document_test.go` around lines 1904 - 1977, Add the missing
authorized-user success case in TestGetDocumentArtifact_AuthGate: after seeding
the owner’s UserCanvas and API4Conversation, assert that
svc.GetDocumentArtifact("result.png", "user-1") does not return
ErrArtifactNotFound. Use the existing GetDocumentArtifact, ErrArtifactNotFound,
and the seeded sess-1/agent-1 records to verify the positive gate path directly,
while keeping the current denial cases intact.

Comment thread internal/service/document.go Resolved

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/agent/component/verify_p1_test.go (1)

32-48: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert pipelinechunker explicitly instead of only widening the count window.

Lines 47-48 now allow a larger registry, but this test still passes if PipelineChunker never registers and some other component keeps the total within range. Since this file is the registration guard, add pipelinechunker to the required set so init() registration is actually covered.

Proposed fix
-	// Always-present P0+P1 (12 names — ExitLoop removed).
+	// Always-present P0+P1 (13 names including PipelineChunker — ExitLoop removed).
 	requiredP0P1 := []string{
 		"agent", "begin", "categorize", "dataoperations",
 		"invoke", "listoperations", "llm", "message", "stringtransform",
-		"switch", "variableaggregator", "variableassigner",
+		"switch", "variableaggregator", "variableassigner", "pipelinechunker",
 	}
@@
-	if got := len(names); got < 12 || got > 32 {
-		t.Errorf("expected 12-32 registered (current plan scope + v1 stubs), got %d: %v", got, names)
+	if got := len(names); got < 13 || got > 32 {
+		t.Errorf("expected 13-32 registered (current plan scope + v1 stubs), got %d: %v", got, names)
 	}
🤖 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 `@internal/agent/component/verify_p1_test.go` around lines 32 - 48, The
registration guard in verify_p1_test.go only widens the allowed component count,
so it can still pass even if PipelineChunker never registers. Update the
requiredP0P1 set in the test to explicitly include pipelinechunker and keep the
existing name-based presence check in verifyP1 registration coverage; use the
names/have checks in this test to ensure init() registration for PipelineChunker
is asserted directly, not inferred from the total count.
internal/handler/document_test.go (1)

84-96: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Capture the forwarded userID in the fake.

The handler contract is now user-scoped, but this stub drops the new argument, so the handler tests cannot fail if GetDocumentArtifact stops passing user.ID.

Example adjustment
 type fakeDocumentService struct {
+	artifactUserID string
 	deleted         int
 	err             error
@@
-func (f *fakeDocumentService) GetDocumentArtifact(filename, _ string) (*service.ArtifactResponse, error) {
+func (f *fakeDocumentService) GetDocumentArtifact(filename, userID string) (*service.ArtifactResponse, error) {
+	f.artifactUserID = userID
 	if filename == "error.txt" {
 		return nil, service.ErrArtifactNotFound
 	}
🤖 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 `@internal/handler/document_test.go` around lines 84 - 96, The
fakeDocumentService.GetDocumentArtifact stub currently ignores the forwarded
user identifier, so the document handler tests cannot verify user-scoped
behavior. Update the fake to capture and store the second argument (the userID)
in the test double, and add/adjust assertions in the document handler tests so
they fail if the handler stops passing user.ID through to GetDocumentArtifact.
♻️ Duplicate comments (7)
internal/agent/component/llm.go (1)

862-870: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Normalize the merged thinking value, not just the override.

Line 862 only validates inputs["thinking"]. If base.Thinking is already set, an explicit thinking: "" cannot clear it back to provider default, and any invalid inherited value still reaches ChatInvokeRequest.

Suggested fix
-	if v, ok := stringFrom(inputs, "thinking"); ok {
-		// Only allow the two known sentinels through; an arbitrary
-		// string from the DSL is dropped to avoid surprising the LLM
-		// driver. Mirrors python llm.py:78-79 which gates on the
-		// same {"enabled","disabled"} set.
-		if v == "enabled" || v == "disabled" {
-			p.Thinking = v
-		}
-	}
+	if raw, ok := inputs["thinking"]; ok {
+		if v, ok := raw.(string); ok {
+			p.Thinking = v
+		}
+	}
+	switch p.Thinking {
+	case "", "enabled", "disabled":
+	default:
+		p.Thinking = ""
+	}
🤖 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 `@internal/agent/component/llm.go` around lines 862 - 870, The merged thinking
handling in the llm request builder only validates the override from inputs, so
inherited values from base.Thinking can still leak through and an explicit empty
thinking cannot reset to provider default. Update the logic around the thinking
merge in the llm.go request construction to normalize the final value after
combining base and override, treating empty as an intentional clear and only
preserving the known enabled/disabled sentinels before populating p.Thinking.
internal/agent/component/pipeline_chunker_test.go (1)

459-469: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the decoded chunk content here.

Lines 459-469 only prove that Invoke succeeded. If "Zm9v" started flowing through as raw text again, this test would still pass. Assert that the emitted chunk is "foo" so the base64 decode path is actually pinned.

Proposed fix
-	_, err = c.Invoke(pipelineChunkerCtx(t), map[string]any{
+	out, err := c.Invoke(pipelineChunkerCtx(t), map[string]any{
 		"file_ref": "Zm9v",
 	})
@@
 	if err != nil {
 		t.Fatalf("Zm9v is valid base64; want no error, got %v", err)
 	}
+	chunks, _ := out["chunks"].([]string)
+	if len(chunks) != 1 || chunks[0] != "foo" {
+		t.Fatalf("file_ref Zm9v: want decoded chunk %q, got %v", "foo", chunks)
+	}
 }
🤖 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 `@internal/agent/component/pipeline_chunker_test.go` around lines 459 - 469,
The pipelineChunker test only checks that Invoke succeeds for the valid base64
input "Zm9v", but it does not verify the emitted chunk content. Update the test
around c.Invoke and the existing pipelineChunkerCtx(t) flow to assert that the
produced chunk text is "foo", using the relevant chunk output from the
pipelineChunker test helpers, so the base64 decode path is explicitly covered
and raw-text fallback cannot slip through.
internal/agent/component/pipeline_chunker.go (2)

394-400: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

The string byte-input contract still falls through as “no input”.

Line 394 skips file_ref: "", so the explicit zero-byte error in decodeFileRefString never runs, and Lines 399-400 still only accept []byte for file_bytes even though Inputs() documents the same base64-string contract as file_ref. Both cases silently bypass validation and end up at the empty-input sentinel.

Proposed fix
-	if s, ok := inputs["file_ref"].(string); ok && s != "" {
+	if s, ok := inputs["file_ref"].(string); ok {
 		return decodeFileRefString(s)
 	}
@@
 	if b, ok := inputs["file_bytes"].([]byte); ok {
 		return validateAndDecodeBytes(b)
 	}
+	if s, ok := inputs["file_bytes"].(string); ok {
+		return decodeFileRefString(s)
+	}
 	return "", nil
 }
🤖 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 `@internal/agent/component/pipeline_chunker.go` around lines 394 - 400, The
input handling in the pipeline chunker is skipping validation for empty string
byte inputs and for base64 string payloads under file_bytes. Update the logic in
the input dispatch around the file_ref and file_bytes cases so that file_ref
always routes through decodeFileRefString, even when the string is empty, and
file_bytes accepts the same string contract documented by Inputs() before
falling back to validateAndDecodeBytes. Keep the existing helper symbols
decodeFileRefString and validateAndDecodeBytes as the single validation paths so
empty or invalid byte inputs do not fall through to the no-input sentinel.

138-141: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject malformed parser_config instead of erasing it.

Line 138 rewrites every non-map parser_config to {}, so Line 164 can never catch a bad value from the normal constructor path. That silently accepts invalid DSL instead of failing fast.

Proposed fix
-	if cfg, ok := conf["parser_config"].(map[string]any); ok {
-		p.ParserConfig = cfg
-	} else {
-		p.ParserConfig = map[string]any{}
-	}
+	if raw, exists := conf["parser_config"]; exists {
+		cfg, ok := raw.(map[string]any)
+		if !ok {
+			return fmt.Errorf("PipelineChunker: parser_config must be a dict")
+		}
+		p.ParserConfig = cfg
+	} else {
+		p.ParserConfig = map[string]any{}
+	}
🤖 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 `@internal/agent/component/pipeline_chunker.go` around lines 138 - 141, The
parser_config handling in the pipeline chunker constructor is too permissive:
when conf["parser_config"] is not a map, it gets replaced with an empty config
and hides malformed DSL. Update the initialization in the pipeline chunker setup
to preserve the invalid value or return an error instead of defaulting
ParserConfig to an empty map, so the existing validation path in the constructor
can fail fast. Use the parser_config parsing block and the ParserConfig field in
the chunker initialization to locate the fix.
internal/service/document_test.go (1)

1944-1976: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Assert the authorized-user success path too.

This test seeds the owner/reference case, but never proves it is reachable. If sandboxArtifactAccessible("result.png", "user-1") regresses to always false, all current assertions still pass.

Minimal assertion
 	svc := testDocumentService(t)
+
+	if !svc.sandboxArtifactAccessible("result.png", "user-1") {
+		t.Fatalf("owner with referenced artifact: want accessible")
+	}
 
 	// Case 1: empty user -> not allowed.
🤖 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 `@internal/service/document_test.go` around lines 1944 - 1976, Add an explicit
success assertion in the GetDocumentArtifact test for the authorized owner path:
after seeding the owner/reference session for user-1, verify that
svc.GetDocumentArtifact("result.png", "user-1") returns the artifact without
ErrArtifactNotFound. Use the existing GetDocumentArtifact and
sandboxArtifactAccessible flow in internal/service/document_test.go to confirm
the reachable happy path, not just the denial cases.
internal/dao/user_canvas.go (1)

139-151: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Accessible still treats every team canvas as globally reachable.

GetByIDForUser scopes team access through tenantIDs, but this helper drops that constraint and authorizes any row with permission = "team". The new artifact/rerun gates inherit that bypass.

Suggested direction
-func (dao *UserCanvasDAO) Accessible(canvasID, userID string) bool {
+func (dao *UserCanvasDAO) Accessible(canvasID, userID string, tenantIDs []string) bool {
 	if canvasID == "" || userID == "" {
 		return false
 	}
+	ownerOrTeam := DB.Where("user_id = ?", userID)
+	if len(tenantIDs) > 0 {
+		ownerOrTeam = ownerOrTeam.Or(
+			"user_id IN ? AND permission = ?", tenantIDs, "team",
+		)
+	}
 	var canvas entity.UserCanvas
 	err := DB.Select("id").
 		Where("id = ?", canvasID).
-		Where("user_id = ? OR permission = ?", userID, "team").
+		Where(ownerOrTeam).
 		First(&canvas).Error
🤖 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 `@internal/dao/user_canvas.go` around lines 139 - 151, The Accessible helper is
still bypassing tenant scoping by allowing any row with permission = "team" to
pass. Update UserCanvasDAO.Accessible to enforce the same tenant-based
restriction used by GetByIDForUser, so team canvases are only accessible when
the canvas belongs to an allowed tenant for the given userID. Keep the existing
canvasID/userID guards, and adjust the DB.Select/Where chain in Accessible to
match the tenant-aware access rules rather than treating team canvases as
globally reachable.
internal/service/document.go (1)

316-323: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Escape % and _ before using filename in the auth query.

filename comes from the request path, and basename validation still allows LIKE wildcards. This query can satisfy the authorization gate with a different referenced artifact name, then the storage read fetches the exact requested key.

Minimal fix
 	artifactRef := "documents/artifact/" + filename
+	filenamePattern := "%" + escapeSQLLike(filename) + "%"
+	artifactRefPattern := "%" + escapeSQLLike(artifactRef) + "%"
 	dialogIDs := make(map[string]struct{})
 	rows, err := dao.DB.Model(&entity.API4Conversation{}).
 		Select("dialog_id").
 		Where("user_id = ? OR exp_user_id = ?", userID, userID).
-		Where("message LIKE ? OR message LIKE ?", "%"+filename+"%", "%"+artifactRef+"%").
+		Where(`message LIKE ? ESCAPE '\\' OR message LIKE ? ESCAPE '\\'`, filenamePattern, artifactRefPattern).
 		Distinct("dialog_id").
 		Rows()
func escapeSQLLike(s string) string {
	return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}
🤖 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 `@internal/service/document.go` around lines 316 - 323, The auth lookup in
document.go is using filename directly inside the LIKE filters in the query
built from dao.DB.Model(&entity.API4Conversation{}), which lets `%` and `_` act
as wildcards. Update the query construction around the artifactRef/Rows logic to
escape SQL LIKE metacharacters before interpolating filename and artifactRef,
and use that escaped value in the message predicates so the authorization check
matches the exact requested artifact name only.
🧹 Nitpick comments (1)
internal/handler/agent_webhook_test.go (1)

83-91: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid mutating caller-provided test params.

Line 87 writes the default security block into the input map, so reused table-test params can inherit anonymous auth after one helper call. Clone before injecting defaults.

Proposed refactor
-	if params == nil {
-		params = map[string]any{}
-	}
-	if _, ok := params["security"]; !ok {
-		params["security"] = map[string]any{
+	mergedParams := map[string]any{}
+	for k, v := range params {
+		mergedParams[k] = v
+	}
+	if _, ok := mergedParams["security"]; !ok {
+		mergedParams["security"] = map[string]any{
 			"auth_type":       "none",
 			"allow_anonymous": true,
 		}
 	}
-	for k, v := range params {
+	for k, v := range mergedParams {
🤖 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 `@internal/handler/agent_webhook_test.go` around lines 83 - 91, The helper in
agent_webhook_test.go is mutating the caller-provided params map when it injects
the default security block, which can leak anonymous auth into reused test
cases. Update the setup logic to work on a cloned copy of params before adding
defaults, and keep the existing defaulting behavior in the same helper path that
handles params["security"].
🤖 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 `@internal/agent/component/invoke_test.go`:
- Around line 31-42: The test setup currently sets ALLOW_ANY_HOST globally in
init(), which affects unrelated tests in the package. Remove the package-wide
init-based env mutation in invoke_test.go and scope the override only to the
specific tests that need loopback httptest access by using t.Setenv inside those
test functions. Keep the existing allowAnyHostForTest intent, but ensure only
the relevant Invoke tests opt into the relaxed SSRF guard while the rest
continue using the default production behavior.

In `@internal/agent/tool/exesql_ssrf_test.go`:
- Around line 148-155: The pinning test is no longer hermetic because
`InvokableRun` proceeds past the `recordingDialer` into `db.PingContext`,
causing a real network timeout. Update the test setup around
`NewExeSQLTool(...).WithExeSQLDialer(rec.dial)` and the `recordingDialer` helper
so the dialer fails fast by default or is explicitly configured with `failFast:
true`, ensuring the test stops after capturing the DSN and never reaches a TCP
connect.

In `@internal/handler/agent.go`:
- Around line 77-91: The optional documentService wiring in AgentHandler creates
an authorization bypass because RerunAgent skips document ownership checks when
the dependency is nil. Update NewAgentHandler and the RerunAgent flow so
document access is required and the request fails closed if the service is
missing, rather than allowing tenant-only authorization; keep the fix centered
on AgentHandler, WithDocumentService, and RerunAgent.

In `@internal/utility/ssrf.go`:
- Around line 37-50: The shared runtime SSRF bypass in allowAnyHost is too broad
because ALLOW_ANY_HOST disables both AssertURLSafe validation and the
resolvedIP-based DNS pinning for all callers. Remove this environment-variable
escape hatch from the production path and move it behind test-only plumbing, so
only tests can opt in to the bypass; update the SSRF helper and any call sites
in the shared validation flow to use a test-only mechanism instead of a live
runtime toggle.

---

Outside diff comments:
In `@internal/agent/component/verify_p1_test.go`:
- Around line 32-48: The registration guard in verify_p1_test.go only widens the
allowed component count, so it can still pass even if PipelineChunker never
registers. Update the requiredP0P1 set in the test to explicitly include
pipelinechunker and keep the existing name-based presence check in verifyP1
registration coverage; use the names/have checks in this test to ensure init()
registration for PipelineChunker is asserted directly, not inferred from the
total count.

In `@internal/handler/document_test.go`:
- Around line 84-96: The fakeDocumentService.GetDocumentArtifact stub currently
ignores the forwarded user identifier, so the document handler tests cannot
verify user-scoped behavior. Update the fake to capture and store the second
argument (the userID) in the test double, and add/adjust assertions in the
document handler tests so they fail if the handler stops passing user.ID through
to GetDocumentArtifact.

---

Duplicate comments:
In `@internal/agent/component/llm.go`:
- Around line 862-870: The merged thinking handling in the llm request builder
only validates the override from inputs, so inherited values from base.Thinking
can still leak through and an explicit empty thinking cannot reset to provider
default. Update the logic around the thinking merge in the llm.go request
construction to normalize the final value after combining base and override,
treating empty as an intentional clear and only preserving the known
enabled/disabled sentinels before populating p.Thinking.

In `@internal/agent/component/pipeline_chunker_test.go`:
- Around line 459-469: The pipelineChunker test only checks that Invoke succeeds
for the valid base64 input "Zm9v", but it does not verify the emitted chunk
content. Update the test around c.Invoke and the existing pipelineChunkerCtx(t)
flow to assert that the produced chunk text is "foo", using the relevant chunk
output from the pipelineChunker test helpers, so the base64 decode path is
explicitly covered and raw-text fallback cannot slip through.

In `@internal/agent/component/pipeline_chunker.go`:
- Around line 394-400: The input handling in the pipeline chunker is skipping
validation for empty string byte inputs and for base64 string payloads under
file_bytes. Update the logic in the input dispatch around the file_ref and
file_bytes cases so that file_ref always routes through decodeFileRefString,
even when the string is empty, and file_bytes accepts the same string contract
documented by Inputs() before falling back to validateAndDecodeBytes. Keep the
existing helper symbols decodeFileRefString and validateAndDecodeBytes as the
single validation paths so empty or invalid byte inputs do not fall through to
the no-input sentinel.
- Around line 138-141: The parser_config handling in the pipeline chunker
constructor is too permissive: when conf["parser_config"] is not a map, it gets
replaced with an empty config and hides malformed DSL. Update the initialization
in the pipeline chunker setup to preserve the invalid value or return an error
instead of defaulting ParserConfig to an empty map, so the existing validation
path in the constructor can fail fast. Use the parser_config parsing block and
the ParserConfig field in the chunker initialization to locate the fix.

In `@internal/dao/user_canvas.go`:
- Around line 139-151: The Accessible helper is still bypassing tenant scoping
by allowing any row with permission = "team" to pass. Update
UserCanvasDAO.Accessible to enforce the same tenant-based restriction used by
GetByIDForUser, so team canvases are only accessible when the canvas belongs to
an allowed tenant for the given userID. Keep the existing canvasID/userID
guards, and adjust the DB.Select/Where chain in Accessible to match the
tenant-aware access rules rather than treating team canvases as globally
reachable.

In `@internal/service/document_test.go`:
- Around line 1944-1976: Add an explicit success assertion in the
GetDocumentArtifact test for the authorized owner path: after seeding the
owner/reference session for user-1, verify that
svc.GetDocumentArtifact("result.png", "user-1") returns the artifact without
ErrArtifactNotFound. Use the existing GetDocumentArtifact and
sandboxArtifactAccessible flow in internal/service/document_test.go to confirm
the reachable happy path, not just the denial cases.

In `@internal/service/document.go`:
- Around line 316-323: The auth lookup in document.go is using filename directly
inside the LIKE filters in the query built from
dao.DB.Model(&entity.API4Conversation{}), which lets `%` and `_` act as
wildcards. Update the query construction around the artifactRef/Rows logic to
escape SQL LIKE metacharacters before interpolating filename and artifactRef,
and use that escaped value in the message predicates so the authorization check
matches the exact requested artifact name only.

---

Nitpick comments:
In `@internal/handler/agent_webhook_test.go`:
- Around line 83-91: The helper in agent_webhook_test.go is mutating the
caller-provided params map when it injects the default security block, which can
leak anonymous auth into reused test cases. Update the setup logic to work on a
cloned copy of params before adding defaults, and keep the existing defaulting
behavior in the same helper path that handles params["security"].
🪄 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: 5b24eea1-e5e8-4c31-8c04-f90fe6a5448e

📥 Commits

Reviewing files that changed from the base of the PR and between c0f6429 and 621472e.

📒 Files selected for processing (44)
  • cmd/server_main.go
  • internal/agent/component/base.go
  • internal/agent/component/base_test.go
  • internal/agent/component/invoke.go
  • internal/agent/component/invoke_test.go
  • internal/agent/component/llm.go
  • internal/agent/component/llm_test.go
  • internal/agent/component/pipeline_chunker.go
  • internal/agent/component/pipeline_chunker_test.go
  • internal/agent/component/switch.go
  • internal/agent/component/switch_test.go
  • internal/agent/component/verify_p1_test.go
  • internal/agent/tool/deepl_test.go
  • internal/agent/tool/exesql.go
  • internal/agent/tool/exesql_ssrf_test.go
  • internal/agent/tool/exesql_test.go
  • internal/agent/tool/exesql_trino_test.go
  • internal/agent/tool/exesql_unsupported_test.go
  • internal/agent/tool/http_timeout_guard_test.go
  • internal/agent/tool/ssrf.go
  • internal/dao/user_canvas.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/handler/agent_webhook_security.go
  • internal/handler/agent_webhook_security_test.go
  • internal/handler/agent_webhook_test.go
  • internal/handler/auth.go
  • internal/handler/bot.go
  • internal/handler/bot_test.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/bot_routes.go
  • internal/router/router.go
  • internal/service/agent_test.go
  • internal/service/bot_completion.go
  • internal/service/bot_completion_history_test.go
  • internal/service/document.go
  • internal/service/document_test.go
  • internal/service/user.go
  • internal/utility/ssrf.go
💤 Files with no reviewable changes (4)
  • internal/entity/models/zhipu-ai.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go

Comment thread internal/agent/component/invoke_test.go Resolved
Comment thread internal/agent/tool/exesql_ssrf_test.go Resolved
Comment thread internal/handler/agent.go Resolved
Comment thread internal/utility/ssrf.go Resolved
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Critical (1):
- handler/auth.go: dereference tok.DialogID before storing in
  gin context so the downstream agentID.(string) assertion
  succeeds for beta-bound tokens.

Major (9):
- agent/component/invoke.go: fail closed when a proxy is set
  with a hostname target URL — the proxy re-resolves the
  target, re-opening the SSRF/DNS-rebinding window the guard
  was supposed to close.
- agent/component/invoke_test.go: pin the proxy DNS pin test
  via t.Fatalf (was t.Logf — the test passed even when the
  pin regressed).
- agent/component/pipeline_chunker.go: accept base64 string
  in file_bytes (matches the file_ref contract and inputs()
  doc).
- agent/tool/exesql.go: route all DSN formats through
  net.JoinHostPort so IPv6 hosts produce bracketed
  tcp([host]:port) form.
- dao/user_canvas.go: scope Accessible's team branch to
  tenantIDs so a permission=team canvas is only reachable when
  the caller belongs to the owner's tenant (mirrors
  GetByIDForUser).
- handler/agent.go: define a narrow documentAccessChecker
  interface so handler tests can inject a deny-all stub
  without standing up the full DocumentService.
- handler/agent_webhook_security.go: share one sentinel
  error between the missing-security and anonymous-without-
  opt-in branches (a probe cannot distinguish them).
- handler/bot.go: surface Redis / JSON decode failures from
  GetAgentbotLogs as a real error envelope instead of
  returning {code: 0, data: {}}.
- service/document.go: escape %, _, ! in the LIKE auth-gate
  filename pattern so a wildcard filename cannot cross-match
  another user's referenced artifact.

Tests:
- handler/agent_test.go: rewire TestRerunAgent_* tests to use
  the new deny-all stubDocService and pin the
  /Document not found/ envelope; add a positive nil-service
  control test.
- handler/agent_webhook_security_test.go: pin the unified
  fail-closed error.
- agent/component/invoke_test.go: switch proxy test to a
  literal IP target; new TestInvoke_ProxyRejectsHostnameTarget.
- agent/tool/exesql_test.go: update DSN expectations for the
  JoinHostPort shape; new TestExeSQL_DSN_IPv6.
- service/document_test.go: new TestEscapeSQLLikePattern
  unit test; new TestSandboxArtifactDialogIDsForUser_LikeWildcardEscaped
  regression test (uses a TEXT-affinity table to bypass
  the SQLite longtext→NUMERIC-affinity quirk).

2124 tests pass, 11 skipped; only the pre-existing flaky
TestAgent_ReActExhaustsSteps (unrelated to this PR) fails.
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 29, 2026
@yuzhichang

Copy link
Copy Markdown
Member Author

Resolved the 1 Critical + 9 Major review comments in commit 7ecb7b6a8:

Critical

  • handler/auth.go:97 — dereference tok.DialogID before stashing in gin context so agentID.(string) succeeds.

Major

  • agent/component/invoke.go — proxy mode now fails closed for hostname targets (the proxy would re-resolve them and re-open the rebinding window).
  • agent/component/invoke_test.go — DNS pin regression now t.Fatalf instead of t.Logf.
  • agent/component/pipeline_chunker.go — file_bytes now accepts the base64 string form, matching file_ref and the doc.
  • agent/tool/exesql.go — all DSN formats routed through net.JoinHostPort so IPv6 produces tcp([host]:port).
  • dao/user_canvas.go — Accessible now scopes team canvases to tenantIDs, matching GetByIDForUser.
  • handler/agent.go — narrow documentAccessChecker interface so tests can inject a deny-all stub; TestRerunAgent_RejectsInaccessibleDocument now exercises the real gate path.
  • handler/agent_webhook_security.go — single errWebhookFailClosed sentinel shared by both fail-closed branches.
  • handler/bot.go — GetAgentbotLogs surfaces Redis and JSON decode failures as real error envelopes.
  • service/document.go — filename escaped via escapeSQLLikePattern before the LIKE … ESCAPE '!' query; a wildcard filename can no longer cross-match another user's referenced artifact.

9 Minor comments deferred (test tightening / doc sync) — not blockers. 2124 tests pass, 11 skipped. The single failure (TestAgent_ReActExhaustsSteps) is the pre-existing sqlmock flake that was already noted in the prior review cycle.

@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: 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 `@internal/agent/tool/exesql.go`:
- Around line 479-506: The DSN construction in the configuration-to-connection
string logic is incorrectly reusing net.JoinHostPort for the Postgres and MSSQL
branches, which merges host and port into one value. Update the switch in the
DSN builder so the MySQL/OceanBase paths keep using hostPort, but the
postgres/postgresql and mssql/sqlserver cases pass c.Host and c.Port as separate
fields in their keyword/ADO strings. Verify the related tests around the DSN
builder and adjust them to match the corrected host/server and port formatting.

In `@internal/service/document_test.go`:
- Around line 1913-1919: Update the test around TestEscapeSQLLikePattern to
mirror the production auth-gate logic used by sandboxArtifactDialogIDsForUser:
build the LIKE pattern with the same leading and trailing percent wrapping
around escapeSQLLikePattern output, and stop hardcoding "!%.png%". Also align
the test comment with the actual ESCAPE character used in the implementation,
which is "!". Ensure the assertions reference the same pattern shape as the
production code so the test cannot pass while diverging from the real
authorization 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6af40931-fb4f-44bd-a526-a5fffa26ae31

📥 Commits

Reviewing files that changed from the base of the PR and between 621472e and 7ecb7b6.

📒 Files selected for processing (14)
  • internal/agent/component/invoke.go
  • internal/agent/component/invoke_test.go
  • internal/agent/component/pipeline_chunker.go
  • internal/agent/tool/exesql.go
  • internal/agent/tool/exesql_test.go
  • internal/dao/user_canvas.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/handler/agent_webhook_security.go
  • internal/handler/agent_webhook_security_test.go
  • internal/handler/auth.go
  • internal/handler/bot.go
  • internal/service/document.go
  • internal/service/document_test.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/handler/auth.go
  • internal/handler/agent.go
  • internal/handler/bot.go
  • internal/handler/agent_webhook_security_test.go
  • internal/handler/agent_webhook_security.go
  • internal/agent/component/pipeline_chunker.go
  • internal/agent/component/invoke.go
  • internal/service/document.go

Comment thread internal/agent/tool/exesql.go Resolved
Comment thread internal/service/document_test.go Resolved
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
…nd 6

- exesql_ssrf_test.go: TestExeSQL_SSRF_PinsToValidatedIP now
  uses failFast:true on the recordingDialer so the test
  stops after recording the DSN and never attempts a real
  TCP connect to 1.2.3.4:3306.
- agent.go: RerunAgent fails closed when documentService is
  nil — a missing dependency used to silently bypass the
  doc-ownership gate. Now returns 500 'server
  misconfiguration' so wiring misses are loud.
- ssrf.go + agent_dbcheck.go: removed the env-var-based
  ALLOW_ANY_HOST bypass from the runtime path and replaced
  it with a process-memory utility.AllowAnyHostForTest /
  service.AllowAnyHostForTest boolean that tests flip
  explicitly. Closes the path where an operator could
  disable the SSRF guard + DNS pinning via env var.
- exesql.go: Postgres and MSSQL DSNs now use distinct host/
  server and port fields (combined 'host=h:p' was rejected
  by lib/pq and go-mssqldb). IPv6 hosts are bracketed in
  the host/server slot only.

Tests:
- invoke_test.go: replaced the file-level init() that set
  ALLOW_ANY_HOST with per-test setupAllowAnyHost helper
  that flips the boolean and restores it via t.Cleanup.
- exesql_test.go: updated DSN expectations to match the
  separate-host/port format.
- agent_test.go: TestRerunAgent_AcceptsCompleteRequest now
  wires the deny-all stub flipped to accessible:true; new
  TestRerunAgent_NoDocumentServiceFailsClosed pins the
  fail-closed behaviour.

2121 tests pass; only the pre-existing flaky
TestAgent_ReActExhaustsSteps (sqlmock, unrelated to this PR)
fails.
@yuzhichang

Copy link
Copy Markdown
Member Author

Resolved 4 new Major review comments in commit 970a1fc3:

  • internal/agent/tool/exesql_ssrf_test.go — TestExeSQL_SSRF_PinsToValidatedIP now uses failFast:true on the recording dialer so the test stops after recording the DSN; no real TCP connect to 1.2.3.4:3306.
  • internal/handler/agent.go — RerunAgent fails closed when documentService is nil (500 "server misconfiguration"). A missing dependency used to silently bypass the doc-ownership gate.
  • internal/utility/ssrf.go + internal/service/agent_dbcheck.go — replaced the env-var ALLOW_ANY_HOST bypass with a process-memory utility.AllowAnyHostForTest / service.AllowAnyHostForTest boolean. No runtime toggle, no deployment flag — only test code can disable the guard.
  • internal/agent/tool/exesql.go — Postgres and MSSQL DSNs now use distinct host=/server= and port= fields (combined host=h:p was rejected by lib/pq and go-mssqldb). IPv6 hosts are bracketed only in the host/server slot.

Tests:

  • invoke_test.go: per-test setupAllowAnyHost(t, true|false) helper replaces the file-level init() that set the env var.
  • exesql_test.go: DSN expectations updated for the separate host/port format.
  • agent_test.go: new TestRerunAgent_NoDocumentServiceFailsClosed; TestRerunAgent_AcceptsCompleteRequest now wires the accessible stub.

2121 tests pass; only the pre-existing flaky TestAgent_ReActExhaustsSteps (sqlmock, unrelated to this PR) fails.

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

♻️ Duplicate comments (1)
internal/agent/component/invoke_test.go (1)

224-247: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the proxy guard output here too.

serverHit is unrelated to 127.0.0.1:8080, so this still passes without proving the unsafe proxy was rejected by the guard. Capture out and assert _ERROR == "URL not valid".

Suggested test tightening
-	_, err := c.Invoke(context.Background(), map[string]any{
+	out, err := c.Invoke(context.Background(), map[string]any{
 		"method": "GET",
 		"url":    "https://example.com/api",
 		"proxy":  "http://127.0.0.1:8080",
 	})
@@
 	if serverHit {
 		t.Errorf("server hit despite unsafe proxy; guard bypassed")
 	}
+	if got, _ := out["_ERROR"].(string); got != "URL not valid" {
+		t.Errorf("_ERROR = %q, want %q", got, "URL not valid")
+	}
🤖 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 `@internal/agent/component/invoke_test.go` around lines 224 - 247, The
proxy-guard test in TestInvoke_SSRFGuard_BlocksProxy does not currently verify
that the unsafe proxy was rejected, so tighten it by capturing the Invoke output
and asserting the guard’s error payload. Update the test around c.Invoke in
Invoke so it checks the returned out for _ERROR equal to "URL not valid" while
still keeping the serverHit assertion, using the existing SSRF guard setup and
proxy argument to confirm the loopback proxy is blocked.
🤖 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.

Duplicate comments:
In `@internal/agent/component/invoke_test.go`:
- Around line 224-247: The proxy-guard test in TestInvoke_SSRFGuard_BlocksProxy
does not currently verify that the unsafe proxy was rejected, so tighten it by
capturing the Invoke output and asserting the guard’s error payload. Update the
test around c.Invoke in Invoke so it checks the returned out for _ERROR equal to
"URL not valid" while still keeping the serverHit assertion, using the existing
SSRF guard setup and proxy argument to confirm the loopback proxy is blocked.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1d9095f9-feeb-435c-ac46-6dbc2af2ffd7

📥 Commits

Reviewing files that changed from the base of the PR and between 7ecb7b6 and 970a1fc.

📒 Files selected for processing (8)
  • internal/agent/component/invoke_test.go
  • internal/agent/tool/exesql.go
  • internal/agent/tool/exesql_ssrf_test.go
  • internal/agent/tool/exesql_test.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/service/agent_dbcheck.go
  • internal/utility/ssrf.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/agent/tool/exesql_ssrf_test.go
  • internal/agent/tool/exesql.go
  • internal/agent/tool/exesql_test.go

yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Critical (1):
- handler/auth.go: dereference tok.DialogID before storing in
  gin context so the downstream agentID.(string) assertion
  succeeds for beta-bound tokens.

Major (9):
- agent/component/invoke.go: fail closed when a proxy is set
  with a hostname target URL — the proxy re-resolves the
  target, re-opening the SSRF/DNS-rebinding window the guard
  was supposed to close.
- agent/component/invoke_test.go: pin the proxy DNS pin test
  via t.Fatalf (was t.Logf — the test passed even when the
  pin regressed).
- agent/component/pipeline_chunker.go: accept base64 string
  in file_bytes (matches the file_ref contract and inputs()
  doc).
- agent/tool/exesql.go: route all DSN formats through
  net.JoinHostPort so IPv6 hosts produce bracketed
  tcp([host]:port) form.
- dao/user_canvas.go: scope Accessible's team branch to
  tenantIDs so a permission=team canvas is only reachable when
  the caller belongs to the owner's tenant (mirrors
  GetByIDForUser).
- handler/agent.go: define a narrow documentAccessChecker
  interface so handler tests can inject a deny-all stub
  without standing up the full DocumentService.
- handler/agent_webhook_security.go: share one sentinel
  error between the missing-security and anonymous-without-
  opt-in branches (a probe cannot distinguish them).
- handler/bot.go: surface Redis / JSON decode failures from
  GetAgentbotLogs as a real error envelope instead of
  returning {code: 0, data: {}}.
- service/document.go: escape %, _, ! in the LIKE auth-gate
  filename pattern so a wildcard filename cannot cross-match
  another user's referenced artifact.

Tests:
- handler/agent_test.go: rewire TestRerunAgent_* tests to use
  the new deny-all stubDocService and pin the
  /Document not found/ envelope; add a positive nil-service
  control test.
- handler/agent_webhook_security_test.go: pin the unified
  fail-closed error.
- agent/component/invoke_test.go: switch proxy test to a
  literal IP target; new TestInvoke_ProxyRejectsHostnameTarget.
- agent/tool/exesql_test.go: update DSN expectations for the
  JoinHostPort shape; new TestExeSQL_DSN_IPv6.
- service/document_test.go: new TestEscapeSQLLikePattern
  unit test; new TestSandboxArtifactDialogIDsForUser_LikeWildcardEscaped
  regression test (uses a TEXT-affinity table to bypass
  the SQLite longtext→NUMERIC-affinity quirk).

2124 tests pass, 11 skipped; only the pre-existing flaky
TestAgent_ReActExhaustsSteps (unrelated to this PR) fails.
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
…nd 6

- exesql_ssrf_test.go: TestExeSQL_SSRF_PinsToValidatedIP now
  uses failFast:true on the recordingDialer so the test
  stops after recording the DSN and never attempts a real
  TCP connect to 1.2.3.4:3306.
- agent.go: RerunAgent fails closed when documentService is
  nil — a missing dependency used to silently bypass the
  doc-ownership gate. Now returns 500 'server
  misconfiguration' so wiring misses are loud.
- ssrf.go + agent_dbcheck.go: removed the env-var-based
  ALLOW_ANY_HOST bypass from the runtime path and replaced
  it with a process-memory utility.AllowAnyHostForTest /
  service.AllowAnyHostForTest boolean that tests flip
  explicitly. Closes the path where an operator could
  disable the SSRF guard + DNS pinning via env var.
- exesql.go: Postgres and MSSQL DSNs now use distinct host/
  server and port fields (combined 'host=h:p' was rejected
  by lib/pq and go-mssqldb). IPv6 hosts are bracketed in
  the host/server slot only.

Tests:
- invoke_test.go: replaced the file-level init() that set
  ALLOW_ANY_HOST with per-test setupAllowAnyHost helper
  that flips the boolean and restores it via t.Cleanup.
- exesql_test.go: updated DSN expectations to match the
  separate-host/port format.
- agent_test.go: TestRerunAgent_AcceptsCompleteRequest now
  wires the deny-all stub flipped to accessible:true; new
  TestRerunAgent_NoDocumentServiceFailsClosed pins the
  fail-closed behaviour.

2121 tests pass; only the pre-existing flaky
TestAgent_ReActExhaustsSteps (sqlmock, unrelated to this PR)
fails.

@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 `@internal/service/chat_session.go`:
- Around line 641-647: `DeleteSessionMessage` is validating session payloads
differently from `UpdateMessageFeedback`, which lets malformed but valid JSON
slip through and get overwritten. Update the validation in
`DeleteSessionMessage` to use `isAcceptedMessageShape` like
`UpdateMessageFeedback` does, and remove the now-dead `messages == nil` fallback
after `parseMessages` in the same flow. Keep the existing `parseMessages` path
only for successfully accepted message shapes so both methods reject the same
bad session blobs.
🪄 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: 1b28f49b-387c-4a54-b8e7-65c4738b77a8

📥 Commits

Reviewing files that changed from the base of the PR and between ca570e1 and 392c51d.

📒 Files selected for processing (1)
  • internal/service/chat_session.go

Comment thread internal/service/chat_session.go Resolved
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Critical (1):
- handler/auth.go: dereference tok.DialogID before storing in
  gin context so the downstream agentID.(string) assertion
  succeeds for beta-bound tokens.

Major (9):
- agent/component/invoke.go: fail closed when a proxy is set
  with a hostname target URL — the proxy re-resolves the
  target, re-opening the SSRF/DNS-rebinding window the guard
  was supposed to close.
- agent/component/invoke_test.go: pin the proxy DNS pin test
  via t.Fatalf (was t.Logf — the test passed even when the
  pin regressed).
- agent/component/pipeline_chunker.go: accept base64 string
  in file_bytes (matches the file_ref contract and inputs()
  doc).
- agent/tool/exesql.go: route all DSN formats through
  net.JoinHostPort so IPv6 hosts produce bracketed
  tcp([host]:port) form.
- dao/user_canvas.go: scope Accessible's team branch to
  tenantIDs so a permission=team canvas is only reachable when
  the caller belongs to the owner's tenant (mirrors
  GetByIDForUser).
- handler/agent.go: define a narrow documentAccessChecker
  interface so handler tests can inject a deny-all stub
  without standing up the full DocumentService.
- handler/agent_webhook_security.go: share one sentinel
  error between the missing-security and anonymous-without-
  opt-in branches (a probe cannot distinguish them).
- handler/bot.go: surface Redis / JSON decode failures from
  GetAgentbotLogs as a real error envelope instead of
  returning {code: 0, data: {}}.
- service/document.go: escape %, _, ! in the LIKE auth-gate
  filename pattern so a wildcard filename cannot cross-match
  another user's referenced artifact.

Tests:
- handler/agent_test.go: rewire TestRerunAgent_* tests to use
  the new deny-all stubDocService and pin the
  /Document not found/ envelope; add a positive nil-service
  control test.
- handler/agent_webhook_security_test.go: pin the unified
  fail-closed error.
- agent/component/invoke_test.go: switch proxy test to a
  literal IP target; new TestInvoke_ProxyRejectsHostnameTarget.
- agent/tool/exesql_test.go: update DSN expectations for the
  JoinHostPort shape; new TestExeSQL_DSN_IPv6.
- service/document_test.go: new TestEscapeSQLLikePattern
  unit test; new TestSandboxArtifactDialogIDsForUser_LikeWildcardEscaped
  regression test (uses a TEXT-affinity table to bypass
  the SQLite longtext→NUMERIC-affinity quirk).

2124 tests pass, 11 skipped; only the pre-existing flaky
TestAgent_ReActExhaustsSteps (unrelated to this PR) fails.
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
…nd 6

- exesql_ssrf_test.go: TestExeSQL_SSRF_PinsToValidatedIP now
  uses failFast:true on the recordingDialer so the test
  stops after recording the DSN and never attempts a real
  TCP connect to 1.2.3.4:3306.
- agent.go: RerunAgent fails closed when documentService is
  nil — a missing dependency used to silently bypass the
  doc-ownership gate. Now returns 500 'server
  misconfiguration' so wiring misses are loud.
- ssrf.go + agent_dbcheck.go: removed the env-var-based
  ALLOW_ANY_HOST bypass from the runtime path and replaced
  it with a process-memory utility.AllowAnyHostForTest /
  service.AllowAnyHostForTest boolean that tests flip
  explicitly. Closes the path where an operator could
  disable the SSRF guard + DNS pinning via env var.
- exesql.go: Postgres and MSSQL DSNs now use distinct host/
  server and port fields (combined 'host=h:p' was rejected
  by lib/pq and go-mssqldb). IPv6 hosts are bracketed in
  the host/server slot only.

Tests:
- invoke_test.go: replaced the file-level init() that set
  ALLOW_ANY_HOST with per-test setupAllowAnyHost helper
  that flips the boolean and restores it via t.Cleanup.
- exesql_test.go: updated DSN expectations to match the
  separate-host/port format.
- agent_test.go: TestRerunAgent_AcceptsCompleteRequest now
  wires the deny-all stub flipped to accessible:true; new
  TestRerunAgent_NoDocumentServiceFailsClosed pins the
  fail-closed behaviour.

2121 tests pass; only the pre-existing flaky
TestAgent_ReActExhaustsSteps (sqlmock, unrelated to this PR)
fails.
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jun 29, 2026
@yuzhichang yuzhichang added ci Continue Integration and removed ci Continue Integration labels Jun 29, 2026
Ports 5 S-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 1 - tool ports
- infiniflow#15609 ExeSQL SSRF guard: add ValidateDBHost to tool/ssrf.go and
  wire into exesql.InvokableRun. Loopback, link-local, RFC1918, and
  empty host are rejected before any driver dispatch. Allowed hosts
  are dialed via the validated/resolved public IP (DNS-pin).
- infiniflow#15436 HTTP timeout: Go side already routes github/qweather/tushare
  through HTTPHelper (client.Timeout: 30s + per-stage timeouts) and
  jin10 is a stub. Added regression guard tests: default client
  timeout, stage timeouts, and AST scan for bare http.Get/Post calls
  outside the helper.

Group 2 - component ports
- infiniflow#16363 be_output restore + DeepL error: add BeOutput(v) helper
  returning {"content": v} frame; add DeepL translation-failure
  regression test using rewriteHostTransport (avoids mutating
  package globals which raced TestDeepL_BuildRequest).
- infiniflow#15644 Switch no longer matches empty condition: evaluateGroup
  empty-clauses short-circuit now returns false (was true) so an
  "and" condition with no clauses falls through to the next
  condition or end_cpn_ids instead of routing to the empty
  group's "to" target. Mirrors the all([]) is True fix.

Group 4 - API ports
- infiniflow#15374 session_id bind to path agent_id: Go DAO already enforces
  WHERE id = ? AND dialog_id = ? (stronger than the Python
  post-fetch check). Added 3 IDOR regression tests at the service
  level (Get/Get mismatch/Delete) confirming the binding holds.

Total: 32 new tests across 4 new test files. All agent/tool and
agent/component tests pass (320 + 331). All new service IDOR
tests pass (3/3). The one failing test in agent/component
(TestAgent_ReActExhaustsSteps) is a pre-existing flaky test that
also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#15609 infiniflow#15436 infiniflow#16363 infiniflow#15644 infiniflow#15374

Apply unstaged agent-go-port prep work

docker/.env
  - switch API_PROXY_SCHEME from python to go (Go server is the default)
  - enable SANDBOX_ENABLED=1 and extend COMPOSE_PROFILES with ragflow-go

web/CLAUDE.md
  - document frontend agent conventions: CSS/flex layout debugging,
    scope boundaries, i18n language files, query-key factory pattern,
    request layering (hook -> service -> next-request), shared UI lock,
    utility libs (dayjs, ahooks, lodash)

web/.agents/skills/tanstack-query-best-practices/
  - remove the full tanstack-query-best-practices skill set
    (SKILL.md + 21 rule files, 1,535 lines total)

Lefthook pre-commit was satisfied after stripping two pre-existing
trailing-whitespace lines from docker/.env comments.

chore(hooks): enable auto-fix for staged file checks

Convert lefthook pre-commit to B-mode (check + auto-fix in place)
for the four fixable jobs:

- end-of-file-fixer, trailing-whitespace, mixed-line-ending: these
  wrap tools/hooks/check_files.py, which gains a --fix mode that
  rewrites staged files in place. Lefthook re-stages the fixes via
  stage_fixed: true, so the next commit naturally includes the
  cleanup. The user no longer has to manually strip whitespace,
  append newlines, or normalize line endings.

- web-eslint: ESLint --fix is enabled; safe auto-fixes are applied,
  warnings still surface.

trailing-whitespace now uses a regex ([ \t]+(?=\r?\n|$)) so it
correctly detects/strips whitespace before a line terminator and
preserves CRLF when only stripping whitespace. A previous
splitlines-based rstrip pass would silently miss
whitespace-before-newline.

Checks that only validate (json, yaml) or detect states that need
human review (case-conflict, merge-conflict, broken symlinks)
remain check-only; their --fix flag is accepted but a no-op.

ruff check/format, gofmt, and web-prettier already auto-fixed in
the previous config and were left unchanged.
lefthook install hard-depends on a git repo via 'git rev-parse', which
fails in Docker build contexts (.dockerignore strips .git). Gate the
install behind a git-dir probe so npm install succeeds in CI while
local hooks still install for developers.
@codecov

codecov Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (540acb4) to head (af87e33).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16455   +/-   ##
=======================================
  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 4c54cef into infiniflow:main Jun 30, 2026
6 of 9 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 1, 2026
…iniflow#16455)

Mirrors 14 merged upstream PRs into the Go agent port.

PRs ported:
  - infiniflow#15609 ExeSQL SSRF guard + DNS pin
  - infiniflow#15436 HTTP timeout on external API tools
  - infiniflow#16363 be_output restore + DeepL error path
  - infiniflow#15644 switch no longer matches empty condition
  - infiniflow#15374 session_id bind to path agent_id (DAO idor guard)
  - infiniflow#16169 sandbox artifact ownership gate
  - infiniflow#15457 tenant ownership on agentbots
  - infiniflow#15145 rerun agent document access check
- infiniflow#15446 thinking switch (component portion; provider policy lives in
internal/llm)
  - infiniflow#15426 Invoke URL/proxy SSRF + DNS pin + no-redirects
  - infiniflow#15238 agentbot thinking-logs beta endpoint
  - infiniflow#14589 UserFillUp SSE event propagation
  - infiniflow#14890 anonymous webhook opt-in
- infiniflow#15068 PipelineChunker new component (text/file_ref/parser_id
dispatch; file-format extraction is a follow-up)

40 files, +2355 / -58 lines. 33 new tests, all targeted package suites
pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant