Repository navigation
fix(go-document): add document and file access checks - #16592
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 (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughDocument handlers now load documents before update, delete, and metadata changes and verify dataset access with the authenticated user ID. File content loading now checks per-file permission using a user ID. Chat pipeline and session paths now pass user IDs through attachment handling and pipeline calls. ChangesAuthorization checks and user-scoped chat flow
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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 (3)
internal/handler/document_test.go (1)
140-148: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: add coverage for the "document not found" branch.
GetDocumentByIDnow supportsdocErr, but no test sets it, so the new not-found response path (400 / code 1) in the handlers is unexercised. A single case settingdocErrwould cover it.🤖 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 140 - 148, The new not-found response path in the handlers is currently untested because no case exercises fakeDocumentService.GetDocumentByID with docErr set. Add a test case in document_test.go that configures fakeDocumentService.docErr and calls the relevant handler so the 400 / code 1 branch is covered, using the existing fakeDocumentService and handler test setup to verify the not-found response.internal/handler/document.go (1)
347-358: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffConsider extracting the repeated authorization gate.
The
GetDocumentByID→ not-found response →datasetService.Accessible(doc.KbID, user.ID)block is duplicated verbatim inDeleteDocument(404-415) andSetMeta(1406-1417). A small helper (e.g.authorizeDocAccess(c, docID, userID) (*service.DocumentResponse, bool)) would prevent these copies from diverging.🤖 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.go` around lines 347 - 358, The document lookup and authorization sequence is duplicated across GetDocumentByID, DeleteDocument, and SetMeta, so extract it into a shared helper to keep behavior consistent. Create a small function such as authorizeDocAccess that wraps documentService.GetDocumentByID and datasetService.Accessible, returns the loaded document plus a success flag, and centralizes the not-found and unauthorized responses. Update the existing handlers to call this helper instead of repeating the GetDocumentByID/doc not found/Accessible block.internal/service/file.go (1)
1134-1151: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winSingle unauthorized file aborts the whole batch and silently drops already-processed content.
Unlike the other skip conditions in this loop (empty id, DAO lookup failure, missing location — all
continue), an authorization failure does a hardreturn, discarding anytexts/imagesalready accumulated from prior, authorized files in the samefileDictsbatch. Downstream,splitFileAttachments/processFileAttachments/extractImageFilesonly log azap.Warnon this error and return empty results — so a single stale/inaccessible attachment silently nukes all attachments in a multi-file chat message, with no indication to the end user that access was denied.Given the DB fixtures for these tests use different
UserID("user-1") andTenantIDseeds, this is clearly a deliberate design choice validated byTestFileService_GetFileContents_NotAccessible, so this isn't necessarily a bug — but consider whether skipping just the unauthorized file (matching the existingcontinuepattern) is preferable to failing the entire batch, to avoid silently dropping otherwise-valid content.♻️ Possible alternative: skip instead of abort
if !s.checkFileTeamPermission(file, uid) { - return nil, nil, fmt.Errorf("No authorization.") + common.Warn("skipping unauthorized file attachment", + zap.String("file_id", id), zap.String("uid", uid)) + continue }Note: this would require updating
TestFileService_GetFileContents_NotAccessibleto match the new (partial-success) semantics.🤖 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/file.go` around lines 1134 - 1151, In FileService.GetFileContents, the authorization failure path currently returns immediately and discards any texts/images already collected from earlier files in the same batch. Update the !s.checkFileTeamPermission(file, uid) branch to follow the loop’s existing skip behavior (like the empty-id and DAO-miss cases) so a single unauthorized attachment does not abort the whole request. If you keep partial-success semantics, make sure splitFileAttachments/processFileAttachments/extractImageFiles behavior still aligns, and adjust TestFileService_GetFileContents_NotAccessible if its expectation changes.
🤖 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_pipeline.go`:
- Around line 327-330: Use the authenticated request user ID for file access
checks instead of chat.TenantID. Thread the user identity through AsyncChat and
AsyncChatSolo, then update the splitFileAttachments call sites in
chat_pipeline.go to pass that user ID into
checkFileTeamPermission/hasKBTeamPermission so permission checks are evaluated
against the actual user rather than the chat tenant.
---
Nitpick comments:
In `@internal/handler/document_test.go`:
- Around line 140-148: The new not-found response path in the handlers is
currently untested because no case exercises fakeDocumentService.GetDocumentByID
with docErr set. Add a test case in document_test.go that configures
fakeDocumentService.docErr and calls the relevant handler so the 400 / code 1
branch is covered, using the existing fakeDocumentService and handler test setup
to verify the not-found response.
In `@internal/handler/document.go`:
- Around line 347-358: The document lookup and authorization sequence is
duplicated across GetDocumentByID, DeleteDocument, and SetMeta, so extract it
into a shared helper to keep behavior consistent. Create a small function such
as authorizeDocAccess that wraps documentService.GetDocumentByID and
datasetService.Accessible, returns the loaded document plus a success flag, and
centralizes the not-found and unauthorized responses. Update the existing
handlers to call this helper instead of repeating the GetDocumentByID/doc not
found/Accessible block.
In `@internal/service/file.go`:
- Around line 1134-1151: In FileService.GetFileContents, the authorization
failure path currently returns immediately and discards any texts/images already
collected from earlier files in the same batch. Update the
!s.checkFileTeamPermission(file, uid) branch to follow the loop’s existing skip
behavior (like the empty-id and DAO-miss cases) so a single unauthorized
attachment does not abort the whole request. If you keep partial-success
semantics, make sure
splitFileAttachments/processFileAttachments/extractImageFiles behavior still
aligns, and adjust TestFileService_GetFileContents_NotAccessible if its
expectation changes.
🪄 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: 5bc9c4c8-d2f4-4831-ac6f-e2e967d19953
📒 Files selected for processing (5)
internal/handler/document.gointernal/handler/document_test.gointernal/service/chat_pipeline.gointernal/service/file.gointernal/service/file_test.go
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/chat_pipeline.go (1)
225-242: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winLangfuse trace still tags the request with
chat.TenantIDasUserID.Now that the real request
userIDis available inAsyncChat, the trace'sUserIDfield is still populated fromchat.TenantIDrather than the actual acting user, which produces misleading identity data in Langfuse traces/audit trails.🐛 Proposed fix
_ = lfClient.PostTrace(ctx, LangfuseTrace{ ID: langfuseTraceID, Name: "openai_chat", - UserID: chat.TenantID, + UserID: userID, SessionID: chat.ID,🤖 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/chat_pipeline.go` around lines 225 - 242, The Langfuse trace in the Phase 3 setup is still using chat.TenantID for LangfuseTrace.UserID, which records the tenant instead of the real acting user. Update the trace creation in chat_pipeline.go to use the actual user ID available on AsyncChat when building the LangfuseTrace, keeping the rest of the trace payload unchanged. Use the LangfuseTrace construction inside the lfClient.PostTrace call as the target for this replacement.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@internal/service/chat_pipeline.go`:
- Around line 225-242: The Langfuse trace in the Phase 3 setup is still using
chat.TenantID for LangfuseTrace.UserID, which records the tenant instead of the
real acting user. Update the trace creation in chat_pipeline.go to use the
actual user ID available on AsyncChat when building the LangfuseTrace, keeping
the rest of the trace payload unchanged. Use the LangfuseTrace construction
inside the lfClient.PostTrace call as the target for this replacement.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 281d8125-9cdd-40fe-a2de-66064f25dcd8
📒 Files selected for processing (5)
internal/service/chat_pipeline.gointernal/service/chat_pipeline_test.gointernal/service/chat_session.gointernal/service/chat_session_test.gointernal/service/openai_chat.go
Summary
Adds ownership/access checks before updating or deleting documents, setting document metadata, and reading file contents from storage. Also adds tests for authorized and unauthorized access paths.