Skip to content

Fix: no more @token_required - #15562

Merged
wangq8 merged 7 commits into
infiniflow:mainfrom
wangq8:bugfix/no-more-token-required
Jun 3, 2026
Merged

wangq8 merged 7 commits into
infiniflow:mainfrom
wangq8:bugfix/no-more-token-required

Conversation

@wangq8

@wangq8 wangq8 commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

Fix: no more @token_required

@coderabbitai

coderabbitai Bot commented Jun 3, 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: 5190f753-27fe-4ad1-b431-b8c7e2f00788

📥 Commits

Reviewing files that changed from the base of the PR and between bcafef9 and 342ba42.

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

📝 Walkthrough

Walkthrough

Moves agent session deletion logic into agent_api.py with deduplication and rich partial-success reporting; removes the legacy session creation/deletion handlers from bot_api.py; updates three chunk_api.py endpoints to use @login_required plus @add_tenant_id_to_kwargs.

Changes

Agent Session Management Migration

Layer / File(s) Summary
Agent API session deletion endpoint
api/apps/restful_apis/agent_api.py
Imports check_duplicate_ids and get_error_data_result, adds async DELETE /agents/<agent_id>/sessions that verifies agent ownership, normalizes targets from request JSON (ids or delete_all), deduplicates IDs, verifies session ownership, deletes sessions, and returns full success, partial success with counts and error lists, or an error result.
Bot API legacy endpoint removal
api/apps/restful_apis/bot_api.py
Removes unused imports and deletes create_agent_session and delete_agent_session handlers that previously managed agent chat sessions and their deletion.

Chunk API Authentication Update

Layer / File(s) Summary
Chunk endpoint decorator migration
api/apps/restful_apis/chunk_api.py
Three endpoints—parse (POST /datasets/<dataset_id>/chunks), stop_parsing (DELETE /datasets/<dataset_id>/chunks), and retrieval_test (POST /retrieval)—replace @token_required with @login_required and add @add_tenant_id_to_kwargs for tenant context injection while preserving handler signatures.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant delete_agent
  participant UserCanvasService
  participant check_duplicate_ids
  participant API4ConversationService

  Client->>delete_agent: DELETE /agents/<agent_id>/sessions { ids | delete_all }
  delete_agent->>UserCanvasService: query(agent_id) for ownership
  UserCanvasService-->>delete_agent: agent record / ownership
  delete_agent->>delete_agent: normalize targets (ids or all)
  delete_agent->>check_duplicate_ids: deduplicate ids
  check_duplicate_ids-->>delete_agent: deduped_ids + duplicate_messages
  loop per id
    delete_agent->>API4ConversationService: query(id, dialog_id) to verify ownership
    API4ConversationService-->>delete_agent: session record / ownership
    delete_agent->>API4ConversationService: delete_by_id(id)
    API4ConversationService-->>delete_agent: deletion success/failure
  end
  delete_agent-->>Client: get_result / get_error_data_result with counts and errors
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15347: Also modifies test/testcases/restful_api/test_retrieval.py to change unauthorized payload expectations and auth-contract behavior.

Suggested labels

🐞 bug, 🐖api

Suggested reviewers

  • xugangqiang

Poem

I’m a rabbit in the code glade, hopping through each route,
Moving sessions to their new home where deletions are made,
Duplicates checked, errors logged, results tidy and neat,
Chunk paths wear login hats so tenant context is sweet,
I celebrate with a nibble — code review feels complete! 🐰

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is identical to the title and lacks all required template sections including problem statement, type of change classification, and meaningful context for reviewers. Complete the description template by explaining what problem this authentication migration solves, selecting the appropriate change type, and providing context about why @token_required is being replaced.
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Fix: no more @token_required' is vague and non-descriptive; it uses vague terminology that doesn't clearly convey what the PR actually accomplishes beyond removing a decorator. Revise the title to clearly describe the main change, such as 'Replace @token_required with @login_required authentication' or 'Migrate API authentication from token-based to login-based decorator'.
✅ Passed checks (2 passed)
Check name Status Explanation
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.


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 added the ci Continue Integration label Jun 3, 2026
@wangq8
wangq8 marked this pull request as ready for review June 3, 2026 05:21
@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: 2

🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

451-498: 💤 Low value

Consider adding logging for this new deletion flow.

The endpoint lacks logging statements. Per coding guidelines, new flows should include logging. Consider adding log entries for successful bulk deletions and error conditions.

