Skip to content

fix(go): redact internal handler errors - #15746

Merged
xugangqiang merged 11 commits into
infiniflow:mainfrom
bitloi:fix/15743-handler-internal-error-redaction
Jun 12, 2026
Merged

xugangqiang merged 11 commits into
infiniflow:mainfrom
bitloi:fix/15743-handler-internal-error-redaction

Conversation

@bitloi

@bitloi bitloi commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Refs #15743

Some Go API handlers return raw err.Error() strings in CodeServerError responses. Those errors can include internal backend details such as database, storage, search engine, or host information.

This PR adds a small shared jsonInternalError helper for handler-level internal failures. The helper logs the raw error server-side with request method/path context, then returns the existing generic common.CodeServerError.Message() to API clients.

This first slice migrates the existing jsonError(c, common.CodeServerError, err.Error()) production call sites in agent, dataset graph, file, and system handlers. It intentionally does not close the full issue because direct c.JSON error responses in other handlers remain for follow-up PRs.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

Tests

  • /root/go/bin/go test ./internal/handler -count=1

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 8, 2026
@coderabbitai

coderabbitai Bot commented Jun 8, 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

Adds a centralized helper jsonInternalError that logs original errors internally and returns a generic CodeServerError JSON response; updates multiple handlers to use this helper; and adds a test ensuring sensitive substrings in raw errors are not exposed in HTTP responses.

Changes

Error Response Redaction

Layer / File(s) Summary
Error redaction helper implementation
internal/handler/error.go
Introduces jsonInternalError helper that logs the original error with common.Warn (including HTTP method and path) and returns a generic CodeServerError JSON response.
Error redaction validation test
internal/handler/error_response_test.go
New test TestJSONInternalErrorRedactsRawError verifies the JSON response contains code/message for CodeServerError and does not include raw sensitive substrings from the original error.
Handler refactoring to use error redaction
internal/handler/agent.go, internal/handler/datasets.go, internal/handler/file.go, internal/handler/system.go, internal/handler/kb.go
Replaces inline server-error JSON responses with jsonInternalError(c, err) in ListAgentVersions, ListTemplates, GetKnowledgeGraph, DeleteKnowledgeGraph, file-related handlers (ListFiles, GetRootFolder, GetParentFolder, GetAllParentFolders, GetFileAncestors, UploadFile), and GetStatus; includes minor formatting shifts in kb.go.

Sequence Diagram

sequenceDiagram
  participant Handler
  participant jsonInternalError
  participant commonWarn
  Handler->>jsonInternalError: jsonInternalError(c, err)
  jsonInternalError->>commonWarn: common.Warn(method, path, err)
  jsonInternalError->>Handler: jsonError(common.CodeServerError, common.CodeServerError.Message())
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

size:L

Poem

🐰 I logged the thump but hid the trail,
A whispered error, calm and pale,
Secrets tucked beneath my paw,
Clients see a steady wall —
I keep the logs and mind the veil.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: redacting internal handler errors to prevent exposure of sensitive backend details.
Description check ✅ Passed The description follows the template, explains the problem being solved with context, and identifies the change type as a bug fix with testing information provided.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% 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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@bitloi

bitloi commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

Hi @xugangqiang would you please review the PR and share your feedback?

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
internal/handler/error_response_test.go (1)

56-58: 💤 Low value

Consider caching the response body string.

recorder.Body.String() is called twice in the conditional. Caching it would improve readability and avoid the redundant call.

