Repository navigation
Refactor: API connectors - #14228
Refactor: API connectors#14228
Conversation
|
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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughConsolidates connector REST endpoints under Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client
participant API as Connector API
participant Service as ConnectorService
participant DB as Database
Client->>API: PATCH /connectors/{id} (prune_freq, refresh_freq, config, timeout_secs)
API->>Service: get_by_id(connector_id)
Service->>DB: SELECT connector WHERE id=...
DB-->>Service: connector record / not found
Service-->>API: record (or None)
API-->>Service: update_by_id(connector_id, payload with forced id)
Service->>DB: UPDATE connectors SET ...
DB-->>Service: update result
Service-->>API: updated record
API->>API: await asyncio.sleep(1)
API->>Service: get_by_id(connector_id) (re-fetch)
Service->>DB: SELECT connector WHERE id=...
DB-->>Service: updated record
Service-->>API: updated connector
API-->>Client: 200 OK, JSON(updated connector)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
api/apps/restful_apis/connector_api.py (3)
57-80:⚠️ Potential issue | 🟠 MajorMissing error response when request body is empty.
If
reqis falsy (empty or None), the code skips saving but still attempts to accessreq["id"]on line 78, which will raise aKeyErrororTypeError.Proposed fix
`@manager.route`("/connectors", methods=["POST"]) # noqa: F821 `@login_required` async def create_connector(): req = await get_request_json() - if req: + if not req: + return get_data_error_result(message="Request body is required") + + req["id"] = get_uuid() + conn = { req["id"] = get_uuid() - conn = { - "id": req["id"], - ... - } - ConnectorService.save(**conn) + "id": req["id"], + "tenant_id": current_user.id, + "name": req["name"], + "source": req["source"], + "input_type": InputType.POLL, + "config": req["config"], + "refresh_freq": int(req.get("refresh_freq", 5)), + "prune_freq": int(req.get("prune_freq", 720)), + "timeout_secs": int(req.get("timeout_secs", 60 * 29)), + "status": TaskStatus.SCHEDULE, + } + ConnectorService.save(**conn) await asyncio.sleep(1) e, conn = ConnectorService.get_by_id(req["id"])🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 57 - 80, The create_connector handler fails to handle an empty or None request body and still accesses req["id"], causing a crash; update create_connector to validate req after await get_request_json() and if falsy return an appropriate error response (e.g., using get_json_result with an error message/status or raise a HTTP exception) instead of continuing; ensure early return prevents calling ConnectorService.save and ConnectorService.get_by_id with a missing id and keep references to get_request_json, ConnectorService.save, ConnectorService.get_by_id, and get_json_result when implementing the check.
457-459:⚠️ Potential issue | 🔴 CriticalNull check occurs after
json.loads, causing crash when cache is missing.
json.loads(REDIS_CONN.get(...))is called on line 457, but the null check on line 458 comes too late. If the cache key doesn't exist,REDIS_CONN.get()returnsNone, andjson.loads(None)will raise aTypeError.Proposed fix
- cache_payload = json.loads(REDIS_CONN.get(_web_state_cache_key(flow_id, "box"))) - if not cache_payload: + cache_raw = REDIS_CONN.get(_web_state_cache_key(flow_id, "box")) + if not cache_raw: return get_json_result(code=RetCode.ARGUMENT_ERROR, message="Box OAuth session expired or invalid.") + cache_payload = json.loads(cache_raw)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 457 - 459, The code calls json.loads on REDIS_CONN.get(...) before checking for absence; change the logic in the block using _web_state_cache_key and REDIS_CONN.get so you first capture the raw value (e.g., raw_cache = REDIS_CONN.get(_web_state_cache_key(flow_id, "box"))), check if raw_cache is None or falsy and return get_json_result(code=RetCode.ARGUMENT_ERROR, message="Box OAuth session expired or invalid.") if missing, and only then call json.loads(raw_cache) to produce cache_payload; update references to cache_payload accordingly.
234-234:⚠️ Potential issue | 🟡 MinorRemove debug print statement.
This
print(credentials)appears to be leftover debug code and could leak sensitive credential data to logs.Proposed fix
- print(credentials)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` at line 234, Remove the leftover debug print that exposes sensitive data: delete the print(credentials) call in connector_api.py (where the credentials variable is handled) and, if you need runtime visibility, replace it with a secure logger call that redacts or masks secrets (e.g., use the existing logger and do not log full credential values).web/src/pages/user-setting/data-source/hooks.ts (1)
90-105:⚠️ Potential issue | 🟡 MinorMissing
isEditin useCallback dependency array.The
handleAddOkcallback referencesisEditon line 93, butisEditis not included in the dependency array on line 104. This can cause stale closure behavior if the hook is reused with differentisEditvalues.Proposed fix
- [hideAddingModal, queryClient], + [hideAddingModal, queryClient, isEdit],🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/pages/user-setting/data-source/hooks.ts` around lines 90 - 105, The useCallback for handleAddOk closes over isEdit but the dependency array only lists hideAddingModal and queryClient; add isEdit to the dependency array so the callback updates when edit mode changes and avoids stale closure behavior. In other words, update the useCallback dependencies for handleAddOk to include isEdit (alongside existing hideAddingModal and queryClient) so the logic that chooses between dataSourceUpdate and dataSourceService.dataSourceSet runs with the current isEdit value.test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py (1)
366-379:⚠️ Potential issue | 🔴 CriticalTest references non-existent
set_connectorfunction.The API was refactored to replace
set_connectorwith separateupdate_connector(line 40) andcreate_connector(line 59) functions, but this test still callsmodule.set_connector()on lines 366 and 375. This will raise anAttributeErrorat runtime.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py` around lines 366 - 379, The test is calling a nonexistent module.set_connector() after the API was split; replace those calls with the correct functions: use module.update_connector() for the case that updates an existing connector (first assertion block expecting update_calls and id "conn-1") and use module.create_connector() for the creation case (second block asserting save_calls and generated-id), and ensure the monkeypatched get_request_json remains paired with the create_connector() call so the input_type and tenant_id assertions still apply.
🧹 Nitpick comments (2)
api/apps/restful_apis/connector_api.py (2)
38-54: Add logging for new connector create/update flows.The new
update_connectorandcreate_connectorendpoints lack logging statements. As per coding guidelines, new flows should include logging for observability.Example logging additions
async def update_connector(connector_id): req = await get_request_json() e, conn = ConnectorService.get_by_id(connector_id) if not e: + logging.warning("Connector not found: %s", connector_id) return get_data_error_result(message="Can't find this Connector!") if req: conn = {fld: req[fld] for fld in ["prune_freq", "refresh_freq", "config", "timeout_secs"] if fld in req} conn["id"] = connector_id ConnectorService.update_by_id(connector_id, conn) + logging.info("Updated connector %s", connector_id)Also applies to: 57-80
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 38 - 54, The update_connector and create_connector flows need observability: add logging calls at key points (entering the handler, received request payload, on validation failures, before calling ConnectorService.update_by_id / ConnectorService.create, and on success) using the module logger (e.g., logger.info/error). Include connector_id and relevant request fields (prune_freq, refresh_freq, config, timeout_secs) in logs and log errors when ConnectorService returns failures so callers and operators can trace create/update operations.
51-52: Consider documenting the purpose of the 1-second sleep.The
asyncio.sleep(1)appears in bothupdate_connectorandcreate_connector. If this is to allow eventual consistency or database propagation, consider adding a brief comment or extracting to a named constant.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 51 - 52, The anonymous 1-second pause before calling ConnectorService.get_by_id (seen in update_connector and create_connector) lacks context; replace the magic number with a named constant (e.g., CONSISTENCY_DELAY_SECONDS) or extract a helper like wait_for_propagation(delay) and add a brief comment explaining why the delay is needed (eventual consistency / DB propagation) so future readers understand its purpose; update both places (asyncio.sleep(1) in update_connector and create_connector) to use the new constant/helper and include the comment near the sleep usage.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@web/src/services/data-source-service.ts`:
- Around line 31-33: The parameter type for dataSourceUpdate is wrong (currently
{ kb_id: string }); change it to reflect connector update fields by defining and
using a proper payload type (e.g., DataSourceUpdatePayload with optional
prune_freq?: number, refresh_freq?: number, config?: Record<string, unknown>,
timeout_secs?: number) and update the function signature export const
dataSourceUpdate = (id: string, data: DataSourceUpdatePayload) => { return
request.patch(api.dataSourceUpdate(id), { data }); } so callers and TS checks
use the correct shape.
---
Outside diff comments:
In `@api/apps/restful_apis/connector_api.py`:
- Around line 57-80: The create_connector handler fails to handle an empty or
None request body and still accesses req["id"], causing a crash; update
create_connector to validate req after await get_request_json() and if falsy
return an appropriate error response (e.g., using get_json_result with an error
message/status or raise a HTTP exception) instead of continuing; ensure early
return prevents calling ConnectorService.save and ConnectorService.get_by_id
with a missing id and keep references to get_request_json,
ConnectorService.save, ConnectorService.get_by_id, and get_json_result when
implementing the check.
- Around line 457-459: The code calls json.loads on REDIS_CONN.get(...) before
checking for absence; change the logic in the block using _web_state_cache_key
and REDIS_CONN.get so you first capture the raw value (e.g., raw_cache =
REDIS_CONN.get(_web_state_cache_key(flow_id, "box"))), check if raw_cache is
None or falsy and return get_json_result(code=RetCode.ARGUMENT_ERROR,
message="Box OAuth session expired or invalid.") if missing, and only then call
json.loads(raw_cache) to produce cache_payload; update references to
cache_payload accordingly.
- Line 234: Remove the leftover debug print that exposes sensitive data: delete
the print(credentials) call in connector_api.py (where the credentials variable
is handled) and, if you need runtime visibility, replace it with a secure logger
call that redacts or masks secrets (e.g., use the existing logger and do not log
full credential values).
In
`@test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py`:
- Around line 366-379: The test is calling a nonexistent module.set_connector()
after the API was split; replace those calls with the correct functions: use
module.update_connector() for the case that updates an existing connector (first
assertion block expecting update_calls and id "conn-1") and use
module.create_connector() for the creation case (second block asserting
save_calls and generated-id), and ensure the monkeypatched get_request_json
remains paired with the create_connector() call so the input_type and tenant_id
assertions still apply.
In `@web/src/pages/user-setting/data-source/hooks.ts`:
- Around line 90-105: The useCallback for handleAddOk closes over isEdit but the
dependency array only lists hideAddingModal and queryClient; add isEdit to the
dependency array so the callback updates when edit mode changes and avoids stale
closure behavior. In other words, update the useCallback dependencies for
handleAddOk to include isEdit (alongside existing hideAddingModal and
queryClient) so the logic that chooses between dataSourceUpdate and
dataSourceService.dataSourceSet runs with the current isEdit value.
---
Nitpick comments:
In `@api/apps/restful_apis/connector_api.py`:
- Around line 38-54: The update_connector and create_connector flows need
observability: add logging calls at key points (entering the handler, received
request payload, on validation failures, before calling
ConnectorService.update_by_id / ConnectorService.create, and on success) using
the module logger (e.g., logger.info/error). Include connector_id and relevant
request fields (prune_freq, refresh_freq, config, timeout_secs) in logs and log
errors when ConnectorService returns failures so callers and operators can trace
create/update operations.
- Around line 51-52: The anonymous 1-second pause before calling
ConnectorService.get_by_id (seen in update_connector and create_connector) lacks
context; replace the magic number with a named constant (e.g.,
CONSISTENCY_DELAY_SECONDS) or extract a helper like wait_for_propagation(delay)
and add a brief comment explaining why the delay is needed (eventual consistency
/ DB propagation) so future readers understand its purpose; update both places
(asyncio.sleep(1) in update_connector and create_connector) to use the new
constant/helper and include the comment near the sleep usage.
🪄 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: 2c57c853-5aea-4b45-abc9-511c1ff54b9e
📒 Files selected for processing (9)
api/apps/restful_apis/connector_api.pydocs/guides/dataset/add_data_source/add_google_drive.mdtest/testcases/test_web_api/test_connector_app/test_connector_oauth_contract.pytest/testcases/test_web_api/test_connector_app/test_connector_routes_unit.pyweb/src/pages/user-setting/data-source/data-source-detail-page/index.tsxweb/src/pages/user-setting/data-source/hooks.tsweb/src/pages/user-setting/data-source/index.tsxweb/src/services/data-source-service.tsweb/src/utils/api.ts
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14228 +/- ##
=======================================
Coverage 95.97% 95.97%
=======================================
Files 10 10
Lines 695 695
Branches 111 111
=======================================
Hits 667 667
Misses 11 11
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
e3cba19 to
bb31044
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
api/apps/restful_apis/connector_api.py (3)
232-235:⚠️ Potential issue | 🟠 MajorRemove the credentials debug print.
Line 234 can leak OAuth client secrets into stdout/container logs. Use structured logging without credential material if diagnostics are needed.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 232 - 235, Remove the debug print that outputs credentials from the try block around _load_credentials(raw_credentials); specifically delete the print(credentials) call and do not log raw_credentials or returned credential fields directly. If you need diagnostics, emit a structured logger message (e.g., using the module logger or processLogger) that logs non-sensitive status only (e.g., "credentials loaded" with masked flags or counts) and ensure any secret fields from the result of _load_credentials are redacted or omitted.
60-80:⚠️ Potential issue | 🟠 MajorValidate create payloads before indexing required fields.
req["name"],req["source"], andreq["config"]can raiseKeyError, and invalid numeric fields can raiseValueError, turning bad client input into a 500. Add required-field validation and returnARGUMENT_ERRORfor invalid integers.Suggested fix
`@manager.route`("/connectors", methods=["POST"]) # noqa: F821 `@login_required` +@validate_request("name", "source", "config") async def create_connector(): req = await get_request_json() - if req: - req["id"] = get_uuid() + try: + refresh_freq = int(req.get("refresh_freq", 5)) + prune_freq = int(req.get("prune_freq", 720)) + timeout_secs = int(req.get("timeout_secs", 60 * 29)) + except (TypeError, ValueError): + return get_json_result(code=RetCode.ARGUMENT_ERROR, message="Invalid connector frequency or timeout value.") + + if req: + req["id"] = get_uuid() conn = { "id": req["id"], "tenant_id": current_user.id, "name": req["name"], "source": req["source"], "input_type": InputType.POLL, "config": req["config"], - "refresh_freq": int(req.get("refresh_freq", 5)), - "prune_freq": int(req.get("prune_freq", 720)), - "timeout_secs": int(req.get("timeout_secs", 60 * 29)), + "refresh_freq": refresh_freq, + "prune_freq": prune_freq, + "timeout_secs": timeout_secs, "status": TaskStatus.SCHEDULE, }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 60 - 80, Validate the incoming payload from get_request_json() before using required keys and converting numeric fields: check that req is not None and that "name", "source", and "config" are present (return ARGUMENT_ERROR if missing), and when reading "refresh_freq", "prune_freq", and "timeout_secs" convert with int() inside a try/except to catch ValueError and return ARGUMENT_ERROR on bad numbers; only then build the conn dict (using get_uuid() for id) and call ConnectorService.save(**conn), and when fetching ConnectorService.get_by_id use the same id variable instead of assuming req["id"]; keep existing references to InputType.POLL, TaskStatus.SCHEDULE, ConnectorService.save/get_by_id, get_json_result.
453-465:⚠️ Potential issue | 🟠 MajorHandle Box OAuth errors and expired state before parsing the cache.
json.loads(REDIS_CONN.get(...))raises when the state key is missing, so expired sessions never reach the intended error response. Also, OAuth denial callbacks often includeerrorwithoutcode, so checkerrorbefore requiringcode.Suggested fix
- code = request.args.get("code") - if not code: - return await _render_web_oauth_popup(flow_id, False, "Missing authorization code from Box.", "box") - - cache_payload = json.loads(REDIS_CONN.get(_web_state_cache_key(flow_id, "box"))) - if not cache_payload: + cache_raw = REDIS_CONN.get(_web_state_cache_key(flow_id, "box")) + if not cache_raw: return get_json_result(code=RetCode.ARGUMENT_ERROR, message="Box OAuth session expired or invalid.") error = request.args.get("error") error_description = request.args.get("error_description") or error if error: REDIS_CONN.delete(_web_state_cache_key(flow_id, "box")) return await _render_web_oauth_popup(flow_id, False, error_description or "Authorization failed.", "box") + + code = request.args.get("code") + if not code: + return await _render_web_oauth_popup(flow_id, False, "Missing authorization code from Box.", "box") + + cache_payload = json.loads(cache_raw)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 453 - 465, Reorder the Box OAuth handling so you check for OAuth errors and the presence of the "error" parameter (via request.args.get("error") and request.args.get("error_description")) before attempting to load the cached state; then only call REDIS_CONN.get(...) and json.loads(...) on _web_state_cache_key(flow_id, "box") after confirming no "error" and after verifying "code" exists; ensure that when an error is present you delete the cached state with REDIS_CONN.delete(_web_state_cache_key(flow_id, "box")) and return via _render_web_oauth_popup(flow_id, False, error_description or "Authorization failed.", "box"), and when the cache is missing handle it by returning get_json_result(code=RetCode.ARGUMENT_ERROR, message="Box OAuth session expired or invalid.").test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py (1)
324-375:⚠️ Potential issue | 🔴 CriticalReplace broken test calls with split handler functions.
The
set_connector()handler no longer exists inconnector_api.py. Replace the two calls withupdate_connector("conn-1")for PATCH operations andcreate_connector()for POST operations. Also update the assertion for the update call—the handler adds theidfield to the payload before callingConnectorService.update_by_id().Required test updates
res = _run(module.set_connector()) - assert update_calls == [("conn-1", {"refresh_freq": 7, "config": {"x": 1}})] + res = _run(module.update_connector("conn-1")) + assert update_calls == [("conn-1", {"refresh_freq": 7, "config": {"x": 1}, "id": "conn-1"})] assert res["data"]["id"] == "conn-1" - res = _run(module.set_connector()) + res = _run(module.create_connector())🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py` around lines 324 - 375, The test is calling the removed handler set_connector(); replace the PATCH call with module.update_connector("conn-1") and the POST call with module.create_connector(), and adjust the update assertion to expect ConnectorService.update_by_id was called with ("conn-1", {"id":"conn-1", "refresh_freq":7, "config":{"x":1}}) because update_connector injects the id into the payload before calling ConnectorService.update_by_id; keep other monkeypatches (get_request_json, get_uuid, etc.) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/apps/restful_apis/connector_api.py`:
- Around line 42-49: The connector update currently fetches by
ConnectorService.get_by_id(connector_id) and updates via
ConnectorService.update_by_id(connector_id, conn) without verifying tenant
ownership; change this to enforce tenant scoping by either calling a
tenant-aware lookup or verifying the fetched connector's tenant_id against the
current tenant (e.g., get tenant_id from the request/context and check
conn["tenant_id"] == current_tenant_id), return a not-found/permission error if
they differ, then call ConnectorService.update_by_id only when ownership is
confirmed; apply the same tenant-ownership check pattern to the other
/connectors/<connector_id> handlers that use ConnectorService.get_by_id or
ConnectorService.update_by_id to prevent cross-tenant reads/mutations.
---
Outside diff comments:
In `@api/apps/restful_apis/connector_api.py`:
- Around line 232-235: Remove the debug print that outputs credentials from the
try block around _load_credentials(raw_credentials); specifically delete the
print(credentials) call and do not log raw_credentials or returned credential
fields directly. If you need diagnostics, emit a structured logger message
(e.g., using the module logger or processLogger) that logs non-sensitive status
only (e.g., "credentials loaded" with masked flags or counts) and ensure any
secret fields from the result of _load_credentials are redacted or omitted.
- Around line 60-80: Validate the incoming payload from get_request_json()
before using required keys and converting numeric fields: check that req is not
None and that "name", "source", and "config" are present (return ARGUMENT_ERROR
if missing), and when reading "refresh_freq", "prune_freq", and "timeout_secs"
convert with int() inside a try/except to catch ValueError and return
ARGUMENT_ERROR on bad numbers; only then build the conn dict (using get_uuid()
for id) and call ConnectorService.save(**conn), and when fetching
ConnectorService.get_by_id use the same id variable instead of assuming
req["id"]; keep existing references to InputType.POLL, TaskStatus.SCHEDULE,
ConnectorService.save/get_by_id, get_json_result.
- Around line 453-465: Reorder the Box OAuth handling so you check for OAuth
errors and the presence of the "error" parameter (via request.args.get("error")
and request.args.get("error_description")) before attempting to load the cached
state; then only call REDIS_CONN.get(...) and json.loads(...) on
_web_state_cache_key(flow_id, "box") after confirming no "error" and after
verifying "code" exists; ensure that when an error is present you delete the
cached state with REDIS_CONN.delete(_web_state_cache_key(flow_id, "box")) and
return via _render_web_oauth_popup(flow_id, False, error_description or
"Authorization failed.", "box"), and when the cache is missing handle it by
returning get_json_result(code=RetCode.ARGUMENT_ERROR, message="Box OAuth
session expired or invalid.").
In
`@test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py`:
- Around line 324-375: The test is calling the removed handler set_connector();
replace the PATCH call with module.update_connector("conn-1") and the POST call
with module.create_connector(), and adjust the update assertion to expect
ConnectorService.update_by_id was called with ("conn-1", {"id":"conn-1",
"refresh_freq":7, "config":{"x":1}}) because update_connector injects the id
into the payload before calling ConnectorService.update_by_id; keep other
monkeypatches (get_request_json, get_uuid, etc.) unchanged.
🪄 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: fe5052ec-253a-48c6-9f24-819569437f07
📒 Files selected for processing (9)
api/apps/restful_apis/connector_api.pydocs/guides/dataset/add_data_source/add_google_drive.mdtest/testcases/test_web_api/test_connector_app/test_connector_oauth_contract.pytest/testcases/test_web_api/test_connector_app/test_connector_routes_unit.pyweb/src/pages/user-setting/data-source/data-source-detail-page/index.tsxweb/src/pages/user-setting/data-source/hooks.tsweb/src/pages/user-setting/data-source/index.tsxweb/src/services/data-source-service.tsweb/src/utils/api.ts
✅ Files skipped from review due to trivial changes (1)
- test/testcases/test_web_api/test_connector_app/test_connector_oauth_contract.py
🚧 Files skipped from review as they are similar to previous changes (4)
- docs/guides/dataset/add_data_source/add_google_drive.md
- web/src/pages/user-setting/data-source/data-source-detail-page/index.tsx
- web/src/pages/user-setting/data-source/hooks.ts
- web/src/services/data-source-service.ts
bb31044 to
c8400e8
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
web/src/pages/user-setting/data-source/hooks.ts (1)
90-105:⚠️ Potential issue | 🟡 Minor
handleAddOkuseCallbackdeps are missingisEdit.
handleAddOkcloses overisEditbut the dependency array is[hideAddingModal, queryClient], so if a caller ever passes a changingisEdit, the memoized callback will keep the stale value and route the request to the wrong endpoint (dataSourceSetvsdataSourceUpdate). Current call sites pass a constant, so this is latent, but worth fixing to match the lint rule and avoid future bugs.Proposed fix
- [hideAddingModal, queryClient], + [hideAddingModal, queryClient, isEdit],🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/pages/user-setting/data-source/hooks.ts` around lines 90 - 105, The useCallback for handleAddOk closes over isEdit but does not list it in its dependency array, risking stale routing between dataSourceUpdate and dataSourceService.dataSourceSet; update the dependency array of handleAddOk to include isEdit (in addition to hideAddingModal and queryClient) so the memoized callback updates when isEdit changes and always calls the correct endpoint.api/apps/restful_apis/connector_api.py (3)
230-235:⚠️ Potential issue | 🟠 MajorRemove the raw credential print.
credentialsmay include OAuth client secrets, andprint(credentials)can leak them into process logs. Use only sanitized metadata if this flow needs observability.Proposed fix
try: credentials = _load_credentials(raw_credentials) - print(credentials) + logging.info("Loaded Google OAuth client config for %s web OAuth flow.", source) except ValueError as exc: return get_json_result(code=RetCode.ARGUMENT_ERROR, message=str(exc))As per coding guidelines,
**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 230 - 235, Remove the sensitive debug print of credentials: delete the print(credentials) call after calling _load_credentials(raw_credentials) and do not log raw or full credential objects; if observability is required, log only sanitized metadata (e.g., credential type, masked client id) using the project's logger instead of print, referencing the raw_credentials variable, the _load_credentials function, and the credentials variable for where to apply the change.
60-80:⚠️ Potential issue | 🟠 MajorValidate and log connector creation before dereferencing the request body.
With an empty body or missing
name/source/config, this falls through toreq["id"]or raisesKeyError, producing a 500 instead of a validation error. Also check the post-save lookup beforeto_dict().Proposed fix
`@manager.route`("/connectors", methods=["POST"]) # noqa: F821 `@login_required` +@validate_request("name", "source", "config") async def create_connector(): req = await get_request_json() - if req: - req["id"] = get_uuid() - conn = { - "id": req["id"], - "tenant_id": current_user.id, - "name": req["name"], - "source": req["source"], - "input_type": InputType.POLL, - "config": req["config"], - "refresh_freq": int(req.get("refresh_freq", 5)), - "prune_freq": int(req.get("prune_freq", 720)), - "timeout_secs": int(req.get("timeout_secs", 60 * 29)), - "status": TaskStatus.SCHEDULE, - } - ConnectorService.save(**conn) + connector_id = get_uuid() + conn = { + "id": connector_id, + "tenant_id": current_user.id, + "name": req["name"], + "source": req["source"], + "input_type": InputType.POLL, + "config": req["config"], + "refresh_freq": int(req.get("refresh_freq", 5)), + "prune_freq": int(req.get("prune_freq", 720)), + "timeout_secs": int(req.get("timeout_secs", 60 * 29)), + "status": TaskStatus.SCHEDULE, + } + ConnectorService.save(**conn) + logging.info("Created connector %s for tenant %s", connector_id, current_user.id) await asyncio.sleep(1) - e, conn = ConnectorService.get_by_id(req["id"]) + e, conn = ConnectorService.get_by_id(connector_id) + if not e: + return get_data_error_result(message="Can't find this Connector!") return get_json_result(data=conn.to_dict())As per coding guidelines,
**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 60 - 80, The handler currently dereferences req and required keys directly (req["id"], req["name"], req["source"], req["config"]) which can raise KeyError or cause a 500; validate that get_request_json() returned a dict and that required fields ("name","source","config") exist and are non-empty before calling get_uuid(), building conn, or calling ConnectorService.save; log a validation error (including current_user.id and missing fields) and return a proper validation response if checks fail; after save, ensure ConnectorService.get_by_id(req["id"]) returns a successful result and a non-None conn before calling conn.to_dict(), log and return a 404/appropriate error if lookup failed.
449-465:⚠️ Potential issue | 🟠 MajorHandle Box OAuth errors and expired state before requiring a code.
An authorization denial can arrive with
errorand nocode, so this currently reports “Missing authorization code” and leaves Redis state behind. Also, an expired Redis key makesjson.loads(None)raise before the intended invalid-session response.Proposed fix
async def box_web_oauth_callback(): flow_id = request.args.get("state") if not flow_id: return await _render_web_oauth_popup("", False, "Missing OAuth parameters.", "box") - - code = request.args.get("code") - if not code: - return await _render_web_oauth_popup(flow_id, False, "Missing authorization code from Box.", "box") - cache_payload = json.loads(REDIS_CONN.get(_web_state_cache_key(flow_id, "box"))) + state_key = _web_state_cache_key(flow_id, "box") + state_cache = REDIS_CONN.get(state_key) + if not state_cache: + return await _render_web_oauth_popup(flow_id, False, "Box OAuth session expired or invalid.", "box") + + try: + cache_payload = json.loads(state_cache) + except json.JSONDecodeError: + REDIS_CONN.delete(state_key) + return await _render_web_oauth_popup(flow_id, False, "Box OAuth session expired or invalid.", "box") + if not cache_payload: - return get_json_result(code=RetCode.ARGUMENT_ERROR, message="Box OAuth session expired or invalid.") + REDIS_CONN.delete(state_key) + return await _render_web_oauth_popup(flow_id, False, "Box OAuth session expired or invalid.", "box") error = request.args.get("error") error_description = request.args.get("error_description") or error if error: - REDIS_CONN.delete(_web_state_cache_key(flow_id, "box")) + REDIS_CONN.delete(state_key) return await _render_web_oauth_popup(flow_id, False, error_description or "Authorization failed.", "box") + + code = request.args.get("code") + if not code: + return await _render_web_oauth_popup(flow_id, False, "Missing authorization code from Box.", "box")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 449 - 465, The current flow checks for code before handling error and blindly calls json.loads on REDIS_CONN.get(...) which can be None; update the logic in the Box OAuth handler (references: flow_id, code, error, error_description, cache_payload, REDIS_CONN, _web_state_cache_key, _render_web_oauth_popup) to: first ensure flow_id exists, then check for an error parameter and if present delete the Redis state key and return the error popup (use error_description fallback), then fetch the cached value from REDIS_CONN and handle a None return safely (avoid json.loads on None) by treating it as expired/invalid: delete the key if present and return the expired-session JSON or popup; only after these checks require and validate the authorization code and proceed.test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py (1)
674-677:⚠️ Potential issue | 🟡 MinorCover the real expired Box OAuth session path.
"null"is not the same as Redis returning no value; the current production path crashes onjson.loads(None). Add a missing-key case so the callback behavior change is protected.Proposed test coverage
+ _set_request(module, args={"state": "flow-missing", "code": "abc"}) + expired_session = _run(module.box_web_oauth_callback()) + assert "expired or invalid" in expired_session.body + redis.store[module._web_state_cache_key("flow-null", "box")] = "null" _set_request(module, args={"state": "flow-null", "code": "abc"}) invalid_session = _run(module.box_web_oauth_callback()) assert invalid_session["code"] == module.RetCode.ARGUMENT_ERRORBased on learnings, Applies to tests/**/*.py : Add/adjust tests for behavior changes.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py` around lines 674 - 677, The test is simulating a Redis value of the string "null" but not the real expired-key behavior where redis returns None, which causes json.loads(None) to crash; update the test to cover the missing-key case by not setting redis.store[module._web_state_cache_key("flow-null","box")] (or explicitly deleting it) and keep using _set_request/_run/module.box_web_oauth_callback() to assert module.RetCode.ARGUMENT_ERROR, and concurrently fix box_web_oauth_callback to defensively handle a None return from redis (check the value from the key retrieved via module._web_state_cache_key(...) before calling json.loads and return ARGUMENT_ERROR when missing/None).
♻️ Duplicate comments (1)
api/apps/restful_apis/connector_api.py (1)
42-54:⚠️ Potential issue | 🟠 MajorScope every connector-id route to
current_user.id.These handlers still fetch or mutate by
connector_idonly, while listing is tenant-scoped. A user who can guess another connector ID could read, update, resume, rebuild, or delete it. Reuse a tenant-aware lookup before callingupdate_by_id,list_sync_tasks,resume,rebuild, ordelete_by_id.Also applies to: 89-133
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/connector_api.py` around lines 42 - 54, Handlers are using ConnectorService.get_by_id and update_by_id (and other ops like list_sync_tasks, resume, rebuild, delete_by_id) without scoping to the current user's tenant, allowing ID guessing; change each route to first perform a tenant-aware lookup (e.g., call a tenant-scoped method or add tenant filtering to ConnectorService.get_by_id such as get_by_id_and_tenant(connector_id, current_user.id) or pass current_user.id into get_by_id) and use that returned connector for authorization before calling ConnectorService.update_by_id, list_sync_tasks, resume, rebuild, or delete_by_id so all fetches and mutations are restricted to current_user.id. Ensure the code paths at the top of the handler (where you call ConnectorService.get_by_id, ConnectorService.update_by_id, and the other listed methods) are updated consistently to use the tenant-scoped lookup and abort/return an error if no connector is found for the current_user.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py`:
- Around line 366-368: The test's expected update payload doesn't include the
added "id" field; update the assertion for update_calls to expect ("conn-1",
{"id": "conn-1", "refresh_freq": 7, "config": {"x": 1}}) so it matches what
update_connector injects before calling ConnectorService.update_by_id (check the
update_connector call and the update_calls/mock used in the test).
---
Outside diff comments:
In `@api/apps/restful_apis/connector_api.py`:
- Around line 230-235: Remove the sensitive debug print of credentials: delete
the print(credentials) call after calling _load_credentials(raw_credentials) and
do not log raw or full credential objects; if observability is required, log
only sanitized metadata (e.g., credential type, masked client id) using the
project's logger instead of print, referencing the raw_credentials variable, the
_load_credentials function, and the credentials variable for where to apply the
change.
- Around line 60-80: The handler currently dereferences req and required keys
directly (req["id"], req["name"], req["source"], req["config"]) which can raise
KeyError or cause a 500; validate that get_request_json() returned a dict and
that required fields ("name","source","config") exist and are non-empty before
calling get_uuid(), building conn, or calling ConnectorService.save; log a
validation error (including current_user.id and missing fields) and return a
proper validation response if checks fail; after save, ensure
ConnectorService.get_by_id(req["id"]) returns a successful result and a non-None
conn before calling conn.to_dict(), log and return a 404/appropriate error if
lookup failed.
- Around line 449-465: The current flow checks for code before handling error
and blindly calls json.loads on REDIS_CONN.get(...) which can be None; update
the logic in the Box OAuth handler (references: flow_id, code, error,
error_description, cache_payload, REDIS_CONN, _web_state_cache_key,
_render_web_oauth_popup) to: first ensure flow_id exists, then check for an
error parameter and if present delete the Redis state key and return the error
popup (use error_description fallback), then fetch the cached value from
REDIS_CONN and handle a None return safely (avoid json.loads on None) by
treating it as expired/invalid: delete the key if present and return the
expired-session JSON or popup; only after these checks require and validate the
authorization code and proceed.
In
`@test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py`:
- Around line 674-677: The test is simulating a Redis value of the string "null"
but not the real expired-key behavior where redis returns None, which causes
json.loads(None) to crash; update the test to cover the missing-key case by not
setting redis.store[module._web_state_cache_key("flow-null","box")] (or
explicitly deleting it) and keep using
_set_request/_run/module.box_web_oauth_callback() to assert
module.RetCode.ARGUMENT_ERROR, and concurrently fix box_web_oauth_callback to
defensively handle a None return from redis (check the value from the key
retrieved via module._web_state_cache_key(...) before calling json.loads and
return ARGUMENT_ERROR when missing/None).
In `@web/src/pages/user-setting/data-source/hooks.ts`:
- Around line 90-105: The useCallback for handleAddOk closes over isEdit but
does not list it in its dependency array, risking stale routing between
dataSourceUpdate and dataSourceService.dataSourceSet; update the dependency
array of handleAddOk to include isEdit (in addition to hideAddingModal and
queryClient) so the memoized callback updates when isEdit changes and always
calls the correct endpoint.
---
Duplicate comments:
In `@api/apps/restful_apis/connector_api.py`:
- Around line 42-54: Handlers are using ConnectorService.get_by_id and
update_by_id (and other ops like list_sync_tasks, resume, rebuild, delete_by_id)
without scoping to the current user's tenant, allowing ID guessing; change each
route to first perform a tenant-aware lookup (e.g., call a tenant-scoped method
or add tenant filtering to ConnectorService.get_by_id such as
get_by_id_and_tenant(connector_id, current_user.id) or pass current_user.id into
get_by_id) and use that returned connector for authorization before calling
ConnectorService.update_by_id, list_sync_tasks, resume, rebuild, or delete_by_id
so all fetches and mutations are restricted to current_user.id. Ensure the code
paths at the top of the handler (where you call ConnectorService.get_by_id,
ConnectorService.update_by_id, and the other listed methods) are updated
consistently to use the tenant-scoped lookup and abort/return an error if no
connector is found for the current_user.
🪄 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: ddab6bf2-805f-43e5-a20f-42f3735f4721
📒 Files selected for processing (9)
api/apps/restful_apis/connector_api.pydocs/guides/dataset/add_data_source/add_google_drive.mdtest/testcases/test_web_api/test_connector_app/test_connector_oauth_contract.pytest/testcases/test_web_api/test_connector_app/test_connector_routes_unit.pyweb/src/pages/user-setting/data-source/data-source-detail-page/index.tsxweb/src/pages/user-setting/data-source/hooks.tsweb/src/pages/user-setting/data-source/index.tsxweb/src/services/data-source-service.tsweb/src/utils/api.ts
✅ Files skipped from review due to trivial changes (2)
- test/testcases/test_web_api/test_connector_app/test_connector_oauth_contract.py
- web/src/pages/user-setting/data-source/index.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
- docs/guides/dataset/add_data_source/add_google_drive.md
- web/src/utils/api.ts
What problem does this PR solve?
Refactor /api/v1/connectors to be more RESTful.
Type of change