Skip to content

Fix: missing authorization checks in /files/link-to-datasets - #14649

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
pekar9781:fix/link-to-datasets-lacks-authorization-checks
May 8, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
pekar9781:fix/link-to-datasets-lacks-authorization-checks

Conversation

@pekar9781

Copy link
Copy Markdown

Related issues

Closes #14648

What problem does this PR solve?

This PR fixes an authorization flaw in POST /files/link-to-datasets.

Before this change, the endpoint only checked whether the supplied file_ids and kb_ids existed. It did not verify whether the authenticated user was actually allowed to access those files or target datasets. As a result, an authenticated user who knew valid IDs could relink another user's files to arbitrary datasets.

This was especially risky because the relinking flow is state-changing: the background worker removes existing file-document mappings and then recreates documents under the attacker-supplied dataset IDs.

This change makes the route enforce the same permission model already used by nearby file and document operations:

  • each resolved file must pass check_file_team_permission(...)
  • each target dataset must pass check_kb_team_permission(...)
  • authorization is enforced before scheduling background relinking work

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

Testing

  • Added regression coverage in test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py
  • Covered:
    • unauthorized file access is rejected
    • unauthorized dataset access is rejected
    • existing success path still returns immediately after scheduling background work
  • Attempted to run:
    • python -m pytest test\\testcases\\test_web_api\\test_file_app\\test_file2document_routes_unit.py -q
  • Local execution in this workspace is currently blocked by missing test dependencies during bootstrap, including ragflow_sdk

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label May 7, 2026
@coderabbitai

coderabbitai Bot commented May 7, 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: ab82098a-73be-4ad2-bd3c-633814fbe332

📥 Commits

Reviewing files that changed from the base of the PR and between c0430c9 and 7e72732.

📒 Files selected for processing (1)
  • api/apps/restful_apis/file2document_api.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/file2document_api.py

📝 Walkthrough

Walkthrough

The /files/link-to-datasets handler now builds a validated kb_map, expands folders to innermost file IDs with existence checks, enforces per-file and per-knowledgebase team-permission checks, logs scheduling context, and schedules _convert_files as background work; tests were extended to cover validation, authorization, scheduling, and exception paths.

Changes

File-to-Dataset Link Authorization

Layer / File(s) Summary
Imports & Logger
api/apps/restful_apis/file2document_api.py
Added imports for check_file_team_permission and check_kb_team_permission and a module logger.
Knowledgebase Validation & Mapping
api/apps/restful_apis/file2document_api.py
Builds kb_map by validating each kb_id via lookup and returns Can't find this dataset! if any are missing.
Folder Expansion & File Existence
api/apps/restful_apis/file2document_api.py
Expands folders to innermost file IDs and validates each expanded file, returning File not found! for missing records.
Per-File and Per-KB Authorization
api/apps/restful_apis/file2document_api.py
Enforces check_file_team_permission for each file and check_kb_team_permission for each knowledgebase, returning No authorization. on denial.
Scheduling Log & Response
api/apps/restful_apis/file2document_api.py
Logs scheduling context (user_id, resource type, all_file_ids, kb_ids) before scheduling background conversion and returning success.
Test Helpers & Stubs
test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py
Introduces _AwaitableValue helper and injects api.common.check_team_permission stub with permission functions for test isolation.
Test Scenarios
test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py
Refactors test_convert_branch_matrix_unit to explicitly cover file missing, dataset missing, file auth denial, dataset auth denial, successful scheduling (including folder expansion), and exception-path handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

size:XS

Suggested reviewers

  • wangq8

Poem

A rabbit peeks, nose twitching bright,
Checks each file and dataset’s right.
Permissions guard the hidden door,
No wandering links again, for sure. 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% 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 'Fix: missing authorization checks in /files/link-to-datasets' directly and specifically describes the main change: adding authorization checks to the endpoint.
Description check ✅ Passed The description includes a clear problem statement, selected the correct type of change (Bug Fix), and added testing notes. It follows the template structure with all major sections addressed.
Linked Issues check ✅ Passed The PR implements all coding requirements from #14648: per-file authorization checks via check_file_team_permission, per-dataset checks via check_kb_team_permission, and enforces authorization before scheduling background work.
Out of Scope Changes check ✅ Passed All changes are directly related to adding authorization checks to the /files/link-to-datasets endpoint as specified in #14648, with appropriate test coverage added.

✏️ 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.

@dosubot dosubot Bot added 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels May 7, 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/restful_apis/file2document_api.py (1)

95-121: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add audit logs for the new authorization branches.

The new file/KB permission flow returns on multiple auth/validation branches but doesn’t log outcomes. Please add structured logs (at least on authorization failures and successful scheduling) to make this path traceable in production.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@api/apps/restful_apis/file2document_api.py` around lines 95 - 121, The
authorization and validation branches in the file-to-document flow lack audit
logging; update the block that calls KnowledgebaseService.get_by_id,
FileService.get_all_innermost_file_ids, FileService.get_by_id,
check_file_team_permission and check_kb_team_permission to emit structured logs
(using the project logger) for: a) lookup failures (e.g., when
KnowledgebaseService.get_by_id or FileService.get_by_id returns error) including
kb_id/file_id and error context, b) authorization failures from
check_file_team_permission and check_kb_team_permission including user_id,
resource id and reason, and c) a success/info entry when scheduling/succeeding
for each file/kb (include user_id, file_id(s), kb_ids); keep messages concise
and use a consistent structured key set (user_id, resource_type, resource_id,
action, result).
🧹 Nitpick comments (1)
test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py (1)

259-269: ⚡ Quick win

Assert that executor scheduling does not happen on authorization failures.

These cases validate the response message, but not the critical side effect boundary. Please stub asyncio.get_running_loop().run_in_executor (or _convert_files) and assert it is not called for unauthorized file/KB paths.

🤖 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 `@test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py`
around lines 259 - 269, The tests currently assert the "No authorization."
responses but do not verify that background scheduling is suppressed; update the
two unauthorized test cases to stub and spy on
asyncio.get_running_loop().run_in_executor (or the internal _convert_files) and
assert the stub was NOT called when calling module.convert(); specifically patch
module._convert_files or monkeypatch asyncio.get_running_loop().run_in_executor
before invoking module.convert(), then after each unauthorized-path assertion
add an assert that the stubbed run_in_executor/_convert_files call_count (or
call) is zero to ensure no executor scheduling occurred in
check_file_team_permission/check_kb_team_permission failure scenarios.
🤖 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 `@api/apps/restful_apis/file2document_api.py`:
- Around line 95-121: The authorization and validation branches in the
file-to-document flow lack audit logging; update the block that calls
KnowledgebaseService.get_by_id, FileService.get_all_innermost_file_ids,
FileService.get_by_id, check_file_team_permission and check_kb_team_permission
to emit structured logs (using the project logger) for: a) lookup failures
(e.g., when KnowledgebaseService.get_by_id or FileService.get_by_id returns
error) including kb_id/file_id and error context, b) authorization failures from
check_file_team_permission and check_kb_team_permission including user_id,
resource id and reason, and c) a success/info entry when scheduling/succeeding
for each file/kb (include user_id, file_id(s), kb_ids); keep messages concise
and use a consistent structured key set (user_id, resource_type, resource_id,
action, result).

---

Nitpick comments:
In `@test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py`:
- Around line 259-269: The tests currently assert the "No authorization."
responses but do not verify that background scheduling is suppressed; update the
two unauthorized test cases to stub and spy on
asyncio.get_running_loop().run_in_executor (or the internal _convert_files) and
assert the stub was NOT called when calling module.convert(); specifically patch
module._convert_files or monkeypatch asyncio.get_running_loop().run_in_executor
before invoking module.convert(), then after each unauthorized-path assertion
add an assert that the stubbed run_in_executor/_convert_files call_count (or
call) is zero to ensure no executor scheduling occurred in
check_file_team_permission/check_kb_team_permission failure scenarios.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a1ac7019-00e8-45b4-af8d-6a573f1007fe

📥 Commits

Reviewing files that changed from the base of the PR and between 59c3510 and c0430c9.

📒 Files selected for processing (2)
  • api/apps/restful_apis/file2document_api.py
  • test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels May 7, 2026
@pekar9781

Copy link
Copy Markdown
Author

@coderabbitai
I added the audit logs you requested. Please re-check.

@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get the current PR diff
gh pr diff 14649 --repo infiniflow/ragflow

Length of output: 8993


@jony376 Thanks for adding the audit logs! I've reviewed the updated diff. Here's a summary of what looks good and a couple of minor points to consider:


✅ What looks good

Aspect Assessment
Module-level logger logging.getLogger(__name__) is correctly placed — no more bare logging.* calls for new events
Severity levels logger.warning for all 5 denial/not-found paths; logger.info for the success path — appropriate
Coverage All security-relevant events are covered: initial file not found, dataset not found, post-expansion file not found, file auth denied, dataset auth denied, and scheduling success
Structured format Consistent key=value pairs (user_id=, resource_type=, resource_id=, action=, result=) work well with log aggregation tools like Loki, Splunk, or CloudWatch Logs Insights

🔍 Minor observations (non-blocking)

  1. resource_id=batch in the success log — this field is a bit misleading since batch is not a real resource identifier. Consider omitting it or replacing it with the count, e.g.:

    logger.info(
        "user_id=%s resource_type=file_to_dataset_link action=schedule_convert result=scheduled "
        "file_count=%d kb_count=%d file_ids=%s kb_ids=%s",
        user_id,
        len(all_file_ids),
        len(kb_ids),
        all_file_ids,
        kb_ids,
    )
  2. Pre-existing root logger in add_done_callback — the existing logging.error("_convert_files failed: %s", ...) in future.add_done_callback still uses the root logger rather than the module logger. This predates this PR, but since you're touching this area, it's a good opportunity to fix it:

    future.add_done_callback(
        lambda f: logger.error("_convert_files failed: %s", f.exception()) if f.exception() else None
    )
  3. Verbose arrays in log lines — file_ids=%s and kb_ids=%s log the full list, which can be very noisy for large folder expansions. You might want to log counts in the warning paths and full IDs only at DEBUG level for forensic purposes, but this is a style preference.


These are all minor polish items. The core implementation — authorization checks with structured audit logs — is solid. The test suite also correctly stubs check_file_team_permission and check_kb_team_permission and covers all new branches.

@wangq8 wangq8 added the ci Continue Integration label May 8, 2026
@wangq8
wangq8 marked this pull request as draft May 8, 2026 05:18
@wangq8
wangq8 marked this pull request as ready for review May 8, 2026 05:18
@wangq8

wangq8 commented May 8, 2026

Copy link
Copy Markdown
Collaborator

LGTM.

@codecov

codecov Bot commented May 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (59c3510) to head (7e72732).
⚠️ Report is 10 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14649      +/-   ##
==========================================
- Coverage   95.59%   94.16%   -1.43%     
==========================================
  Files          10       10              
  Lines         703      703              
  Branches      112      112              
==========================================
- Hits          672      662      -10     
- Misses         21       25       +4     
- Partials       10       16       +6     

☔ View full report in Codecov by Sentry.
📢 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.

@wangq8
wangq8 merged commit 6547751 into infiniflow:main May 8, 2026
2 checks passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
…iflow#14649)

### Related issues
Closes infiniflow#14648

### What problem does this PR solve?

This PR fixes an authorization flaw in `POST /files/link-to-datasets`.

Before this change, the endpoint only checked whether the supplied
`file_ids` and `kb_ids` existed. It did not verify whether the
authenticated user was actually allowed to access those files or target
datasets. As a result, an authenticated user who knew valid IDs could
relink another user's files to arbitrary datasets.

This was especially risky because the relinking flow is state-changing:
the background worker removes existing file-document mappings and then
recreates documents under the attacker-supplied dataset IDs.

This change makes the route enforce the same permission model already
used by nearby file and document operations:

- each resolved file must pass `check_file_team_permission(...)`
- each target dataset must pass `check_kb_team_permission(...)`
- authorization is enforced before scheduling background relinking work

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):

### Testing

- Added regression coverage in
`test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py`
- Covered:
  - unauthorized file access is rejected
  - unauthorized dataset access is rejected
- existing success path still returns immediately after scheduling
background work
- Attempted to run:
- `python -m pytest
test\\testcases\\test_web_api\\test_file_app\\test_file2document_routes_unit.py
-q`
- Local execution in this workspace is currently blocked by missing test
dependencies during bootstrap, including `ragflow_sdk`

---------

Co-authored-by: jony376 <[email protected]>
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…iflow#14649)

### Related issues
Closes infiniflow#14648

### What problem does this PR solve?

This PR fixes an authorization flaw in `POST /files/link-to-datasets`.

Before this change, the endpoint only checked whether the supplied
`file_ids` and `kb_ids` existed. It did not verify whether the
authenticated user was actually allowed to access those files or target
datasets. As a result, an authenticated user who knew valid IDs could
relink another user's files to arbitrary datasets.

This was especially risky because the relinking flow is state-changing:
the background worker removes existing file-document mappings and then
recreates documents under the attacker-supplied dataset IDs.

This change makes the route enforce the same permission model already
used by nearby file and document operations:

- each resolved file must pass `check_file_team_permission(...)`
- each target dataset must pass `check_kb_team_permission(...)`
- authorization is enforced before scheduling background relinking work

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):

### Testing

- Added regression coverage in
`test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py`
- Covered:
  - unauthorized file access is rejected
  - unauthorized dataset access is rejected
- existing success path still returns immediately after scheduling
background work
- Attempted to run:
- `python -m pytest
test\\testcases\\test_web_api\\test_file_app\\test_file2document_routes_unit.py
-q`
- Local execution in this workspace is currently blocked by missing test
dependencies during bootstrap, including `ragflow_sdk`

---------

Co-authored-by: jony376 <[email protected]>
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. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants