Skip to content

fix: prevent sensitive fields from leaking in user API responses - #14792

Merged
JinHai-CN merged 9 commits into
infiniflow:mainfrom
dale053:fix/filter-sensitive-fields-from-user-api-response
May 22, 2026
Merged

JinHai-CN merged 9 commits into
infiniflow:mainfrom
dale053:fix/filter-sensitive-fields-from-user-api-response

Conversation

@dale053

@dale053 dale053 commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #14789

What problem does this PR solve?

User API endpoints (login, user_profile, user_add, forget_reset_password) were returning full user objects via to_json() / to_dict(), which included sensitive fields like password and access_token in the response body. This leaks credentials to the client.

This PR adds a to_safe_dict() method on the User model that strips sensitive fields (password, access_token) and replaces all affected call sites to use it.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels May 11, 2026
@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: ba15323c-c153-4e1a-b60a-9c2fec432246

📥 Commits

Reviewing files that changed from the base of the PR and between 53bb530 and 44cb556.

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

📝 Walkthrough

Walkthrough

User model now filters sensitive fields (password, access_token, email) via to_safe_dict(for_self=True); login, OAuth-init, logout, profile, registration, and password-reset endpoints now return filtered user dicts and emit additional auth-related logs.

Changes

Secure User Data Serialization

Layer / File(s) Summary
Data Model: Safe Dictionary Serialization
api/db/db_models.py, test/testcases/restful_api/test_user_tenant_routes_unit.py
User.SENSITIVE_FIELDS now includes password, access_token, and email. to_safe_dict(self, *, for_self: bool = False) filters those keys from to_dict() and logs filtered fields; test stub _DummyUser gains a matching helper (ranges: range_0ff9004ee5a9, range_c64d432e0e11, range_68f9cf5d8720).
API Endpoints: Login flow
api/apps/restful_apis/user_api.py
Login handler adds warnings for invalid/empty JSON and unregistered email, logs password decryption failures, disabled accounts, successful login, and wrong credentials; returns user.to_safe_dict(for_self=True) on success (ranges: range_388be106e655, range_0a8e1d7f9d6f).
API Endpoints: OAuth initiation
api/apps/restful_apis/user_api.py
OAuth login initiation logs the selected channel and generated state (range_e4d0a4f1b70e).
API Endpoints: Logout
api/apps/restful_apis/user_api.py
Logout invalidates the access token, calls logout_user(), and logs the user_id (range_8d1ec9923637).
API Endpoints: Profile
api/apps/restful_apis/user_api.py
/users/me GET now returns current_user.to_safe_dict(for_self=True) instead of to_dict() (range_bdbf9c95aeff).
API Endpoints: Registration
api/apps/restful_apis/user_api.py
/users POST registration success returns user.to_safe_dict(for_self=True) instead of to_json() (range_4e781ae7f765).
API Endpoints: Password reset
api/apps/restful_apis/user_api.py
/auth/password/reset success response returns user.to_safe_dict(for_self=True) instead of to_json() (range_690dee2608bc).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

"I hop through fields both near and far,
I hide the secrets under fur and star,
Passwords and tokens tucked away,
Safe bytes for morning, safe bytes for day,
A tiny rabbit keeps leaks at bay." 🐰

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 clearly and accurately describes the main change: preventing sensitive fields from leaking in user API responses.
Description check ✅ Passed The description follows the template with both required sections completed: problem statement explaining the security vulnerability and Type of change marked as Bug Fix.
Linked Issues check ✅ Passed The PR successfully implements all objectives from #14789: adds User.to_safe_dict() method stripping password and access_token, updates all four affected endpoints (login, profile, registration, password-reset), and includes logging enhancements.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the security vulnerability: User model modifications, API endpoint updates, and test helper updates are all necessary to address the issue.

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

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

64-840: ⚠️ Potential issue | 🟠 Major

Add logging to critical authentication endpoints.

The reviewed code properly uses to_safe_dict() for all user serialization in API responses, correctly filtering password and access_token fields. However, three critical authentication endpoints lack logging statements, violating the guideline to "Add logging for new flows":

  • login() (lines 64–131): No logging for login success or failure
  • oauth_login() (lines 160–177): No logging for OAuth flow initiation
  • log_out() (lines 280–289): No logging for logout operations

Add logging.info() or logging.warning() calls to these endpoints to track authentication events, especially for failed attempts and user state changes.

