Skip to content

Refactor: migrate artifact API - #14348

Merged
yingfeng merged 5 commits into
infiniflow:mainfrom
xugangqiang:doc-artifact
Apr 27, 2026
Merged

yingfeng merged 5 commits into
infiniflow:mainfrom
xugangqiang:doc-artifact

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Before migration: GET /v1/document/artifact/
After migration: GET /api/v1/documents/artifact/

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 84d1c543-9baf-4238-b99b-f0249ac59ab4

📥 Commits

Reviewing files that changed from the base of the PR and between 7545f53 and 8aaa2dc.

📒 Files selected for processing (1)
  • api/apps/document_app.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/document_app.py

📝 Walkthrough

Walkthrough

Migrates artifact handling to a new versioned API path: agent upload payloads now reference /api/v1/documents/artifact/; the legacy GET /artifact/<filename> route is removed and replaced by an authenticated GET /documents/artifact/<filename> handler that validates filenames, enforces an extension allowlist, fetches bytes from storage, and returns safe file responses; frontend artifact detection updated accordingly.

Changes

Cohort / File(s) Summary
Agent Artifact URL
agent/tools/code_exec.py
Change upload response artifact URLs from "/v1/document/artifact/" to "/api/v1/documents/artifact/".
API Endpoint Migration
api/apps/document_app.py, api/apps/restful_apis/document_api.py
Remove legacy GET /artifact/<filename> route from document_app.py; add authenticated GET /documents/artifact/<filename> in restful_apis/document_api.py that enforces basename-only filenames, extension allowlist → fixed MIME mapping, retrieves bytes from SANDBOX_ARTIFACT_BUCKET via thread_pool_exec and settings.STORAGE_IMPL.get, and applies safe file response headers and Content-Disposition.
Frontend Artifact Detection
web/src/components/next-markdown-content/index.tsx
Change artifact URL detection to match the new path /api/v1/documents/artifact/ (previously looked for /document/artifact/) so links/images route to Artifact components correctly.

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)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

☯️ refactor

Suggested reviewers

  • yingfeng
  • yuzhichang
  • JinHai-CN

Poem

🐰 I hopped through paths both old and new,
I nudged the artifacts to a safer view,
From uploads to GETs, the routes align,
Headers wrapped snug, filenames fine,
A tiny rabbit celebrates this tidy design.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: migrating the artifact API endpoint from one path to another, which is the primary objective across all modified files.
Description check ✅ Passed The description includes the required template sections with the problem statement showing the endpoint migration (before/after) and the refactoring type selected, though the context could be slightly more detailed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@xugangqiang xugangqiang added the ci Continue Integration label Apr 24, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review April 24, 2026 05:13
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 24, 2026
@xugangqiang xugangqiang self-assigned this Apr 24, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
api/apps/restful_apis/document_api.py (2)

1072-1078: Minor: redundant fallback in content_type lookup.

ext is already validated against ARTIFACT_CONTENT_TYPES on lines 1073–1074, so the "application/octet-stream" default on line 1078 is unreachable. You can simplify to content_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 warning and successful retrievals at info/debug with at least filename and requester id to aid forensics and debugging. Currently only the catch-all server_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

📥 Commits

Reviewing files that changed from the base of the PR and between aadd9a3 and 5520a70.

📒 Files selected for processing (4)
  • agent/tools/code_exec.py
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py
  • web/src/components/next-markdown-content/index.tsx

@xugangqiang xugangqiang changed the title migrate artifact API Refactor: migrate artifact API Apr 24, 2026
@codecov

codecov Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (6a23dfe) to head (8aaa2dc).
⚠️ Report is 4 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Apr 24, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
api/apps/restful_apis/document_api.py (1)

1339-1386: ⚠️ Potential issue | 🟠 Major

Authorization scoping — any authenticated user can fetch any tenant's artifact.

get_artifact only enforces @login_required and reads directly from SANDBOX_ARTIFACT_BUCKET keyed by the caller-supplied basename, 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 local settings import.

settings is already imported at module scope on line 42 (from common import settings). The local re-import inside get_artifact is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5520a70 and cf2d187.

📒 Files selected for processing (3)
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py
  • web/src/locales/zh.ts
✅ Files skipped from review due to trivial changes (1)
  • web/src/locales/zh.ts

Comment on lines +1339 to +1386
@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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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)

Comment thread api/apps/restful_apis/document_api.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)

1485-1485: Redundant local settings import.

settings is already imported at module scope (line 44: from common import settings). The local re-import inside get_artifact is 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

📥 Commits

Reviewing files that changed from the base of the PR and between cf2d187 and 7545f53.

📒 Files selected for processing (2)
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py

Comment thread api/apps/document_app.py Resolved
@yingfeng
yingfeng merged commit 290f029 into infiniflow:main Apr 27, 2026
1 check passed
@xugangqiang
xugangqiang deleted the doc-artifact branch May 15, 2026 06:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants