refactor(api): deduplicate sources router - #1069
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
1 issue found across 2 files
Confidence score: 5/5
- In
api/routers/sources.py, the router refactor is missing its ADR and approved-issue linkage, which could make the design rationale hard to recover later and slow future maintenance or rollback decisions; add the ADR and link the assigned issue before merging.
You’re at about 92% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="api/routers/sources.py">
<violation number="1" location="api/routers/sources.py:337">
P3: This sizeable structural router refactor lacks the required decision record and approved-issue reference. Add the ADR (and link the assigned issue) before merging so the new router structure and rationale are traceable.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| raise HTTPException(status_code=500, detail="Error fetching sources") | ||
|
|
||
|
|
||
| def _source_to_response( |
Contributor
There was a problem hiding this comment.
P3: This sizeable structural router refactor lacks the required decision record and approved-issue reference. Add the ADR (and link the assigned issue) before merging so the new router structure and rationale are traceable.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At api/routers/sources.py, line 337:
<comment>This sizeable structural router refactor lacks the required decision record and approved-issue reference. Add the ADR (and link the assigned issue) before merging so the new router structure and rationale are traceable.</comment>
<file context>
@@ -348,6 +334,251 @@ async def get_sources(
raise HTTPException(status_code=500, detail="Error fetching sources")
+def _source_to_response(
+ source: Source, embedded_chunks: int = 0, **extras: Any
+) -> SourceResponse:
</file context>
- Extract _source_to_response() shared builder (SourceResponse was hand-rolled 5x with the same nested AssetModel ternary) - Extract _cleanup_uploaded_file() (the unlink ritual was pasted 6x inside create_source); inner cleanups were redundant with the outer exception handlers, which always run for the same failures - Split create_source into _build_content_state() (type validation + SSRF/LFI guards) and _create_source_async_path() / _create_source_sync_path() - Unify the paginated list query (with/without notebook filter differed only in the FROM clause and bound params) Pure structural refactor: same status codes, error messages and response shapes. Security checks (atomic filename claim via touch(exist_ok=False), path-traversal containment, SSRF/LFI guards) preserved verbatim, with their comments.
lfnovo
force-pushed
the
refactor/sources-router-dedup
branch
from
July 11, 2026 22:02
a44308b to
fd27533
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Pure structural deduplication of
api/routers/sources.py(1113 → 1075 lines; −318/+280 in the router). No behavior change: same status codes, same error messages, same response shapes.Deduplications
_source_to_response()— theSourceResponse(...)constructor with the nestedAssetModel(...) if source.asset else Noneternary was hand-rolled 5× (async create, sync create, get, update, retry). Any new response field required five edits. Endpoint-specific fields (command_id,status,processing_info,notebooks,file_available) are passed as overrides._cleanup_uploaded_file()— theif file_path and upload_file: try: os.unlink(...)ritual was pasted 6× insidecreate_source(). The three copies inside the sync/async branches were redundant: every failure path re-raises into the outer exception handlers, which perform the same (idempotent, error-swallowing) cleanup. Now there are exactly the three outer call sites.create_source()split (was 293 lines): notebook/transformation validation stays in the endpoint; type-specific input validation moved to_build_content_state()(this is where the SSRF and LFI guards live); the two processing branches became_create_source_async_path()/_create_source_sync_path().get_sources()— the with/without-notebook-filter queries were identical except for theFROMclause and bound params.Security checks preserved verbatim
This file contains deliberate security code, all kept exactly as-is (code + issue-referencing comments):
touch(exist_ok=False)(O_EXCL) ingenerate_unique_filename()— covered bytests/test_upload_toctou_race.pygenerate_unique_filename) and read (_resolve_source_file,_is_source_file_available) — covered bytests/test_source_path_containment.pyandtests/test_upload_type_mitigations.pyvalidate_url) and LFI uploads-directory containment in the (moved, not modified) content-state builder — covered bytests/test_sources_api.py/tests/test_source_create_array_limits.pypathsVerification
uv run pytest tests/— 403 passed (including the TOCTOU race, path-containment and upload-mitigation regression suites)ruff check .— clean;ruff format --check— cleanmypy api/routers/sources.py— 25 pre-existing errors in dependencies, 0 in this file, identical count onmain(no regression)