Skip to content

Commit a9d962c

Browse files
committed
feat: implement RestrictedUnpickler for secure deserialization and enhance import functionality
1 parent cc0e431 commit a9d962c

File tree

1 file changed

+36
-20
lines changed

1 file changed

+36
-20
lines changed

apps/tools/serializers/tool.py

+36-20
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# -*- coding: utf-8 -*-
2+
import io
23
import json
34
import pickle
45
import re
@@ -26,6 +27,22 @@ def __init__(self, tool: dict, version: str):
2627
self.version = version
2728

2829

30+
ALLOWED_CLASSES = {
31+
("builtins", "dict"),
32+
('uuid', 'UUID'),
33+
("tools.serializers.tool", "ToolInstance")
34+
}
35+
36+
37+
class RestrictedUnpickler(pickle.Unpickler):
38+
39+
def find_class(self, module, name):
40+
if (module, name) in ALLOWED_CLASSES:
41+
return super().find_class(module, name)
42+
raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
43+
(module, name))
44+
45+
2946
def encryption(message: str):
3047
"""
3148
加密敏感字段数据 加密方式是 如果密码是 1234567890 那么给前端则是 123******890
@@ -258,26 +275,25 @@ class Import(serializers.Serializer):
258275
def import_(self):
259276
self.is_valid()
260277

261-
# user_id = self.data.get('user_id')
262-
# flib_instance_bytes = self.data.get('file').read()
263-
# try:
264-
# RestrictedUnpickler(io.BytesIO(s)).load()
265-
# flib_instance = restricted_loads(flib_instance_bytes)
266-
# except Exception as e:
267-
# raise AppApiException(1001, _("Unsupported file format"))
268-
# tool = flib_instance.tool
269-
# tool_model = Tool(
270-
# id=uuid.uuid7(),
271-
# name=tool.get('name'),
272-
# desc=tool.get('desc'),
273-
# code=tool.get('code'),
274-
# user_id=user_id,
275-
# input_field_list=tool.get('input_field_list'),
276-
# init_field_list=tool.get('init_field_list', []),
277-
# scope=ToolScope.WORKSPACE,
278-
# is_active=False
279-
# )
280-
# tool_model.save()
278+
user_id = self.data.get('user_id')
279+
tool_instance_bytes = self.data.get('file').read()
280+
try:
281+
tool_instance = RestrictedUnpickler(io.BytesIO(tool_instance_bytes)).load()
282+
except Exception as e:
283+
raise AppApiException(1001, _("Unsupported file format"))
284+
tool = tool_instance.tool
285+
tool_model = Tool(
286+
id=uuid.uuid7(),
287+
name=tool.get('name'),
288+
desc=tool.get('desc'),
289+
code=tool.get('code'),
290+
user_id=user_id,
291+
input_field_list=tool.get('input_field_list'),
292+
init_field_list=tool.get('init_field_list', []),
293+
scope=ToolScope.WORKSPACE,
294+
is_active=False
295+
)
296+
tool_model.save()
281297
return True
282298

283299

0 commit comments

Comments
 (0)