Repository navigation
Conversation
|
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe PR initializes a request-scoped ChangesUser ID Attribution Fix via Authentication Context
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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 (2)
api/apps/restful_apis/memory_api.py (1)
192-195: 💤 Low value
RuntimeErrorguard is reachable only outside an app context — confirm intent.
getattr(g, "auth_via_api_token", False)already returnsFalseif the attribute is unset ong; theRuntimeErrorbranch only fires when there is no Quart app/request context at all (e.g., bare imports/tests), per the PR description. That intent is fine, but note that within@login_requiredhandlers an app context is guaranteed, so this fallback is dead code on the actual request path. Consider a brief inline comment to make that intent obvious to future readers, or drop thetry/exceptif it is only there for unit tests that should be usingapp.test_request_context()instead.🤖 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/memory_api.py` around lines 192 - 195, The try/except around getattr(g, "auth_via_api_token", False) that sets trust_client_subject is only needed when no Quart app/request context exists (it raises RuntimeError); inside real request handlers protected by `@login_required` that fallback is unreachable. Either remove the try/except and assign trust_client_subject = bool(getattr(g, "auth_via_api_token", False)), or keep it but add a one-line inline comment above the assignment referencing trust_client_subject, g and auth_via_api_token to explain that the RuntimeError catch is only for out-of-request contexts (e.g., unit tests) and therefore dead code in `@login_required` handlers.api/apps/__init__.py (1)
99-99: 💤 Low valueRedundant re-assignment of
g.auth_via_api_tokenon the JWT success path.Line 99 already initializes
g.auth_via_api_token = False, so the re-assignment at Line 130 right before the JWT success return is a no-op. Safe to remove for clarity, or alternatively drop the default at Line 99 and only set the flag explicitly on each success branch — pick one convention rather than both.♻️ Proposed cleanup
if not user[0].access_token or not user[0].access_token.strip(): logging.warning(f"User {user[0].email} has empty access_token in database") return None - g.auth_via_api_token = False g.user = user[0] return user[0]Also applies to: 130-130
🤖 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` at line 99, Remove the redundant re-assignment of g.auth_via_api_token on the JWT success path: either delete the default initialization g.auth_via_api_token = False at module/function start or remove the later reassignment before the JWT success return so the flag is set only once; locate the JWT success branch that sets g.auth_via_api_token and ensure the code uses a single convention (explicitly set on success or rely on the initial default) and update the JWT handler accordingly.
🤖 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/memory_api.py`:
- Around line 191-199: Add logging around the auth-context user_id resolution:
when trust_client_subject (from getattr(g, "auth_via_api_token", False) used to
decide effective_user_id) is True, emit an info/debug log that includes the
trusted external subject (req.get("user_id")) and the resolved
effective_user_id; if that external subject differs from current_user.id, emit a
security/audit log noting the mismatch. Use the module's logger (e.g., logger or
processLogger) and include clear context strings mentioning
trust_client_subject, req.get("user_id"), effective_user_id, and current_user.id
so the decision branch is auditable.
---
Nitpick comments:
In `@api/apps/__init__.py`:
- Line 99: Remove the redundant re-assignment of g.auth_via_api_token on the JWT
success path: either delete the default initialization g.auth_via_api_token =
False at module/function start or remove the later reassignment before the JWT
success return so the flag is set only once; locate the JWT success branch that
sets g.auth_via_api_token and ensure the code uses a single convention
(explicitly set on success or rely on the initial default) and update the JWT
handler accordingly.
In `@api/apps/restful_apis/memory_api.py`:
- Around line 192-195: The try/except around getattr(g, "auth_via_api_token",
False) that sets trust_client_subject is only needed when no Quart app/request
context exists (it raises RuntimeError); inside real request handlers protected
by `@login_required` that fallback is unreachable. Either remove the try/except
and assign trust_client_subject = bool(getattr(g, "auth_via_api_token", False)),
or keep it but add a one-line inline comment above the assignment referencing
trust_client_subject, g and auth_via_api_token to explain that the RuntimeError
catch is only for out-of-request contexts (e.g., unit tests) and therefore dead
code in `@login_required` handlers.
🪄 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: 0a2fd8c6-98e2-44bd-a9dc-aa9792649821
📒 Files selected for processing (3)
api/apps/__init__.pyapi/apps/restful_apis/memory_api.pysdk/python/ragflow_sdk/ragflow.py
| # JWT / session users cannot spoof attribution; API-key callers may supply an external subject id. | ||
| try: | ||
| trust_client_subject = bool(getattr(g, "auth_via_api_token", False)) | ||
| except RuntimeError: | ||
| trust_client_subject = False | ||
| if trust_client_subject: | ||
| effective_user_id = req.get("user_id", "") | ||
| else: | ||
| effective_user_id = current_user.id |
There was a problem hiding this comment.
Add logging for the new auth-context-driven user_id resolution flow.
Per coding guidelines, new flows should emit logging. This is a security-relevant decision branch (deciding whether to trust client-supplied subject id) and currently runs silently. At minimum, log when a JWT-authenticated request supplied a user_id that differs from current_user.id so spoofing attempts are auditable; a debug/info line on the API-key path showing the trusted external subject is also useful.
📝 Proposed addition
# JWT / session users cannot spoof attribution; API-key callers may supply an external subject id.
try:
trust_client_subject = bool(getattr(g, "auth_via_api_token", False))
except RuntimeError:
trust_client_subject = False
if trust_client_subject:
effective_user_id = req.get("user_id", "")
+ logging.debug(
+ "add_message: API-key auth, using client-supplied user_id=%r", effective_user_id
+ )
else:
+ client_user_id = req.get("user_id")
+ if client_user_id and client_user_id != current_user.id:
+ logging.warning(
+ "add_message: ignoring client-supplied user_id=%r for JWT-authenticated user=%r",
+ client_user_id, current_user.id,
+ )
effective_user_id = current_user.idAs per coding guidelines: "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/memory_api.py` around lines 191 - 199, Add logging
around the auth-context user_id resolution: when trust_client_subject (from
getattr(g, "auth_via_api_token", False) used to decide effective_user_id) is
True, emit an info/debug log that includes the trusted external subject
(req.get("user_id")) and the resolved effective_user_id; if that external
subject differs from current_user.id, emit a security/audit log noting the
mismatch. Use the module's logger (e.g., logger or processLogger) and include
clear context strings mentioning trust_client_subject, req.get("user_id"),
effective_user_id, and current_user.id so the decision branch is auditable.
Resolve api/apps/__init__.py: keep session fallback from main and g.auth_via_api_token=True on successful APIToken auth. Co-authored-by: Cursor <[email protected]>
|
Hi @Lynn-Inf |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14745 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
…infiniflow#14745) ### Related issues Closes infiniflow#14744 ### What problem does this PR solve? The Memory REST endpoint `POST /api/v1/messages` previously persisted whatever `user_id` the client sent in the JSON body. Memory rows were therefore attributed to an arbitrary string, even when the caller authenticated as a normal workspace user via JWT (browser/session-style bearer token decoded into an access token). That broke attribution and audit semantics for shared memories (team visibility): any authorized writer could spoof another subject id. The Python SDK already sends an optional `user_id` for integrations using **API keys** (`APIToken`) to tag an external subject distinct from the tenant owner user. ### Solution - Record **`g.auth_via_api_token`** in `_load_user` (`api/apps/__init__.py`): set `True` only when authentication resolves via `APIToken`, otherwise `False` after JWT-based login succeeds. - In **`POST /messages`** (`memory_api.add_message`): if the request was authenticated with an API key, keep accepting optional `user_id` from the body (default empty string). For JWT-authenticated users, **always** set stored `user_id` to **`current_user.id`** and ignore the client field. - Guard reads of `g` with **`RuntimeError`** handling so isolated imports or tests without a Quart application context do not fail when resolving `user_id`. - Document on **`RAGFlow.add_message`** that `user_id` is only meaningful for API-key authentication. ### 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 - `python -m py_compile` on modified modules (`api/apps/__init__.py`, `api/apps/restful_apis/memory_api.py`). - Recommended: run web/SDK memory message tests (`test_add_message`, `test_message_routes_unit`) against a full environment with `quart` and configured services. ### Notes for reviewers - Behavior change **only** for callers using JWT-style authorization on `POST /messages`; API-key callers keep prior optional `user_id` semantics. Co-authored-by: jony376 <[email protected]> Co-authored-by: Cursor <[email protected]>
Related issues
Closes #14744
What problem does this PR solve?
The Memory REST endpoint
POST /api/v1/messagespreviously persisted whateveruser_idthe client sent in the JSON body. Memory rows were therefore attributed to an arbitrary string, even when the caller authenticated as a normal workspace user via JWT (browser/session-style bearer token decoded into an access token). That broke attribution and audit semantics for shared memories (team visibility): any authorized writer could spoof another subject id.The Python SDK already sends an optional
user_idfor integrations using API keys (APIToken) to tag an external subject distinct from the tenant owner user.Solution
g.auth_via_api_tokenin_load_user(api/apps/__init__.py): setTrueonly when authentication resolves viaAPIToken, otherwiseFalseafter JWT-based login succeeds.POST /messages(memory_api.add_message): if the request was authenticated with an API key, keep accepting optionaluser_idfrom the body (default empty string). For JWT-authenticated users, always set storeduser_idtocurrent_user.idand ignore the client field.gwithRuntimeErrorhandling so isolated imports or tests without a Quart application context do not fail when resolvinguser_id.RAGFlow.add_messagethatuser_idis only meaningful for API-key authentication.Type of change
Testing
python -m py_compileon modified modules (api/apps/__init__.py,api/apps/restful_apis/memory_api.py).test_add_message,test_message_routes_unit) against a full environment withquartand configured services.Notes for reviewers
POST /messages; API-key callers keep prior optionaluser_idsemantics.