Repository navigation
Fix: consolidate beta auth - #15581
Conversation
📝 WalkthroughWalkthroughCentralizes 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. ChangesAuthentication system refactoring and endpoint migration
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the 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: 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 winTypo 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 valueInconsistent 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
📒 Files selected for processing (3)
api/apps/__init__.pyapi/apps/restful_apis/bot_api.pyapi/apps/restful_apis/document_api.py
| else: | ||
| logging.warning(f"load_user: No APIToken found for token={auth_token[:10]}...") |
There was a problem hiding this comment.
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.
| if not tenant_id: | ||
| return get_error_data_result(message="permission denined.") |
There was a problem hiding this comment.
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.
| if not tenant_id: | ||
| return get_error_data_result(message="permission denined.") |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
6a28029 to
8642535
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
api/apps/__init__.pyapi/apps/restful_apis/document_api.pytest/testcases/restful_api/test_retrieval.pytest/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]) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/testcases/restful_api/test_document_raw_routes.py (1)
23-28: ⚡ Quick winAdd 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) andtest_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
📒 Files selected for processing (1)
test/testcases/restful_api/test_document_raw_routes.py
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.
Fix: consolidate beta auth