*: Add type hints for diagnose method

Helps: #2410.

- Ensure that diagnostics methods and parameters are type checked so that we can
catch any potential issues.

- Move plinth/modules/diagnostics/check.py to plinth/diagnostic_check.py to
avoid many circular dependencies created. This is due to
plinth.modules.diagnostics automatically imported when
plinth.modules.diagnostics.check is imported. Also app.py is already (type)
dependent on diagnostic_check due to diagnose() method. To make the Check
classes independent of diagnostic module is okay.

Tests:

- Run make check-type.

- Run full diagnostics with following apps installed: torproxy, tor.
  - Test to netcat to 9051 in tor works.
  - Test 'port available for internal/external networks' in firewall works.
  - Test 'Package is latest' works.
  - Test 'Access url with proxy' in privoxy works.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
[jvalleroy: Also move tests for diagnostic_check]
Signed-off-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa authored and James Valleroy committed 2024-03-09 14:23:33 -05:00
1 parent f9b186e14f
commit 4b09d91f93
28 files changed
+161 -117

No files matched your search

+18 -8
View File
@@ -7,7 +7,8 @@ import subprocess
from django.utils.translation import gettext_noop
from plinth import action_utils, app
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
from plinth.diagnostic_check import (DiagnosticCheck,
DiagnosticCheckParameters, Result)
from plinth.privileged import service as service_privileged
from . import privileged
@@ -58,7 +59,7 @@ class Webserver(app.LeaderComponent):
"""Disable the Apache configuration."""
privileged.disable(self.web_name, self.kind)
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Check if the web path is accessible by clients.
See :py:meth:`plinth.app.Component.diagnose`.
@@ -135,8 +136,12 @@ class Uwsgi(app.LeaderComponent):
and action_utils.service_is_running('uwsgi')
def diagnose_url(url, kind=None, env=None, check_certificate=True,
extra_options=None, wrapper=None, expected_output=None):
def diagnose_url(url: str, kind: str | None = None,
env: dict[str, str] | None = None,
check_certificate: bool = True,
extra_options: list[str] | None = None,
wrapper: str | None = None,
expected_output: str | None = None) -> DiagnosticCheck:
"""Run a diagnostic on whether a URL is accessible.
Kind can be '4' for IPv4 or '6' for IPv6.
@@ -148,7 +153,7 @@ def diagnose_url(url, kind=None, env=None, check_certificate=True,
except FileNotFoundError:
result = Result.ERROR
parameters = {'url': url, 'kind': kind}
parameters: DiagnosticCheckParameters = {'url': url, 'kind': kind}
if kind:
check_id = f'apache-url-kind-{url}-{kind}'
description = gettext_noop('Access URL {url} on tcp{kind}')
@@ -159,7 +164,8 @@ def diagnose_url(url, kind=None, env=None, check_certificate=True,
return DiagnosticCheck(check_id, description, result, parameters)
def diagnose_url_on_all(url, expect_redirects=False, **kwargs):
def diagnose_url_on_all(url: str, expect_redirects: bool = False,
**kwargs) -> list[DiagnosticCheck]:
"""Run a diagnostic on whether a URL is accessible."""
results = []
for address in action_utils.get_addresses():
@@ -173,8 +179,12 @@ def diagnose_url_on_all(url, expect_redirects=False, **kwargs):
return results
def check_url(url, kind=None, env=None, check_certificate=True,
extra_options=None, wrapper=None, expected_output=None):
def check_url(url: str, kind: str | None = None,
env: dict[str, str] | None = None,
check_certificate: bool = True,
extra_options: list[str] | None = None,
wrapper: str | None = None,
expected_output: str | None = None) -> bool:
"""Check whether a URL is accessible."""
command = ['curl', '--location', '-f', '-w', '%{response_code}']
@@ -9,10 +9,10 @@ from unittest.mock import call, patch
import pytest
from plinth import app
from plinth.diagnostic_check import DiagnosticCheck, Result
from plinth.modules.apache.components import (Uwsgi, Webserver, check_url,
diagnose_url,
diagnose_url_on_all)
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
def test_webserver_init():
+3 -3
View File
@@ -11,8 +11,8 @@ from django.utils.translation import gettext_noop
from plinth import app as app_module
from plinth import menu
from plinth.daemon import Daemon, RelatedDaemon
from plinth.diagnostic_check import DiagnosticCheck, Result
from plinth.modules.backups.components import BackupRestore
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
from plinth.package import Packages
from . import manifest
@@ -89,7 +89,7 @@ class DateTimeApp(app_module.App):
**manifest.backup)
self.add(backup_restore)
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
if self._is_time_managed():
@@ -107,7 +107,7 @@ class DateTimeApp(app_module.App):
self.enable()
def _diagnose_time_synchronized():
def _diagnose_time_synchronized() -> DiagnosticCheck:
"""Check whether time is synchronized to NTP server."""
result = Result.FAILED
try:
+3 -2
View File
@@ -17,11 +17,12 @@ from django.utils.translation import gettext_noop
from plinth import app as app_module
from plinth import daemon, glib, kvstore, menu
from plinth import operation as operation_module
from plinth.diagnostic_check import (CheckJSONDecoder, CheckJSONEncoder,
DiagnosticCheck, Result)
from plinth.modules.apache.components import diagnose_url_on_all
from plinth.modules.backups.components import BackupRestore
from . import manifest
from .check import CheckJSONDecoder, CheckJSONEncoder, Result
_description = [
_('The system diagnostic test will run a number of checks on your '
@@ -75,7 +76,7 @@ class DiagnosticsApp(app_module.App):
super().setup(old_version)
self.enable()
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
results.append(daemon.diagnose_port_listening(8000, 'tcp4'))
-67
View File
@@ -1,67 +0,0 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Diagnostic check data type."""
import dataclasses
import json
from dataclasses import dataclass, field
from enum import StrEnum
from django.utils.translation import gettext
from plinth.utils import SafeFormatter
class Result(StrEnum):
"""The result of a diagnostic check."""
NOT_DONE = 'not_done'
PASSED = 'passed'
WARNING = 'warning'
FAILED = 'failed'
ERROR = 'error'
@dataclass
class DiagnosticCheck:
"""A diagnostic check and optional result and parameters."""
check_id: str
description: str
result: Result = Result.NOT_DONE
parameters: dict = field(default_factory=dict)
@property
def translated_description(self):
"""Return translated string for description."""
description = gettext(self.description)
if self.parameters:
return SafeFormatter().vformat(description, [], self.parameters)
return description
class CheckJSONEncoder(json.JSONEncoder):
"""Encode objects that include DiagnosticChecks."""
def default(self, o):
"""Add class tag to DiagnosticChecks."""
if isinstance(o, DiagnosticCheck):
o = dataclasses.asdict(o)
o.update({'__class__': 'DiagnosticCheck'})
return o
return super().default(o)
class CheckJSONDecoder(json.JSONDecoder):
"""Decode objects that include DiagnosticChecks."""
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=CheckJSONDecoder.from_dict)
@staticmethod
def from_dict(data):
"""Convert tagged data to DiagnosticCheck."""
if data.get('__class__') == 'DiagnosticCheck':
return DiagnosticCheck(data['check_id'], data['description'],
data['result'], data['parameters'])
return data
@@ -1,68 +0,0 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Tests for diagnostic check data type."""
import json
import pytest
from plinth.modules.diagnostics.check import (CheckJSONDecoder,
CheckJSONEncoder,
DiagnosticCheck, Result)
def test_result():
"""Test result enum type."""
assert Result.__members__['ERROR'].name == 'ERROR'
assert Result.__members__['ERROR'].value == 'error'
assert Result.NOT_DONE == 'not_done'
assert Result.PASSED == 'passed'
assert Result.WARNING == 'warning'
assert Result.FAILED == 'failed'
assert Result.ERROR == 'error'
def test_diagnostic_check():
"""Test the diagnostic check data class."""
with pytest.raises(TypeError):
DiagnosticCheck()
check = DiagnosticCheck('some-check-id', 'sample check')
assert check.check_id == 'some-check-id'
assert check.description == 'sample check'
assert check.translated_description == 'sample check'
assert check.result == Result.NOT_DONE
assert not check.parameters
check = DiagnosticCheck('some-check-id', 'sample check', Result.PASSED)
assert check.result == Result.PASSED
assert not check.parameters
check = DiagnosticCheck('some-check-id', 'sample check', Result.PASSED,
{'key': 'value'})
assert check.parameters['key'] == 'value'
def test_translate():
"""Test formatting the translated description."""
check = DiagnosticCheck('some-check-id', 'sample check {key}',
Result.FAILED, {'key': 'value'})
assert check.translated_description == 'sample check value'
check = DiagnosticCheck('some-check-id', 'sample check {missing}',
Result.PASSED, {'key': 'value'})
assert check.translated_description == 'sample check ?missing?'
def test_json_encoder_decoder():
"""Test encoding and decoding as JSON."""
check = DiagnosticCheck('some-check-id', 'sample check', Result.PASSED)
check_json = json.dumps(check, cls=CheckJSONEncoder)
for string in [
'"check_id": "some-check-id"', '"description": "sample check"',
'"result": "passed"', '"parameters": {}',
'"__class__": "DiagnosticCheck"'
]:
assert string in check_json
decoded_check = json.loads(check_json, cls=CheckJSONDecoder)
assert decoded_check == check
+1 -1
View File
@@ -14,10 +14,10 @@ from django.views.generic import TemplateView
from plinth import operation
from plinth.app import App
from plinth.diagnostic_check import Result
from plinth.modules import diagnostics
from plinth.views import AppView
from .check import Result
from .forms import ConfigureForm
logger = logging.getLogger(__name__)
+8 -5
View File
@@ -10,8 +10,8 @@ from django.utils.translation import gettext_noop
from plinth import app as app_module
from plinth import cfg, menu
from plinth.daemon import Daemon
from plinth.diagnostic_check import DiagnosticCheck, Result
from plinth.modules.backups.components import BackupRestore
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
from plinth.package import Packages, install
from plinth.utils import Version, format_lazy, import_from_gi
@@ -96,7 +96,7 @@ class FirewallApp(app_module.App):
_run_setup()
return True
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
config = privileged.get_config()
@@ -265,7 +265,8 @@ def remove_passthrough(ipv, *args):
config_direct.removePassthrough('(sas)', ipv, args)
def _diagnose_default_zone(config):
def _diagnose_default_zone(
config: privileged.FirewallConfig) -> DiagnosticCheck:
"""Diagnose whether the default zone is external."""
check_id = 'firewall-default-zone'
description = gettext_noop('Default zone is external')
@@ -274,7 +275,8 @@ def _diagnose_default_zone(config):
return DiagnosticCheck(check_id, description, result)
def _diagnose_firewall_backend(config):
def _diagnose_firewall_backend(
config: privileged.FirewallConfig) -> DiagnosticCheck:
"""Diagnose whether the firewall backend is nftables."""
check_id = 'firewall-backend'
description = gettext_noop('Firewall backend is nftables')
@@ -283,7 +285,8 @@ def _diagnose_firewall_backend(config):
return DiagnosticCheck(check_id, description, result)
def _diagnose_direct_passthroughs(config):
def _diagnose_direct_passthroughs(
config: privileged.FirewallConfig) -> DiagnosticCheck:
"""Diagnose direct passthroughs for local service protection.
Currently, we just check that the number of passthroughs is at least 12,
+11 -5
View File
@@ -5,16 +5,19 @@ App component for other apps to use firewall functionality.
import logging
import re
from typing import ClassVar
from typing import ClassVar, TypeAlias
from django.utils.translation import gettext_noop
from plinth import app
from plinth.diagnostic_check import (DiagnosticCheck,
DiagnosticCheckParameters, Result)
from plinth.modules import firewall
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
logger = logging.getLogger(__name__)
_list_type: TypeAlias = list
class Firewall(app.FollowerComponent):
"""Component to open/close firewall ports for an app."""
@@ -114,7 +117,7 @@ class Firewall(app.FollowerComponent):
if not re.fullmatch(r'tun\d+', interface)
]
def diagnose(self):
def diagnose(self) -> _list_type[DiagnosticCheck]:
"""Check if the firewall ports are open and only as expected.
See :py:meth:`plinth.app.Component.diagnose`.
@@ -124,7 +127,7 @@ class Firewall(app.FollowerComponent):
internal_ports = firewall.get_enabled_services(zone='internal')
external_ports = firewall.get_enabled_services(zone='external')
for port_detail in self.ports_details:
port = port_detail['name']
port = str(port_detail['name'])
details = ', '.join(
(f'{port_number}/{protocol}'
for port_number, protocol in port_detail['details']))
@@ -134,7 +137,10 @@ class Firewall(app.FollowerComponent):
result = Result.PASSED if port in internal_ports else Result.FAILED
description = gettext_noop(
'Port {name} ({details}) available for internal networks')
parameters = {'name': port, 'details': details}
parameters: DiagnosticCheckParameters = {
'name': port,
'details': details
}
results.append(
DiagnosticCheck(check_id, description, result, parameters))
+5 -2
View File
@@ -2,12 +2,15 @@
"""Configuration helper for FreedomBox firewall interface."""
import subprocess
from typing import TypeAlias
import augeas
from plinth import action_utils
from plinth.actions import privileged
FirewallConfig: TypeAlias = dict[str, str | list[str]]
def _flush_iptables_rules():
"""Flush firewalld iptables rules before restarting it.
@@ -132,9 +135,9 @@ def setup():
@privileged
def get_config():
def get_config() -> FirewallConfig:
"""Return firewalld configuration for diagnostics."""
config = {}
config: FirewallConfig = {}
# Get the default zone.
output = subprocess.check_output(['firewall-cmd', '--get-default-zone'])
@@ -8,7 +8,7 @@ from unittest.mock import call, patch
import pytest
from plinth.app import App
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
from plinth.diagnostic_check import DiagnosticCheck, Result
from plinth.modules.firewall.components import (Firewall,
FirewallLocalProtection)
+2 -2
View File
@@ -11,10 +11,10 @@ from django.utils.translation import gettext_noop
from plinth import app as app_module
from plinth import cfg, menu
from plinth.config import DropinConfigs
from plinth.diagnostic_check import DiagnosticCheck, Result
from plinth.modules import names
from plinth.modules.apache.components import diagnose_url
from plinth.modules.backups.components import BackupRestore
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
from plinth.modules.names.components import DomainType
from plinth.package import Packages
from plinth.signals import domain_added, domain_removed, post_app_loading
@@ -89,7 +89,7 @@ class LetsEncryptApp(app_module.App):
post_app_loading.connect(_certificate_handle_modified)
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
+2 -1
View File
@@ -9,6 +9,7 @@ from django.utils.translation import gettext_lazy as _
from plinth import app as app_module
from plinth import daemon, kvstore, menu, network
from plinth.config import DropinConfigs
from plinth.diagnostic_check import DiagnosticCheck
from plinth.package import Packages
from . import privileged
@@ -72,7 +73,7 @@ class NetworksApp(app_module.App):
])
self.add(dropin_configs)
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
+5 -4
View File
@@ -11,6 +11,7 @@ from plinth import action_utils
from plinth import app as app_module
from plinth import cfg, frontpage, menu
from plinth.daemon import Daemon
from plinth.diagnostic_check import DiagnosticCheck
from plinth.modules.apache.components import diagnose_url
from plinth.modules.backups.components import BackupRestore
from plinth.modules.firewall.components import Firewall
@@ -86,7 +87,7 @@ class PrivoxyApp(app_module.App):
**manifest.backup)
self.add(backup_restore)
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
results.append(diagnose_url('https://www.debian.org'))
@@ -102,16 +103,16 @@ class PrivoxyApp(app_module.App):
self.enable()
def diagnose_url_with_proxy():
def diagnose_url_with_proxy() -> list[DiagnosticCheck]:
"""Run a diagnostic on a URL with a proxy."""
url = 'https://debian.org/' # Gives a simple redirect to www.
results = []
for address in action_utils.get_addresses():
proxy = 'http://{host}:8118/'.format(host=address['url_address'])
proxy = f'http://{address["url_address"]}:8118/'
env = {'https_proxy': proxy}
result = diagnose_url(url, kind=address['kind'], env=env)
result = diagnose_url(url, kind=str(address['kind']), env=env)
result.check_id = f'privoxy-url-proxy-kind-{url}-{address["kind"]}'
result.description = gettext_noop(
'Access {url} with proxy {proxy} on tcp{kind}')
+5 -5
View File
@@ -13,10 +13,10 @@ from plinth import cfg, kvstore, menu
from plinth import setup as setup_module_ # Not setup_module, for pytest
from plinth.daemon import (Daemon, app_is_running, diagnose_netcat,
diagnose_port_listening)
from plinth.diagnostic_check import DiagnosticCheck, Result
from plinth.modules import torproxy
from plinth.modules.apache.components import Webserver
from plinth.modules.backups.components import BackupRestore
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
from plinth.modules.firewall.components import Firewall
from plinth.modules.names.components import DomainType
from plinth.modules.torproxy.utils import is_apt_transport_tor_enabled
@@ -123,7 +123,7 @@ class TorApp(app_module.App):
super().disable()
update_hidden_service_domain()
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
@@ -235,7 +235,7 @@ def update_hidden_service_domain(status=None):
name=status['hs_hostname'], services=services)
def _diagnose_control_port():
def _diagnose_control_port() -> list[DiagnosticCheck]:
"""Diagnose whether Tor control port is open on 127.0.0.1 only."""
results = []
@@ -249,7 +249,7 @@ def _diagnose_control_port():
negate = False
results.append(
diagnose_netcat(address['address'], 9051, input='QUIT\n',
negate=negate))
diagnose_netcat(str(address['address']), 9051,
remote_input='QUIT\n', negate=negate))
return results
+5 -3
View File
@@ -11,6 +11,7 @@ from django.utils.translation import gettext_noop
from plinth import app as app_module
from plinth import cfg, frontpage, kvstore, menu
from plinth.daemon import Daemon
from plinth.diagnostic_check import DiagnosticCheck
from plinth.modules.apache.components import diagnose_url
from plinth.modules.backups.components import BackupRestore
from plinth.modules.firewall.components import Firewall
@@ -100,7 +101,7 @@ class TorProxyApp(app_module.App):
privileged.configure(apt_transport_tor=False)
super().disable()
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
results.append(_diagnose_url_via_tor('http://www.debian.org', '4'))
@@ -133,7 +134,8 @@ class TorProxyApp(app_module.App):
privileged.uninstall()
def _diagnose_url_via_tor(url, kind=None):
def _diagnose_url_via_tor(url: str,
kind: str | None = None) -> DiagnosticCheck:
"""Diagnose whether a URL is reachable via Tor."""
result = diagnose_url(url, kind=kind, wrapper='torsocks')
result.check_id = 'torproxy-url'
@@ -142,7 +144,7 @@ def _diagnose_url_via_tor(url, kind=None):
return result
def _diagnose_tor_use(url, kind=None):
def _diagnose_tor_use(url: str, kind: str | None = None) -> DiagnosticCheck:
"""Diagnose whether webpage at URL reports that we are using Tor."""
expected_output = 'Congratulations. This browser is configured to use Tor.'
result = diagnose_url(url, kind=kind, wrapper='torsocks',
+10 -8
View File
@@ -13,7 +13,8 @@ from plinth import app as app_module
from plinth import cfg, menu
from plinth.config import DropinConfigs
from plinth.daemon import Daemon
from plinth.modules.diagnostics.check import DiagnosticCheck, Result
from plinth.diagnostic_check import (DiagnosticCheck,
DiagnosticCheckParameters, Result)
from plinth.package import Packages
from plinth.privileged import service as service_privileged
@@ -85,7 +86,7 @@ class UsersApp(app_module.App):
groups=groups)
self.add(users_and_groups)
def diagnose(self):
def diagnose(self) -> list[DiagnosticCheck]:
"""Run diagnostics and return the results."""
results = super().diagnose()
@@ -112,7 +113,7 @@ class UsersApp(app_module.App):
privileged.create_group('freedombox-share')
def _diagnose_ldap_entry(search_item):
def _diagnose_ldap_entry(search_item: str) -> DiagnosticCheck:
"""Diagnose that an LDAP entry exists."""
check_id = f'users-ldap-entry-{search_item}'
result = Result.FAILED
@@ -125,12 +126,13 @@ def _diagnose_ldap_entry(search_item):
pass
description = gettext_noop('Check LDAP entry "{search_item}"')
parameters = {'search_item': search_item}
parameters: DiagnosticCheckParameters = {'search_item': search_item}
return DiagnosticCheck(check_id, description, result, parameters)
def _diagnose_nslcd_config(config, key, value):
def _diagnose_nslcd_config(config: dict[str, str], key: str,
value: str) -> DiagnosticCheck:
"""Diagnose that nslcd has a configuration."""
check_id = f'users-nslcd-config-{key}'
try:
@@ -139,12 +141,12 @@ def _diagnose_nslcd_config(config, key, value):
result = Result.FAILED
description = gettext_noop('Check nslcd config "{key} {value}"')
parameters = {'key': key, 'value': value}
parameters: DiagnosticCheckParameters = {'key': key, 'value': value}
return DiagnosticCheck(check_id, description, result, parameters)
def _diagnose_nsswitch_config():
def _diagnose_nsswitch_config() -> list[DiagnosticCheck]:
"""Diagnose that Name Service Switch is configured to use LDAP."""
nsswitch_conf = '/etc/nsswitch.conf'
aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
@@ -169,7 +171,7 @@ def _diagnose_nsswitch_config():
break
description = gettext_noop('Check nsswitch config "{database}"')
parameters = {'database': database}
parameters: DiagnosticCheckParameters = {'database': database}
results.append(
DiagnosticCheck(check_id, description, result, parameters))
+1 -1
View File
@@ -178,7 +178,7 @@ def _configure_ldapscripts():
@privileged
def get_nslcd_config():
def get_nslcd_config() -> dict[str, str]:
"""Get nslcd configuration for diagnostics."""
nslcd_conf = '/etc/nslcd.conf'
aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +