Skip to content

feat(go-api): migrate agent file download handler to Go with strict P… - #15769

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat-agents-download-get
Jun 10, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat-agents-download-get

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

What does this PR do?

This PR migrates the Agent Temporary File Download endpoint (GET /api/v1/agents/download) from the Python backend to the Go backend, optimizing the data retrieval flow and maintaining strict functional parity. It also fixes a persistent parsing error in the Sandbox code execution node.

1. Go Handler Alignment & Optimization

  • Issue: The previous Go placeholder implementation was doing unnecessary DB queries looking for standard Knowledge Base documents (entity.File), which fundamentally mismatched how agent chat attachments were stored.
  • Fix: Rewrote DownloadAgentFile in internal/service/file.go and internal/handler/agent.go. The service now directly accesses the underlying storageImpl, correctly targeting the [tenantID]-downloads bucket using the provided id, exactly as the Python implementation (agent_app.py) does.

2. Sandbox Execution Node Patch

  • Issue: When running Code Nodes locally, Python execution frequently crashed with NameError: name 'null' is not defined due to unsafe string interpolation of JSON payloads directly into Python source code.
  • Fix: Switched agent/sandbox/result_protocol.py to use base64-encoded payload transmission, letting the internal json.loads() safely deserialize JS data types (like null) into native Python types (None).

Testing Done

  • Manually verified the GET /api/v1/agents/download endpoint correctly returns binaries (e.g. images, PDFs).
  • Ran Go unit tests covering handlers and services (TestDownloadAgentFile, TestUploadAgentFileHandler, TestFileService_DownloadAgentFile_Success).
  • Added fully-isolated Mock implementations for storage.Storage without polluting unrelated tests.

Checklist

  • Code logic matches Python implementation
  • All local unit tests passed
  • No breaking changes to existing router interfaces

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jun 8, 2026
@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0c480a43-84a5-4cf1-becc-0e9aa0da5cee

📥 Commits

Reviewing files that changed from the base of the PR and between 779fffd and 810fc79.

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

📝 Walkthrough

Walkthrough

This PR adds a complete agent-generated file download flow. The service layer retrieves files from tenant-scoped storage buckets, the handler validates requests and serves bytes with appropriate content-type and attachment headers, routing maps the endpoint, and comprehensive tests cover success and error cases.

Changes

Agent File Download Feature

Layer / File(s) Summary
File service download capability
internal/service/file.go, internal/service/file_test.go
FileService.DownloadAgentFile fetches agent-generated files from a tenant-scoped -downloads bucket in storage; unit tests verify success path (correct bucket/filename, blob returned) and error path (error propagation, nil blob).
Handler interface and dependency injection
internal/handler/agent.go
New agentFileService interface contracts both upload and download operations; AgentHandler.fileService field and NewAgentHandler constructor wired to use the interface; imports added for net/url and utility helpers.
Handler endpoint implementation
internal/handler/agent.go
AgentHandler.DownloadAgentFile endpoint authenticates user, requires id query parameter, downloads bytes, computes content-type (defaulting to application/octet-stream), optionally sets nosniff and UTF-8 Content-Disposition: attachment, and streams response.
HTTP routing registration
internal/router/router.go
GET /api/v1/agents/download route registered under authenticated agents group; wired to agentHandler.DownloadAgentFile.
Handler tests and test compatibility
internal/handler/agent_test.go, internal/handler/agent_upload_test.go
fakeAgentFileService test double supports configurable downloads; TestDownloadAgentFile_Success verifies 200 status and PDF content-type; TestDownloadAgentFile_MissingID verifies argument error; upload test double panics on download to prevent accidental use; multipart import added; formatting cleanup.

Sequence Diagram

sequenceDiagram
  participant Client
  participant AgentHandler
  participant FileService
  participant Storage
  Client->>AgentHandler: GET /api/v1/agents/download?id=location
  AgentHandler->>FileService: DownloadAgentFile(tenantID, location)
  FileService->>Storage: Get(bucket: tenantID-downloads, object: location)
  Storage-->>FileService: blob bytes / error
  FileService-->>AgentHandler: blob bytes / error
  AgentHandler-->>Client: 200 + Content-Type [+ Content-Disposition] + blob
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • infiniflow/ragflow#15146: Adds agent attachment/file download endpoint on the Python side with similar agent-file download routing and flow structure.
  • infiniflow/ragflow#15633: Introduces the initial fileUploader dependency on AgentHandler; this PR extends it to the broader agentFileService interface.
  • infiniflow/ragflow#14011: Establishes download/attachment utility helpers (GetContentType, ShouldForceAttachment) that are reused in this PR's response header logic.

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386
  • JinHai-CN
  • yingfeng
  • yuzhichang

Poem

🐰 A rabbit downloads files so fast,
From storage buckets vast,
With content-types and headers set just right,
The agent's gifts now shine so bright!
Hop, hop, hooray! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: migrating the agent file download handler to Go with strict parity to the Python implementation.
Description check ✅ Passed The PR description comprehensively covers the problem solved, includes a clear 'Type of change' classification (New Feature), documents testing performed, and lists a thorough checklist.
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.

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label Jun 8, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 8, 2026 08:25
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 8, 2026 08:25

