签入版本
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
"""utils/file.py 魔数校验:读取异常必须 fail-closed 拒绝上传,不得放行伪装文件。"""
|
||||
import io
|
||||
|
||||
from utils.file import verify_file_magic
|
||||
|
||||
|
||||
class _BrokenStream:
|
||||
"""模拟文件流读取失败(seek/read 抛异常)。"""
|
||||
|
||||
def read(self, n):
|
||||
raise OSError('模拟读取失败')
|
||||
|
||||
def seek(self, n):
|
||||
raise OSError('模拟 seek 失败')
|
||||
|
||||
|
||||
def test_verify_file_magic_fail_closed_on_read_error():
|
||||
is_valid, msg = verify_file_magic(_BrokenStream(), '.jpg')
|
||||
assert is_valid is False
|
||||
assert '校验异常' in msg
|
||||
|
||||
|
||||
def test_verify_file_magic_accepts_valid_magic():
|
||||
png_header = b'\x89PNG\r\n\x1a\n' + b'filler' * 10
|
||||
is_valid, msg = verify_file_magic(io.BytesIO(png_header), '.png')
|
||||
assert is_valid is True
|
||||
assert msg == ''
|
||||
|
||||
|
||||
def test_verify_file_magic_rejects_mismatched_content():
|
||||
# 内容与扩展名不符(JPEG 头冒充 .png)→ 拒绝
|
||||
jpeg_bytes = b'\xff\xd8\xff\xe0' + b'filler' * 10
|
||||
is_valid, msg = verify_file_magic(io.BytesIO(jpeg_bytes), '.png')
|
||||
assert is_valid is False
|
||||
assert '不匹配' in msg
|
||||
|
||||
|
||||
def test_verify_file_magic_txt_accepts_text_content():
|
||||
# 文本无固定二进制签名,可读文本(含空文件)放行
|
||||
for content in (b'hello world', b'', '你好,世界'.encode('utf-8')):
|
||||
is_valid, msg = verify_file_magic(io.BytesIO(content), '.txt')
|
||||
assert is_valid is True, content
|
||||
assert msg == ''
|
||||
|
||||
|
||||
def test_verify_file_magic_txt_rejects_binary_content():
|
||||
# 二进制内容伪装成 .txt(含 NUL 字节)→ 拒绝,防伪装文件绕过
|
||||
binary = b'\x00\x00\x00\xff' + b'filler' * 10
|
||||
is_valid, msg = verify_file_magic(io.BytesIO(binary), '.txt')
|
||||
assert is_valid is False
|
||||
assert '不匹配' in msg
|
||||
Reference in New Issue
Block a user