Repository navigation
fix: File preview cannot be previewed in embedded mode - #8305
Conversation
| def test_missing_credentials_pass_none(self): | ||
| request = self.factory.get("/chat/oss/file/file-id") | ||
|
|
||
| self.assertIsNone(self.retrieve(request)) |
There was a problem hiding this comment.
Here are the issues and suggestions I found:
Potential issues
-
Broken
subTestargument (Bug)with self.subTest(authorization=[API_KEY]):
[API_KEY]is undefined andauthorizationshould be bound to the loop variable. This will raiseNameError. It should be:with self.subTest(authorization=authorization):
-
Shared
cookiesmutated across tests viaself.factory
self.factory.cookies[...] = ...mutates state on the factory instance. SincesetUpcreates a freshAPIRequestFactoryper test this is currently safe, but it's fragile β reading viarequest.COOKIESsemantics (factory.cookiesvs request cookie passing) can be confusing. Consider usingself.factory.get(..., cookies={...})or DRF'sclientfor clarity. -
patchtarget coupling
The test asserts onoperate.return_value.get.call_args.kwargs["mk_file_auth"]. If the view calls.get()multiple times or positional args change,call_argswill be wrong (it captures only the last call). Preferassert_called_once_with(...)on the expected call for robustness. -
Mock return type doesn't reflect
HttpResponseusage
Patching the wholeOperateclass and returning anHttpResponsefrom 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 aFileResponse). -
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 patchedHttpResponsewould catch regressions where the view errors before calling the serializer.
Test quality suggestions
-
Coverage gap on whitespace / casing of header
You testBearerandbearer, but not values like"Bearer token"(multiple spaces) or a token containing spaces. Add explicit cases reflecting the actual parsing logic. -
Explicitly document/intend prefix matching
If the code usesstartswith("bearer ")(case-insensitive), test mixed case (bEaReR) explicitly for clarity and intent. -
Missing "empty Bearer falls back to cookie even without cookie β None" symmetry β minor, optional.
Style/nits
retrievehelper name shadows Django'sretrievesemantics β consider_extract_mk_file_authfor readability.- Docstring in Chinese while answers/filenames are English β fine per project convention, just noting consistency.
FILE_AUTH_COOKIEimported fromoss.views.filebut view imported viaoss.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.
| const result = await load(fetchFile) | ||
| if (!controller.signal.aborted) data.value = result | ||
| } catch { | ||
| if (!controller.signal.aborted) error.value = t('chat.filePreview.loadFailedMessage') |
There was a problem hiding this comment.
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) β oncelink.click()returns, most browsers have already started the download. - Or use the
'download'event /URL.revokeObjectURLin afinallyafter 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
AbortControlleris created unconditionally at setup time; ifusePreviewLoaderis ever instantiated outside a mounted component context, the abort semantics still work, but confirmonBeforeUnmountactually callscontroller.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: stringthen assigned insidetryβ TS strict mode is fine because assignment happens before use, but declaringconst objectUrl = ...inside the try and moving the rest into the try block would be cleaner.Object.keys(headers).lengthcreates an array each call; afor...incheck orheaders && Object.keys(headers).length > 0guard againstundefinedwould 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.
| mk_file_auth=get_file_auth(request), | ||
| thumbnail=request.query_params.get("variant") == "thumbnail", | ||
| ) | ||
|
|
There was a problem hiding this comment.
Here's my review of the code:
Potential Issues
-
request.COOKIESaccess viaget_file_authβ In some Django/DRF contexts (e.g., whenCSRF_COOKIE_HTTPONLY=Falsematters or with custom Request subclasses),request.COOKIESis fine, but be aware DRF'sRequestwraps the underlyingHttpRequest. Ensurerequest.COOKIESresolves correctly (it does via DRF forwarding, but worth verifying your version). -
Bearer scheme parsing is loose β
partition(" ")splits on the first space only. Headers likeBearer token(multiple spaces) will leave leading whitespace intoken, which.strip()handles. However headers likeBearerwith no token β_separator == "",token == "", falls through correctly. OK, but consider stricter validation. -
Case-insensitivity of scheme β Handled via
.lower(). Good. -
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).
-
No logging/observability β Consider logging when falling back between auth methods for debugging cross-site iframe issues.
Optimization / Improvements
-
Type hints β Return type should be
Optional[str]:def get_file_auth(request: Request) -> Optional[str]:
-
Centralize the cookie name constant β The old code used a string literal
"mk_file_auth". If other modules reference it, importFILE_AUTH_COOKIEthere too (grep the codebase). -
Stricter Bearer parsing β Optional:
auth = request.headers.get("Authorization", "") if auth.lower().startswith("bearer "): return auth[7:].strip() or None
-
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.
-
Test coverage β Add tests for: header-only, cookie-only, both present (header wins), empty bearer, malformed scheme.
-
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.
fix: File preview cannot be previewed in embedded mode