@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

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

432-446: 💤 Low value

Consider simplifying the Content-Type handling for clarity.

The code manually sets the Content-Type header and then passes a potentially empty contentType to c.Data. While this works because Gin's c.Data only sets the header if not already present, it's confusing and could be simplified.

♻️ Clearer implementation
 	ext := utility.GetFileExtension(fileID)
 	contentType := utility.GetContentType(ext, "")
-	if contentType != "" {
-		c.Header("Content-Type", contentType)
-	} else {
-		c.Header("Content-Type", "application/octet-stream")
+	if contentType == "" {
+		contentType = "application/octet-stream"
 	}
+	c.Header("Content-Type", contentType)

 	if utility.ShouldForceAttachment(ext, contentType) {
 		c.Header("X-Content-Type-Options", "nosniff")
 		encodedName := url.QueryEscape(fileID)
 		c.Header("Content-Disposition", "attachment; filename*=UTF-8''"+encodedName)
 	}

 	c.Data(http.StatusOK, contentType, blob)
🤖 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 432 - 446, The Content-Type logic is
confusing because it sets the header then passes possibly-empty contentType to
c.Data; instead compute a non-empty contentType local (call
GetFileExtension(fileID) and GetContentType(...)) and if empty set it to
"application/octet-stream", then call c.Header only when needed for attachment
(using utility.ShouldForceAttachment(ext, contentType)) and finally pass the
resolved non-empty contentType variable to c.Data(fileData) so the header and
body call use the same value (refer to symbols: utility.GetFileExtension,
utility.GetContentType, utility.ShouldForceAttachment, fileID, contentType,
c.Header, c.Data, Content-Disposition).
internal/handler/agent_test.go (1)

541-567: 💤 Low value

Consider verifying service method arguments in the test.

The test successfully verifies the response, but doesn't assert that DownloadAgentFile was called with the correct tenantID and location parameters. This would make the test more thorough.

♻️ Enhanced test with parameter verification
 type fakeAgentFileService struct {
-	blob []byte
-	err  error
+	blob         []byte
+	err          error
+	lastTenantID string
+	lastLocation string
 }

 func (f *fakeAgentFileService) UploadFile(tenantID, parentID string, files []*multipart.FileHeader) ([]map[string]interface{}, error) {
 	return nil, nil
 }

 func (f *fakeAgentFileService) DownloadAgentFile(tenantID, location string) ([]byte, error) {
+	f.lastTenantID = tenantID
+	f.lastLocation = location
 	return f.blob, f.err
 }

 func TestDownloadAgentFile_Success(t *testing.T) {
 	c, w, _ := setupGinContextWithUserAndDB(t, http.MethodGet, "/api/v1/agents/download?id=test-file.pdf")
 	
 	fakeFileSvc := &fakeAgentFileService{
 		blob: []byte("test content"),
 		err:  nil,
 	}
 	
 	h := &AgentHandler{
 		agentService: service.NewAgentService(),
 		fileService:  fakeFileSvc,
 	}
 	
 	h.DownloadAgentFile(c)

 	if w.Code != http.StatusOK {
 		t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
 	}
+
+	if fakeFileSvc.lastTenantID != "user-1" {
+		t.Errorf("expected tenantID 'user-1', got %s", fakeFileSvc.lastTenantID)
+	}
+	if fakeFileSvc.lastLocation != "test-file.pdf" {
+		t.Errorf("expected location 'test-file.pdf', got %s", fakeFileSvc.lastLocation)
+	}
 	
 	if w.Header().Get("Content-Type") != "application/pdf" {
 		t.Errorf("expected Content-Type application/pdf, got %s", w.Header().Get("Content-Type"))
 	}
 	
 	if w.Body.String() != "test content" {
 		t.Errorf("expected 'test content', got %s", w.Body.String())
 	}
 }
🤖 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_test.go` around lines 541 - 567,
TestDownloadAgentFile_Success currently checks HTTP response but doesn't assert
that AgentHandler.DownloadAgentFile invoked the file service with the expected
tenantID and location; update the fakeAgentFileService implementation used in
the test to record the arguments passed (e.g., store tenantID and location
fields) and after calling h.DownloadAgentFile(c) add assertions that those
recorded values match the expected tenant ID from the context and the "id" query
param ("test-file.pdf"). Locate the fakeAgentFileService used by the test and
its method that implements the file fetch (the one wired into
AgentHandler.fileService) to add the argument capture and expose fields for the
test to assert against. Ensure assertions fail the test when values differ.
🤖 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 420-430: Validate and sanitize the user-controlled fileID from
c.Query before calling h.fileService.DownloadAgentFile: reject empty values
(already done), disallow path traversal patterns (e.g., "..", slashes), enforce
a strict format/whitelist (e.g., UUID or allowed charset and length) and return
jsonError(c, common.CodeArgumentError, "invalid id parameter") on validation
failure; when DownloadAgentFile returns an error, log the full error server-side
(do not return err.Error() to the client) and respond with a generic
jsonError(c, common.CodeServerError, "failed to download file") while retaining
the original error in internal logs for debugging (use your existing logger or
context-aware logging).

---

Nitpick comments:
In `@internal/handler/agent_test.go`:
- Around line 541-567: TestDownloadAgentFile_Success currently checks HTTP
response but doesn't assert that AgentHandler.DownloadAgentFile invoked the file
service with the expected tenantID and location; update the fakeAgentFileService
implementation used in the test to record the arguments passed (e.g., store
tenantID and location fields) and after calling h.DownloadAgentFile(c) add
assertions that those recorded values match the expected tenant ID from the
context and the "id" query param ("test-file.pdf"). Locate the
fakeAgentFileService used by the test and its method that implements the file
fetch (the one wired into AgentHandler.fileService) to add the argument capture
and expose fields for the test to assert against. Ensure assertions fail the
test when values differ.

In `@internal/handler/agent.go`:
- Around line 432-446: The Content-Type logic is confusing because it sets the
header then passes possibly-empty contentType to c.Data; instead compute a
non-empty contentType local (call GetFileExtension(fileID) and
GetContentType(...)) and if empty set it to "application/octet-stream", then
call c.Header only when needed for attachment (using
utility.ShouldForceAttachment(ext, contentType)) and finally pass the resolved
non-empty contentType variable to c.Data(fileData) so the header and body call
use the same value (refer to symbols: utility.GetFileExtension,
utility.GetContentType, utility.ShouldForceAttachment, fileID, contentType,
c.Header, c.Data, Content-Disposition).
🪄 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: e263645c-6eba-4732-8332-7b1d27b84c23

📥 Commits

Reviewing files that changed from the base of the PR and between e2b0da9 and d4c9e0e.

📒 Files selected for processing (7)
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/handler/agent_upload_test.go
  • internal/router/router.go
  • internal/service/file.go
  • internal/service/file_test.go
  • internal/service/metadata_filter_test.go

Comment thread internal/handler/agent.go
Comment on lines +420 to +430
fileID := c.Query("id")
if fileID == "" {
jsonError(c, common.CodeArgumentError, "id parameter is required")
return
}

blob, err := h.fileService.DownloadAgentFile(user.ID, fileID)
if err != nil {
jsonError(c, common.CodeServerError, err.Error())
return
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate the fileID query parameter before using it.

The fileID query parameter is user-controlled input that flows through to the storage layer as the object location. Without validation, this could allow path traversal attempts or other malicious input.

Additionally, Line 428 returns the raw error message to the client, which might expose internal storage paths or configuration details.

🛡️ Recommended validation and error handling
 	fileID := c.Query("id")
 	if fileID == "" {
 		jsonError(c, common.CodeArgumentError, "id parameter is required")
 		return
 	}
+	// Validate fileID format to prevent path traversal
+	if strings.Contains(fileID, "..") || strings.HasPrefix(fileID, "/") {
+		jsonError(c, common.CodeArgumentError, "invalid file id format")
+		return
+	}

 	blob, err := h.fileService.DownloadAgentFile(user.ID, fileID)
 	if err != nil {
-		jsonError(c, common.CodeServerError, err.Error())
+		jsonError(c, common.CodeServerError, "failed to download file")
 		return
 	}
📝 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
fileID := c.Query("id")
if fileID == "" {
jsonError(c, common.CodeArgumentError, "id parameter is required")
return
}
blob, err := h.fileService.DownloadAgentFile(user.ID, fileID)
if err != nil {
jsonError(c, common.CodeServerError, err.Error())
return
}
fileID := c.Query("id")
if fileID == "" {
jsonError(c, common.CodeArgumentError, "id parameter is required")
return
}
// Validate fileID format to prevent path traversal
if strings.Contains(fileID, "..") || strings.HasPrefix(fileID, "/") {
jsonError(c, common.CodeArgumentError, "invalid file id format")
return
}
blob, err := h.fileService.DownloadAgentFile(user.ID, fileID)
if err != nil {
jsonError(c, common.CodeServerError, "failed to download file")
return
}
🤖 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 420 - 430, Validate and sanitize the
user-controlled fileID from c.Query before calling
h.fileService.DownloadAgentFile: reject empty values (already done), disallow
path traversal patterns (e.g., "..", slashes), enforce a strict format/whitelist
(e.g., UUID or allowed charset and length) and return jsonError(c,
common.CodeArgumentError, "invalid id parameter") on validation failure; when
DownloadAgentFile returns an error, log the full error server-side (do not
return err.Error() to the client) and respond with a generic jsonError(c,
common.CodeServerError, "failed to download file") while retaining the original
error in internal logs for debugging (use your existing logger or context-aware
logging).

@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 (093eec3) to head (810fc79).

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

@xugangqiang

Copy link
Copy Markdown
Contributor

Please resolve conflicts

@JinHai-CN
JinHai-CN merged commit 3796835 into infiniflow:main Jun 10, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants