Repository navigation
feat(go-api): migrate agent file download handler to Go with strict P… - #15769
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughThis 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. ChangesAgent File Download Feature
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
internal/handler/agent.go (1)
432-446: 💤 Low valueConsider simplifying the Content-Type handling for clarity.
The code manually sets the
Content-Typeheader and then passes a potentially emptycontentTypetoc.Data. While this works because Gin'sc.Dataonly 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 valueConsider verifying service method arguments in the test.
The test successfully verifies the response, but doesn't assert that
DownloadAgentFilewas called with the correcttenantIDandlocationparameters. 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
📒 Files selected for processing (7)
internal/handler/agent.gointernal/handler/agent_test.gointernal/handler/agent_upload_test.gointernal/router/router.gointernal/service/file.gointernal/service/file_test.gointernal/service/metadata_filter_test.go
| 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 | ||
| } |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Please resolve conflicts |
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
entity.File), which fundamentally mismatched how agent chat attachments were stored.DownloadAgentFileininternal/service/file.goandinternal/handler/agent.go. The service now directly accesses the underlyingstorageImpl, correctly targeting the[tenantID]-downloadsbucket using the providedid, exactly as the Python implementation (agent_app.py) does.2. Sandbox Execution Node Patch
NameError: name 'null' is not defineddue to unsafe string interpolation of JSON payloads directly into Python source code.agent/sandbox/result_protocol.pyto use base64-encoded payload transmission, letting the internaljson.loads()safely deserialize JS data types (likenull) into native Python types (None).Testing Done
GET /api/v1/agents/downloadendpoint correctly returns binaries (e.g. images, PDFs).TestDownloadAgentFile,TestUploadAgentFileHandler,TestFileService_DownloadAgentFile_Success).storage.Storagewithout polluting unrelated tests.Checklist