Harden media token decoding
这个提交存在于:
父节点
d61dbfd3a4
当前提交
819b1d23c1
共有 2 个文件被更改,包括 25 次插入 和 2 次删除
|
|
@ -3,6 +3,7 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
|
import binascii
|
||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import json
|
import json
|
||||||
|
|
@ -83,10 +84,16 @@ class MediaProxy:
|
||||||
payload_part.encode("ascii"),
|
payload_part.encode("ascii"),
|
||||||
hashlib.sha256,
|
hashlib.sha256,
|
||||||
).digest()
|
).digest()
|
||||||
actual = _b64decode(signature_part)
|
actual = _safe_b64decode(signature_part)
|
||||||
if not hmac.compare_digest(expected, actual):
|
if not hmac.compare_digest(expected, actual):
|
||||||
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token signature")
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token signature")
|
||||||
return json.loads(_b64decode(payload_part).decode("utf-8"))
|
try:
|
||||||
|
payload = json.loads(_safe_b64decode(payload_part).decode("utf-8"))
|
||||||
|
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
|
||||||
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token payload") from exc
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token payload")
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
def _guess_content_type(path: Path) -> str:
|
def _guess_content_type(path: Path) -> str:
|
||||||
|
|
@ -100,3 +107,10 @@ def _b64encode(value: bytes) -> str:
|
||||||
def _b64decode(value: str) -> bytes:
|
def _b64decode(value: str) -> bytes:
|
||||||
padding = "=" * (-len(value) % 4)
|
padding = "=" * (-len(value) % 4)
|
||||||
return base64.urlsafe_b64decode(value + padding)
|
return base64.urlsafe_b64decode(value + padding)
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_b64decode(value: str) -> bytes:
|
||||||
|
try:
|
||||||
|
return _b64decode(value)
|
||||||
|
except (binascii.Error, ValueError) as exc:
|
||||||
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token encoding") from exc
|
||||||
|
|
|
||||||
|
|
@ -633,6 +633,15 @@ database:
|
||||||
self.assertEqual(fetched["data"]["size_bytes"], 5)
|
self.assertEqual(fetched["data"]["size_bytes"], 5)
|
||||||
self.assertNotIn(str(self.root), str(fetched["data"]))
|
self.assertNotIn(str(self.root), str(fetched["data"]))
|
||||||
|
|
||||||
|
bad_token = fetch_media(
|
||||||
|
RequestContext(),
|
||||||
|
{"token": "bad.token"},
|
||||||
|
self.media_service,
|
||||||
|
)
|
||||||
|
self.assertFalse(bad_token["ok"])
|
||||||
|
self.assertEqual(bad_token["error_code"], "FORBIDDEN")
|
||||||
|
self.assertNotIn(str(self.root), str(bad_token))
|
||||||
|
|
||||||
planned = migrate_storage(
|
planned = migrate_storage(
|
||||||
self.ctx,
|
self.ctx,
|
||||||
{
|
{
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用