Skip to content

fix(api): enforce tenant access for connector routes - #14747

Merged
KevinHuSh merged 1 commit into
infiniflow:mainfrom
WT-WSL:fix/connector-tenant-authorization
May 18, 2026
Merged

KevinHuSh merged 1 commit into
infiniflow:mainfrom
WT-WSL:fix/connector-tenant-authorization

Conversation

@WT-WSL

@WT-WSL WT-WSL commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #14746.

Adds tenant access checks for connector-by-id REST routes before reading connector details, mutating connector config/status, deleting connectors, rebuilding, or listing sync logs. Unauthorized callers now receive RetCode.AUTHENTICATION_ERROR with No authorization. without reaching the connector/log mutation paths.

Validation:

  • python3 -m pytest --confcutdir=test/testcases/test_web_api/test_connector_app test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
  • uvx ruff check api/apps/restful_apis/connector_api.py api/db/services/connector_service.py test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

Type of change

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

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 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

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: 2430a412-0426-44c8-b671-473a0693599c

📥 Commits

Reviewing files that changed from the base of the PR and between bacbde4 and 252f7cf.

📒 Files selected for processing (4)
  • api/apps/restful_apis/connector_api.py
  • api/db/services/connector_service.py
  • test/testcases/restful_api/test_connector_routes_unit.py
  • test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/testcases/restful_api/test_connector_routes_unit.py
  • test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
  • api/apps/restful_apis/connector_api.py

📝 Walkthrough

Walkthrough

Adds ConnectorService.accessible() and uses it in per-connector REST handlers to reject cross-tenant access; introduces _connector_auth_error helper; replaces rebuild decorator with runtime kb_id validation; adds unit tests asserting denied access returns RetCode.AUTHENTICATION_ERROR and prevents downstream processing.

Changes

Connector Cross-Tenant Authorization

Layer / File(s) Summary
Authorization Service Method
api/db/services/connector_service.py
Adds DB import and LOGGER; implements ConnectorService.accessible(connector_id, user_id) wrapped with @DB.connection_context() to verify same-tenant or joined-tenant access.
API Endpoint Authorization Guards
api/apps/restful_apis/connector_api.py
Adds _connector_auth_error() helper and early ConnectorService.accessible(...) checks to update, get, logs, resume, rebuild, delete, and test endpoints; rebuild no longer uses @validate_request("kb_id") and instead checks kb_id at runtime returning ARGUMENT_ERROR if missing.
Tests / Stubs & Verification
test/testcases/test_web_api/..., test/testcases/restful_api/...
Test scaffolding adds ConnectorService.accessible() stub and RetCode.AUTHENTICATION_ERROR = 109; new tests patch accessible() to return False, call all by-id routes, assert AUTHENTICATION_ERROR / "No authorization." / data is False, and verify no service or request-body helpers were invoked.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Endpoint
  participant ConnectorService
  participant TenantService
  participant DB
  Client->>Endpoint: request /connectors/{id} (GET/PATCH/DELETE/POST)
  Endpoint->>ConnectorService: accessible(connector_id, current_user.id)
  ConnectorService->>DB: connection_context()
  ConnectorService->>ConnectorService: get_by_id(connector_id)
  ConnectorService->>TenantService: get_joined_tenants_by_user_id(user_id)
  alt Access Denied
    ConnectorService-->>Endpoint: False
    Endpoint->>Client: RetCode.AUTHENTICATION_ERROR ("No authorization.")
  else Access Granted
    ConnectorService-->>Endpoint: True
    Endpoint->>Client: 200 OK (normal processing)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14228: Refactors the same connector route handlers (update_connector, get_connector, list_logs, resume, rebuild, rm_connector) and overlaps at the handler code level.

Suggested reviewers

  • wangq8

Poem

🐇 I hop the paths where connectors dwell,
I check each tenant, guard the shell,
If access fails I softly plea,
"No authorization" — let secrets be,
Safe burrows for each token and key.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.83% 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 'fix(api): enforce tenant access for connector routes' clearly and specifically describes the main change—adding tenant access authorization checks to connector REST API routes.
Description check ✅ Passed The description includes the required sections: clearly states the problem (fixes #14746, adds tenant access checks), marks the Type of change as Bug Fix, and provides validation steps.
Linked Issues check ✅ Passed The PR fully addresses the IDOR vulnerability described in issue #14746 by implementing tenant authorization checks on all affected connector-by-id endpoints (GET, PATCH, DELETE, POST resume/rebuild, GET logs) and returning RetCode.AUTHENTICATION_ERROR to unauthorized callers.
Out of Scope Changes check ✅ Passed All changes directly support the objective of fixing the IDOR vulnerability: authorization enforcement in ConnectorService, authorization checks in connector_api routes, rebuild validation adjustment, logging, docstrings, and comprehensive unit tests—no out-of-scope changes detected.

✏️ 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: 3

🤖 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/connector_api.py`:
- Around line 46-47: Authorization failures from ConnectorService.accessible are
not logged; update the authorization checks to emit a security log containing
connector_id and current_user.id when access is denied. Either add structured
logging inside the existing _connector_auth_error() helper to log connector_id
and user_id (so all call sites benefit), or add a logging call immediately
before returning _connector_auth_error() at each call site that invokes
ConnectorService.accessible (e.g., the checks using ConnectorService.accessible,
current_user.id and connector_id). Use the same logger used elsewhere in this
module and include a clear message like "connector access denied" plus
connector_id and user_id for auditing.
- Around line 137-140: In the rebuild endpoint, move the authorization check
before parsing the request body: call ConnectorService.accessible(connector_id,
current_user.id) at the top of async def rebuild(connector_id) and return
_connector_auth_error() if not accessible, and only after that call await
get_request_json(); ensure you reference the existing symbols (rebuild,
ConnectorService.accessible, current_user.id, _connector_auth_error,
get_request_json) to reorder the logic consistently with other endpoints like
update_connector and resume.

In `@api/db/services/connector_service.py`:
- Around line 38-51: The accessible method lacks audit logging for denied
authorizations; add warning logs using a module logger
(logging.getLogger(__name__)) inside accessible and log the connector_id and
user_id whenever access is denied—include distinct messages for "connector not
found" (after get_by_id returns no entity) and "tenant mismatch" (when
connector.tenant_id != user_id and not in
TenantService.get_joined_tenants_by_user_id), so both failure modes are recorded
for auditing and debugging.
🪄 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: 657a1279-930b-4985-862e-c8a3237b31f4

📥 Commits

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

📒 Files selected for processing (3)
  • api/apps/restful_apis/connector_api.py
  • api/db/services/connector_service.py
  • test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

Comment thread api/apps/restful_apis/connector_api.py Resolved
Comment thread api/apps/restful_apis/connector_api.py Resolved
Comment thread api/db/services/connector_service.py Resolved
@WT-WSL
WT-WSL force-pushed the fix/connector-tenant-authorization branch from bfe308d to 1279b3a Compare May 9, 2026 13:57
@WT-WSL

WT-WSL commented May 9, 2026

Copy link
Copy Markdown
Contributor Author

Resolved CodeRabbit feedback in the amended single commit 1279b3a33:

  • Added connector access-denial logging in the REST helper with connector_id and user_id.
  • Added service-level warning logs for connector-not-found and tenant-mismatch authorization denials.
  • Moved rebuild authorization before request body parsing by removing the route-level validation decorator and validating kb_id after access is confirmed.
  • Added docstrings for the new helper/access method and strengthened the unauthorized route test to assert body parsing is not reached.

Validation:

  • python3 -m pytest --confcutdir=test/testcases/test_web_api/test_connector_app test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
  • uvx ruff check api/apps/restful_apis/connector_api.py api/db/services/connector_service.py test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

@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

🤖 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/connector_api.py`:
- Line 147: The validation message returned by get_json_result uses incorrect
grammar ("required argument are missing"); update the message in the return
statement that calls get_json_result (the one returning RetCode.ARGUMENT_ERROR)
to use correct singular phrasing such as "required argument is missing: kb_id"
(or similar) so the message reads grammatically correct; keep the call to
get_json_result and RetCode.ARGUMENT_ERROR unchanged except for the message
string.
🪄 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: 0691be5f-a0b4-4ba4-b1a1-83c338c7fe84

📥 Commits

Reviewing files that changed from the base of the PR and between bfe308d and 1279b3a.

📒 Files selected for processing (3)
  • api/apps/restful_apis/connector_api.py
  • api/db/services/connector_service.py
  • test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • api/db/services/connector_service.py
  • test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

Comment thread api/apps/restful_apis/connector_api.py Resolved
@WT-WSL
WT-WSL force-pushed the fix/connector-tenant-authorization branch from 1279b3a to 0250e47 Compare May 9, 2026 14:14
@WT-WSL

WT-WSL commented May 9, 2026

Copy link
Copy Markdown
Contributor Author

Resolved the latest CodeRabbit feedback in amended commit 0250e47f4:

  • Updated the rebuild missing-kb_id message to required argument is missing: kb_id.
  • Added concise docstrings to the connector route handlers touched by this PR and the new denial test.

Validation:

  • python3 -m pytest --confcutdir=test/testcases/test_web_api/test_connector_app test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
  • uvx ruff check api/apps/restful_apis/connector_api.py api/db/services/connector_service.py test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

Latest CodeRabbit pass reports no actionable comments.

@JinHai-CN
JinHai-CN requested a review from Magicbook1108 May 11, 2026 08:50
@WT-WSL

WT-WSL commented May 11, 2026

Copy link
Copy Markdown
Contributor Author

@Magicbook1108
Could you please review my PR and give me feedback?
Thanks.

@KevinHuSh KevinHuSh added the ci Continue Integration label May 15, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 15, 2026 04:22
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 15, 2026 04:22
@dosubot dosubot Bot added 🌈 python Pull requests that update Python code 🐖api The modified files are located under directory 'api/apps/sdk' 🧪 test Pull requests that update test cases. labels May 15, 2026
@codecov

codecov Bot commented May 15, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14747   +/-   ##
=======================================
  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

Copy link
Copy Markdown
Contributor

Appreciations!

CI failure.

=================================== FAILURES ===================================
________________ test_connector_basic_routes_and_task_controls _________________
test/testcases/restful_api/test_connector_routes_unit.py:369: in test_connector_basic_routes_and_task_controls
    res = _run(module.update_connector("conn-1"))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
test/testcases/restful_api/test_connector_routes_unit.py:143: in _run
    return asyncio.run(coro)
           ^^^^^^^^^^^^^^^^^
/home/alice/.local/share/uv/python/cpython-3.12.12-linux-x86_64-gnu/lib/python3.12/asyncio/runners.py:195: in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
/home/alice/.local/share/uv/python/cpython-3.12.12-linux-x86_64-gnu/lib/python3.12/asyncio/runners.py:118: in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/home/alice/.local/share/uv/python/cpython-3.12.12-linux-x86_64-gnu/lib/python3.12/asyncio/base_events.py:691: in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
api/apps/restful_apis/connector_api.py:52: in update_connector
    if not ConnectorService.accessible(connector_id, current_user.id):
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
E   AttributeError: type object '_StubConnectorService' has no attribute 'accessible'

@WT-WSL
WT-WSL force-pushed the fix/connector-tenant-authorization branch from 0250e47 to bacbde4 Compare May 15, 2026 11:32
@WT-WSL

WT-WSL commented May 15, 2026

Copy link
Copy Markdown
Contributor Author

Hi @KevinHuSh
Could you please review my PR again?
thanks.

@WT-WSL

WT-WSL commented May 15, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai plz review my PR to be able to pass ci test.

@coderabbitai

coderabbitai Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

Let me inspect the relevant files to understand exactly what's missing.


🏁 Script executed:

#!/bin/bash
# Check the failing test file for _StubConnectorService definition
echo "=== test/testcases/restful_api/test_connector_routes_unit.py (stub + accessible) ==="
rg -n "accessible\|_StubConnectorService\|AUTHENTICATION_ERROR" test/testcases/restful_api/test_connector_routes_unit.py

echo ""
echo "=== test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py (stub + accessible) ==="
rg -n "accessible\|_StubConnectorService\|AUTHENTICATION_ERROR" test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

echo ""
echo "=== Stub class definition in restful_api test file ==="
rg -n -A 30 "class _StubConnectorService" test/testcases/restful_api/test_connector_routes_unit.py

echo ""
echo "=== Stub class definition in test_web_api test file ==="
rg -n -A 30 "class _StubConnectorService" test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

echo ""
echo "=== connector_api.py accessible call context ==="
rg -n -C 3 "accessible" api/apps/restful_apis/connector_api.py

echo ""
echo "=== connector_service.py accessible method ==="
rg -n -A 20 "def accessible" api/db/services/connector_service.py

Length of output: 5449


The accessible stub appears to be present in both test files. Let me dig deeper to check the full context of the failing test and the RetCode mock in that file.


🏁 Script executed:

#!/bin/bash
echo "=== RetCode mock in restful_api test file ==="
rg -n "RetCode\|AUTHENTICATION_ERROR" test/testcases/restful_api/test_connector_routes_unit.py

echo ""
echo "=== Lines 350-420 of restful_api test file (failing test context) ==="
sed -n '350,420p' test/testcases/restful_api/test_connector_routes_unit.py

echo ""
echo "=== Lines 1-100 of restful_api test file (imports/mocks setup) ==="
sed -n '1,100p' test/testcases/restful_api/test_connector_routes_unit.py

echo ""
echo "=== Lines 100-190 of restful_api test file ==="
sed -n '100,190p' test/testcases/restful_api/test_connector_routes_unit.py

echo ""
echo "=== New cross-tenant test in restful_api test file ==="
rg -n -A 50 "test_connector_by_id_routes_reject_cross_tenant" test/testcases/restful_api/test_connector_routes_unit.py

Length of output: 11561


Let me check the RetCode mock setup and the full _load_connector_app function body.


🏁 Script executed:

#!/bin/bash
echo "=== Lines 190-350 of restful_api test file (RetCode mock + _load_connector_app body) ==="
sed -n '190,350p' test/testcases/restful_api/test_connector_routes_unit.py

echo ""
echo "=== Check for AUTHENTICATION_ERROR in both test files (plain rg) ==="
rg -n "AUTHENTICATION_ERROR" test/testcases/restful_api/test_connector_routes_unit.py
rg -n "AUTHENTICATION_ERROR" test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

echo ""
echo "=== Check RetCode mock in both test files ==="
rg -n "RetCode" test/testcases/restful_api/test_connector_routes_unit.py | head -30
rg -n "RetCode" test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py | head -30

Length of output: 8313


@dev111-actor Good news — the CI failure that KevinHuSh reported is already fixed in the current branch. Here is a full breakdown of what I found:


✅ CI Failure — Already Resolved

The original failure was:

AttributeError: type object '_StubConnectorService' has no attribute 'accessible'

The fix is confirmed present in the current branch in both test files:

File accessible stub AUTHENTICATION_ERROR=109 New cross-tenant test
test/testcases/restful_api/test_connector_routes_unit.py Line 204 ✅ Line 253 ✅ Line 429 ✅
test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py Line 204 ✅ Line 253 ✅ Line 429 ✅

🔍 Remaining Minor Issue

The new test_connector_by_id_routes_reject_cross_tenant_access at line 429 is missing a @pytest.mark decorator, while the adjacent test_connector_oauth_helper_functions (line 463) has @pytest.mark.p2. This is a style inconsistency that won't break CI, but for consistency you may want to add @pytest.mark.p1 (security tests are typically higher priority):

`@pytest.mark.p1`
def test_connector_by_id_routes_reject_cross_tenant_access(monkeypatch):

This applies equally to both test files.


✅ Logic Correctness

  • test_connector_basic_routes_and_task_controls — does not patch accessible, but the stub default returns True, so all sub-assertions (including get_connector("missing") after patching get_by_id) flow correctly through the new auth guard.
  • ConnectorService.accessible() — correctly handles connector-not-found (returns False) and team-tenant sharing via TenantService.get_joined_tenants_by_user_id.
  • All 6 per-id routes (update, get, list_logs, resume, rebuild, rm_connector) correctly gate on accessible() before any body parsing or service mutation.

The PR is in good shape for CI. You can request a re-run of the failing job — it should pass now. 🐇✅

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@WT-WSL

WT-WSL commented May 15, 2026 •

Copy link
Copy Markdown
Contributor Author

@coderabbitai plz review again...i have already fixed it(minor issue)...

@coderabbitai

coderabbitai Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor

@dev111-actor Sure! Kicking off a full re-review of the PR now. 🐇✅

✅ Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor

@dev111-actor Sure, triggering a full re-review now! 🐇✅

✅ Actions performed

Full review triggered.

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

174-194: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

test_connector endpoint is still missing the tenant access check.

This route also takes connector_id from the path and loads the connector via ConnectorService.get_by_id(connector_id) without first calling ConnectorService.accessible(connector_id, current_user.id). The same IDOR class described in issue #14746 applies here: any authenticated user can target another tenant's connector and trigger an outbound validation request that uses the victim tenant's saved credentials (config.credentials), and can observe success vs. validation/server errors — leaking existence and partial config state across tenants, and abusing stored secrets to make external calls.

Although the original issue enumerated GET/PATCH/DELETE/resume/logs, this endpoint shares the same per-id pattern and arguably has a higher impact (it uses stored credentials). Recommend gating it the same way before any work is done.

🔒 Proposed fix
 `@manager.route`("/connectors/<connector_id>/test", methods=["POST"])  # noqa: F821
 `@login_required`
 async def test_connector(connector_id):
     """Validate connector configuration without persisting changes or triggering sync.

     For the REST API connector, this uses `RestAPIConnector.validate_config`
     against the existing saved configuration.
     """
+    if not ConnectorService.accessible(connector_id, current_user.id):
+        return _connector_auth_error(connector_id, current_user.id)
+
     from common.data_source.rest_api_connector import RestAPIConnector
     from common.data_source.exceptions import ConnectorMissingCredentialError, ConnectorValidationError

     ok, conn = ConnectorService.get_by_id(connector_id)
🤖 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/connector_api.py` around lines 174 - 194, The
test_connector endpoint currently calls ConnectorService.get_by_id(connector_id)
without checking tenant access; before loading or using the connector (and
before any outbound validation), call ConnectorService.accessible(connector_id,
current_user.id) and enforce failure (return appropriate
error/RetCode.ARGUMENT_ERROR or permission error) if it returns false, so only
the owning tenant's users can reach the RestAPIConnector.validate_config flow
and access stored credentials; update the logic around test_connector, replacing
or preceding ConnectorService.get_by_id usage with the accessibility check (use
symbols: test_connector, ConnectorService.accessible,
ConnectorService.get_by_id, current_user.id).
🧹 Nitpick comments (3)
api/db/services/connector_service.py (1)

35-65: 💤 Low value

Logger naming inconsistency within the module.

The new code introduces a module-level LOGGER = logging.getLogger(__name__) and uses it for the accessible flow, while pre-existing code in SyncLogsService (e.g., lines 244, 246, 251, 262) still calls logging.info/warning/exception on the root logger. This split means audit/security logs from accessible go through a named logger while operational logs from the same module go through the root logger, which complicates filtering/levels in production.

Either route the new logs through logging.warning(...) for consistency with the rest of the file, or (preferred) migrate the existing logging.* call sites in this module to use LOGGER so all logs share the same namespace.

🤖 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/db/services/connector_service.py` around lines 35 - 65, The module now
defines LOGGER = logging.getLogger(__name__) but other logging calls in this
file (e.g., calls inside SyncLogsService) still use the root logging functions
(logging.info/warning/exception), causing inconsistent logger namespaces; update
those existing call sites to use the module logger (replace
logging.info/warning/exception with LOGGER.info/warning/exception) so all logs
(including ConnectorService.accessible) use the same named logger, or if you
prefer the opposite approach change ConnectorService.accessible to use
logging.warning(...), but the preferred fix is to replace root logging usages
with LOGGER in SyncLogsService and any other functions in the same module so the
logger name is consistent.
api/apps/restful_apis/connector_api.py (1)

152-156: 💤 Low value

Validate kb_id is non-empty/string, not just present.

if "kb_id" not in req only rejects the missing-key case. An empty string, None, or a non-string kb_id will still flow into ConnectorService.rebuild(req["kb_id"], connector_id, current_user.id), where it ends up in DB queries and SyncLogsService.filter_delete / SyncLogsService.schedule calls (api/db/services/connector_service.py lines 105-108). Adds little effort here and keeps the runtime validation behavior on par with what the removed @validate_request("kb_id") decorator was likely doing.

📝 Proposed tightening
-    if "kb_id" not in req:
-        return get_json_result(code=RetCode.ARGUMENT_ERROR, message="required argument is missing: kb_id")
+    kb_id = req.get("kb_id")
+    if not isinstance(kb_id, str) or not kb_id:
+        return get_json_result(code=RetCode.ARGUMENT_ERROR, message="required argument is missing: kb_id")
 
-    err = ConnectorService.rebuild(req["kb_id"], connector_id, current_user.id)
+    err = ConnectorService.rebuild(kb_id, connector_id, current_user.id)
🤖 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/connector_api.py` around lines 152 - 156, The handler
currently only checks for the presence of "kb_id" in req but allows
empty/None/non-string values; before calling
ConnectorService.rebuild(req["kb_id"], connector_id, current_user.id) validate
that req.get("kb_id") is a non-empty string (e.g., value = req.get("kb_id"); if
not isinstance(value, str) or not value.strip(): return
get_json_result(code=RetCode.ARGUMENT_ERROR, message="required argument is
missing or invalid: kb_id")), then pass the validated value into
ConnectorService.rebuild to avoid invalid IDs reaching DB operations and
SyncLogsService calls.
test/testcases/restful_api/test_connector_routes_unit.py (1)

428-460: ⚡ Quick win

Consider extending the cross-tenant test to cover test_connector as well.

The new test verifies that update/get/list_logs/resume/rebuild/rm all reject denied access. The sibling POST /connectors/<connector_id>/test route (api/apps/restful_apis/connector_api.py lines 174-219) is also a per-id endpoint and is currently unguarded — see the separate comment on that route. Once it is gated by ConnectorService.accessible(...), please extend this test to include it so the regression net covers the full per-id surface.

🤖 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_connector_routes_unit.py` around lines 428 -
460, Add the per-id test route for connector testing to the exercised responses:
in test_connector_by_id_routes_reject_cross_tenant_access append a call to
module.test_connector("conn-victim") into the responses list (wrap with
_run(...) if test_connector is async, matching how other async routes are
invoked) so the same AUTHENTICATION_ERROR / "No authorization." / data False
assertions and touched==[] verification cover the POST
/connectors/<connector_id>/test endpoint as well.
🤖 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/connector_api.py`:
- Around line 174-194: The test_connector endpoint currently calls
ConnectorService.get_by_id(connector_id) without checking tenant access; before
loading or using the connector (and before any outbound validation), call
ConnectorService.accessible(connector_id, current_user.id) and enforce failure
(return appropriate error/RetCode.ARGUMENT_ERROR or permission error) if it
returns false, so only the owning tenant's users can reach the
RestAPIConnector.validate_config flow and access stored credentials; update the
logic around test_connector, replacing or preceding ConnectorService.get_by_id
usage with the accessibility check (use symbols: test_connector,
ConnectorService.accessible, ConnectorService.get_by_id, current_user.id).

---

Nitpick comments:
In `@api/apps/restful_apis/connector_api.py`:
- Around line 152-156: The handler currently only checks for the presence of
"kb_id" in req but allows empty/None/non-string values; before calling
ConnectorService.rebuild(req["kb_id"], connector_id, current_user.id) validate
that req.get("kb_id") is a non-empty string (e.g., value = req.get("kb_id"); if
not isinstance(value, str) or not value.strip(): return
get_json_result(code=RetCode.ARGUMENT_ERROR, message="required argument is
missing or invalid: kb_id")), then pass the validated value into
ConnectorService.rebuild to avoid invalid IDs reaching DB operations and
SyncLogsService calls.

In `@api/db/services/connector_service.py`:
- Around line 35-65: The module now defines LOGGER = logging.getLogger(__name__)
but other logging calls in this file (e.g., calls inside SyncLogsService) still
use the root logging functions (logging.info/warning/exception), causing
inconsistent logger namespaces; update those existing call sites to use the
module logger (replace logging.info/warning/exception with
LOGGER.info/warning/exception) so all logs (including
ConnectorService.accessible) use the same named logger, or if you prefer the
opposite approach change ConnectorService.accessible to use
logging.warning(...), but the preferred fix is to replace root logging usages
with LOGGER in SyncLogsService and any other functions in the same module so the
logger name is consistent.

In `@test/testcases/restful_api/test_connector_routes_unit.py`:
- Around line 428-460: Add the per-id test route for connector testing to the
exercised responses: in test_connector_by_id_routes_reject_cross_tenant_access
append a call to module.test_connector("conn-victim") into the responses list
(wrap with _run(...) if test_connector is async, matching how other async routes
are invoked) so the same AUTHENTICATION_ERROR / "No authorization." / data False
assertions and touched==[] verification cover the POST
/connectors/<connector_id>/test endpoint as well.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 77247224-a159-4bb2-bb5e-7d073749ddc8

📥 Commits

Reviewing files that changed from the base of the PR and between bf41d35 and bacbde4.

📒 Files selected for processing (4)
  • api/apps/restful_apis/connector_api.py
  • api/db/services/connector_service.py
  • test/testcases/restful_api/test_connector_routes_unit.py
  • test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

@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

🤖 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/connector_api.py`:
- Around line 42-45: The test_connector route currently only requires
`@login_required` and must also enforce tenant-level access: call
ConnectorService.accessible(connector_id, user) (or the existing accessibility
check used elsewhere) before proceeding, and if it returns False return the same
denial response via _connector_auth_error(connector_id, user_id) (so it is
included in the denial matrix); update test_connector to fetch the connector ID
the same way as other routes, perform the ConnectorService.accessible(...) check
early, and short-circuit with the existing
_connector_auth_error/RetCode.AUTHENTICATION_ERROR JSON response when not
accessible.
🪄 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: 830cb873-4243-4cfa-81d9-acf2fd09d2bc

📥 Commits

Reviewing files that changed from the base of the PR and between bf41d35 and bacbde4.

📒 Files selected for processing (4)
  • api/apps/restful_apis/connector_api.py
  • api/db/services/connector_service.py
  • test/testcases/restful_api/test_connector_routes_unit.py
  • test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py

Comment thread api/apps/restful_apis/connector_api.py Resolved
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:M This PR changes 30-99 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants