Repository navigation
fix: File preview cannot be previewed in embedded mode #8305
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| from unittest.mock import patch | ||
|
|
||
| from django.http import HttpResponse | ||
| from django.test import SimpleTestCase | ||
| from rest_framework.test import APIRequestFactory | ||
|
|
||
| from oss.views import FileRetrievalView | ||
| from oss.views.file import FILE_AUTH_COOKIE | ||
|
|
||
|
|
||
| class FileRetrievalAuthTestCase(SimpleTestCase): | ||
| """文件读取接口的凭证来源:请求头优先,cookie 兜底。""" | ||
|
|
||
| def setUp(self): | ||
| self.factory = APIRequestFactory() | ||
|
|
||
| def retrieve(self, request): | ||
| with patch("oss.views.file.FileSerializer.Operate") as operate: | ||
| operate.return_value.get.return_value = HttpResponse() | ||
| FileRetrievalView.as_view()(request, file_id="file-id") | ||
| return operate.return_value.get.call_args.kwargs["mk_file_auth"] | ||
|
|
||
| def test_bearer_header_is_used_when_cookie_is_missing(self): | ||
| request = self.factory.get("/chat/oss/file/file-id", HTTP_AUTHORIZATION="Bearer header-token") | ||
|
|
||
| self.assertEqual(self.retrieve(request), "header-token") | ||
|
|
||
| def test_bearer_header_takes_precedence_over_cookie(self): | ||
| self.factory.cookies[FILE_AUTH_COOKIE] = "cookie-token" | ||
| request = self.factory.get("/chat/oss/file/file-id", HTTP_AUTHORIZATION="bearer header-token") | ||
|
|
||
| self.assertEqual(self.retrieve(request), "header-token") | ||
|
|
||
| def test_cookie_is_used_without_bearer_header(self): | ||
| self.factory.cookies[FILE_AUTH_COOKIE] = "cookie-token" | ||
| request = self.factory.get("/chat/oss/file/file-id") | ||
|
|
||
| self.assertEqual(self.retrieve(request), "cookie-token") | ||
|
|
||
| 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") | ||
|
|
||
| def test_missing_credentials_pass_none(self): | ||
| request = self.factory.get("/chat/oss/file/file-id") | ||
|
|
||
| self.assertIsNone(self.retrieve(request)) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -21,6 +21,20 @@ | |
| from oss.serializers.file import FileSerializer, get_url_content | ||
|
|
||
|
|
||
| FILE_AUTH_COOKIE = "mk_file_auth" | ||
|
|
||
|
|
||
| def get_file_auth(request: Request): | ||
| """ | ||
| 读取文件凭证:优先使用 Authorization 请求头中的 Bearer token,没有时使用 cookie。 | ||
| 对话页以 iframe 嵌入第三方页面时,浏览器可能不发送跨站 cookie,前端改用请求头携带同一个 token。 | ||
| """ | ||
| scheme, _separator, token = request.headers.get("Authorization", "").partition(" ") | ||
| if scheme.lower() == "bearer" and token.strip(): | ||
| return token.strip() | ||
| return request.COOKIES.get(FILE_AUTH_COOKIE) | ||
|
|
||
|
|
||
| class FileRetrievalView(APIView): | ||
| @extend_schema( | ||
| methods=["GET"], | ||
|
|
@@ -41,7 +55,7 @@ def get(self, request: Request, file_id: str): | |
| "http_range": request.headers.get("Range", ""), | ||
| } | ||
| ).get( | ||
| mk_file_auth=request.COOKIES.get("mk_file_auth"), | ||
| mk_file_auth=get_file_auth(request), | ||
| thumbnail=request.query_params.get("variant") == "thumbnail", | ||
| ) | ||
|
|
||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here's my review of the code: Potential Issues
Optimization / Improvements
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. |
||
|
|
||
There was a problem hiding this comment.
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
Broken
subTestargument (Bug)[API_KEY]is undefined andauthorizationshould be bound to the loop variable. This will raiseNameError. It should be:Shared
cookiesmutated across tests viaself.factoryself.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 couplingThe 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_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
HttpResponseusagePatching the whole
Operateclass 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 test
Bearerandbearer, 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 uses
startswith("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.FILE_AUTH_COOKIEimported fromoss.views.filebut view imported viaoss.views— mixing import paths; pick one for consistency.Minimal fix for the blocking bug
The
subTest(authorization=[API_KEY])line is the only outright defect; the rest are robustness/maintainability improvements.