🤖 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/agent_api.py` around lines 451 - 498, Add structured
logging for the new deletion flow: log at start of operation (include
tenant/agent_id and incoming ids/delete_all flag from get_request_json), log
each per-session outcome inside the loop (success when
API4ConversationService.delete_by_id succeeds and error when conv is None or
deletion fails), and log final summary before each return (use success_count,
errors, duplicate_messages). Reference the existing symbols get_request_json,
UserCanvasService.query, check_duplicate_ids,
API4ConversationService.delete_by_id and ensure logs include identifying context
(tenant_id, agent_id, session_id) and use the module's logger for
info/warn/error as appropriate.
🤖 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/agent_api.py`:
- Around line 446-450: The delete_agent_session handler is defined async but
decorated with `@_require_canvas_access_sync` which does synchronous I/O and can
block the event loop; replace that decorator with `@_require_canvas_access_async`
(the same async access decorator used on create_agent_session) so the access
check runs without blocking, keeping the async signature of delete_agent_session
and preserving `@login_required` and `@add_tenant_id_to_kwargs` order.
- Around line 483-496: When both errors (from ownership checks) and
duplicate_messages (from check_duplicate_ids) can be present the current early
return in the if errors: branch hides duplicate_messages; update the logic in
the deletion response handling to merge duplicate_messages into the errors list
(or vice versa) before returning so both are reported. Concretely, in the block
using errors and duplicate_messages, build a single combined_errors list and use
get_result or get_error_data_result with that combined list and correct
success_count, ensuring both sources are included in the message; update
references around errors, duplicate_messages, get_result and
get_error_data_result accordingly.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 451-498: Add structured logging for the new deletion flow: log at
start of operation (include tenant/agent_id and incoming ids/delete_all flag
from get_request_json), log each per-session outcome inside the loop (success
when API4ConversationService.delete_by_id succeeds and error when conv is None
or deletion fails), and log final summary before each return (use success_count,
errors, duplicate_messages). Reference the existing symbols get_request_json,
UserCanvasService.query, check_duplicate_ids,
API4ConversationService.delete_by_id and ensure logs include identifying context
(tenant_id, agent_id, session_id) and use the module's logger for
info/warn/error as appropriate.
🪄 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: 63d4c2b3-7880-4a01-8466-ecd2ac7b6134

📥 Commits

Reviewing files that changed from the base of the PR and between c41855d and 53c2899.

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

Comment thread api/apps/restful_apis/agent_api.py Resolved
Comment on lines +483 to +496
if errors:
if success_count > 0:
return get_result(data={"success_count": success_count, "errors": errors},
message=f"Partially deleted {success_count} sessions with {len(errors)} errors")
else:
return get_error_data_result(message="; ".join(errors))

if duplicate_messages:
if success_count > 0:
return get_result(
message=f"Partially deleted {success_count} sessions with {len(duplicate_messages)} errors",
data={"success_count": success_count, "errors": duplicate_messages})
else:
return get_error_data_result(message=";".join(duplicate_messages))

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 | 🟠 Major | ⚡ Quick win

Duplicate messages silently lost when deletion errors exist.

If both errors (from sessions not owned by the agent) and duplicate_messages (from check_duplicate_ids) exist, the if errors: block returns early and duplicate_messages are never reported to the caller.

🐛 Proposed fix: Combine errors and duplicate messages
+    all_errors = errors + duplicate_messages
+
-    if errors:
+    if all_errors:
         if success_count > 0:
-            return get_result(data={"success_count": success_count, "errors": errors},
-                              message=f"Partially deleted {success_count} sessions with {len(errors)} errors")
+            return get_result(data={"success_count": success_count, "errors": all_errors},
+                              message=f"Partially deleted {success_count} sessions with {len(all_errors)} errors")
         else:
-            return get_error_data_result(message="; ".join(errors))
-
-    if duplicate_messages:
-        if success_count > 0:
-            return get_result(
-                message=f"Partially deleted {success_count} sessions with {len(duplicate_messages)} errors",
-                data={"success_count": success_count, "errors": duplicate_messages})
-        else:
-            return get_error_data_result(message=";".join(duplicate_messages))
+            return get_error_data_result(message="; ".join(all_errors))

     return get_result()
📝 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 errors:
if success_count > 0:
return get_result(data={"success_count": success_count, "errors": errors},
message=f"Partially deleted {success_count} sessions with {len(errors)} errors")
else:
return get_error_data_result(message="; ".join(errors))
if duplicate_messages:
if success_count > 0:
return get_result(
message=f"Partially deleted {success_count} sessions with {len(duplicate_messages)} errors",
data={"success_count": success_count, "errors": duplicate_messages})
else:
return get_error_data_result(message=";".join(duplicate_messages))
all_errors = errors + duplicate_messages
if all_errors:
if success_count > 0:
return get_result(data={"success_count": success_count, "errors": all_errors},
message=f"Partially deleted {success_count} sessions with {len(all_errors)} errors")
else:
return get_error_data_result(message="; ".join(all_errors))
return get_result()
🤖 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/agent_api.py` around lines 483 - 496, When both errors
(from ownership checks) and duplicate_messages (from check_duplicate_ids) can be
present the current early return in the if errors: branch hides
duplicate_messages; update the logic in the deletion response handling to merge
duplicate_messages into the errors list (or vice versa) before returning so both
are reported. Concretely, in the block using errors and duplicate_messages,
build a single combined_errors list and use get_result or get_error_data_result
with that combined list and correct success_count, ensuring both sources are
included in the message; update references around errors, duplicate_messages,
get_result and get_error_data_result accordingly.

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

450-498: ⚡ Quick win

Add audit logging to the new bulk-delete flow.

This new destructive endpoint has no request/outcome logging, which makes owner denials, partial deletes, and bulk delete_all operations hard to trace in production. Please log the mode (delete_all vs explicit ids), requested count, and final success/error counts without dumping raw session IDs.

🪵 Suggested logging points
 async def delete_agent_session(tenant_id, agent_id):
     errors = []
     success_count = 0
     req = await get_request_json()
+    logging.info(
+        "Bulk agent session delete requested: tenant_id=%s agent_id=%s delete_all=%s ids_count=%d",
+        tenant_id,
+        agent_id,
+        bool(req and req.get("delete_all") is True),
+        len((req or {}).get("ids") or []),
+    )
     cvs = await thread_pool_exec(UserCanvasService.query, user_id=tenant_id, id=agent_id)
     if not cvs:
+        logging.warning(
+            "Bulk agent session delete denied: tenant_id=%s agent_id=%s reason=not_owner",
+            tenant_id,
+            agent_id,
+        )
         return get_error_data_result(f"You don't own the agent {agent_id}")
@@
     if errors:
+        logging.warning(
+            "Bulk agent session delete completed with ownership/missing errors: tenant_id=%s agent_id=%s success_count=%d error_count=%d",
+            tenant_id,
+            agent_id,
+            success_count,
+            len(errors),
+        )
         if success_count > 0:
             return get_result(data={"success_count": success_count, "errors": errors},
                               message=f"Partially deleted {success_count} sessions with {len(errors)} errors")
@@
     if duplicate_messages:
+        logging.info(
+            "Bulk agent session delete completed with duplicate ids: tenant_id=%s agent_id=%s success_count=%d duplicate_count=%d",
+            tenant_id,
+            agent_id,
+            success_count,
+            len(duplicate_messages),
+        )
         if success_count > 0:
             return get_result(
                 message=f"Partially deleted {success_count} sessions with {len(duplicate_messages)} errors",
                 data={"success_count": success_count, "errors": duplicate_messages})
         else:
             return get_error_data_result(message=";".join(duplicate_messages))
 
+    logging.info(
+        "Bulk agent session delete succeeded: tenant_id=%s agent_id=%s success_count=%d",
+        tenant_id,
+        agent_id,
+        success_count,
+    )
     return get_result()

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/agent_api.py` around lines 450 - 498, In
delete_agent_session, add audit logs that record the delete mode (set a variable
when you check req.get("delete_all") vs explicit ids), the requested_count (len
of conv_list before deduplication), and final success_count and error counts
(len(errors) and len(duplicate_messages)) but never log raw session IDs; log an
owner-denial event when you append to errors (inside the loop where you check
API4ConversationService.query) and log a summary after the deletion loop before
each return path that currently returns get_result/get_error_data_result, so
callers and ops can see whether the request was delete_all or explicit ids, how
many were requested, how many succeeded, and how many failed. Use the existing
function name delete_agent_session and services (UserCanvasService.query,
API4ConversationService.delete_by_id, check_duplicate_ids) to locate insertion
points.
🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 450-498: In delete_agent_session, add audit logs that record the
delete mode (set a variable when you check req.get("delete_all") vs explicit
ids), the requested_count (len of conv_list before deduplication), and final
success_count and error counts (len(errors) and len(duplicate_messages)) but
never log raw session IDs; log an owner-denial event when you append to errors
(inside the loop where you check API4ConversationService.query) and log a
summary after the deletion loop before each return path that currently returns
get_result/get_error_data_result, so callers and ops can see whether the request
was delete_all or explicit ids, how many were requested, how many succeeded, and
how many failed. Use the existing function name delete_agent_session and
services (UserCanvasService.query, API4ConversationService.delete_by_id,
check_duplicate_ids) to locate insertion points.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2e8d29e6-3adf-406f-8220-4823e11ceadf

📥 Commits

Reviewing files that changed from the base of the PR and between 2784650 and 508bb0e.

📒 Files selected for processing (2)
  • api/apps/restful_apis/agent_api.py
  • api/apps/restful_apis/bot_api.py
💤 Files with no reviewable changes (1)
  • api/apps/restful_apis/bot_api.py

@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 (ff59714) to head (342ba42).
⚠️ Report is 10 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15562   +/-   ##
=======================================
  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 merged commit d6fc50a into infiniflow:main Jun 3, 2026
1 check passed
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