🤖 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/user_api.py` around lines 64 - 840, The three auth
endpoints (login, oauth_login, log_out) lack audit logging; add appropriate
logging calls: in login() log failed login attempts (invalid JSON, unregistered
email, failed decryption, wrong credentials) and successful logins with user
id/email using logging.warning or logging.info; in oauth_login(channel) log
initiation of OAuth flow including channel and generated state; in log_out() log
the user id/email and that their access_token was invalidated (use
logging.info). Place logs near the error/return points and after state changes
(e.g., after setting access_token, after login_user/logout_user) in the login,
oauth_login, and log_out functions respectively.
🧹 Nitpick comments (1)
api/apps/restful_apis/user_api.py (1)

131-131: 💤 Low value

Consider adding logging for security audit trail.

While the security fix is correctly implemented, consider adding logging when user data is serialized for API responses. This would create an audit trail showing when and where user data is accessed, which is valuable for security monitoring and compliance.

Example approach:

def to_safe_dict(self):
    result = {k: v for k, v in self.to_dict().items() if k not in self.SENSITIVE_FIELDS}
    logging.debug(f"User {self.id} serialized safely, filtered fields: {self.SENSITIVE_FIELDS}")
    return result

As per coding guidelines, new flows should include logging. While this is a data method rather than a flow, security-related operations typically benefit from audit logging.

Also applies to: 385-385, 530-530, 839-839

🤖 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/user_api.py` at line 131, Add audit logging when user
data is serialized for API responses: update the user.to_safe_dict
implementation (and any places that call it such as the response construction in
construct_response where user.to_safe_dict() and user.get_id() are used) to emit
an appropriate log entry (e.g., logging.info or logging.debug) that records the
user id, the API endpoint context (or function name), and a non-sensitive
summary of filtered fields; ensure the log message does not include sensitive
values, uses the existing logging facility, and is added consistently for other
occurrences noted (lines calling user.to_safe_dict at locations referenced).
🤖 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/user_api.py`:
- Around line 64-840: The three auth endpoints (login, oauth_login, log_out)
lack audit logging; add appropriate logging calls: in login() log failed login
attempts (invalid JSON, unregistered email, failed decryption, wrong
credentials) and successful logins with user id/email using logging.warning or
logging.info; in oauth_login(channel) log initiation of OAuth flow including
channel and generated state; in log_out() log the user id/email and that their
access_token was invalidated (use logging.info). Place logs near the
error/return points and after state changes (e.g., after setting access_token,
after login_user/logout_user) in the login, oauth_login, and log_out functions
respectively.

---

Nitpick comments:
In `@api/apps/restful_apis/user_api.py`:
- Line 131: Add audit logging when user data is serialized for API responses:
update the user.to_safe_dict implementation (and any places that call it such as
the response construction in construct_response where user.to_safe_dict() and
user.get_id() are used) to emit an appropriate log entry (e.g., logging.info or
logging.debug) that records the user id, the API endpoint context (or function
name), and a non-sensitive summary of filtered fields; ensure the log message
does not include sensitive values, uses the existing logging facility, and is
added consistently for other occurrences noted (lines calling user.to_safe_dict
at locations referenced).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b42d3db7-3312-4a35-80a8-97a5c3723931

📥 Commits

Reviewing files that changed from the base of the PR and between 39ee2fb and e1427b6.

📒 Files selected for processing (2)
  • api/apps/restful_apis/user_api.py
  • api/db/db_models.py

@dale053

dale053 commented May 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8
I have just completed this PR.
When you have a moment, could you please review it?
Thank you for your time.

@JinHai-CN
JinHai-CN requested a review from wangq8 May 12, 2026 12:29
Comment thread api/apps/restful_apis/user_api.py Resolved
Comment thread api/db/db_models.py Resolved
@wangq8

wangq8 commented May 13, 2026

Copy link
Copy Markdown
Collaborator

@dale053 I finished my review, please have a check.

@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 13, 2026
@dale053

dale053 commented May 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8,@KevinHuSh
I have just fixed this PR.
When you have a moment, could you please review it?

@dale053

dale053 commented May 20, 2026

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8
Could you please review this PR again?

@KevinHuSh KevinHuSh added the ci Continue Integration label May 21, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 21, 2026 07:00
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 21, 2026 07:00
@codecov

codecov Bot commented May 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (440153c) to head (44cb556).
⚠️ Report is 19 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14792   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  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.

@KevinHuSh

Copy link
Copy Markdown
Contributor

CI failure.

=================================== FAILURES ===================================
___________________ test_logout_setting_profile_matrix_unit ____________________
test/testcases/restful_api/test_user_tenant_routes_unit.py:1027: in test_logout_setting_profile_matrix_unit
    res = _run(module.user_profile())
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
test/testcases/restful_api/test_user_tenant_routes_unit.py:70: in _run
    return asyncio.run(coro)
           ^^^^^^^^^^^^^^^^^
/home/alice/.local/share/uv/python/cpython-3.13.10-linux-x86_64-gnu/lib/python3.13/asyncio/runners.py:195: in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
/home/alice/.local/share/uv/python/cpython-3.13.10-linux-x86_64-gnu/lib/python3.13/asyncio/runners.py:118: in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/home/alice/.local/share/uv/python/cpython-3.13.10-linux-x86_64-gnu/lib/python3.13/asyncio/base_events.py:725: in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
api/apps/restful_apis/user_api.py:394: in user_profile
    return get_json_result(data=current_user.to_safe_dict(for_self=True))
                                ^^^^^^^^^^^^^^^^^^^^^^^^^

@JinHai-CN

Copy link
Copy Markdown
Member

@dale053 I've just reset your PR #14863 because it contained binary files. Could you please recreate a PR with the same content as #14863? Thanks!

@dale053

dale053 commented May 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN
You mean that I should create a PR that remove binary file like admin-sandbox-settings.png in the #14863?

@dale053

dale053 commented May 21, 2026

Copy link
Copy Markdown
Contributor Author

Hi,@KevinHuSh
All checks have passed! Could you please review this PR?

@JinHai-CN
JinHai-CN merged commit c33d0b8 into infiniflow:main May 22, 2026
1 check passed
mhtkarakose added a commit to mhtkarakose/ragflow that referenced this pull request May 22, 2026
…tive fields

The regular login() path and every other user-data response in this file
use user.to_safe_dict(for_self=True), per the infiniflow#14792 hardening that keeps
sensitive columns out of API responses. ldap_login() still built its
response with user.to_json(), so a successful LDAP login leaked those
fields. Align it with the rest of the file.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
mhtkarakose added a commit to mhtkarakose/ragflow that referenced this pull request May 22, 2026
…tive fields

The regular login() path and every other user-data response in this file
use user.to_safe_dict(for_self=True), per the infiniflow#14792 hardening that keeps
sensitive columns out of API responses. ldap_login() still built its
response with user.to_json(), so a successful LDAP login leaked those
fields. Align it with the rest of the file.
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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: User Credentials (Password Hash + Access Token) Leaked in Login API Response via to_json()/to_dict()

4 participants