Skip to content

fix: File preview cannot be previewed in embedded mode - #8305

Merged
shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_embed_file_preview
Dec 4, 2026
Merged

shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_embed_file_preview

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

fix: File preview cannot be previewed in embedded mode

def test_missing_credentials_pass_none(self):
request = self.factory.get("/chat/oss/file/file-id")

self.assertIsNone(self.retrieve(request))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Here are the issues and suggestions I found:

Potential issues

  1. Broken subTest argument (Bug)

    with self.subTest(authorization=[API_KEY]):

    [API_KEY] is undefined and authorization should be bound to the loop variable. This will raise NameError. It should be:

    with self.subTest(authorization=authorization):
  2. Shared cookies mutated across tests via self.factory
    self.factory.cookies[...] = ... mutates state on the factory instance. Since setUp creates a fresh APIRequestFactory per test this is currently safe, but it's fragile β€” reading via request.COOKIES semantics (factory.cookies vs request cookie passing) can be confusing. Consider using self.factory.get(..., cookies={...}) or DRF's client for clarity.

  3. patch target coupling
    The test asserts on operate.return_value.get.call_args.kwargs["mk_file_auth"]. If the view calls .get() multiple times or positional args change, call_args will be wrong (it captures only the last call). Prefer assert_called_once_with(...) on the expected call for robustness.

  4. Mock return type doesn't reflect HttpResponse usage
    Patching the whole Operate class and returning an HttpResponse from the mock means the view's response handling is bypassed/simulated. Fine for a focused unit test, but make sure this isn't hiding real behavior (e.g., if the view expects a FileResponse).

  5. No assertion that the view returns the mocked response / status
    The helper discards the view's response. Adding a check that .as_view()(...) returns the patched HttpResponse would catch regressions where the view errors before calling the serializer.

Test quality suggestions

  1. Coverage gap on whitespace / casing of header
    You test Bearer and bearer , but not values like "Bearer token" (multiple spaces) or a token containing spaces. Add explicit cases reflecting the actual parsing logic.

  2. Explicitly document/intend prefix matching
    If the code uses startswith("bearer ") (case-insensitive), test mixed case (bEaReR) explicitly for clarity and intent.

  3. Missing "empty Bearer falls back to cookie even without cookie β†’ None" symmetry β€” minor, optional.

Style/nits

  1. retrieve helper name shadows Django's retrieve semantics β€” consider _extract_mk_file_auth for readability.
  2. Docstring in Chinese while answers/filenames are English β€” fine per project convention, just noting consistency.
  3. FILE_AUTH_COOKIE imported from oss.views.file but view imported via oss.views β€” mixing import paths; pick one for consistency.

Minimal fix for the blocking bug

def test_other_authorization_schemes_fall_back_to_cookie(self):
    self.factory.cookies[FILE_AUTH_COOKIE] = "cookie-token"
    for authorization in ("Basic dXNlcjpwYXNz", "Bearer ", "Bearer"):
        with self.subTest(authorization=authorization):
            request = self.factory.get("/chat/oss/file/file-id", HTTP_AUTHORIZATION=authorization)
            self.assertEqual(self.retrieve(request), "cookie-token")

The subTest(authorization=[API_KEY]) line is the only outright defect; the rest are robustness/maintainability improvements.

@shaohuzhang1
shaohuzhang1 merged commit 7861854 into v3 Dec 4, 2026
3 of 4 checks passed
@shaohuzhang1
shaohuzhang1 deleted the pr@v3@fix_embed_file_preview branch December 4, 2026 10:33
const result = await load(fetchFile)
if (!controller.signal.aborted) data.value = result
} catch {
if (!controller.signal.aborted) error.value = t('chat.filePreview.loadFailedMessage')

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Issues and Suggestions

1. Memory leak risk on objectUrl (high priority)

In downloadChatFile, if anything throws between URL.createObjectURL(...) and the setTimeout cleanup, the object URL is never revoked (it's only revoked in the success path). Wrap the DOM/clipboard part in try/finally, or revoke inside finally. Also note that if fetchPreviewFile succeeds but .blob() or link creation fails, the blob URL leaks.

2. 60s revoke delay is arbitrary and fragile

window.setTimeout(..., 60_000) keeps a timer alive for a minute per download. Better:

  • Use requestAnimationFrame / small timeout (e.g., a few hundred ms) β€” once link.click() returns, most browsers have already started the download.
  • Or use the 'download' event / URL.revokeObjectURL in a finally after click. Revoking too early can break Safari/Firefox, so a short delay (~1–5s) is usually enough; 60s Γ— many files accumulates timers.

3. Silent catch swallows errors

catch { downloadByURL(...) } silently hides failures (network error, CORS, 401). Consider logging the error or surfacing it to help diagnosis; the fallback URL may also fail silently.

4. Header forwarding / credentials semantics

  • If the request headers carry auth, falling back to downloadByURL(url, name) will likely fail for protected resources (no headers). Users get a broken download with no feedback.
  • Consider passing credentials: 'include' in the fetch options when relevant, or explicitly documenting the trade-off.

5. fetchFile recreated per call β€” race with abort

fetchFile captures controller.signal at hook setup, which is fine, but:

  • getFileRequestHeaders() is called per fetch, which is good (fresh headers), but if it's expensive, memoize.
  • The AbortController is created unconditionally at setup time; if usePreviewLoader is ever instantiated outside a mounted component context, the abort semantics still work, but confirm onBeforeUnmount actually calls controller.abort() (not shown in the diff β€” verify the removed lines).

6. load signature change is a breaking API change

Changing load(signal) β†’ load(fetchFile) forces every caller to update. All existing call sites must now use the provided fetchFile instead of constructing their own fetch; any caller still doing raw fetch loses abort/header behavior silently. Worth grepping all consumers.

7. Non-null / typing details

  • let objectUrl: string then assigned inside try β€” TS strict mode is fine because assignment happens before use, but declaring const objectUrl = ... inside the try and moving the rest into the try block would be cleaner.
  • Object.keys(headers).length creates an array each call; a for...in check or headers && Object.keys(headers).length > 0 guard against undefined would be safer (the type says required, but runtime callers may pass undefined).

8. name sanitization

link.download = name β€” if name contains /, \, or traversal sequences, some browsers ignore download or sanitize oddly. Sanitize the filename before assigning.

9. Status code in error message

throw new Error(String(response.status)) loses the status text and URL context. Prefer includes like response.statusText and the url for debuggability.

10. Minor: import placement / circular dependency

import { useFileRequestHeaders } from '../../view/index' β€” importing from a barrel index can increase bundle coupling and risks circular imports (view/index ↔ this util). Import from the specific module directly if possible. Also fetchPreviewFile now lives in a file that imports Vue lifecycle hooks and view internals β€” consider separating the pure fetch helper from the composable for testability.

11. usePreviewLoader β€” aborted-but-not-reset edge

On unmount the controller aborts, but loading is never reset to false; if the component is reused/re-keyed rather than destroyed, loading stays true forever. Confirm the component is truly remounted per file (the comment says "ι’ζΏζŒ‰ζ–‡δ»Άεœ°ε€ι‡ε»Ί", so probably OK, but worth a guard).

12. No retry / timeout

Neither fetch has a timeout; a hung request leaves loading=true indefinitely until unmount. Consider AbortSignal.timeout(ms) combined with the external signal.

Comment thread apps/oss/views/file.py
mk_file_auth=get_file_auth(request),
thumbnail=request.query_params.get("variant") == "thumbnail",
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Here's my review of the code:

Potential Issues

  1. request.COOKIES access via get_file_auth β€” In some Django/DRF contexts (e.g., when CSRF_COOKIE_HTTPONLY=False matters or with custom Request subclasses), request.COOKIES is fine, but be aware DRF's Request wraps the underlying HttpRequest. Ensure request.COOKIES resolves correctly (it does via DRF forwarding, but worth verifying your version).

  2. Bearer scheme parsing is loose β€” partition(" ") splits on the first space only. Headers like Bearer token (multiple spaces) will leave leading whitespace in token, which .strip() handles. However headers like Bearer with no token β†’ _separator == "", token == "", falls through correctly. OK, but consider stricter validation.

  3. Case-insensitivity of scheme β€” Handled via .lower(). Good.

  4. Header precedence over cookie β€” Intentional per docstring. But note: if an attacker can set a malformed/empty Authorization header, it falls back to cookie. Acceptable, but document the security implications (header presence alone doesn't block cookie fallback unless token is non-empty).

  5. No logging/observability β€” Consider logging when falling back between auth methods for debugging cross-site iframe issues.

Optimization / Improvements

  1. Type hints β€” Return type should be Optional[str]:

    def get_file_auth(request: Request) -> Optional[str]:
  2. Centralize the cookie name constant β€” The old code used a string literal "mk_file_auth". If other modules reference it, import FILE_AUTH_COOKIE there too (grep the codebase).

  3. Stricter Bearer parsing β€” Optional:

    auth = request.headers.get("Authorization", "")
    if auth.lower().startswith("bearer "):
        return auth[7:].strip() or None
  4. Security consideration β€” Accepting bearer tokens from third-party iframe contexts increases exposure surface (tokens in URLs/logs/referer). Ensure the token TTL is short and scoped to file resources only. Also verify CORS/allowed origins.

  5. Test coverage β€” Add tests for: header-only, cookie-only, both present (header wins), empty bearer, malformed scheme.

  6. Docstring language consistency β€” Code comments are in Chinese while the project may standardize on English; confirm team convention.

Overall the change is reasonable and the logic is sound. Main action items: add return type hint, confirm constant is reused consistently, and add tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant