mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-11-29 08:25:10 +00:00
bepasty: Use privileged decorator for actions
Tests: - Functional tests - Initial setup - Sets the domain to freedombox.local (SITENAME) - Default permissions are set to read - Three passwords with varying permissions are create by default - Current configuration is retrieved properly (default permissions, passwords) - Adding passwords works, they are list as expected - With or without comment - Removing password works - Setting default permissions works - Untested: - Upgrade from version 1 Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org> Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
1 parent
3e2900b48b
commit
212364ba2a
3 files changed
+34
-121
No files matched your search
@@ -1,13 +1,8 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""
|
||||
FreedomBox app for bepasty.
|
||||
"""
|
||||
|
||||
import json
|
||||
"""FreedomBox app for bepasty."""
|
||||
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from plinth import actions
|
||||
from plinth import app as app_module
|
||||
from plinth import frontpage, menu
|
||||
from plinth.modules.apache.components import Uwsgi, Webserver
|
||||
@@ -15,7 +10,7 @@ from plinth.modules.backups.components import BackupRestore
|
||||
from plinth.modules.firewall.components import Firewall
|
||||
from plinth.package import Packages
|
||||
|
||||
from . import manifest
|
||||
from . import manifest, privileged
|
||||
|
||||
_description = [
|
||||
_('bepasty is a web application that allows large files to be uploaded '
|
||||
@@ -97,38 +92,10 @@ class BepastyApp(app_module.App):
|
||||
def setup(self, old_version):
|
||||
"""Install and configure the app."""
|
||||
super().setup(old_version)
|
||||
actions.superuser_run('bepasty',
|
||||
['setup', '--domain-name', 'freedombox.local'])
|
||||
privileged.setup('freedombox.local')
|
||||
self.enable()
|
||||
if old_version == 1 and not get_configuration().get(
|
||||
if old_version == 1 and not privileged.get_configuration().get(
|
||||
'DEFAULT_PERMISSIONS'):
|
||||
# Upgrade to a better default only if user hasn't changed the
|
||||
# value.
|
||||
set_default_permissions('read')
|
||||
|
||||
|
||||
def get_configuration():
|
||||
"""Get a full configuration including passwords and defaults."""
|
||||
output = actions.superuser_run('bepasty', ['get-configuration'])
|
||||
return json.loads(output)
|
||||
|
||||
|
||||
def add_password(permissions, comment=None):
|
||||
"""Generate a password with given permissions."""
|
||||
command = ['add-password', '--permissions'] + permissions
|
||||
if comment:
|
||||
command += ['--comment', comment]
|
||||
|
||||
actions.superuser_run('bepasty', command)
|
||||
|
||||
|
||||
def remove_password(password):
|
||||
"""Remove a password and its permissions."""
|
||||
actions.superuser_run('bepasty', ['remove-password'],
|
||||
input=password.encode())
|
||||
|
||||
|
||||
def set_default_permissions(permissions):
|
||||
"""Set default permissions."""
|
||||
perm = permissions.split()
|
||||
actions.superuser_run('bepasty', ['set-default', '--permissions'] + perm)
|
||||
privileged.set_default(['read'])
|
||||
@@ -0,0 +1,170 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""Configuration helper for bepasty."""
|
||||
|
||||
import collections
|
||||
import grp
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import pwd
|
||||
import secrets
|
||||
import shutil
|
||||
import string
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
|
||||
import augeas
|
||||
|
||||
from plinth import action_utils
|
||||
from plinth.actions import privileged
|
||||
from plinth.modules import bepasty
|
||||
|
||||
DATA_DIR = '/var/lib/bepasty'
|
||||
|
||||
PASSWORD_LENGTH = 20
|
||||
|
||||
CONF_FILE = pathlib.Path('/etc/bepasty-freedombox.conf')
|
||||
|
||||
|
||||
def _augeas_load():
|
||||
"""Initialize Augeas."""
|
||||
aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
|
||||
augeas.Augeas.NO_MODL_AUTOLOAD)
|
||||
aug.set('/augeas/load/Simplevars/lens', 'Simplevars.lns')
|
||||
aug.set('/augeas/load/Simplevars/incl[last() + 1]', str(CONF_FILE))
|
||||
aug.load()
|
||||
return aug
|
||||
|
||||
|
||||
def _key_path(key):
|
||||
"""Return the augeas path for the key."""
|
||||
return '/files' + str(CONF_FILE) + '/' + key
|
||||
|
||||
|
||||
def conf_file_read():
|
||||
"""Read and return the configuration."""
|
||||
aug = _augeas_load()
|
||||
conf = collections.OrderedDict()
|
||||
for path in aug.match(_key_path('*')):
|
||||
key = path.rsplit('/', 1)[-1]
|
||||
if key[0] != '#':
|
||||
conf[key] = json.loads(aug.get(path))
|
||||
|
||||
return conf
|
||||
|
||||
|
||||
def conf_file_write(conf):
|
||||
"""Write configuration to the file."""
|
||||
aug = _augeas_load()
|
||||
for key, value in conf.items():
|
||||
if not key.startswith('#'):
|
||||
value = json.dumps(value)
|
||||
|
||||
aug.set(_key_path(key), value)
|
||||
|
||||
aug.save()
|
||||
|
||||
|
||||
@privileged
|
||||
def setup(domain_name: str):
|
||||
"""Post installation actions for bepasty."""
|
||||
# Create bepasty group if needed.
|
||||
try:
|
||||
grp.getgrnam('bepasty')
|
||||
except KeyError:
|
||||
subprocess.run(['addgroup', '--system', 'bepasty'], check=True)
|
||||
|
||||
# Create bepasty user if needed.
|
||||
try:
|
||||
pwd.getpwnam('bepasty')
|
||||
except KeyError:
|
||||
subprocess.run([
|
||||
'adduser', '--system', '--ingroup', 'bepasty', '--home',
|
||||
'/var/lib/bepasty', '--gecos', 'bepasty file sharing', 'bepasty'
|
||||
], check=True)
|
||||
|
||||
# Create data directory if needed.
|
||||
if not os.path.exists(DATA_DIR):
|
||||
os.makedirs(DATA_DIR, mode=0o750)
|
||||
shutil.chown(DATA_DIR, user='bepasty', group='bepasty')
|
||||
|
||||
# Create configuration file if needed.
|
||||
if not CONF_FILE.is_file():
|
||||
passwords = [_generate_password() for _ in range(3)]
|
||||
conf = {
|
||||
'#comment':
|
||||
'This file is managed by FreedomBox. Only a small subset of '
|
||||
'the original configuration format is supported. Each line '
|
||||
'should be in KEY = VALUE format. VALUE must be a JSON '
|
||||
'encoded string.',
|
||||
'SITENAME': domain_name,
|
||||
'STORAGE_FILESYSTEM_DIRECTORY': '/var/lib/bepasty',
|
||||
'SECRET_KEY': secrets.token_hex(64),
|
||||
'PERMISSIONS': {
|
||||
passwords[0]: 'admin,list,create,read,delete',
|
||||
passwords[1]: 'list,create,read,delete',
|
||||
passwords[2]: 'list,read',
|
||||
},
|
||||
'PERMISSION_COMMENTS': {
|
||||
passwords[0]: 'admin',
|
||||
passwords[1]: 'editor',
|
||||
passwords[2]: 'viewer',
|
||||
},
|
||||
'DEFAULT_PERMISSIONS': 'read',
|
||||
}
|
||||
conf_file_write(conf)
|
||||
CONF_FILE.chmod(0o640)
|
||||
shutil.chown(CONF_FILE, user='bepasty', group='bepasty')
|
||||
|
||||
|
||||
@privileged
|
||||
def get_configuration() -> dict[str, object]:
|
||||
"""Get default permissions, passwords, permissions and comments."""
|
||||
return conf_file_read()
|
||||
|
||||
|
||||
@privileged
|
||||
def add_password(permissions: list[str], comment: Optional[str] = None):
|
||||
"""Generate a password with given permissions."""
|
||||
conf = conf_file_read()
|
||||
permissions = _format_permissions(permissions)
|
||||
password = _generate_password()
|
||||
conf['PERMISSIONS'][password] = permissions
|
||||
if comment:
|
||||
conf['PERMISSION_COMMENTS'][password] = comment
|
||||
|
||||
conf_file_write(conf)
|
||||
action_utils.service_try_restart('uwsgi')
|
||||
|
||||
|
||||
@privileged
|
||||
def remove_password(password: str):
|
||||
"""Remove a password and its permissions."""
|
||||
conf = conf_file_read()
|
||||
if password in conf['PERMISSIONS']:
|
||||
del conf['PERMISSIONS'][password]
|
||||
|
||||
if password in conf['PERMISSION_COMMENTS']:
|
||||
del conf['PERMISSION_COMMENTS'][password]
|
||||
conf_file_write(conf)
|
||||
action_utils.service_try_restart('uwsgi')
|
||||
|
||||
|
||||
@privileged
|
||||
def set_default(permissions: list[str]):
|
||||
"""Set default permissions."""
|
||||
conf = {'DEFAULT_PERMISSIONS': _format_permissions(permissions)}
|
||||
conf_file_write(conf)
|
||||
action_utils.service_try_restart('uwsgi')
|
||||
|
||||
|
||||
def _format_permissions(permissions=None):
|
||||
"""Format permissions as comma-separated."""
|
||||
return ','.join(set(bepasty.PERMISSIONS.keys()).intersection(
|
||||
permissions)) if permissions else ''
|
||||
|
||||
|
||||
def _generate_password():
|
||||
"""Generate a random password."""
|
||||
alphabet = string.ascii_letters + string.digits
|
||||
return ''.join(secrets.choice(alphabet) for _ in range(PASSWORD_LENGTH))
|
||||
@@ -1,7 +1,5 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""
|
||||
Views for the bepasty app.
|
||||
"""
|
||||
"""Views for the bepasty app."""
|
||||
|
||||
from django.contrib import messages
|
||||
from django.contrib.messages.views import SuccessMessageMixin
|
||||
@@ -11,10 +9,9 @@ from django.utils.translation import gettext_lazy as _
|
||||
from django.views.decorators.http import require_POST
|
||||
from django.views.generic import FormView
|
||||
|
||||
from plinth.errors import ActionError
|
||||
from plinth.modules import bepasty
|
||||
from plinth.views import AppView
|
||||
|
||||
from . import privileged
|
||||
from .forms import AddPasswordForm, SetDefaultPermissionsForm
|
||||
|
||||
# i18n for permission comments
|
||||
@@ -27,6 +24,7 @@ PERMISSION_COMMENTS_STRINGS = {
|
||||
|
||||
class BepastyView(AppView):
|
||||
"""Serve configuration page."""
|
||||
|
||||
app_id = 'bepasty'
|
||||
form_class = SetDefaultPermissionsForm
|
||||
template_name = 'bepasty.html'
|
||||
@@ -39,7 +37,7 @@ class BepastyView(AppView):
|
||||
def _get_configuration(self):
|
||||
"""Return the current configuration."""
|
||||
if not self.conf:
|
||||
self.conf = bepasty.get_configuration()
|
||||
self.conf = privileged.get_configuration()
|
||||
|
||||
return self.conf
|
||||
|
||||
@@ -85,10 +83,10 @@ class BepastyView(AppView):
|
||||
|
||||
if old_data['default_permissions'] != form_data['default_permissions']:
|
||||
try:
|
||||
bepasty.set_default_permissions(
|
||||
form_data['default_permissions'])
|
||||
privileged.set_default(
|
||||
form_data['default_permissions'].split(' '))
|
||||
messages.success(self.request, _('Configuration updated.'))
|
||||
except ActionError:
|
||||
except Exception:
|
||||
messages.error(self.request,
|
||||
_('An error occurred during configuration.'))
|
||||
|
||||
@@ -112,17 +110,14 @@ class AddPasswordView(SuccessMessageMixin, FormView):
|
||||
|
||||
def form_valid(self, form):
|
||||
"""Add the password on valid form submission."""
|
||||
_add_password(form.cleaned_data)
|
||||
form_data = form.cleaned_data
|
||||
privileged.add_password(form_data['permissions'], form_data['comment'])
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
def _add_password(form_data):
|
||||
bepasty.add_password(form_data['permissions'], form_data['comment'])
|
||||
|
||||
|
||||
@require_POST
|
||||
def remove(request, password):
|
||||
"""View to remove a password."""
|
||||
bepasty.remove_password(password)
|
||||
privileged.remove_password(password)
|
||||
messages.success(request, _('Password deleted.'))
|
||||
return redirect(reverse_lazy('bepasty:index'))
|
||||
Reference in new issue
Block a user