users: Add component for managing users and groups

- Handle groups needed by an app.
- Handle reserved usernames for an app.
- Updated documentation
- Updated unit tests

Tests performed:
  - Reserved usernames: ez-ipupd, ejabberd, Debian-minetest, mldonkey,
    monkeysphere, mumble-server, privoxy, quasselcore, radicale, debian-tor,
    debian-transmission
  - Reserved usernames checks should work in the following forms:
    - Create user
    - Update user
    - First boot user creation
  - Full list of available groups should appear in following cases:
    - Create user form
    - Update user form
  - Full list of groups should get created in Django DB during:
    - Update user form display
    - First boot form save
  - When updating the last admin user, the 'admin' group choice is checked
    and disabled.
  - Following groups show up (sorted by group name):
    - bit-torrent: Download files using BitTorrent applications
    - git-access: Read-write access to Git repositories
    - i2p: Manage I2P application
    - wiki: View and edit wiki applications
    - minidlna: Media streaming server
    - ed2k: Download files using eDonkey applications
    - freedombox-share: Access to the private shares
    - web-search: Search the web
    - syncthing: Administer Syncthing application
    - feed-reader: Read and subscribe to news feeds
    - admin: Access to all services and system settings
  - Directory validation form checks for write permissions for following apps:
    - deluge with debian-deluged user
    - transmission with debian-transmission user
  - Sharing app should show all the groups in add/edit share forms
  - The following apps should get added to share group during setup:
    debian-transmission
    debian-deluged
  - Unit tests pass
  - Functional tests for users and groups pass
  - Test that an app (example syncthing) provides the necessary
    permissions to users in that group (but not in admin group).

Signed-off-by: Joseph Nuthalapati <njoseph@riseup.net>
[sunil: Fix i18n of group descriptions]
[sunil: Update developer documentation]
[sunil: Separate out cosmetic changes]
[sunil: Fix component ID for mumble]
[sunil: sharing: Remove unneeded dependency on users app]
[sunil: Implement better API for getting groups in component]
[sunil: Fix incorrect regression change ttrss app]
[sunil: Make iterating over gourps more readable]
[sunil: Improve tests, drop single use fixtures]
[sunil: Simplify test_view.py fixture]
Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Tested-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Joseph Nuthalapati authored and James Valleroy committed 2020-04-04 09:31:35 -04:00
1 parent e6e67f7d53
commit e04ae48637
30 files changed
+344 -166

No files matched your search

