Repository navigation
Refactor: migrate artifact API - #14348
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)
📝 WalkthroughWalkthroughMigrates artifact handling to a new versioned API path: agent upload payloads now reference Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant API as Document API (/documents/artifact/<filename>)
participant ThreadPool
participant Storage
participant Response
Client->>API: GET /documents/artifact/<filename>
API->>API: validate basename, check extension allowlist
API->>ThreadPool: task => Storage.get(bucket, key)
ThreadPool->>Storage: fetch bytes
Storage-->>ThreadPool: artifact bytes / not found
ThreadPool-->>API: result
API->>API: apply_safe_file_response_headers, set Content-Disposition
API-->>Client: 200 + bytes (or error response)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested labels
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. 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
🧹 Nitpick comments (2)
api/apps/restful_apis/document_api.py (2)
1072-1078: Minor: redundant fallback incontent_typelookup.
extis already validated againstARTIFACT_CONTENT_TYPESon lines 1073–1074, so the"application/octet-stream"default on line 1078 is unreachable. You can simplify tocontent_type = ARTIFACT_CONTENT_TYPES[ext]for clarity.♻️ Proposed tweak
- content_type = ARTIFACT_CONTENT_TYPES.get(ext, "application/octet-stream") + content_type = ARTIFACT_CONTENT_TYPES[ext]🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/document_api.py` around lines 1072 - 1078, The content_type lookup uses a redundant fallback after you've already validated ext against ARTIFACT_CONTENT_TYPES; replace the safe .get usage with a direct index access so set content_type = ARTIFACT_CONTENT_TYPES[ext] (referencing ARTIFACT_CONTENT_TYPES, content_type, and ext) to remove the unreachable "application/octet-stream" fallback and clarify intent.
1066-1086: Add logging for the new artifact-serving flow.Per coding guidelines, new Python flows should emit logs. Consider logging denied requests (invalid filename / extension / missing data) at
warningand successful retrievals atinfo/debugwith at leastfilenameand requester id to aid forensics and debugging. Currently only the catch-allserver_error_response(e)path surfaces information.As per coding guidelines: "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/document_api.py` around lines 1066 - 1086, Add structured logging to the artifact-serving flow: emit warning logs for denied requests (invalid filename check, invalid extension, missing data from thread_pool_exec) and info/debug logs for successful retrievals (after make_response and before return) including at minimum the basename/filename and a requester identifier (e.g., request.state.user.id or a request header like X-Request-Id); use the same logging facility used elsewhere in the module and reference the symbols in this diff (filename/basename, SANDBOX_ARTIFACT_BUCKET, thread_pool_exec, get_data_error_result, make_response, apply_safe_file_response_headers, server_error_response) so each error branch logs a warning with details and the success branch logs info/debug with filename and requester id before returning the response.
🤖 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/document_api.py`:
- Around line 1039-1086: get_artifact exposes any artifact to any logged-in user
because it reads from SANDBOX_ARTIFACT_BUCKET using the caller-supplied filename
without tenant ownership checks; fix by enforcing tenant-scoped access: persist
ownership metadata when artifacts are created (associate filename/blob key with
tenant_id and creator_id/canvas_id) and, inside get_artifact, resolve the
requested filename against that metadata (e.g., lookup by basename) and verify
the current user's tenant_id matches before calling settings.STORAGE_IMPL.get;
alternatively, instead of returning raw blob data, change get_artifact to return
a short-lived signed URL from your storage layer (e.g., via
settings.STORAGE_IMPL.get_signed_url or equivalent) that is issued only after
the same ownership check, and ensure the existing filename validation
(basename/ext) remains.
---
Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1072-1078: The content_type lookup uses a redundant fallback after
you've already validated ext against ARTIFACT_CONTENT_TYPES; replace the safe
.get usage with a direct index access so set content_type =
ARTIFACT_CONTENT_TYPES[ext] (referencing ARTIFACT_CONTENT_TYPES, content_type,
and ext) to remove the unreachable "application/octet-stream" fallback and
clarify intent.
- Around line 1066-1086: Add structured logging to the artifact-serving flow:
emit warning logs for denied requests (invalid filename check, invalid
extension, missing data from thread_pool_exec) and info/debug logs for
successful retrievals (after make_response and before return) including at
minimum the basename/filename and a requester identifier (e.g.,
request.state.user.id or a request header like X-Request-Id); use the same
logging facility used elsewhere in the module and reference the symbols in this
diff (filename/basename, SANDBOX_ARTIFACT_BUCKET, thread_pool_exec,
get_data_error_result, make_response, apply_safe_file_response_headers,
server_error_response) so each error branch logs a warning with details and the
success branch logs info/debug with filename and requester id before returning
the response.
🪄 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: 0bd4e80a-3be1-48c4-9a99-e1908f6109da
📒 Files selected for processing (4)
agent/tools/code_exec.pyapi/apps/document_app.pyapi/apps/restful_apis/document_api.pyweb/src/components/next-markdown-content/index.tsx
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14348 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
ecf0801 to
cf2d187
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
api/apps/restful_apis/document_api.py (1)
1339-1386:⚠️ Potential issue | 🟠 MajorAuthorization scoping — any authenticated user can fetch any tenant's artifact.
get_artifactonly enforces@login_requiredand reads directly fromSANDBOX_ARTIFACT_BUCKETkeyed by the caller-suppliedbasename, with no mapping back to a tenant/user owner. Anyone who can guess or harvest an artifact UUID (logs, chat transcripts, leaked URLs) can download another tenant's artifacts, which may contain PII or proprietary exported data.Mitigations to consider:
- Persist
(filename → tenant_id/user_id/canvas_id)ownership metadata at upload time and verify it on retrieval, or- Issue short-lived signed URLs from the storage layer (after the same ownership check) instead of streaming bucket contents directly by filename.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/document_api.py` around lines 1339 - 1386, get_artifact currently trusts a caller-supplied filename and reads directly from SANDBOX_ARTIFACT_BUCKET, allowing any authenticated user to fetch any tenant's artifact; fix by verifying ownership before returning data: persist ownership metadata at upload time (map filename → tenant_id/user_id/canvas_id) and in get_artifact (function get_artifact) look up that metadata and compare against the current authenticated user/tenant, returning an authorization error if it doesn't match; alternatively, instead of streaming via settings.STORAGE_IMPL.get, call the storage layer to generate a short-lived signed URL (e.g., STORAGE_IMPL.get_signed_url or equivalent) only after the same ownership check and return that URL or redirect; ensure checks reference the same unique filename/basename and keep input validation (basename, ext) intact.
🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)
1364-1364: Drop the redundant localsettingsimport.
settingsis already imported at module scope on line 42 (from common import settings). The local re-import insideget_artifactis dead and should be removed for clarity.♻️ Proposed cleanup
- from common import settings - try: bucket = SANDBOX_ARTIFACT_BUCKET🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/document_api.py` at line 1364, Remove the redundant local import of settings inside the get_artifact function: there is already a module-level import "from common import settings" so delete the inner "from common import settings" statement in get_artifact to avoid a dead/redundant re-import and keep the function using the module-scope settings reference.
🤖 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/document_api.py`:
- Around line 1376-1377: The check "if not data:" incorrectly treats
empty-but-existing artifacts (b"") as missing; update the existence check in the
artifact retrieval logic to distinguish between None and empty bytes by either
calling the backend obj_exist() before fetching or changing the condition to "if
data is None:" so only truly missing keys trigger get_data_error_result; adjust
the code paths around the variable data and preserve the use of
get_data_error_result for actual missing artifacts.
---
Duplicate comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1339-1386: get_artifact currently trusts a caller-supplied
filename and reads directly from SANDBOX_ARTIFACT_BUCKET, allowing any
authenticated user to fetch any tenant's artifact; fix by verifying ownership
before returning data: persist ownership metadata at upload time (map filename →
tenant_id/user_id/canvas_id) and in get_artifact (function get_artifact) look up
that metadata and compare against the current authenticated user/tenant,
returning an authorization error if it doesn't match; alternatively, instead of
streaming via settings.STORAGE_IMPL.get, call the storage layer to generate a
short-lived signed URL (e.g., STORAGE_IMPL.get_signed_url or equivalent) only
after the same ownership check and return that URL or redirect; ensure checks
reference the same unique filename/basename and keep input validation (basename,
ext) intact.
---
Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Line 1364: Remove the redundant local import of settings inside the
get_artifact function: there is already a module-level import "from common
import settings" so delete the inner "from common import settings" statement in
get_artifact to avoid a dead/redundant re-import and keep the function using the
module-scope settings reference.
🪄 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: 7f4f439f-7e69-4e44-a951-6fffeb6809c7
📒 Files selected for processing (3)
api/apps/document_app.pyapi/apps/restful_apis/document_api.pyweb/src/locales/zh.ts
✅ Files skipped from review due to trivial changes (1)
- web/src/locales/zh.ts
| @manager.route("/documents/artifact/<filename>", methods=["GET"]) # noqa: F821 | ||
| @login_required | ||
| async def get_artifact(filename): | ||
| """ | ||
| Get an artifact file. | ||
| --- | ||
| tags: | ||
| - Documents | ||
| security: | ||
| - ApiKeyAuth: [] | ||
| parameters: | ||
| - in: path | ||
| name: filename | ||
| type: string | ||
| required: true | ||
| description: Name of the artifact file. | ||
| - in: header | ||
| name: Authorization | ||
| type: string | ||
| required: true | ||
| description: Bearer token for authentication. | ||
| responses: | ||
| 200: | ||
| description: Artifact file returned successfully. | ||
| """ | ||
| from common import settings | ||
|
|
||
| try: | ||
| bucket = SANDBOX_ARTIFACT_BUCKET | ||
| # Validate filename: must be uuid hex + allowed extension, nothing else | ||
| basename = os.path.basename(filename) | ||
| if basename != filename or "/" in filename or "\\" in filename: | ||
| return get_data_error_result(message="Invalid filename.") | ||
| ext = os.path.splitext(basename)[1].lower() | ||
| if ext not in ARTIFACT_CONTENT_TYPES: | ||
| return get_data_error_result(message="Invalid file type.") | ||
| data = await thread_pool_exec(settings.STORAGE_IMPL.get, bucket, basename) | ||
| if not data: | ||
| return get_data_error_result(message="Artifact not found.") | ||
| content_type = ARTIFACT_CONTENT_TYPES.get(ext, "application/octet-stream") | ||
| response = await make_response(data) | ||
| safe_filename = re.sub(r"[^\w.\-]", "_", basename) | ||
| apply_safe_file_response_headers(response, content_type, ext) | ||
| if not response.headers.get("Content-Disposition"): | ||
| response.headers.set("Content-Disposition", f'inline; filename="{safe_filename}"') | ||
| return response | ||
| except Exception as e: | ||
| return server_error_response(e) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Add logging for the new artifact-serving flow.
This is a brand-new request flow with security-relevant validation (filename rejection, extension allowlist, missing-object handling, generic exception fallback). None of the failure or success branches emit logs, which makes operational triage and abuse detection harder.
As per coding guidelines (**/*.py: Add logging for new flows), please add logging calls — at minimum on the validation-rejection branches and the unexpected-exception branch — e.g.:
📝 Suggested logging additions
try:
bucket = SANDBOX_ARTIFACT_BUCKET
# Validate filename: must be uuid hex + allowed extension, nothing else
basename = os.path.basename(filename)
if basename != filename or "/" in filename or "\\" in filename:
+ logging.warning("Rejected artifact request with unsafe filename: %r", filename)
return get_data_error_result(message="Invalid filename.")
ext = os.path.splitext(basename)[1].lower()
if ext not in ARTIFACT_CONTENT_TYPES:
+ logging.warning("Rejected artifact request with disallowed extension: %r", ext)
return get_data_error_result(message="Invalid file type.")
data = await thread_pool_exec(settings.STORAGE_IMPL.get, bucket, basename)
if not data:
+ logging.info("Artifact not found in bucket %s: %s", bucket, basename)
return get_data_error_result(message="Artifact not found.")
content_type = ARTIFACT_CONTENT_TYPES.get(ext, "application/octet-stream")
response = await make_response(data)
safe_filename = re.sub(r"[^\w.\-]", "_", basename)
apply_safe_file_response_headers(response, content_type, ext)
if not response.headers.get("Content-Disposition"):
response.headers.set("Content-Disposition", f'inline; filename="{safe_filename}"')
return response
except Exception as e:
+ logging.exception("Failed to serve artifact %r", filename)
return server_error_response(e)There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)
1485-1485: Redundant localsettingsimport.
settingsis already imported at module scope (line 44:from common import settings). The local re-import insideget_artifactis unnecessary and shadows the module-level name.♻️ Proposed cleanup
async def get_artifact(filename): """ ... """ - from common import settings - try: bucket = SANDBOX_ARTIFACT_BUCKET🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/document_api.py` at line 1485, Remove the redundant local import of settings inside get_artifact that shadows the module-level name; simply delete the line "from common import settings" within the get_artifact function so the function uses the already-imported module-level settings reference.
🤖 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/document_app.py`:
- Line 41: Remove the incorrect import symbol ParserTyp from the import list
(leave RetCode, SANDBOX_ARTIFACT_BUCKET, TaskStatus intact) in the import
statement that currently reads "from common.constants import RetCode, ParserTyp,
SANDBOX_ARTIFACT_BUCKET, TaskStatus" so the module imports only existing symbols
(e.g., ParserType is defined in common.constants but is not used here); this
prevents the ImportError that stops route registration in document_app.py.
---
Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Line 1485: Remove the redundant local import of settings inside get_artifact
that shadows the module-level name; simply delete the line "from common import
settings" within the get_artifact function so the function uses the
already-imported module-level settings reference.
🪄 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: 81dbbe97-1fb8-4b4d-90ed-6b545eee4bb1
📒 Files selected for processing (2)
api/apps/document_app.pyapi/apps/restful_apis/document_api.py
What problem does this PR solve?
Before migration: GET /v1/document/artifact/
After migration: GET /api/v1/documents/artifact/
Type of change