deluge: Don't use code execution for editing configuration

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: Veiko Aasa <veiko17@disroot.org>
This commit is contained in:
Sunil Mohan Adapa authored and Veiko Aasa committed 2020-02-21 12:41:24 +02:00
1 parent 5c17c8c31e
commit 10d66d76ce
3 files changed
+160 -44

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Tests for utilities that edit Deluge configuration files.
"""
import pytest
from plinth.modules.deluge.utils import Config
test_content = '''{
"file": 3,
"format": 1
}{
"hosts": [
[
"c582deb3aeac48e5ba6f629ec363ea68",
"127.0.0.1",
58846,
"localclient",
"aa1d33728187a2c2516e7363d6e8fd9178abb6aa"
]
]
}'''
@pytest.fixture(name='deluge_config')
def fixture_deluge_config(tmp_path):
"""Fixture to provide a test deluge configuration file."""
path = tmp_path / 'deluge_config'
path.write_text(test_content)
yield path
def test_initialization(tmp_path):
"""Test object initialization."""
test_file = tmp_path / 'test_file'
config = Config(str(test_file))
assert config.file_name == str(test_file)
assert config.file == test_file
assert config._version is None
assert config.content is None
assert config._original_content is None
def test_load(deluge_config):
"""Test loading the configuration file."""
with Config(str(deluge_config)) as config:
assert config._version['file'] == 3
assert config._version['format'] == 1
assert config.content['hosts'][0][1] == '127.0.0.1'
def test_save(deluge_config):
"""Test save the configuration file."""
with Config(str(deluge_config)) as config:
pass
assert deluge_config.read_text() == test_content
with Config(str(deluge_config)) as config:
config.content['hosts'][0][1] = '0.0.0.0'
assert deluge_config.read_text() == test_content.replace(
'127.0.0.1', '0.0.0.0')
with Config(str(deluge_config)) as config:
assert config.content['hosts'][0][1] == '0.0.0.0'
assert deluge_config.stat().st_mode & 0o777 == 0o600
+74
View File
@@ -0,0 +1,74 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Utilities for editing configuration files of Deluge.
"""
import copy
import json
import os
import pathlib
import re
import shutil
import tempfile
_JSON_FORMAT = {'indent': 4, 'sort_keys': True, 'ensure_ascii': False}
class Config:
"""Read or edit a Deluge configuration file."""
def __init__(self, file_name):
"""Initialize the configuration object."""
self.file_name = file_name
self.file = pathlib.Path(self.file_name)
self._version = None
self.content = None
self._original_content = None
def load(self):
"""Parse the configuration file into memory."""
text = self.file.read_text()
matches = re.match(r'^({[^}]*})(.*)$', text, re.DOTALL)
if not matches:
raise Exception('Unexpected file format.')
try:
self._version = json.loads(matches.group(1))
self.content = json.loads(matches.group(2))
except json.decoder.JSONDecoderError:
raise Exception('Unable to parse JSON in file.')
if self._version['format'] != 1:
raise Exception('Version of the config file not understood')
self._original_content = copy.deepcopy(self.content)
def save(self):
"""Atomically save the modified configuration to file."""
if self.content == self._original_content:
return
with tempfile.NamedTemporaryFile(dir=self.file.parent,
delete=False) as new_file:
new_file.write(json.dumps(self._version, **_JSON_FORMAT).encode())
new_file.write(json.dumps(self.content, **_JSON_FORMAT).encode())
new_file.flush()
os.fsync(new_file.fileno())
new_file_path = pathlib.Path(new_file.name)
new_file_path.chmod(0o600)
try:
shutil.chown(str(new_file_path), 'debian-deluged',
'debian-deluged')
except (PermissionError, LookupError):
pass # Not running as root, or deluge is not installed
new_file_path.rename(self.file)
def __enter__(self):
"""Enter the context."""
self.load()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context."""
self.save()