+8 -7
View File
@@ -14,6 +14,8 @@ from plinth import cfg, menu
from plinth.daemon import Daemon
from plinth.utils import format_lazy
from .components import UsersAndGroups
version = 3
is_essential = True
@@ -45,9 +47,6 @@ _description = [
box_name=_(cfg.box_name))
]
# All FreedomBox user groups
groups = dict()
app = None
@@ -75,6 +74,12 @@ class UsersApp(app_module.App):
listen_ports=[(389, 'tcp4'), (389, 'tcp6')])
self.add(daemon)
# Add the admin group
groups = {'admin': _('Access to all services and system settings')}
users_and_groups = UsersAndGroups('users-and-groups-admin',
groups=groups)
self.add(users_and_groups)
def diagnose(self):
"""Run diagnostics and return the results."""
results = super().diagnose()
@@ -129,10 +134,6 @@ def remove_group(group):
actions.superuser_run('users', options=['remove-group', group])
def register_group(group):
groups[group[0]] = group[1]
def get_last_admin_user():
"""If there is only one admin user return its name else return None."""
output = actions.superuser_run('users', ['get-group-users', 'admin'])
+56
View File
@@ -0,0 +1,56 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
App component to manage users and groups.
"""
import itertools
from plinth import app
class UsersAndGroups(app.FollowerComponent):
"""Component to manage users and groups of an app."""
# Class variable to hold a list of user groups for apps
_all_components = set()
def __init__(self, component_id, reserved_usernames=[], groups={}):
"""Store reserved_usernames and groups of the app.
'reserved_usernames' is a list of operating system user names that the
app uses. It is not permitted to create a FreedomBox user with one of
these names.
'groups' is a dictionary of the following format: {"group_name": "A
localized string describing what permissions are offered to the users
of this group"}.
"""
super().__init__(component_id)
self.reserved_usernames = reserved_usernames
self.groups = groups
self._all_components.add(self)
@classmethod
def get_groups(cls):
"""Return a set of all groups."""
all_groups = itertools.chain(*(component.groups.keys()
for component in cls._all_components))
return set(all_groups)
@classmethod
def get_group_choices(cls):
"""Return list of groups that can be used as form choices."""
all_groups = itertools.chain(*(component.groups.items()
for component in cls._all_components))
choices = [(group, f'{description} ({group})')
for group, description in set(all_groups)]
return sorted(choices, key=lambda g: g[0])
@classmethod
def is_username_reserved(cls, username):
"""Returns whether the given username is reserved or not."""
return any((username in component.reserved_usernames
for component in cls._all_components))
+16 -28
View File
@@ -3,7 +3,6 @@
import pwd
import re
import plinth.forms
from django import forms
from django.contrib import auth, messages
from django.contrib.auth.forms import SetPasswordForm, UserCreationForm
@@ -13,23 +12,17 @@ from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
from plinth import actions, module_loader
import plinth.forms
from plinth import actions
from plinth.errors import ActionError
from plinth.modules import first_boot, users
from plinth.modules import first_boot
from plinth.modules.security import set_restricted_access
from plinth.translation import set_language
from plinth.utils import is_user_admin
from . import get_last_admin_user
def get_group_choices():
"""Return localized group description and group name in one string."""
admin_group = ('admin', _('Access to all services and system settings'))
users.register_group(admin_group)
choices = [(k, ('{} ({})'.format(users.groups[k], k)))
for k in users.groups]
return sorted(choices, key=lambda g: g[0])
from .components import UsersAndGroups
class ValidNewUsernameCheckMixin(object):
@@ -40,8 +33,8 @@ class ValidNewUsernameCheckMixin(object):
username = self.cleaned_data['username']
if self.instance.username != username and \
not self.is_valid_new_username():
raise ValidationError(
_('Username is taken or is reserved.'), code='invalid')
raise ValidationError(_('Username is taken or is reserved.'),
code='invalid')
return username
@@ -52,10 +45,8 @@ class ValidNewUsernameCheckMixin(object):
if username.lower() in existing_users:
return False
for module_name, module in module_loader.loaded_modules.items():
for reserved_username in getattr(module, 'reserved_usernames', []):
if username.lower() == reserved_username.lower():
return False
if UsersAndGroups.is_username_reserved(username.lower()):
return False
return True
@@ -88,10 +79,9 @@ class CreateUserForm(ValidNewUsernameCheckMixin,
"""
username = USERNAME_FIELD
groups = forms.MultipleChoiceField(
choices=get_group_choices(), label=ugettext_lazy('Permissions'),
required=False, widget=forms.CheckboxSelectMultiple,
help_text=ugettext_lazy(
'Select which services should be available to the new '
choices=UsersAndGroups.get_group_choices,
label=ugettext_lazy('Permissions'), required=False,
widget=forms.CheckboxSelectMultiple, help_text=ugettext_lazy(
'user. The user will be able to log in to services that '
'support single sign-on through LDAP, if they are in the '
'appropriate group.<br /><br />Users in the admin group '
@@ -109,7 +99,6 @@ class CreateUserForm(ValidNewUsernameCheckMixin,
"""Initialize the form with extra request argument."""
self.request = request
super(CreateUserForm, self).__init__(*args, **kwargs)
self.fields['groups'].choices = get_group_choices()
self.fields['username'].widget.attrs.update({
'autofocus': 'autofocus',
'autocapitalize': 'none',
@@ -175,7 +164,7 @@ class UserUpdateForm(ValidNewUsernameCheckMixin,
def __init__(self, request, username, *args, **kwargs):
"""Initialize the form with extra request argument."""
group_choices = dict(get_group_choices())
group_choices = dict(UsersAndGroups.get_group_choices())
for group in group_choices:
Group.objects.get_or_create(name=group)
@@ -313,9 +302,8 @@ class UserChangePasswordForm(SetPasswordForm):
"""Initialize the form with extra request argument."""
self.request = request
super(UserChangePasswordForm, self).__init__(*args, **kwargs)
self.fields['new_password1'].widget.attrs.update({
'autofocus': 'autofocus'
})
self.fields['new_password1'].widget.attrs.update(
{'autofocus': 'autofocus'})
def save(self, commit=True):
"""Save the user model and change LDAP password as well."""
@@ -366,7 +354,7 @@ class FirstBootForm(ValidNewUsernameCheckMixin, auth.forms.UserCreationForm):
_('Failed to add new user to admin group.'))
# Create initial Django groups
for group_choice in get_group_choices():
for group_choice in UsersAndGroups.get_group_choices():
auth.models.Group.objects.get_or_create(name=group_choice[0])
admin_group = auth.models.Group.objects.get(name='admin')
@@ -0,0 +1,67 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Tests for the UsersAndGroups app component.
"""
import pytest
from ..components import UsersAndGroups
@pytest.fixture(autouse=True)
def fixture_empty_components():
"""Remove all components from the global list before every test."""
UsersAndGroups._all_components = set()
def test_create_users_and_groups_component():
"""Test initialization of users and groups component."""
component = UsersAndGroups('simple-component')
assert component.groups == {}
assert component.reserved_usernames == []
assert len(component._all_components) == 1
assert component in component._all_components
groups = {'test-group1', 'Test description'}
component = UsersAndGroups('another-component', groups=groups,
reserved_usernames=['test-user1'])
assert component.groups == groups
assert component.reserved_usernames == ['test-user1']
assert len(component._all_components) == 2
assert component in component._all_components
def test_get_groups():
"""Test getting all the groups.
Test that:
1. Group names are unique
2. All components have the same global set of groups
"""
UsersAndGroups('component-with-no-groups')
UsersAndGroups('component-with-one-group',
groups={'group1': 'description1'})
UsersAndGroups('component-with-groups', groups={
'group1': 'description1',
'group2': 'description2'
})
assert UsersAndGroups.get_groups() == {'group1', 'group2'}
assert UsersAndGroups.get_group_choices() == [
('group1', 'description1 (group1)'),
('group2', 'description2 (group2)')
]
def test_check_username_reservation():
"""Test username reservations by multiple components."""
UsersAndGroups('complex-component',
reserved_usernames=['username1', 'username2'],
groups={'somegroup', 'some description'})
assert not UsersAndGroups.is_username_reserved('something')
assert UsersAndGroups.is_username_reserved('username1')
assert not UsersAndGroups.is_username_reserved('username3')
UsersAndGroups('temp-component', reserved_usernames=['username3'])
assert UsersAndGroups.is_username_reserved('username3')
-18
View File
@@ -1,18 +0,0 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Test module to exercise group registration.
It is recommended to run this module with root privileges in a virtual machine.
"""
from plinth.modules import users
def test_register_group():
"""Test for multi addition of same group"""
users.groups = dict() # reset groups
group = ('TestGroup', 'Group for testing')
users.register_group(group)
users.register_group(group)
assert len(users.groups) == 1
return users.groups
+9 -6
View File
@@ -13,6 +13,8 @@ from django.core.exceptions import PermissionDenied
from plinth import module_loader
from plinth.modules.users import views
from ..components import UsersAndGroups
# For all tests, plinth.urls instead of urls configured for testing, and
# django database
pytestmark = [pytest.mark.urls('plinth.urls'), pytest.mark.django_db]
@@ -43,15 +45,16 @@ def action_run(action, options, **kwargs):
@pytest.fixture(autouse=True)
def module_patch():
"""Patch users module."""
loaded_modules = [('minetest',
Mock(reserved_usernames=['Debian-minetest']))]
pwd_users = [Mock(pw_name='root'), Mock(pw_name='plinth')]
with patch('pwd.getpwall', return_value=pwd_users),\
patch('plinth.actions.superuser_run', side_effect=action_run),\
patch('plinth.module_loader.loaded_modules.items',
return_value=loaded_modules):
UsersAndGroups._all_components = set()
UsersAndGroups('test-users-and-groups',
groups={'admin': 'The admin group'})
UsersAndGroups('users-and-groups-minetest',
reserved_usernames=['debian-minetest'])
with patch('pwd.getpwall', return_value=pwd_users),\
patch('plinth.actions.superuser_run', side_effect=action_run):
yield