Skip to content

Fix: bind memory message user_id to authenticated user for JWT auth - #14745

Merged
KevinHuSh merged 2 commits into
infiniflow:mainfrom
pekar9781:fix/post-message-trusts-client-supplied-user-id
May 11, 2026
Merged

KevinHuSh merged 2 commits into
infiniflow:mainfrom
pekar9781:fix/post-message-trusts-client-supplied-user-id

Conversation

@pekar9781

Copy link
Copy Markdown

Related issues

Closes #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

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

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. labels May 9, 2026
@coderabbitai

coderabbitai Bot commented May 9, 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: c4adc08d-7a91-4763-bde3-78fff2e969ac

📥 Commits

Reviewing files that changed from the base of the PR and between 34a6538 and 3572463.

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

📝 Walkthrough

Walkthrough

The PR initializes a request-scoped g.auth_via_api_token flag during user loading and uses it in the memory /messages POST endpoint to decide whether to trust a client-supplied user_id; the SDK docstring for RAGFlow.add_message was updated to reflect this behavior.

Changes

User ID Attribution Fix via Authentication Context

Layer / File(s) Summary
Authentication Flag Setup
api/apps/__init__.py
Request-scoped flag g.auth_via_api_token is initialized to False and set to True on API-token auth success before g.user assignment.
Message Endpoint User ID Protection
api/apps/restful_apis/memory_api.py
/messages imports g and computes effective_user_id: trusts client user_id only when g.auth_via_api_token is truthy, otherwise uses current_user.id (with RuntimeError fallback).
SDK Documentation
sdk/python/ragflow_sdk/ragflow.py
Docstring added to RAGFlow.add_message() clarifying user_id forwarding applies only to API-key authentication.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

I hop through requests both near and far,
A tiny flag tells me who you are.
Keys earn trust, sessions stay true,
No more forged names in the message queue. 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% 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 accurately describes the main fix: binding memory message user_id to the authenticated user for JWT authentication, which is the core problem addressed.
Description check ✅ Passed The description comprehensively covers the problem, solution, type of change, testing approach, and notes for reviewers, aligning well with the template requirements.
Linked Issues check ✅ Passed The code changes directly address issue #14744 by preventing JWT-authenticated users from spoofing user_id on memory messages while preserving API-key authentication semantics.
Out of Scope Changes check ✅ Passed All changes are within scope: setting g.auth_via_api_token flag, controlling user_id attribution in POST /messages, adding RuntimeError guards, and documenting the behavior change.

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

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

@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 (2)
api/apps/restful_apis/memory_api.py (1)

192-195: 💤 Low value

RuntimeError guard is reachable only outside an app context — confirm intent.

getattr(g, "auth_via_api_token", False) already returns False if the attribute is unset on g; the RuntimeError branch 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_required handlers 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 the try/except if it is only there for unit tests that should be using app.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 value

Redundant re-assignment of g.auth_via_api_token on 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

📥 Commits

Reviewing files that changed from the base of the PR and between 048ec2f and 34a6538.

📒 Files selected for processing (3)
  • api/apps/__init__.py
  • api/apps/restful_apis/memory_api.py
  • sdk/python/ragflow_sdk/ragflow.py

Comment on lines +191 to +199
# 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

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

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

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

@KevinHuSh
KevinHuSh requested a review from Lynn-Inf May 11, 2026 02:36
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]>
@pekar9781

Copy link
Copy Markdown
Author

Hi @Lynn-Inf
Please check this PR. I fixed conflicts. thanks.

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

LGTM

@KevinHuSh KevinHuSh added the ci Continue Integration label May 11, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 11, 2026 04:44
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 11, 2026 04:44
@codecov

codecov Bot commented May 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (827ccec) to head (3572463).
⚠️ Report is 14 commits behind head on main.

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

@KevinHuSh
KevinHuSh merged commit 46897d6 into infiniflow:main May 11, 2026
2 checks passed
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 🌈 python Pull requests that update Python code size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants