Skip to content

fix(go-document): add document and file access checks - #16592

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:fix/A-B-document-update
Jul 6, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:fix/A-B-document-update

Conversation

@Harry-Hz-Zhang

@Harry-Hz-Zhang Harry-Hz-Zhang commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

coderabbitai Bot commented Jul 3, 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: 8b266a1c-1dff-403c-b1a8-bce184e66e51

📥 Commits

Reviewing files that changed from the base of the PR and between a6825c5 and ad05845.

📒 Files selected for processing (2)
  • internal/service/file.go
  • internal/service/file_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/service/file.go
  • internal/service/file_test.go

📝 Walkthrough

Walkthrough

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

Changes

Authorization checks and user-scoped chat flow

Layer / File(s) Summary
Document handler authorization gates
internal/handler/document.go
UpdateDocument, DeleteDocument, and SetMeta load the target document, check dataset accessibility with the authenticated user ID, and return error responses when the document is missing or access is denied.
Document handler tests
internal/handler/document_test.go
fakeDocumentService captures document lookup and mutation calls, setupDocumentPermissionDB creates an in-memory permission database, and handler tests cover accessible and inaccessible cases for SetMeta, DeleteDocument, and UpdateDocument.
File content authorization
internal/service/file.go, internal/service/file_test.go
GetFileContents accepts a user ID and checks per-file team permission before loading content, with tests covering authorized and unauthorized reads.
Chat attachment user ID propagation
internal/service/chat_pipeline.go, internal/service/chat_pipeline_test.go
AsyncChat and AsyncChatSolo accept userID, and attachment helpers pass that ID into GetFileContents while preserving the image2text raw-URL path.
Pipeline user ID wiring and tests
internal/service/chat_session.go, internal/service/openai_chat.go, internal/service/chat_session_test.go
chat_session updates the AsyncChat interface and call sites to pass userID, openai_chat forwards the new argument, and tests record and assert that the request user ID reaches the pipeline.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Suggested labels: 🧪 test

Suggested reviewers: Haruko386, qinling0210, JinHai-CN

Poem

A rabbit hops on careful feet,
through docs and files and chat complete.
With user IDs tucked in the cart,
it checks the keys before it starts.
🐰🔐 The carrots wait behind the gate,
and only safe paths reach the plate.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise, specific, and accurately summarizes the main access-check changes in the PR.
Description check ✅ Passed The description matches the required Summary section and clearly explains the PR's purpose and added tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

@Harry-Hz-Zhang Harry-Hz-Zhang added 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration labels Jul 3, 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: 1

🧹 Nitpick comments (3)
internal/handler/document_test.go (1)

140-148: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: add coverage for the "document not found" branch.

GetDocumentByID now supports docErr, but no test sets it, so the new not-found response path (400 / code 1) in the handlers is unexercised. A single case setting docErr would 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 tradeoff

Consider extracting the repeated authorization gate.

The GetDocumentByID → not-found response → datasetService.Accessible(doc.KbID, user.ID) block is duplicated verbatim in DeleteDocument (404-415) and SetMeta (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 win

Single 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 hard return, discarding any texts/images already accumulated from prior, authorized files in the same fileDicts batch. Downstream, splitFileAttachments/processFileAttachments/extractImageFiles only log a zap.Warn on 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") and TenantID seeds, this is clearly a deliberate design choice validated by TestFileService_GetFileContents_NotAccessible, so this isn't necessarily a bug — but consider whether skipping just the unauthorized file (matching the existing continue pattern) 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_NotAccessible to 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

📥 Commits

Reviewing files that changed from the base of the PR and between 383d059 and 72f7dea.

📒 Files selected for processing (5)
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/service/chat_pipeline.go
  • internal/service/file.go
  • internal/service/file_test.go

Comment thread internal/service/chat_pipeline.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.

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 win

Langfuse trace still tags the request with chat.TenantID as UserID.

Now that the real request userID is available in AsyncChat, the trace's UserID field is still populated from chat.TenantID rather 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

📥 Commits

Reviewing files that changed from the base of the PR and between 72f7dea and a6825c5.

📒 Files selected for processing (5)
  • internal/service/chat_pipeline.go
  • internal/service/chat_pipeline_test.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/openai_chat.go

@JinHai-CN
JinHai-CN merged commit 358152f into infiniflow:main Jul 6, 2026
3 checks passed
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.

2 participants