diff --git a/docs/deployment.md b/docs/deployment.md index 4488a8e..a5c7238 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -496,6 +496,20 @@ connected. Follow their logs with `journalctl`. sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat ``` +## Manage panel roles + +A verified superuser can assign a Customer or Customer manager role to an +active login from **Customers** or **Customer managers**. Choose **Assign +to existing login** and enter the username. Customer roles use their own +assigned hosting accounts. Customer managers use their own hosting account +assignments and hosting plan policy. New manager assignments use the default +customer manager profile when one is configured. + +Logins with multiple roles can choose **Panel role** in the account area. +The role applies to the session, including direct page requests and actions. +Returning to the administrator role requires a verified second factor. If the +active role assignment is revoked, the session asks the user to sign in again. + ## Select a panel theme The panel follows the browser's light or dark preference on the first visit. @@ -2657,6 +2671,25 @@ Keep the managed data directories on their service filesystems to allow an atomic move into the archive directory. Existing backup archives remain available to operators with backup access. +## Configure installed features in the panel + +Open **About Coulobre → Configure features** as a superuser with a verified +second factor. The page shows the installation prerequisites and distinguishes +local mail and DNS services from linked receivers. Use **Configure DNS +defaults** to edit the zone template for new hosting accounts. + +The switches control which installed capabilities the panel offers for new +actions. Existing managed sites, mailbox delivery, published DNS records, +schedules and queued provisioning continue running. Backup archives remain +accessible when new backup requests are paused. Pausing an application sign-in +also prevents redemption of pending tickets for that application. + +Configure service packages, linked receiver identities, bridge keys and +backup credentials on the host using their deployment procedures. Enabling +a paused feature checks its available service socket and, for linked mail or +DNS, the receiver's readiness and version. A failed prerequisite check leaves +the saved choices intact. Changes are recorded in the administrator audit log. + ## Monitor local and remote services The panel's **Service health** page shows the latest observation and timestamp diff --git a/src/coulobre/hosting/account_backup_forms.py b/src/coulobre/hosting/account_backup_forms.py index 5e8ad10..362a929 100644 --- a/src/coulobre/hosting/account_backup_forms.py +++ b/src/coulobre/hosting/account_backup_forms.py @@ -11,6 +11,7 @@ from coulobre.account_restore_request import ( ) from coulobre.database_node import DatabaseSpec +from .installation_features import panel_feature_allowed from .models import AccountBackupSchedule SCHEDULE_FIELDS = ( @@ -49,7 +50,11 @@ class AccountBackupScheduleForm(forms.Form): self.allow_mail = allow_mail if not allow_mail and not self.initial.get("include_mailboxes"): del self.fields["include_mailboxes"] - destinations = settings.OFFSITE_BACKUP_DESTINATIONS + destinations = ( + settings.OFFSITE_BACKUP_DESTINATIONS + if panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS") + else {} + ) current = self.initial.get("offsite_destination") if destinations or current: choices = [("", "Local archive only"), *destinations.items()] diff --git a/src/coulobre/hosting/account_setup.py b/src/coulobre/hosting/account_setup.py index f53f143..a01f327 100644 --- a/src/coulobre/hosting/account_setup.py +++ b/src/coulobre/hosting/account_setup.py @@ -11,6 +11,7 @@ from coulobre.web_node import WebSite from .dns_defaults import zone_defaults from .dns_forms import normalize_record_rows from .dns_publication import queue_zone_snapshot +from .installation_features import panel_feature_allowed from .mail_dns_setup import mail_dns_proposal from .models import ( HostingDnsZone, @@ -70,8 +71,8 @@ def setup_new_account(account, options): ) if managed_dns: existing_managed_mail = ( - settings.LOCAL_MAILBOX_PROVISIONING - and settings.MANAGE_MAIL_DNS + panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") + and panel_feature_allowed("MANAGE_MAIL_DNS") and account.mail_domains.filter(domain=domain).exists() ) create_default_dns_zone( diff --git a/src/coulobre/hosting/independent_website_views.py b/src/coulobre/hosting/independent_website_views.py index c77d68c..d5e68d6 100644 --- a/src/coulobre/hosting/independent_website_views.py +++ b/src/coulobre/hosting/independent_website_views.py @@ -1,5 +1,4 @@ from django import forms -from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.exceptions import ValidationError from django.db import IntegrityError @@ -20,6 +19,7 @@ from .independent_websites import ( create_website, queue_website_operation, ) +from .installation_features import panel_feature_allowed from .models import HostingAccount, IndependentWebsite, WebsiteDomain @@ -79,7 +79,7 @@ class IndependentWebsiteEditor( template_name = "hosting/independent_website_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -130,7 +130,9 @@ class IndependentWebsiteOperation(IndependentWebsiteEditor): operation = Operation(self.kwargs["operation"]) except ValueError: raise Http404 from None - if operation == Operation.HTTPS and not settings.LOCAL_WEB_HTTPS: + if operation == Operation.HTTPS and not panel_feature_allowed( + "LOCAL_WEB_HTTPS" + ): raise Http404 return operation diff --git a/src/coulobre/hosting/independent_websites.py b/src/coulobre/hosting/independent_websites.py index 094b798..90d4691 100644 --- a/src/coulobre/hosting/independent_websites.py +++ b/src/coulobre/hosting/independent_websites.py @@ -9,6 +9,7 @@ from coulobre.php_runtime import validate_php_version from coulobre.service_access import ServiceAccessRequest from .access import is_tenant, manages_account +from .installation_features import panel_feature_allowed from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob from .node_client import ( activate_local_site, @@ -54,7 +55,7 @@ def website_actions(website): if website.suspended: return (Operation.RESUME, Operation.RETIRE) actions = (Operation.PHP, Operation.SUSPEND) - if settings.LOCAL_WEB_HTTPS and not website.https_enabled: + if panel_feature_allowed("LOCAL_WEB_HTTPS") and not website.https_enabled: actions += (Operation.HTTPS,) return actions diff --git a/src/coulobre/hosting/installation_features.py b/src/coulobre/hosting/installation_features.py new file mode 100644 index 0000000..bf499a8 --- /dev/null +++ b/src/coulobre/hosting/installation_features.py @@ -0,0 +1,193 @@ +from contextvars import ContextVar +from dataclasses import dataclass +from pathlib import Path + +from django.conf import settings +from django.utils.functional import cached_property + +from coulobre.linked_updates import UNIT_DIR + +from .dns_defaults import zone_defaults +from .models import PanelFeaturePolicy + + +@dataclass(frozen=True) +class Feature: + setting: str + label: str + prerequisite: str + socket: str = "" + role: str = "" + + @property + def configured(self): + if self.setting == "DEFAULT_DNS_ZONES": + defaults = zone_defaults() + return bool( + settings.LOCAL_DNS_PUBLISHING + and defaults.nameservers + and defaults.addresses + ) + if self.setting == "PHPMYADMIN_URL": + return bool( + settings.PHPMYADMIN_URL and settings.LOCAL_DATABASE_CREDENTIALS + ) + if self.setting == "ROUNDCUBE_URL": + return bool( + settings.ROUNDCUBE_URL + and ( + settings.LOCAL_MAILBOX_CREDENTIALS + or settings.REMOTE_MAILBOX_CREDENTIALS + ) + ) + return bool(getattr(settings, self.setting)) + + @property + def linked(self): + return ( + bool(self.role) + and ( + UNIT_DIR / f"coulobre-{self.role}-apply@.service.d/remote.conf" + ).is_file() + ) + + @property + def socket_ready(self): + if self.setting == "ROUNDCUBE_URL": + socket = ( + "coulobre-mail-credentials" + if settings.REMOTE_MAILBOX_CREDENTIALS + else "coulobre-service-credentials" + ) + return Path(f"/run/{socket}.sock").is_socket() + return not self.socket or Path(f"/run/{self.socket}.sock").is_socket() + + +FEATURES = ( + Feature( + "LOCAL_WEB_ACTIVATION", + "Website provisioning", + "Apache and PHP provisioning", + "coulobre-web-apply", + ), + Feature( + "LOCAL_WEB_HTTPS", + "Managed website certificates", + "Website certificate provisioning", + "coulobre-https-apply", + ), + Feature( + "WEB_FILE_MANAGER", + "Website file manager", + "Website file service", + "coulobre-website-files", + ), + Feature( + "WEBSITE_JOBS", + "Website scheduled tasks", + "Website task service", + "coulobre-website-jobs", + ), + Feature( + "LOCAL_DNS_PUBLISHING", + "DNS publishing", + "Local BIND9 or a linked DNS receiver", + "coulobre-dns-apply", + "dns", + ), + Feature( + "DEFAULT_DNS_ZONES", + "Default managed DNS zones for new accounts", + "DNS publishing, nameservers and hosting IP addresses", + ), + Feature( + "LOCAL_MAILBOX_PROVISIONING", + "Mailbox provisioning", + "Local mail services or a linked mail receiver", + "coulobre-mail-apply", + "mail", + ), + Feature( + "MANAGE_MAIL_DNS", + "Managed mail DNS records", + "Mail exchanger and sending IP addresses", + ), + Feature( + "LOCAL_DATABASE_PROVISIONING", + "Database provisioning", + "MariaDB provisioning", + "coulobre-database-apply", + ), + Feature( + "LOCAL_ACCOUNT_BACKUPS", + "Local account backups", + "Local backup service", + "coulobre-account-backup", + ), + Feature( + "OFFSITE_BACKUP_DESTINATIONS", + "Off-site backup destinations", + "A configured destination and the transfer service", + "coulobre-account-offsite", + ), + Feature( + "PHPMYADMIN_URL", + "phpMyAdmin sign-in", + "phpMyAdmin bridge and MariaDB credential service", + "coulobre-service-credentials", + ), + Feature( + "ROUNDCUBE_URL", + "Roundcube sign-in", + "Roundcube bridge and mailbox credential service", + ), +) + + +class FeaturePolicy: + @cached_property + def saved(self): + return ( + PanelFeaturePolicy.objects.filter(pk=1).first() + or PanelFeaturePolicy() + ) + + @cached_property + def disabled(self): + return frozenset(self.saved.disabled) + + +current_policy = ContextVar("current_feature_policy", default=None) + + +def panel_feature_allowed(setting): + if not getattr(settings, setting): + return False + return not panel_feature_paused(setting) + + +def panel_feature_paused(setting): + policy = current_policy.get() or FeaturePolicy() + return setting in policy.disabled + + +def default_dns_zones_allowed(defaults): + if not defaults.nameservers or not defaults.addresses: + return False + policy = current_policy.get() or FeaturePolicy() + return ( + panel_feature_allowed("LOCAL_DNS_PUBLISHING") + and "DEFAULT_DNS_ZONES" not in policy.disabled + ) + + +class FeaturePolicyMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + token = current_policy.set(FeaturePolicy()) + try: + return self.get_response(request) + finally: + current_policy.reset(token) diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index 24544c1..9e73056 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -1,13 +1,23 @@ from importlib.metadata import PackageNotFoundError, version -from django.conf import settings -from django.contrib.auth.mixins import PermissionRequiredMixin +from django import forms +from django.contrib import messages +from django.contrib.admin.models import CHANGE, LogEntry +from django.contrib.auth.mixins import ( + PermissionRequiredMixin, + UserPassesTestMixin, +) +from django.db import transaction +from django.db.models import F +from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache -from django.views.generic import TemplateView +from django.views.generic import FormView, TemplateView from .access import OperatorOnlyMixin -from .dns_defaults import zone_defaults +from .installation_features import FEATURES, FeaturePolicy +from .models import PanelFeaturePolicy +from .update_views import inspect_linked_nodes @method_decorator(never_cache, name="dispatch") @@ -22,41 +32,137 @@ class InstallationView( installed_version = version("coulobre-panel") except PackageNotFoundError: installed_version = "Unavailable" - - dns_defaults = zone_defaults() - features = ( - ("Local website provisioning", settings.LOCAL_WEB_ACTIVATION), - ("Managed website certificates", settings.LOCAL_WEB_HTTPS), - ("Website file manager", settings.WEB_FILE_MANAGER), - ("Website scheduled tasks", settings.WEBSITE_JOBS), - ("Local DNS publishing", settings.LOCAL_DNS_PUBLISHING), - ( - "Default managed DNS zones for new accounts", - settings.LOCAL_DNS_PUBLISHING - and dns_defaults.nameservers - and dns_defaults.addresses, - ), - ( - "Local mailbox provisioning", - settings.LOCAL_MAILBOX_PROVISIONING, - ), - ("Managed mail DNS records", settings.MANAGE_MAIL_DNS), - ( - "Local database provisioning", - settings.LOCAL_DATABASE_PROVISIONING, - ), - ("Local account backups", settings.LOCAL_ACCOUNT_BACKUPS), - ( - "Off-site backup destinations", - settings.OFFSITE_BACKUP_DESTINATIONS, - ), - ("phpMyAdmin sign-in", settings.PHPMYADMIN_URL), - ("Roundcube sign-in", settings.ROUNDCUBE_URL), - ) + policy = FeaturePolicy() + features = [] + for feature in FEATURES: + configured = feature.configured + enabled = ( + configured + and feature.setting not in policy.disabled + and ( + feature.setting != "DEFAULT_DNS_ZONES" + or "LOCAL_DNS_PUBLISHING" not in policy.disabled + ) + ) + features.append((feature, configured, enabled)) return super().get_context_data( - installed_version=installed_version, - features=[ - (name, bool(configured)) for name, configured in features - ], - **kwargs, + installed_version=installed_version, features=features, **kwargs + ) + + +class FeatureConfigurationForm(forms.Form): + revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput) + + def __init__(self, *args, policy, **kwargs): + super().__init__(*args, **kwargs) + self.initial["revision"] = policy.saved.revision + self.configured_features = [ + feature for feature in FEATURES if feature.configured + ] + for feature in self.configured_features: + self.fields[feature.setting] = forms.BooleanField( + required=False, + label=feature.label, + help_text=feature.prerequisite, + initial=feature.setting not in policy.disabled, + ) + + def changed_features(self): + return [ + feature + for feature in self.configured_features + if feature.setting in self.changed_data + ] + + +def check_features(form, changed): + new_enabled = [ + feature for feature in changed if form.cleaned_data[feature.setting] + ] + nodes = {} + if any(feature.linked for feature in new_enabled): + topology = inspect_linked_nodes() + nodes = {node["role"]: node for node in topology.get("nodes", [])} + for feature in new_enabled: + if not feature.socket_ready: + form.add_error( + feature.setting, + "Start the configured service before enabling this feature.", + ) + elif feature.linked: + report = nodes.get(feature.role, {}) + if report.get("state") != "configured" or report.get( + "release" + ) != version("coulobre-panel"): + form.add_error( + feature.setting, + "The linked receiver must be ready and on the same " + "release.", + ) + if ( + feature.setting == "DEFAULT_DNS_ZONES" + and not form.cleaned_data.get("LOCAL_DNS_PUBLISHING") + ): + form.add_error(feature.setting, "Enable DNS publishing first.") + + +@method_decorator(never_cache, name="dispatch") +class FeatureConfigurationView(UserPassesTestMixin, FormView): + form_class = FeatureConfigurationForm + template_name = "hosting/feature_configuration.html" + success_url = reverse_lazy("panel:installation") + + def test_func(self): + return ( + self.request.user.is_superuser and self.request.user.is_verified() + ) + + def get_form_kwargs(self): + return {**super().get_form_kwargs(), "policy": FeaturePolicy()} + + def form_valid(self, form): + revision = form.cleaned_data["revision"] + policy = FeaturePolicy() + if revision != policy.saved.revision: + return self.stale_form(form) + changed = form.changed_features() + if not changed: + return super().form_valid(form) + check_features(form, changed) + if form.errors: + return self.form_invalid(form) + disabled = set(policy.disabled) + for feature in changed: + if form.cleaned_data[feature.setting]: + disabled.discard(feature.setting) + else: + disabled.add(feature.setting) + with transaction.atomic(): + saved, _ = PanelFeaturePolicy.objects.get_or_create(pk=1) + updated = PanelFeaturePolicy.objects.filter( + pk=1, revision=revision + ).update(disabled=sorted(disabled), revision=F("revision") + 1) + if not updated: + return self.stale_form(form) + LogEntry.objects.log_actions( + self.request.user.pk, + [saved], + CHANGE, + [ + { + "changed": { + "fields": [feature.label for feature in changed] + } + } + ], + ) + messages.success(self.request, "Feature configuration saved.") + return super().form_valid(form) + + def stale_form(self, form): + form.add_error( + None, "The configuration changed. Reopen this page and try again." + ) + return self.render_to_response( + self.get_context_data(form=form), status=409 ) diff --git a/src/coulobre/hosting/mail_dns_views.py b/src/coulobre/hosting/mail_dns_views.py index d9a715c..5cc74f9 100644 --- a/src/coulobre/hosting/mail_dns_views.py +++ b/src/coulobre/hosting/mail_dns_views.py @@ -22,6 +22,7 @@ from coulobre.mail_dns import ( ) from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant +from .installation_features import panel_feature_allowed from .mail_dns_setup import ( closest_zone, mail_dns_proposal, @@ -156,8 +157,8 @@ class MailDnsCheckView( report=report, mail_domain=self.object, can_refresh=( - settings.MANAGE_MAIL_DNS - and settings.LOCAL_MAILBOX_PROVISIONING + panel_feature_allowed("MANAGE_MAIL_DNS") + and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") and not is_tenant(self.request.user) and self.request.user.has_perms(PROVISION_MAILBOX) and self.object.mailboxes.filter( @@ -261,7 +262,8 @@ class RequestMailDnsSetup(OperatorOnlyMixin, PermissionRequiredMixin, View): def post(self, request, pk): if not ( - settings.MANAGE_MAIL_DNS and settings.LOCAL_MAILBOX_PROVISIONING + panel_feature_allowed("MANAGE_MAIL_DNS") + and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") ): raise Http404 domain = get_object_or_404(HostingMailDomain, pk=pk) diff --git a/src/coulobre/hosting/mail_queue_views.py b/src/coulobre/hosting/mail_queue_views.py index 778d61b..c857c67 100644 --- a/src/coulobre/hosting/mail_queue_views.py +++ b/src/coulobre/hosting/mail_queue_views.py @@ -1,6 +1,5 @@ from datetime import timedelta -from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.db import transaction from django.http import Http404 @@ -11,6 +10,7 @@ from django.views.decorators.cache import never_cache from django.views.generic import TemplateView from .access import OperatorOnlyMixin +from .installation_features import panel_feature_allowed from .models import HostingMailDomain from .tasks import refresh_mail_queue @@ -24,7 +24,7 @@ class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView): template_name = "hosting/mail_queue.html" def get_domain(self, *, locked=False): - if not settings.LOCAL_MAILBOX_PROVISIONING: + if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"): raise Http404 domains = HostingMailDomain.objects.filter( account__retired_at__isnull=True diff --git a/src/coulobre/hosting/migrations/0059_panel_feature_policy.py b/src/coulobre/hosting/migrations/0059_panel_feature_policy.py new file mode 100644 index 0000000..feec519 --- /dev/null +++ b/src/coulobre/hosting/migrations/0059_panel_feature_policy.py @@ -0,0 +1,28 @@ +# Generated by Django 5.2.19 on 2026-11-23 19:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0058_scope_service_signon_grants"), + ] + + operations = [ + migrations.CreateModel( + name="PanelFeaturePolicy", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("disabled", models.JSONField(blank=True, default=list)), + ("revision", models.PositiveBigIntegerField(default=0)), + ], + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index e7ac10f..a2c0fc9 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -608,6 +608,11 @@ class DirectAdminImport(models.Model): fingerprint = models.CharField(max_length=64, unique=True) +class PanelFeaturePolicy(models.Model): + disabled = models.JSONField(default=list, blank=True) + revision = models.PositiveBigIntegerField(default=0) + + class DnsZoneDefaults(models.Model): nameservers = models.JSONField(default=list, blank=True) addresses = models.JSONField(default=list, blank=True) diff --git a/src/coulobre/hosting/phpmyadmin.py b/src/coulobre/hosting/phpmyadmin.py index 9d7e356..5ce089c 100644 --- a/src/coulobre/hosting/phpmyadmin.py +++ b/src/coulobre/hosting/phpmyadmin.py @@ -12,6 +12,7 @@ from django.views.decorators.http import require_POST from .access import customer_for_user from .credential_views import DatabaseCredentialView +from .installation_features import panel_feature_allowed from .models import HostingDatabase, PhpMyAdminGrant, ServiceCredentialAccess from .service_credentials import ( CredentialKind, @@ -30,7 +31,7 @@ from .signon import ( def phpmyadmin_available(request): return bool( - settings.PHPMYADMIN_URL + panel_feature_allowed("PHPMYADMIN_URL") and settings.PHPMYADMIN_BRIDGE_KEY and enabled_credential_access(request, CredentialKind.DATABASE) ) diff --git a/src/coulobre/hosting/roundcube.py b/src/coulobre/hosting/roundcube.py index cbc5a61..6006ec0 100644 --- a/src/coulobre/hosting/roundcube.py +++ b/src/coulobre/hosting/roundcube.py @@ -12,6 +12,7 @@ from django.views.decorators.http import require_POST from .access import customer_for_user from .credential_views import MailboxCredentialView +from .installation_features import panel_feature_allowed from .models import HostingMailbox, RoundcubeGrant, ServiceCredentialAccess from .service_credentials import ( CredentialKind, @@ -30,7 +31,7 @@ from .signon import ( def roundcube_available(request): return bool( - settings.ROUNDCUBE_URL + panel_feature_allowed("ROUNDCUBE_URL") and settings.ROUNDCUBE_BRIDGE_KEY and enabled_credential_access(request, CredentialKind.MAILBOX) ) diff --git a/src/coulobre/hosting/templates/hosting/account_backups.html b/src/coulobre/hosting/templates/hosting/account_backups.html index 1ac1d91..ccbc916 100644 --- a/src/coulobre/hosting/templates/hosting/account_backups.html +++ b/src/coulobre/hosting/templates/hosting/account_backups.html @@ -16,7 +16,7 @@

{% endif %} - {% if not account_backup_pending %} + {% if can_request_account_backup and not account_backup_pending %}
{% csrf_token %} {% if account_backup_allow_mail %} diff --git a/src/coulobre/hosting/templates/hosting/feature_configuration.html b/src/coulobre/hosting/templates/hosting/feature_configuration.html new file mode 100644 index 0000000..429dc89 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/feature_configuration.html @@ -0,0 +1,27 @@ +{% extends "hosting/base.html" %} +{% block title %}Configure features · Coulobre Panel{% endblock %} +{% block content %} + ← About Coulobre +

Configure features

+
+

Choose which configured features the panel can use for new requests. Existing sites, mailboxes, scheduled tasks and backups keep running.

+ + {% csrf_token %} + {{ form.non_field_errors }} + {{ form.revision }} + {% for field in form.visible_fields %} +
+ + {{ field.errors }} +

{{ field.help_text }}

+
+ {% empty %} +

No installed features can be configured here yet.

+ {% endfor %} +
+ {% if form.visible_fields %}{% endif %} + Cancel +
+ +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/installation.html b/src/coulobre/hosting/templates/hosting/installation.html index 866dab3..af16dc4 100644 --- a/src/coulobre/hosting/templates/hosting/installation.html +++ b/src/coulobre/hosting/templates/hosting/installation.html @@ -4,6 +4,7 @@ {% block content %}

About Coulobre

+ {% for message in messages %}

{{ message }}

{% endfor %}

Installation

@@ -17,22 +18,28 @@

Feature configuration

See Service health for the latest local and remote checks.

+ {% if request.user.is_superuser and request.user.is_verified %} + Configure features + {% endif %}
- + - {% for name, enabled in features %} + {% for feature, configured, enabled in features %} - + + {% endfor %} diff --git a/src/coulobre/hosting/test_feature_configuration.py b/src/coulobre/hosting/test_feature_configuration.py new file mode 100644 index 0000000..b4da145 --- /dev/null +++ b/src/coulobre/hosting/test_feature_configuration.py @@ -0,0 +1,140 @@ +from unittest.mock import PropertyMock, patch + +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse +from django_otp.plugins.otp_totp.models import TOTPDevice + +from .models import AccountBackupJob, HostingAccount, PanelFeaturePolicy + + +@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_DNS_PUBLISHING=True) +class FeatureConfigurationTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.operator = get_user_model().objects.create_superuser("operator") + cls.device = TOTPDevice.objects.create(user=cls.operator, name="Panel") + cls.account = HostingAccount.objects.create( + name="Existing account", primary_domain="site.example" + ) + + def sign_in(self, *, verified=True): + self.client.force_login(self.operator) + if verified: + session = self.client.session + session["otp_device_id"] = self.device.persistent_id + session.save() + + def save(self, **data): + return self.client.post(reverse("panel:feature_configuration"), data) + + def test_paused_backup_option_blocks_new_jobs_but_archives_stay_visible( + self, + ): + self.sign_in() + result = self.save(revision=0, LOCAL_DNS_PUBLISHING="on") + self.assertRedirects(result, reverse("panel:installation")) + self.assertEqual( + PanelFeaturePolicy.objects.get().disabled, + ["LOCAL_ACCOUNT_BACKUPS"], + ) + self.assertEqual( + self.client.post( + reverse("panel:account_backup_create", args=[self.account.pk]) + ).status_code, + 404, + ) + self.assertFalse(AccountBackupJob.objects.exists()) + self.assertEqual( + self.client.get( + reverse( + "panel:account_backup_archives", args=[self.account.pk] + ) + ).status_code, + 200, + ) + + def test_failed_preflight_preserves_all_choices_and_revision(self): + self.sign_in() + policy = PanelFeaturePolicy.objects.create( + pk=1, disabled=["LOCAL_DNS_PUBLISHING"], revision=2 + ) + with patch( + "coulobre.hosting.installation_features.Feature.socket_ready", + new_callable=PropertyMock, + return_value=False, + ): + response = self.save(revision=2, LOCAL_DNS_PUBLISHING="on") + self.assertContains( + response, "Start the configured service before enabling" + ) + policy.refresh_from_db() + self.assertEqual(policy.disabled, ["LOCAL_DNS_PUBLISHING"]) + self.assertEqual(policy.revision, 2) + self.assertEqual(self.save(revision=1).status_code, 409) + + def test_linked_receiver_must_match_panel_release_before_enabling(self): + self.sign_in() + policy = PanelFeaturePolicy.objects.create( + pk=1, disabled=["LOCAL_DNS_PUBLISHING"] + ) + module = "coulobre.hosting.installation_features.Feature" + update = "coulobre.hosting.installation_views" + with ( + patch( + f"{module}.linked", + new_callable=PropertyMock, + return_value=True, + ), + patch( + f"{module}.socket_ready", + new_callable=PropertyMock, + return_value=True, + ), + patch(f"{update}.version", return_value="1.0.0"), + patch( + f"{update}.inspect_linked_nodes", + return_value={ + "nodes": [ + { + "role": "dns", + "release": "0.9.0", + "state": "configured", + } + ] + }, + ) as linked, + ): + response = self.save( + revision=0, + LOCAL_DNS_PUBLISHING="on", + LOCAL_ACCOUNT_BACKUPS="on", + ) + self.assertContains(response, "linked receiver must be ready") + linked.return_value["nodes"][0]["release"] = "1.0.0" + response = self.save( + revision=0, + LOCAL_DNS_PUBLISHING="on", + LOCAL_ACCOUNT_BACKUPS="on", + ) + self.assertRedirects(response, reverse("panel:installation")) + policy.refresh_from_db() + self.assertEqual(policy.disabled, []) + self.assertEqual(policy.revision, 1) + + @override_settings(LOCAL_WEB_HTTPS=False) + def test_requires_verified_admin_and_never_enables_unconfigured_service( + self, + ): + self.sign_in(verified=False) + response = self.save(revision=0) + self.assertEqual(response.status_code, 403) + self.sign_in() + response = self.save( + revision=0, + LOCAL_DNS_PUBLISHING="on", + LOCAL_ACCOUNT_BACKUPS="on", + LOCAL_WEB_HTTPS="on", + ) + self.assertRedirects(response, reverse("panel:installation")) + self.assertFalse(PanelFeaturePolicy.objects.exists()) diff --git a/src/coulobre/hosting/test_service_health.py b/src/coulobre/hosting/test_service_health.py index 4a6e300..d09117f 100644 --- a/src/coulobre/hosting/test_service_health.py +++ b/src/coulobre/hosting/test_service_health.py @@ -171,6 +171,7 @@ class ServiceHealthPanelTests(TestCase): HOSTING_PUBLIC_ADDRESSES=("192.0.2.20",), ROUNDCUBE_URL="https://webmail.example.net", ROUNDCUBE_BRIDGE_KEY="test-only-bridge-key", + LOCAL_MAILBOX_CREDENTIALS=True, ) def test_installation_reports_configuration_to_operators(self): url = reverse("panel:installation") @@ -190,7 +191,10 @@ class ServiceHealthPanelTests(TestCase): self.assertContains(response, "1.2.3") self.assertContains(response, "Apache License 2.0") self.assertContains(response, reverse("panel:service_health")) - features = dict(response.context["features"]) + features = { + feature.label: enabled + for feature, _, enabled in response.context["features"] + } self.assertTrue(features["Default managed DNS zones for new accounts"]) self.assertTrue(features["Roundcube sign-in"]) self.assertNotContains(response, "test-only-bridge-key") @@ -207,11 +211,11 @@ class ServiceHealthPanelTests(TestCase): ) self.client.force_login(self.admin) response = self.client.get(reverse("panel:installation")) - self.assertTrue( - dict(response.context["features"])[ - "Default managed DNS zones for new accounts" - ] - ) + features = { + feature.label: enabled + for feature, _, enabled in response.context["features"] + } + self.assertTrue(features["Default managed DNS zones for new accounts"]) self.assertContains(response, "Configure DNS defaults") def test_view_marks_missing_and_old_observations_distinctly(self): diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index ede017a..c151a2f 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -22,7 +22,7 @@ from .independent_website_views import ( IndependentWebsiteManifest, IndependentWebsiteOperation, ) -from .installation_views import InstallationView +from .installation_views import FeatureConfigurationView, InstallationView from .invitations import AcceptInvitation, ManageInvitation from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup from .mail_policy_views import MailRoutingEditor, MailVacationEditor @@ -89,6 +89,11 @@ urlpatterns = [ "service-health/", ServiceHealthView.as_view(), name="service_health" ), path("about/", InstallationView.as_view(), name="installation"), + path( + "about/features/", + FeatureConfigurationView.as_view(), + name="feature_configuration", + ), path("account/role/", switch_panel_role, name="switch_panel_role"), path( "logins/assign-role/", diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 6607f20..999f89c 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -93,6 +93,11 @@ from .independent_websites import ( website_actions, website_limit, ) +from .installation_features import ( + default_dns_zones_allowed, + panel_feature_allowed, + panel_feature_paused, +) from .invitations import InviteLoginForm, queue_invitation from .mail_policy_views import mail_policy_enabled from .models import ( @@ -249,7 +254,7 @@ def missing_account_setup(account, actor): defaults = zone_defaults() options = [] if ( - settings.LOCAL_WEB_ACTIVATION + panel_feature_allowed("LOCAL_WEB_ACTIVATION") and actor.has_perms(ACTIVATE_WEB) and not account.webprovisioningplan_set.filter( primary_domain=domain, activation__isnull=False @@ -257,16 +262,14 @@ def missing_account_setup(account, actor): ): options.append(("setup_website", "Set up the primary website")) if ( - settings.LOCAL_DNS_PUBLISHING - and defaults.nameservers - and defaults.addresses + default_dns_zones_allowed(defaults) and actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone")) and not HostingDnsZone.objects.filter(domain=domain).exists() ): options.append(("setup_dns", "Publish a Coulobre DNS zone")) if ( - settings.LOCAL_MAILBOX_PROVISIONING - and settings.MANAGE_MAIL_DNS + panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") + and panel_feature_allowed("MANAGE_MAIL_DNS") and actor.has_perms(PROVISION_MAILBOX) and not account.mail_domains.filter(domain=domain).exists() ): @@ -313,7 +316,7 @@ class ExistingAccountSetup( and bool(form["setup_email"].value()) ) or ( - settings.MANAGE_MAIL_DNS + panel_feature_allowed("MANAGE_MAIL_DNS") and self.account.mail_domains.filter( domain=self.account.primary_domain ).exists() @@ -481,19 +484,12 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): actor = self.request.user reseller = reseller_for_user(actor) is not None defaults = zone_defaults() - web = settings.LOCAL_WEB_ACTIVATION and ( + web = panel_feature_allowed("LOCAL_WEB_ACTIVATION") and ( reseller or actor.has_perms(ACTIVATE_WEB) ) - dns = ( - settings.LOCAL_DNS_PUBLISHING - and defaults.nameservers - and defaults.addresses - and ( - reseller - or actor.has_perms( - (*PUBLISH_DNS, "hosting.add_hostingdnszone") - ) - ) + dns = default_dns_zones_allowed(defaults) and ( + reseller + or actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone")) ) choices = { "setup_website": (web, "Set up the primary website"), @@ -505,8 +501,8 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): "setup_www": (web or dns, "Include the www hostname"), "setup_wildcard": (dns, "Include a wildcard (*) DNS record"), "setup_email": ( - settings.LOCAL_MAILBOX_PROVISIONING - and settings.MANAGE_MAIL_DNS + panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") + and panel_feature_allowed("MANAGE_MAIL_DNS") and (reseller or actor.has_perms(PROVISION_MAILBOX)), "Set up email DNS for this domain", ), @@ -620,7 +616,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) context["show_mail_queue"] = ( not tenant - and settings.LOCAL_MAILBOX_PROVISIONING + and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") and user.has_perm("hosting.view_hostingmaildomain") ) manage_resources = reseller is not None and reseller.manage_resources @@ -645,10 +641,11 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["primary_file_access"] = manage_files and site_is_active( self.object ) + website_provisioning = panel_feature_allowed("LOCAL_WEB_ACTIVATION") if settings.LOCAL_WEB_ACTIVATION or manage_files: websites = list(account_websites(self.object)) can_manage = ( - settings.LOCAL_WEB_ACTIVATION + website_provisioning and not self.object.services_suspended and (tenant or user.has_perm(CHANGE_ACCOUNTS)) and getattr(self.request, "impersonation", None) is None @@ -687,7 +684,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ): context["website_storage"] = storage context["can_measure_site_storage"] = ( - settings.LOCAL_WEB_ACTIVATION + panel_feature_allowed("LOCAL_WEB_ACTIVATION") and not tenant and user.has_perms(MEASURE_SITE_STORAGE) ) @@ -698,7 +695,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): if quota is not None and quota.domain == self.object.primary_domain: context["website_limit"] = quota context["can_change_site_storage_limit"] = ( - settings.LOCAL_WEB_ACTIVATION + panel_feature_allowed("LOCAL_WEB_ACTIVATION") and not tenant and user.has_perms(CHANGE_SITE_STORAGE_LIMIT) ) @@ -721,7 +718,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) context["website_php_job"] = php_job context["can_change_php_settings"] = ( - not tenant and user.has_perms(CHANGE_SITE_PHP_SETTINGS) + website_provisioning + and not tenant + and user.has_perms(CHANGE_SITE_PHP_SETTINGS) ) version_job = getattr(self.object, "php_version_job", None) if ( @@ -734,7 +733,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) context["website_php_version_job"] = version_job context["can_change_php_version"] = ( - can_change_php_version(self.request) + website_provisioning + and can_change_php_version(self.request) and not self.object.services_suspended and ( version_job is None @@ -746,13 +746,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): .select_related("reservation") .order_by("reservation__domain") ) - if not tenant and user.has_perms(MANAGE_WEBSITE_ALIASES): + if ( + website_provisioning + and not tenant + and user.has_perms(MANAGE_WEBSITE_ALIASES) + ): context["manage_website_aliases"] = True context["can_add_website_alias"] = site_active - context["can_enable_alias_https"] = ( - settings.LOCAL_WEB_HTTPS - and user.has_perms(ENABLE_WEB_HTTPS) - ) + context["can_enable_alias_https"] = panel_feature_allowed( + "LOCAL_WEB_HTTPS" + ) and user.has_perms(ENABLE_WEB_HTTPS) context["export_backup_manifest"] = not tenant and user.has_perms( EXPORT_BACKUP_MANIFEST ) @@ -766,7 +769,12 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ): can_view_mailboxes = user.has_perm(VIEW_MAILBOXES) context["show_account_backups"] = True - context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP) + context["can_request_account_backup"] = panel_feature_allowed( + "LOCAL_ACCOUNT_BACKUPS" + ) + context["can_retry_offsite"] = panel_feature_allowed( + "OFFSITE_BACKUP_DESTINATIONS" + ) and user.has_perms(RETRY_OFFSITE_BACKUP) context["manage_backup_retention"] = ( settings.LOCAL_BACKUP_RETENTION and user.has_perms(MANAGE_BACKUP_RETENTION) @@ -799,9 +807,10 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): or can_view_mailboxes ): context["account_backup_schedule"] = schedule - context["edit_account_backup_schedule"] = user.has_perms( - MANAGE_BACKUP_SCHEDULE - ) + context["edit_account_backup_schedule"] = ( + schedule is not None + or context["can_request_account_backup"] + ) and user.has_perms(MANAGE_BACKUP_SCHEDULE) context["manage_sftp"] = ( settings.LOCAL_WEB_SFTP and can_manage_sftp(user) @@ -831,7 +840,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["automatic_database_provisioning"] = ( automatic_resource_provisioning( user, - settings.LOCAL_DATABASE_PROVISIONING, + panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"), PROVISION_DATABASE, ) ) @@ -840,8 +849,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): not tenant and user.has_perms(PROVISION_DATABASE) ): context["manage_database_provisioning"] = True - context["local_database_enabled"] = ( - settings.LOCAL_DATABASE_PROVISIONING + context["local_database_enabled"] = panel_feature_allowed( + "LOCAL_DATABASE_PROVISIONING" ) context["databases"] = databases if tenant or user.has_perm(VIEW_DNS_ZONES): @@ -851,15 +860,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): "publication__manifest" ) context["tenant_dns_editing"] = True - context["tenant_dns_publishing"] = ( - settings.LOCAL_DNS_PUBLISHING + context["tenant_dns_publishing"] = panel_feature_allowed( + "LOCAL_DNS_PUBLISHING" ) if not tenant and user.has_perms(PUBLISH_DNS): zone_list = zone_list.select_related("publication").defer( "publication__manifest" ) context["manage_dns_publishing"] = True - context["local_dns_enabled"] = settings.LOCAL_DNS_PUBLISHING + context["local_dns_enabled"] = panel_feature_allowed( + "LOCAL_DNS_PUBLISHING" + ) zones = list(zone_list) context["dns_zones"] = zones context["dns_zone_records"] = [ @@ -876,11 +887,15 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["has_primary_zone"] = primary_zone is not None if primary_zone is None: context["dns_readiness"] = "No managed zone" - if not tenant and settings.LOCAL_DNS_PUBLISHING: + if not tenant and panel_feature_allowed( + "LOCAL_DNS_PUBLISHING" + ): try: draft = default_dns_zone( self.object, - managed_mail=settings.MANAGE_MAIL_DNS + managed_mail=panel_feature_allowed( + "MANAGE_MAIL_DNS" + ) and self.object.mail_domains.filter( domain=self.object.primary_domain ).exists(), @@ -904,7 +919,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["automatic_mailbox_provisioning"] = ( automatic_resource_provisioning( user, - settings.LOCAL_MAILBOX_PROVISIONING, + panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"), PROVISION_MAILBOX, ) ) @@ -929,8 +944,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): not tenant and user.has_perms(PROVISION_MAILBOX) ): context["manage_mailbox_provisioning"] = True - context["local_mailbox_enabled"] = ( - settings.LOCAL_MAILBOX_PROVISIONING + context["local_mailbox_enabled"] = panel_feature_allowed( + "LOCAL_MAILBOX_PROVISIONING" ) context["change_mailbox_quota"] = ( not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA) @@ -1002,7 +1017,7 @@ class SiteStorageLimitEdit( template_name = "hosting/site_storage_limit_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -1051,7 +1066,7 @@ class SitePhpSettingsEdit( template_name = "hosting/site_php_settings_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -1098,7 +1113,7 @@ class SitePhpVersionEdit(PermissionRequiredMixin, FormView): template_name = "hosting/site_php_version_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -1160,7 +1175,7 @@ class WebsiteAliasEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView): template_name = "hosting/website_alias_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -1214,9 +1229,9 @@ class WebsiteAliasAction(WebsiteAliasEditor): ) def can_enable_https(self): - return settings.LOCAL_WEB_HTTPS and self.request.user.has_perms( - ENABLE_WEB_HTTPS - ) + return panel_feature_allowed( + "LOCAL_WEB_HTTPS" + ) and self.request.user.has_perms(ENABLE_WEB_HTTPS) def has_permission(self): if not super().has_permission(): @@ -1259,7 +1274,7 @@ class RequestSiteStorageMeasurement( permission_required = MEASURE_SITE_STORAGE def post(self, request, pk): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 try: queue_site_storage_measurement(pk) @@ -1305,7 +1320,7 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View): permission_required = MANAGE_ACCOUNT_BACKUPS def post(self, request, pk): - if not settings.LOCAL_ACCOUNT_BACKUPS: + if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"): raise Http404 include_mailboxes = request.POST.get("include_mail") == "1" if include_mailboxes: @@ -1354,7 +1369,9 @@ class AccountBackupArchiveList( def get_context_data(self, **kwargs): context = super().get_context_data(account=self.account, **kwargs) user = self.request.user - context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP) + context["can_retry_offsite"] = panel_feature_allowed( + "OFFSITE_BACKUP_DESTINATIONS" + ) and user.has_perms(RETRY_OFFSITE_BACKUP) context["manage_backup_retention"] = ( settings.LOCAL_BACKUP_RETENTION and user.has_perms(MANAGE_BACKUP_RETENTION) @@ -1378,7 +1395,9 @@ class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View): permission_required = RETRY_OFFSITE_BACKUP def post(self, request, pk, backup_pk): - if not settings.LOCAL_ACCOUNT_BACKUPS: + if not settings.LOCAL_ACCOUNT_BACKUPS or not panel_feature_allowed( + "OFFSITE_BACKUP_DESTINATIONS" + ): raise Http404 account = get_object_or_404(HostingAccount, pk=pk) backup = get_object_or_404( @@ -1689,6 +1708,8 @@ class EditAccountBackupSchedule( def get_initial(self): schedule = getattr(self.account, "backup_schedule", None) if schedule is None: + if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"): + raise Http404 return { "enabled": True, "frequency": AccountBackupSchedule.Frequency.DAILY, @@ -1711,6 +1732,15 @@ class EditAccountBackupSchedule( return super().get_context_data(account=self.account, **kwargs) def form_valid(self, form): + if ( + form.cleaned_data["enabled"] + and not self.get_initial()["enabled"] + and not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS") + ): + form.add_error( + "enabled", "New backup requests are paused in the panel." + ) + return self.form_invalid(form) try: save_backup_schedule( self.account.pk, @@ -1977,7 +2007,7 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def auto_provision(self): return automatic_resource_provisioning( self.request.user, - getattr(settings, self.provisioning_setting), + panel_feature_allowed(self.provisioning_setting), self.provisioning_permissions, ) @@ -2070,7 +2100,7 @@ class ResourceProvisioningRequest(PermissionRequiredMixin, View): ) def post(self, request, pk): - if not getattr(settings, self.enabled_setting): + if not panel_feature_allowed(self.enabled_setting): raise Http404 queryset = self.queryset.all() if self.reseller is not None: @@ -2141,7 +2171,7 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): try: draft = default_dns_zone( self.account, - managed_mail=settings.MANAGE_MAIL_DNS + managed_mail=panel_feature_allowed("MANAGE_MAIL_DNS") and self.account.mail_domains.filter( domain=self.domain ).exists(), @@ -2157,9 +2187,9 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): @cached_property def publish_on_create(self): - return settings.LOCAL_DNS_PUBLISHING and self.request.user.has_perms( - PUBLISH_DNS - ) + return panel_feature_allowed( + "LOCAL_DNS_PUBLISHING" + ) and self.request.user.has_perms(PUBLISH_DNS) def get_context_data(self, **kwargs): return super().get_context_data( @@ -2167,6 +2197,13 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): ) def form_valid(self, form): + if form.cleaned_data["manage_mail_dns"] and panel_feature_paused( + "MANAGE_MAIL_DNS" + ): + form.add_error( + "manage_mail_dns", "Managed mail DNS is paused in the panel." + ) + return self.form_invalid(form) try: with transaction.atomic(): account = lock_hosting_account( @@ -2272,6 +2309,15 @@ class DnsZoneEdit(DnsZoneEditor): def form_valid(self, form): values = form.cleaned_data + if ( + values["manage_mail_dns"] + and not self.zone.manage_mail_dns + and panel_feature_paused("MANAGE_MAIL_DNS") + ): + form.add_error( + "manage_mail_dns", "Managed mail DNS is paused in the panel." + ) + return self.form_invalid(form) serial = values["serial"] if all( getattr(self.zone, field) == value @@ -2344,7 +2390,7 @@ class RequestDnsPublication(PermissionRequiredMixin, View): return super().has_permission() def post(self, request, pk): - if not settings.LOCAL_DNS_PUBLISHING: + if not panel_feature_allowed("LOCAL_DNS_PUBLISHING"): raise Http404 try: zone = queue_dns_publication( @@ -2569,10 +2615,12 @@ class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): return super().get_context_data( manage_activation=not is_tenant(user) and user.has_perms(ACTIVATE_WEB), - local_activation_enabled=settings.LOCAL_WEB_ACTIVATION, + local_activation_enabled=panel_feature_allowed( + "LOCAL_WEB_ACTIVATION" + ), manage_https=not is_tenant(user) and user.has_perms(ENABLE_WEB_HTTPS), - local_https_enabled=settings.LOCAL_WEB_HTTPS, + local_https_enabled=panel_feature_allowed("LOCAL_WEB_HTTPS"), **kwargs, ) @@ -2584,7 +2632,7 @@ class RequestWebActivation( permission_required = ACTIVATE_WEB def post(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 plan = self.get_object() if not plan.can_export: @@ -2610,7 +2658,7 @@ class RequestWebHTTPS( permission_required = ENABLE_WEB_HTTPS def post(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_HTTPS: + if not panel_feature_allowed("LOCAL_WEB_HTTPS"): raise Http404 plan = self.get_object() if not plan.can_enable_https: diff --git a/src/coulobre/hosting/website_file_views.py b/src/coulobre/hosting/website_file_views.py index 50da522..e65fc3a 100644 --- a/src/coulobre/hosting/website_file_views.py +++ b/src/coulobre/hosting/website_file_views.py @@ -1,7 +1,6 @@ from urllib.parse import urlencode from django import forms -from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.exceptions import ValidationError from django.http import Http404, StreamingHttpResponse @@ -22,6 +21,7 @@ from coulobre.website_files import ( from .access import TenantScopeMixin, is_tenant from .independent_websites import active_websites +from .installation_features import panel_feature_allowed from .models import HostingAccount from .resource_requests import require_active_services from .sftp import site_is_active @@ -34,7 +34,7 @@ UNAVAILABLE = "The website files service is unavailable. Try again later." def can_manage_website_files(request): user = request.user return ( - settings.WEB_FILE_MANAGER + panel_feature_allowed("WEB_FILE_MANAGER") and getattr(request, "impersonation", None) is None and (is_tenant(user) or user.has_perms(MANAGE_FILES)) ) @@ -75,7 +75,7 @@ class WebsiteFilesView( permission_required = MANAGE_FILES def dispatch(self, request, *args, **kwargs): - if not settings.WEB_FILE_MANAGER: + if not panel_feature_allowed("WEB_FILE_MANAGER"): raise Http404 return super().dispatch(request, *args, **kwargs) diff --git a/src/coulobre/hosting/website_job_views.py b/src/coulobre/hosting/website_job_views.py index 1944d6b..66a8268 100644 --- a/src/coulobre/hosting/website_job_views.py +++ b/src/coulobre/hosting/website_job_views.py @@ -1,5 +1,4 @@ from django import forms -from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.exceptions import ValidationError from django.db import transaction @@ -18,6 +17,7 @@ from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command from .access import TenantScopeMixin, is_tenant from .independent_websites import check_actor +from .installation_features import panel_feature_allowed from .models import HostingAccount from .resource_requests import lock_hosting_account from .website_job_schedule import next_website_run @@ -33,7 +33,7 @@ MANAGE_JOBS = ("hosting.view_hostingaccount", "hosting.manage_website_jobs") def can_manage_website_jobs(request): user = request.user return ( - settings.WEBSITE_JOBS + panel_feature_allowed("WEBSITE_JOBS") and getattr(request, "impersonation", None) is None and (is_tenant(user) or user.has_perms(MANAGE_JOBS)) ) @@ -104,7 +104,7 @@ class WebsiteJobAccountView( permission_required = MANAGE_JOBS def dispatch(self, request, *args, **kwargs): - if not settings.WEBSITE_JOBS: + if not panel_feature_allowed("WEBSITE_JOBS"): raise Http404 return super().dispatch(request, *args, **kwargs) diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index bbdfe69..c38d540 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -91,6 +91,7 @@ MIDDLEWARE = [ "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "coulobre.hosting.panel_roles.PanelRoleMiddleware", + "coulobre.hosting.installation_features.FeaturePolicyMiddleware", "coulobre.hosting.impersonation.CustomerImpersonationMiddleware", ]
FeatureConfiguration
FeatureConfigurationPrerequisites
{{ name }}{{ feature.label }}
- {% if enabled %}Enabled{% else %}Disabled{% endif %} - {% if request.user.is_superuser and name == 'Default managed DNS zones for new accounts' %} + {% if enabled %}Enabled{% elif configured %}Paused in panel{% else %}Requires setup{% endif %} + {% if enabled and not feature.socket_ready %}Service socket unavailable{% endif %} + {% if configured and feature.role %}{% if feature.linked %}Linked receiver{% else %}Local{% endif %}{% endif %} + {% if request.user.is_superuser and feature.setting == 'DEFAULT_DNS_ZONES' %} Configure DNS defaults {% endif %}
{{ feature.prerequisite }}