Skip to content
This repository has been archived by the owner on Nov 29, 2021. It is now read-only.

Commit

Permalink
Create the file with permission only for the owner.
Browse files Browse the repository at this point in the history
Add test.
  • Loading branch information
jjnicola committed May 29, 2020
1 parent db078a4 commit d232623
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
23 changes: 22 additions & 1 deletion ospd/datapickler.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import logging
import pickle
import os

from hashlib import sha256
from pathlib import Path
Expand All @@ -29,10 +30,26 @@

logger = logging.getLogger(__name__)

OWNER_ONLY_RW_PERMISSION = 0o600


class DataPickler:
def __init__(self, storage_path):
self._storage_path = storage_path
self._storage_fd = None

def _fd_opener(self, path, flags):
os.umask(0)
flags = os.O_CREAT | os.O_WRONLY
self._storage_fd = os.open(path, flags, mode=OWNER_ONLY_RW_PERMISSION)
return self._storage_fd

def _fd_close(self):
try:
self._storage_fd.close()
self._storage_fd = None
except Exception: # pylint: disable=broad-except
pass

def remove_file(self, filename):
""" Remove the file containing a scan_info pickled object """
Expand Down Expand Up @@ -65,13 +82,17 @@ def store_data(self, filename: str, data_object: Dict) -> str:
)

try:
with storage_file_path.open('wb') as scan_info_f:
with open(
storage_file_path, 'wb', opener=self._fd_opener
) as scan_info_f:
scan_info_f.write(pickled_data)
except Exception as e: # pylint: disable=broad-except
self._fd_close()
raise OspdCommandError(
'Not possible to store scan info for %s. %s' % (filename, e),
'start_scan',
)
self._fd_close()

return self._pickled_data_hash_generator(pickled_data)

Expand Down
15 changes: 15 additions & 0 deletions tests/test_datapickler.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,21 @@ def test_store_data_failed(self):
OspdCommandError, data_pickler.store_data, filename, data
)

def test_store_data_check_permission(self):
OWNER_ONLY_RW_PERMISSION = '0o100600'
data = {'foo', 'bar'}
filename = 'scan_info_1'

data_pickler = DataPickler('/tmp')
data_pickler.store_data(filename, data)

file_path = Path(data_pickler._storage_path) / filename
self.assertEqual(
oct(file_path.stat().st_mode), OWNER_ONLY_RW_PERMISSION
)

data_pickler.remove_file(filename)

def test_load_data(self):

data_pickler = DataPickler('/tmp')
Expand Down

0 comments on commit d232623

Please sign in to comment.