Skip to content

fix(preview): authenticate markdown document preview requests - #15589

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
monsterdavidliu-ux:fix/issue-15585-markdown-preview
Jun 11, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
monsterdavidliu-ux:fix/issue-15585-markdown-preview

Conversation

@monsterdavidliu-ux

@monsterdavidliu-ux monsterdavidliu-ux commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #15585.

  • Route markdown preview through the shared request client (same as txt/image previewers) so Authorization headers and interceptors are applied consistently.
  • Add a unit test covering AUTH_BETA token loading for embedded search auth.

Root cause

Search result preview for .md/.mdx used raw fetch, which did not apply the same auth path as other preview types. That led to 401 on GET /api/v1/documents/{id}/preview even when the user was logged in or using an embedded search auth query param.

Test plan

  • Log in, run a search, open a markdown citation link — preview loads (no 401).
  • Open an embedded shared search URL with auth query param, preview a markdown file — preview loads.
  • Confirm PDF/txt preview still works in the same search UI.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: 5c6e7f08-de9c-4944-ba5c-7e07dce3fbaf

📥 Commits

Reviewing files that changed from the base of the PR and between dba6342 and 248de9e.

📒 Files selected for processing (1)
  • test/testcases/test_web_api/test_system_app/test_apps_init_unit.py

📝 Walkthrough

Walkthrough

Markdown preview now uses the shared authenticated request utility with loading and lifecycle-safe handling; tests add a beta-token fallback case verifying bearer auth maps to AUTH_BETA and returns the beta user.

Changes

File preview authentication and loading

Layer / File(s) Summary
Markdown preview request utility refactoring
web/src/components/document-preview/md/index.tsx
Imports updated to use request, Spin, and message. Component fetches markdown via request (blob -> text), tracks loading with a centered spinner, uses a cancelled flag to avoid post-unmount state updates, clears state when url is falsy, and sets local error while calling message.error('Failed to load file'). Container className adds relative.
API token beta field fallback test coverage
test/testcases/test_web_api/test_system_app/test_apps_init_unit.py
Adds beta_user fixture with a 32-character access_token. APIToken.query mock returns tenant only when beta == "embed-beta". UserService.query returns beta_user for the matching tenant/status. Test asserts _load_user(auth_types=[AUTH_BETA]) authenticates Bearer embed-beta, returns beta_user, sets g.auth_type to AUTH_BETA, and that Bearer invalid-beta yields None.

Sequence Diagram

sequenceDiagram
  participant MdComponent
  participant request_util
  participant DocumentsAPI
  MdComponent->>request_util: request(url, responseType='blob')
  request_util->>DocumentsAPI: GET /documents/:id/preview (with auth)
  DocumentsAPI-->>request_util: returns markdown blob or 401
  request_util-->>MdComponent: blob.text() -> render or set error
Loading

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Possibly related PRs

Suggested reviewers

  • cike8899

🐰 I hopped through code with a twitch and a cheer,
Spun markdown loads so previews appear,
Beta tokens now find their rightful home,
No more 401s when users roam,
A carrot-shaped commit — hooray, good cheer!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 directly relates to the main change: authenticating markdown preview requests via the shared request client instead of raw fetch.
Description check ✅ Passed The description covers the problem, root cause, solution approach, and test plan; it matches the template structure with clear context for reviewers.
Linked Issues check ✅ Passed The PR directly addresses #15585 by routing markdown preview through the shared request client with proper auth headers, matching the expected behavior of preview functionality without 401 errors.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing markdown preview authentication and adding related unit test coverage; no unrelated modifications detected.

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

@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jun 3, 2026
Route .md/.mdx preview through the shared request client so Authorization
headers and interceptors match txt/image previewers. Add a unit test for
AUTH_BETA token loading used by embedded search.

Fixes infiniflow#15585

@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)
test/testcases/test_web_api/test_system_app/test_apps_init_unit.py (1)

188-190: ⚡ Quick win

Consider adding a negative test case for invalid beta token.

The current test validates the happy path where the beta token is valid. Consider adding a test case to verify that authentication fails when the beta token is not found in the APIToken.query lookup, ensuring the AUTH_BETA path correctly rejects invalid tokens.

🧪 Example negative test case

Add after line 190:

        # Test invalid beta token returns None
        async with quart_app.test_request_context("/", headers={"Authorization": "Bearer invalid-beta"}):
            user = apps_module._load_user(auth_types=[apps_module.AUTH_BETA])
            assert user is None
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/test_web_api/test_system_app/test_apps_init_unit.py` around
lines 188 - 190, Add a negative test that asserts _load_user returns None when
an invalid beta token is presented: within
test_web_api/test_system_app/test_apps_init_unit.py create an async
test_request_context with an Authorization header using an invalid beta token,
call apps_module._load_user(auth_types=[apps_module.AUTH_BETA]) and assert the
result is None; this verifies the AUTH_BETA path and the APIToken.query lookup
correctly rejects tokens not found.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/testcases/test_web_api/test_system_app/test_apps_init_unit.py`:
- Line 186: The UserService.query mock currently ignores arguments; update the
monkeypatch for apps_module.UserService.query so it validates the contract used
in api/apps/__init__.py by asserting or checking that it is called with
id=objs[0].tenant_id and status=StatusEnum.VALID.value (or return empty list if
not), then return [beta_user] only when those parameters match; reference
UserService.query, objs[0].tenant_id, and StatusEnum.VALID.value when
implementing the check so the test fails if the implementation passes incorrect
params.

---

Nitpick comments:
In `@test/testcases/test_web_api/test_system_app/test_apps_init_unit.py`:
- Around line 188-190: Add a negative test that asserts _load_user returns None
when an invalid beta token is presented: within
test_web_api/test_system_app/test_apps_init_unit.py create an async
test_request_context with an Authorization header using an invalid beta token,
call apps_module._load_user(auth_types=[apps_module.AUTH_BETA]) and assert the
result is None; this verifies the AUTH_BETA path and the APIToken.query lookup
correctly rejects tokens not found.
🪄 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: 0fbd5923-836b-43a3-b318-76c02e0a7938

📥 Commits

Reviewing files that changed from the base of the PR and between 997123a and ebdcba5.

📒 Files selected for processing (1)
  • test/testcases/test_web_api/test_system_app/test_apps_init_unit.py

@monsterdavidliu-ux
monsterdavidliu-ux force-pushed the fix/issue-15585-markdown-preview branch from ebdcba5 to dba6342 Compare June 3, 2026 12:38
@yingfeng yingfeng added the ci Continue Integration label Jun 3, 2026
@yingfeng
yingfeng marked this pull request as draft June 3, 2026 13:47
@yingfeng
yingfeng marked this pull request as ready for review June 3, 2026 13:47
@codecov

codecov Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (a1dc2da) to head (c6f97f7).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15589   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 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.

bitloi and others added 3 commits June 3, 2026 15:02
Validate UserService.query tenant/status contract and reject unknown
beta tokens in test_load_user_api_token_fallback_and_fallback_exception.
@wangq8
wangq8 requested review from cike8899 and dcc123456 June 11, 2026 06:57
@wangq8
wangq8 merged commit a851228 into infiniflow:main Jun 11, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: failed to preview markdown file

5 participants