Skip to content

Fix: consolidate beta auth - #15581

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
wangq8:bugfix/consolidate-beta-auth
Jun 3, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
wangq8:bugfix/consolidate-beta-auth

Conversation

@wangq8

@wangq8 wangq8 commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

Fix: consolidate beta auth

@wangq8
wangq8 requested a review from Lynn-Inf June 3, 2026 09:03
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Centralizes auth to support AUTH_BETA/AUTH_JWT/AUTH_API with auth-type normalization, priority-ordered _load_user dispatch (BETA→JWT→API) and login_required(auth_types) decorator; migrates many bot endpoints to decorator-provided tenant_id and constrains document preview/image/thumbnail endpoints to explicit auth types.

Changes

Authentication system refactoring and endpoint migration

Layer / File(s) Summary
Auth type constants and normalization helper
api/apps/__init__.py
Introduces AUTH_JWT, AUTH_API, AUTH_BETA and a _normalize_auth_types() helper to standardize auth_types input handling.
Multi-path user loading with priority token dispatch
api/apps/__init__.py
Implements _load_user(auth_types=None) with header parsing, bearer extraction, and priority-ordered authentication attempts (BETA→JWT→API), sets g auth flags, and falls back to session loading when JWT is permitted.
login_required decorator signature and behavior
api/apps/__init__.py
Extends decorator to accept optional auth_types; calls _load_user(auth_types) and returns JSON RetCode.DATA_ERROR with g.auth_error_message for BETA-only failures, otherwise raises Unauthorized.
Bot API endpoint migration and decorator adoption
api/apps/restful_apis/bot_api.py
Updates imports (AUTH_BETA, login_required, add_tenant_id_to_kwargs). Refactors multiple handlers to use @login_required(auth_types=AUTH_BETA) + @add_tenant_id_to_kwargs, adds tenant_id=None parameters, removes per-handler APIToken lookups, and passes decorator-derived tenant_id downstream.
Document API auth constraint specification
api/apps/restful_apis/document_api.py
Imports AUTH_JWT, AUTH_API, AUTH_BETA and updates preview/image/thumbnail GET endpoints to @login_required(auth_types=[AUTH_JWT, AUTH_API, AUTH_BETA]).
Tests: adjust auth assertions and client usage
test/testcases/restful_api/*
Use authenticated client for one missing-question test and broaden/strip error-message assertions to accept several authorized/unauthorized message variants.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Decorator as `@login_required` / `@add_tenant_id_to_kwargs`
  participant UserLoader as _load_user
  participant Backend as Service/Storage
  Client->>Decorator: Request + Authorization header
  Decorator->>UserLoader: _load_user(auth_types=AUTH_BETA)
  UserLoader->>UserLoader: Parse Bearer token
  UserLoader->>UserLoader: Try BETA token lookup
  alt BETA token found
    UserLoader->>UserLoader: Set auth_via_beta_token
  else Try JWT decode
    UserLoader->>UserLoader: Validate JWT
  else Try API token
    UserLoader->>UserLoader: Query API token
  end
  UserLoader->>Decorator: Return g.user + auth flags
  Decorator->>Decorator: Extract tenant_id from user
  Decorator->>Backend: Call handler(tenant_id=...)
  Backend-->>Decorator: Result
  Decorator-->>Client: Response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15562: Overlaps migration of REST handlers to centralized login_required/decorator-based auth and related test adjustments.
  • infiniflow/ragflow#14592: Related tenant-scoped dialog/session validation and tenant_id derivation for completions.

Suggested labels

🧪 test, 🐖api

🐰 I hopped through headers, bearer in paw,
BETA first, then JWT — orderly law.
Decorators fetch tenants with a jaunty spin,
Tests now welcome messages they once pinned.
A rabbit’s small cheer for auth made keen.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is minimal and only repeats the title without providing required template sections like problem statement, change type, or implementation details. Expand the description to include: What problem this consolidation solves, the type of change (Bug Fix/Refactoring), implementation details, and why beta auth needed consolidation.
Docstring Coverage ⚠️ Warning Docstring coverage is 29.17% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix: consolidate beta auth' directly describes the main change: consolidating beta authentication handling across multiple endpoints and decorators.
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.

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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.

@wangq8
wangq8 requested a review from buua436 June 3, 2026 09:04
@wangq8 wangq8 added the ci Continue Integration label Jun 3, 2026
@wangq8
wangq8 marked this pull request as ready for review June 3, 2026 09:04
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 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: 3

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/bot_api.py (1)

308-309: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Typo in error message: "denined" → "denied".

Proposed fix
     if not tenant_id:
-        return get_error_data_result(message="permission denined.")
+        return get_error_data_result(message="Permission denied.")
🤖 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/bot_api.py` around lines 308 - 309, Fix the typo in the
error message returned when tenant_id is missing: update the call to
get_error_data_result (the branch that checks if not tenant_id) to use the
correct wording, e.g. "permission denied." or "Permission denied." instead of
"permission denined." Ensure you change the string in the relevant conditional
that references tenant_id and get_error_data_result.
🧹 Nitpick comments (1)
api/apps/__init__.py (1)

184-187: 💤 Low value

Inconsistent error message formatting.

Line 184 has a trailing space while line 187 does not. This could cause inconsistent user-facing messages.

✏️ Proposed fix for consistency
-            g.auth_error_message = 'Authentication error: API key is invalid! '
+            g.auth_error_message = 'Authentication error: API key is invalid!'
🤖 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/__init__.py` around lines 184 - 187, The two assignments to
g.auth_error_message in the exception handlers are inconsistent (one ends with a
trailing space, the other does not); update the assignment used in the except
block(s) (references: g.auth_error_message, the except Exception as e_beta
handler) so both set the exact same string (remove the trailing space) to ensure
consistent user-facing messages.
🤖 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 `@api/apps/__init__.py`:
- Around line 230-231: The warning in load_user logs a partial auth_token
(auth_token[:10]) which risks leaking secrets; remove any direct token substring
from the log and instead log a non-sensitive message using logging.warning in
the same else branch (e.g., "load_user: No APIToken found for provided token" or
include a deterministic safe identifier such as a short hash derived via
hashlib.sha256(auth_token.encode()).hexdigest() if you need correlation),
replacing the current logging.warning call that references auth_token.

In `@api/apps/restful_apis/bot_api.py`:
- Around line 426-427: Fix the typo in the tenant check response: in the block
that checks tenant_id and returns get_error_data_result, change the message
string from "permission denined." to a correct phrasing such as "permission
denied." (or "Permission denied.") so the error message uses the correct
spelling; the surrounding code references tenant_id and calls
get_error_data_result.
- Around line 467-468: Fix the typo in the error message returned when tenant_id
is missing: in the code path that checks tenant_id and calls
get_error_data_result (the conditional using tenant_id), change the message text
from "permission denined." to "permission denied." so the returned error string
is spelled correctly.

---

Outside diff comments:
In `@api/apps/restful_apis/bot_api.py`:
- Around line 308-309: Fix the typo in the error message returned when tenant_id
is missing: update the call to get_error_data_result (the branch that checks if
not tenant_id) to use the correct wording, e.g. "permission denied." or
"Permission denied." instead of "permission denined." Ensure you change the
string in the relevant conditional that references tenant_id and
get_error_data_result.

---

Nitpick comments:
In `@api/apps/__init__.py`:
- Around line 184-187: The two assignments to g.auth_error_message in the
exception handlers are inconsistent (one ends with a trailing space, the other
does not); update the assignment used in the except block(s) (references:
g.auth_error_message, the except Exception as e_beta handler) so both set the
exact same string (remove the trailing space) to ensure consistent user-facing
messages.
🪄 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: fc3e557d-7f74-48e6-921a-f9f43e09f372

📥 Commits

Reviewing files that changed from the base of the PR and between d736f35 and ef0ff14.

📒 Files selected for processing (3)
  • api/apps/__init__.py
  • api/apps/restful_apis/bot_api.py
  • api/apps/restful_apis/document_api.py

Comment thread api/apps/__init__.py
Comment on lines +230 to +231
else:
logging.warning(f"load_user: No APIToken found for token={auth_token[:10]}...")

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 | 🟡 Minor | ⚡ Quick win

Avoid logging partial tokens - potential secret leakage.

Logging auth_token[:10] could expose partial API keys or tokens in log files. Even partial tokens can aid attackers in brute-force attempts or correlation attacks. Log files may also be accessible in monitoring systems with broader access.

🔒 Proposed fix
             else:
-                logging.warning(f"load_user: No APIToken found for token={auth_token[:10]}...")
+                logging.warning("load_user: No APIToken found for provided token")
🤖 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/__init__.py` around lines 230 - 231, The warning in load_user logs a
partial auth_token (auth_token[:10]) which risks leaking secrets; remove any
direct token substring from the log and instead log a non-sensitive message
using logging.warning in the same else branch (e.g., "load_user: No APIToken
found for provided token" or include a deterministic safe identifier such as a
short hash derived via hashlib.sha256(auth_token.encode()).hexdigest() if you
need correlation), replacing the current logging.warning call that references
auth_token.

Comment on lines 426 to 427
if not tenant_id:
return get_error_data_result(message="permission denined.")

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 | 🟡 Minor | ⚡ Quick win

Same typo: "denined" → "denied".

Proposed fix
     if not tenant_id:
-        return get_error_data_result(message="permission denined.")
+        return get_error_data_result(message="Permission denied.")
🤖 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/bot_api.py` around lines 426 - 427, Fix the typo in the
tenant check response: in the block that checks tenant_id and returns
get_error_data_result, change the message string from "permission denined." to a
correct phrasing such as "permission denied." (or "Permission denied.") so the
error message uses the correct spelling; the surrounding code references
tenant_id and calls get_error_data_result.

Comment on lines 467 to 468
if not tenant_id:
return get_error_data_result(message="permission denined.")

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 | 🟡 Minor | ⚡ Quick win

Same typo: "denined" → "denied".

Proposed fix
     if not tenant_id:
-        return get_error_data_result(message="permission denined.")
+        return get_error_data_result(message="Permission denied.")
📝 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
if not tenant_id:
return get_error_data_result(message="permission denined.")
if not tenant_id:
return get_error_data_result(message="Permission denied.")
🤖 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/bot_api.py` around lines 467 - 468, Fix the typo in the
error message returned when tenant_id is missing: in the code path that checks
tenant_id and calls get_error_data_result (the conditional using tenant_id),
change the message text from "permission denined." to "permission denied." so
the returned error string is spelled correctly.

@codecov

codecov Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (d736f35) to head (590a736).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15581   +/-   ##
=======================================
  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 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 force-pushed the bugfix/consolidate-beta-auth branch from 6a28029 to 8642535 Compare June 3, 2026 09:46

@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

🤖 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 `@api/apps/restful_apis/document_api.py`:
- Line 1194: The three endpoints decorated with `@login_required`—list_thumbnails,
get_document_image, and get—currently only authenticate the caller but do not
enforce tenant/resource ownership, allowing cross-tenant reads; update each
route to accept/derive tenant_id (e.g., from path, query, or token) and before
any storage or DB read call invoke the appropriate authorization check
(KnowledgebaseService.accessible(...) for dataset/thumbnail reads and
DocumentService.accessible(...) for document reads) using the resolved tenant_id
and resource id, and return a 403/404 when not accessible; ensure all places
that fetch raw bytes (the storage reads in get_document_image and get, and the
doc_id list retrieval in list_thumbnails) are behind those accessible(...)
checks so only authorized tenant principals can read the assets.
🪄 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: 9ea1a977-5620-44f8-b875-93da0268dcd9

📥 Commits

Reviewing files that changed from the base of the PR and between 6a28029 and 8642535.

📒 Files selected for processing (4)
  • api/apps/__init__.py
  • api/apps/restful_apis/document_api.py
  • test/testcases/restful_api/test_retrieval.py
  • test/testcases/restful_api/test_sessions.py
💤 Files with no reviewable changes (1)
  • api/apps/init.py



@manager.route("/thumbnails", methods=["GET"]) # noqa: F821
@login_required(auth_types=[AUTH_JWT, AUTH_API, AUTH_BETA])

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 | 🔴 Critical | ⚡ Quick win

Authentication-only guards still leave these asset endpoints cross-tenant readable.

Line 1194, Line 1691, and Line 1913 only constrain how the caller authenticates. The handlers still never verify that the authenticated user owns the requested resources: list_thumbnails() fetches arbitrary doc_ids unscoped, get_document_image() reads storage directly from the user-controlled {dataset_id}-{thumbnail} pair, and get() returns raw bytes from doc_id alone. Any valid token from another tenant can read previews/thumbnails if it knows or guesses IDs. Please inject tenant_id on these routes and gate the storage reads with KnowledgebaseService.accessible(...) / DocumentService.accessible(...) first.

Also applies to: 1691-1691, 1913-1913

🤖 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/document_api.py` at line 1194, The three endpoints
decorated with `@login_required`—list_thumbnails, get_document_image, and
get—currently only authenticate the caller but do not enforce tenant/resource
ownership, allowing cross-tenant reads; update each route to accept/derive
tenant_id (e.g., from path, query, or token) and before any storage or DB read
call invoke the appropriate authorization check
(KnowledgebaseService.accessible(...) for dataset/thumbnail reads and
DocumentService.accessible(...) for document reads) using the resolved tenant_id
and resource id, and return a 403/404 when not accessible; ensure all places
that fetch raw bytes (the storage reads in get_document_image and get, and the
doc_id list retrieval in list_thumbnails) are behind those accessible(...)
checks so only authorized tenant principals can read the assets.

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

🧹 Nitpick comments (1)
test/testcases/restful_api/test_document_raw_routes.py (1)

23-28: ⚡ Quick win

Add test coverage for authentication enforcement on the image endpoint.

The test correctly switched to an authenticated client, but following the pattern of test_document_download_by_id_requires_auth (lines 32-39) and test_document_artifact_requires_auth (lines 52-56), there should be a dedicated test verifying that /documents/images/{id} actually rejects unauthenticated requests with a 401 response.

✅ Proposed test to verify auth enforcement
`@pytest.mark.p2`
def test_document_image_requires_auth(rest_client_noauth):
    res = rest_client_noauth.get("/documents/images/not-a-valid-image-id")
    assert res.status_code == 401
    payload = res.json()
    assert payload["code"] == 401, payload
🤖 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/restful_api/test_document_raw_routes.py` around lines 23 - 28,
Add a new auth-enforcement test mirroring the pattern in
test_document_download_by_id_requires_auth and
test_document_artifact_requires_auth: create a pytest-marked test named
test_document_image_requires_auth that uses rest_client_noauth to GET
"/documents/images/not-a-valid-image-id", asserts res.status_code == 401 and
that payload["code"] == 401; place it alongside the other tests so the image
endpoint's unauthenticated rejection is covered.
🤖 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.

Nitpick comments:
In `@test/testcases/restful_api/test_document_raw_routes.py`:
- Around line 23-28: Add a new auth-enforcement test mirroring the pattern in
test_document_download_by_id_requires_auth and
test_document_artifact_requires_auth: create a pytest-marked test named
test_document_image_requires_auth that uses rest_client_noauth to GET
"/documents/images/not-a-valid-image-id", asserts res.status_code == 401 and
that payload["code"] == 401; place it alongside the other tests so the image
endpoint's unauthenticated rejection is covered.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f7bc000e-d472-4895-9e4c-54a3d5c53d05

📥 Commits

Reviewing files that changed from the base of the PR and between 8642535 and 590a736.

📒 Files selected for processing (1)
  • test/testcases/restful_api/test_document_raw_routes.py

@wangq8
wangq8 merged commit b946df8 into infiniflow:main Jun 3, 2026
1 check passed
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request Jun 4, 2026
The /documents/<doc_id>/preview handler gained a duplicate
DocumentService.accessible() check (infiniflow#15505) placed before get_by_id, on
top of the canonical post-existence check (infiniflow#15508). The early call makes
the handler probe access for a missing doc, which the infiniflow#15501 regression
test forbids and which leaks a server_error instead of 'Document not
found!'. Remove the redundant check (line 1928 still enforces access, so
cross-tenant reads stay blocked).

Also extend the test's api.apps stub with AUTH_JWT/AUTH_API/AUTH_BETA and a
factory-aware login_required so loading document_api.py (which now imports
those constants via infiniflow#15581) does not fail at import time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant