Repository navigation
fix(api): enforce tenant access for connector routes - #14747
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughAdds 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. ChangesConnector Cross-Tenant Authorization
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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
📒 Files selected for processing (3)
api/apps/restful_apis/connector_api.pyapi/db/services/connector_service.pytest/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
bfe308d to
1279b3a
Compare
|
Resolved CodeRabbit feedback in the amended single commit
Validation:
|
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
api/apps/restful_apis/connector_api.pyapi/db/services/connector_service.pytest/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
1279b3a to
0250e47
Compare
|
Resolved the latest CodeRabbit feedback in amended commit
Validation:
Latest CodeRabbit pass reports no actionable comments. |
|
@Magicbook1108 |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Appreciations! CI failure. |
0250e47 to
bacbde4
Compare
|
Hi @KevinHuSh |
|
@coderabbitai plz review my PR to be able to pass ci test. |
🧩 Analysis chainLet me inspect the relevant files to understand exactly what's missing. 🏁 Script executed: Length of output: 5449 The 🏁 Script executed: Length of output: 11561 Let me check the RetCode mock setup and the full 🏁 Script executed: Length of output: 8313
✅ CI Failure — Already ResolvedThe original failure was: The fix is confirmed present in the current branch in both test files:
🔍 Remaining Minor IssueThe new `@pytest.mark.p1`
def test_connector_by_id_routes_reject_cross_tenant_access(monkeypatch):This applies equally to both test files. ✅ Logic Correctness
The PR is in good shape for CI. You can request a re-run of the failing job — it should pass now. 🐇✅ ✅ Actions performedReview triggered.
|
|
@coderabbitai plz review again...i have already fixed it(minor issue)... |
|
✅ Actions performedFull review triggered. |
|
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
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_connectorendpoint is still missing the tenant access check.This route also takes
connector_idfrom the path and loads the connector viaConnectorService.get_by_id(connector_id)without first callingConnectorService.accessible(connector_id, current_user.id). The same IDOR class described in issue#14746applies 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 valueLogger naming inconsistency within the module.
The new code introduces a module-level
LOGGER = logging.getLogger(__name__)and uses it for theaccessibleflow, while pre-existing code inSyncLogsService(e.g., lines 244, 246, 251, 262) still callslogging.info/warning/exceptionon the root logger. This split means audit/security logs fromaccessiblego 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 existinglogging.*call sites in this module to useLOGGERso 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 valueValidate
kb_idis non-empty/string, not just present.
if "kb_id" not in reqonly rejects the missing-key case. An empty string,None, or a non-stringkb_idwill still flow intoConnectorService.rebuild(req["kb_id"], connector_id, current_user.id), where it ends up in DB queries andSyncLogsService.filter_delete/SyncLogsService.schedulecalls (api/db/services/connector_service.pylines 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 winConsider extending the cross-tenant test to cover
test_connectoras well.The new test verifies that
update/get/list_logs/resume/rebuild/rmall reject denied access. The siblingPOST /connectors/<connector_id>/testroute (api/apps/restful_apis/connector_api.pylines 174-219) is also a per-id endpoint and is currently unguarded — see the separate comment on that route. Once it is gated byConnectorService.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
📒 Files selected for processing (4)
api/apps/restful_apis/connector_api.pyapi/db/services/connector_service.pytest/testcases/restful_api/test_connector_routes_unit.pytest/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
api/apps/restful_apis/connector_api.pyapi/db/services/connector_service.pytest/testcases/restful_api/test_connector_routes_unit.pytest/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
bacbde4 to
252f7cf
Compare
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_ERRORwithNo 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.pyuvx 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.pyType of change