Skip to content

Commit 67ccfde

Browse files
committed
refact: security issue
1 parent ea0e60e commit 67ccfde

File tree

2 files changed

+27
-18
lines changed

2 files changed

+27
-18
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ dist-back*
88
!build.sh
99
*.spec
1010

11-
env
11+
env
12+
temp

yigesamo/server.py

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
)
2828

2929
LOGGER = logging.getLogger(__name__)
30+
TEMP_FILE_DIR = 'temp'
3031

3132

3233
class Helper:
@@ -37,48 +38,52 @@ def get_random_file_name():
3738
)
3839

3940
@staticmethod
40-
def remove_temp_file(q):
41+
def get_path(file_name):
42+
return os.path.join(TEMP_FILE_DIR, file_name)
43+
44+
@classmethod
45+
def remove_temp_file(cls, q):
4146
"""Remove user content.
4247
"""
48+
path = cls.get_path(file_name=q)
4349
# sleep 30s to let user download file
4450
time.sleep(30)
45-
if os.path.exists(q):
46-
os.remove(q)
47-
LOGGER.info('file {} removed'.format(q))
51+
if os.path.exists(path):
52+
os.remove(path)
53+
LOGGER.info('file {} removed'.format(path))
4854
else:
49-
LOGGER.info('file {} not exists'.format(q))
55+
LOGGER.info('file {} not exists'.format(path))
5056

5157
@classmethod
5258
def make_file_response(cls, text_content):
5359
"""Redirect to file download page.
5460
"""
55-
path = cls.get_random_file_name()
61+
file_name = cls.get_random_file_name()
62+
path = cls.get_path(file_name)
63+
LOGGER.info('path: {}'.format(path))
64+
5665
with open(path, 'wb') as f:
5766
f.write(text_content)
5867

5968
# here convert user post text
6069
try:
6170
converter(path, True)
6271
except Exception as e:
63-
return HTTPException(418, "I'm a teapot.")
72+
raise HTTPException(418, "I'm a teapot.")
6473

6574
return RedirectResponse(
66-
'/result?q={}'.format(path),
75+
'/result?q={}'.format(file_name),
6776
status_code=307
6877
)
6978

7079
@classmethod
7180
def get_file_response(cls, q):
72-
# prevent internal file
73-
if any(
74-
'/' in q,
75-
not q.endswith('ris'),
76-
not os.path.exists(q)
77-
):
78-
return HTTPException(404, 'file not found')
81+
path = cls.get_path(file_name=q)
82+
if not os.path.exists(path):
83+
raise HTTPException(404, 'file not found')
7984

8085
return FileResponse(
81-
path=q,
86+
path=path,
8287
media_type='application/octet-stream',
8388
filename='convert_result_{}.ris'.format(q.split('_')[0])
8489
)
@@ -107,10 +112,13 @@ async def get_result(q, background_tasks: BackgroundTasks):
107112

108113
@app.get('/')
109114
async def health():
110-
return RedirectResponse('/docs')
115+
return RedirectResponse('/converter')
111116

112117

113118
def start_server():
119+
if not os.path.exists(TEMP_FILE_DIR):
120+
os.mkdir(TEMP_FILE_DIR)
121+
114122
LOGGER.info('starting server...')
115123
uvicorn.run(app, host='0.0.0.0', port=5000, log_level='info')
116124

0 commit comments

Comments
 (0)