♻️ Optional refactor
-	if strings.Contains(recorder.Body.String(), "password=secret") || strings.Contains(recorder.Body.String(), "10.0.0.1") {
-		t.Fatalf("response leaked raw error details: %s", recorder.Body.String())
+	bodyStr := recorder.Body.String()
+	if strings.Contains(bodyStr, "password=secret") || strings.Contains(bodyStr, "10.0.0.1") {
+		t.Fatalf("response leaked raw error details: %s", bodyStr)
 	}
🤖 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/error_response_test.go` around lines 56 - 58, Cache the
response body into a local variable once instead of calling
recorder.Body.String() multiple times: e.g., assign recorder.Body.String() to a
variable (like respBody) and then use respBody in the conditional and in the
t.Fatalf call so you avoid redundant calls and improve readability, updating the
code around the existing check that references recorder.Body.String().
internal/handler/kb.go (1)

63-72: ⚡ Quick win

Consider adding a nil check for the error parameter.

While production code paths should always pass a non-nil error, adding a defensive check would prevent confusing log entries if jsonInternalError is accidentally called with nil.

🛡️ Suggested defensive check
 func jsonInternalError(c *gin.Context, err error) {
+	if err == nil {
+		err = errors.New("unknown error")
+	}
 	common.Warn("handler internal error",
 		zap.Error(err),
 		zap.String("method", c.Request.Method),
 		zap.String("path", c.Request.URL.Path),
 	)
 	jsonError(c, common.CodeServerError, common.CodeServerError.Message())
 }
🤖 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/kb.go` around lines 63 - 72, jsonInternalError currently
assumes err is non-nil; add a defensive nil check at the start of
jsonInternalError (function name: jsonInternalError, params: c *gin.Context, err
error) to avoid logging confusing nil errors: if err is nil, log a clear message
(e.g., "internal error: nil error passed") via common.Warn with method/path
context and then call jsonError(c, common.CodeServerError,
common.CodeServerError.Message()); otherwise proceed to log zap.Error(err) as
before and return the same generic JSON error.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/handler/error_response_test.go`:
- Around line 56-58: Cache the response body into a local variable once instead
of calling recorder.Body.String() multiple times: e.g., assign
recorder.Body.String() to a variable (like respBody) and then use respBody in
the conditional and in the t.Fatalf call so you avoid redundant calls and
improve readability, updating the code around the existing check that references
recorder.Body.String().

In `@internal/handler/kb.go`:
- Around line 63-72: jsonInternalError currently assumes err is non-nil; add a
defensive nil check at the start of jsonInternalError (function name:
jsonInternalError, params: c *gin.Context, err error) to avoid logging confusing
nil errors: if err is nil, log a clear message (e.g., "internal error: nil error
passed") via common.Warn with method/path context and then call jsonError(c,
common.CodeServerError, common.CodeServerError.Message()); otherwise proceed to
log zap.Error(err) as before and return the same generic JSON error.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a25bfdb0-19ee-49fc-af4c-7bce4d0de635

📥 Commits

Reviewing files that changed from the base of the PR and between b0a4580 and d06f691.

📒 Files selected for processing (6)
  • internal/handler/agent.go
  • internal/handler/datasets.go
  • internal/handler/error_response_test.go
  • internal/handler/file.go
  • internal/handler/kb.go
  • internal/handler/system.go

@xugangqiang xugangqiang added the ci Continue Integration label Jun 8, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 8, 2026 02:53
@xugangqiang
xugangqiang marked this pull request as ready for review June 8, 2026 02:53
@codecov

codecov Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (49ef959) to head (8798043).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15746   +/-   ##
=======================================
  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.

@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/handler/agent.go`:
- Around line 174-180: Replace the direct exposure of internal errors (sending
err.Error() in the JSON response) with the centralized redaction helper
jsonInternalError in the three error blocks in internal/handler/agent.go;
specifically, update the error branches inside CreateAgentSessionItem,
UpdateAgentSessionItem and DeleteAgentSessionItem to call jsonInternalError(c,
code) (or the existing jsonInternalError signature used elsewhere) instead of
embedding err.Error(), and for DeleteAgentSessionItem ensure the response
follows the contract by returning data: false where the JSON contract expects
that branch.
🪄 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: 42c8c5e8-23bc-4703-a2aa-a7166157a464

📥 Commits

Reviewing files that changed from the base of the PR and between d06f691 and 9eaf36c.

📒 Files selected for processing (2)
  • internal/handler/agent.go
  • internal/handler/datasets.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/handler/datasets.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/handler/agent.go`:
- Around line 174-180: Replace the direct exposure of internal errors (sending
err.Error() in the JSON response) with the centralized redaction helper
jsonInternalError in the three error blocks in internal/handler/agent.go;
specifically, update the error branches inside CreateAgentSessionItem,
UpdateAgentSessionItem and DeleteAgentSessionItem to call jsonInternalError(c,
code) (or the existing jsonInternalError signature used elsewhere) instead of
embedding err.Error(), and for DeleteAgentSessionItem ensure the response
follows the contract by returning data: false where the JSON contract expects
that branch.
🪄 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: 42c8c5e8-23bc-4703-a2aa-a7166157a464

📥 Commits

Reviewing files that changed from the base of the PR and between d06f691 and 9eaf36c.

📒 Files selected for processing (2)
  • internal/handler/agent.go
  • internal/handler/datasets.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/handler/datasets.go
🛑 Comments failed to post (1)
internal/handler/agent.go (1)

174-180: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use centralized redaction for internal session-handler failures.

Line 174, Line 245, and Line 294 still send raw err.Error() to clients. That can expose internal backend details and bypasses the jsonInternalError redaction contract this PR is introducing.

Suggested patch pattern
  if err != nil {
-   c.JSON(http.StatusOK, gin.H{
-     "code":    code,
-     "data":    nil,
-     "message": err.Error(),
-   })
+   if code == common.CodeServerError {
+     jsonInternalError(c, err)
+     return
+   }
+   jsonError(c, code, err.Error())
    return
  }

Apply the same pattern to each of the three error blocks (use data: false branch similarly in DeleteAgentSessionItem if needed by response contract).

Also applies to: 245-251, 294-300

🤖 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 174 - 180, Replace the direct
exposure of internal errors (sending err.Error() in the JSON response) with the
centralized redaction helper jsonInternalError in the three error blocks in
internal/handler/agent.go; specifically, update the error branches inside
CreateAgentSessionItem, UpdateAgentSessionItem and DeleteAgentSessionItem to
call jsonInternalError(c, code) (or the existing jsonInternalError signature
used elsewhere) instead of embedding err.Error(), and for DeleteAgentSessionItem
ensure the response follows the contract by returning data: false where the JSON
contract expects that branch.

@bitloi

bitloi commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

Hi @wangq8, @JinHai-CN, @yingfeng, would you please review my PR and give me your feedback?

Comment thread internal/handler/kb.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.

🧹 Nitpick comments (1)
internal/handler/error.go (1)

30-30: 💤 Low value

Consider adding nil error guard.

While zap.Error(nil) is safe (logs error=null), a nil error suggests incorrect usage of this function. Consider adding a defensive check or documenting that callers must pass a non-nil error.

🛡️ Optional defensive guard
 func jsonInternalError(c *gin.Context, err error) {
+	if err == nil {
+		err = fmt.Errorf("jsonInternalError called with nil error")
+	}
 	common.Warn("handler internal 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/handler/error.go` at line 30, The jsonInternalError function should
defensively handle a nil err to avoid signaling incorrect usage; inside
jsonInternalError check if err == nil and replace it with a clear sentinel error
(e.g., errors.New("internal error: missing error") or "unknown error") and/or
log a warning before continuing so zap.Error is never passed nil; update
jsonInternalError to perform this nil-guard and ensure callers remain unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/handler/error.go`:
- Line 30: The jsonInternalError function should defensively handle a nil err to
avoid signaling incorrect usage; inside jsonInternalError check if err == nil
and replace it with a clear sentinel error (e.g., errors.New("internal error:
missing error") or "unknown error") and/or log a warning before continuing so
zap.Error is never passed nil; update jsonInternalError to perform this
nil-guard and ensure callers remain unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 06eefacd-51a5-4dc2-9d89-a0342e2df4eb

📥 Commits

Reviewing files that changed from the base of the PR and between 388bfc2 and 88aab9b.

📒 Files selected for processing (2)
  • internal/handler/error.go
  • internal/handler/kb.go
💤 Files with no reviewable changes (1)
  • internal/handler/kb.go

@bitloi

bitloi commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

Hi @yingfeng would you please review my PR?

@xugangqiang
xugangqiang merged commit 22a058f into infiniflow:main Jun 12, 2026
1 check passed
dripsmvcp added a commit to dripsmvcp/ragflow that referenced this pull request Jun 12, 2026
…nfiniflow#15715)

Resolve conflicts from main's ingestion refactor (infiniflow#15327) and handler-error redaction (infiniflow#15746): union the documentServiceIface upload* and *IngestionTasks methods, adopt main's renamed ingestionTaskDAO/ingestionTaskLogDAO while keeping fileDAO, and dedupe the internal/server import. Build, vet, gofmt and service/handler/dao/router tests (incl. upload-linkage regression tests) pass.
@coderabbitai coderabbitai Bot mentioned this pull request Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants